@darkbear9494/dsh-model-manager 0.1.0
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/LICENSE +21 -0
- package/README.md +1231 -0
- package/client.js +955 -0
- package/cordis.patch.yml +36 -0
- package/lib/index.js +1593 -0
- package/locale/en.json +4 -0
- package/locale/zh.json +4 -0
- package/package.json +73 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1593 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @darkbear9494/dsh-model-manager — role-based model manager for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* Assign models to four roles (main / planning / execution / vision), route
|
|
5
|
+
* subagent work to the right role, and report which model every subagent used.
|
|
6
|
+
*
|
|
7
|
+
* Design rules for this plugin (learned the hard way on DSH 0.1.7-rc.2):
|
|
8
|
+
* - No `settings.installSection` / `installSettingsSection` / `settingsNamespace`.
|
|
9
|
+
* That API was removed in 0.1.7; calling it fails *apply* and takes the whole
|
|
10
|
+
* plugin tree (and therefore startup) down. This host half instead exports a
|
|
11
|
+
* volatile `Config`, which the harness auto-generates a Settings form from
|
|
12
|
+
* (`autoGenerate` defaults to true) and which the Web client half in
|
|
13
|
+
* `client.js` renders as a model picker per role. Neither touches the removed
|
|
14
|
+
* settings API.
|
|
15
|
+
* - A volatile-only Settings save is committed in place and the loader returns
|
|
16
|
+
* before re-running `apply`, so `attach()` listens on
|
|
17
|
+
* `loader/volatile-update` to re-read this config.
|
|
18
|
+
* - No import of `@deepseek-ai/dsh-tools` / `dsh-llm` / `cordis`: those are not
|
|
19
|
+
* resolvable from a profile-installed plugin. Tools are registered in the
|
|
20
|
+
* normalized shape the registry expects, using plain JSON Schema.
|
|
21
|
+
* - Nothing optional may throw. Every integration is probed and wrapped, and
|
|
22
|
+
* `apply` has a final backstop: a misconfiguration must degrade routing,
|
|
23
|
+
* never prevent the harness from booting.
|
|
24
|
+
*
|
|
25
|
+
* @module @darkbear9494/dsh-model-manager
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Optional schema dependency.
|
|
30
|
+
*
|
|
31
|
+
* Loaded dynamically so that a resolution failure degrades — no schema
|
|
32
|
+
* validation and no auto-generated Settings page — instead of aborting module
|
|
33
|
+
* load, which would fail the loader entry and therefore *startup*. cordis's
|
|
34
|
+
* `resolveConfig` treats a plugin with no `Config` export as valid and passes
|
|
35
|
+
* the raw config straight through (`if (!runtime.Config) return config`), and
|
|
36
|
+
* `readConfig` below already normalizes raw values defensively.
|
|
37
|
+
*/
|
|
38
|
+
let z;
|
|
39
|
+
try {
|
|
40
|
+
z = (await import('@deepseek-ai/schemastery')).default;
|
|
41
|
+
} catch {
|
|
42
|
+
z = undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Stable Cordis identity. */
|
|
46
|
+
export const name = 'model-manager';
|
|
47
|
+
|
|
48
|
+
const ROLE_NAMES = ['main', 'planning', 'execution', 'vision'];
|
|
49
|
+
|
|
50
|
+
const KNOWN_TOP_KEYS = ['enabled', 'roles', 'strategy'];
|
|
51
|
+
const KNOWN_ROLE_KEYS = ['models', 'pick', 'note'];
|
|
52
|
+
const KNOWN_ROUTE_KEYS = ['provider', 'model', 'reasoningEffort'];
|
|
53
|
+
const KNOWN_STRATEGY_KEYS = ['mode', 'visionKeywords', 'planningKeywords', 'historyLimit'];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Bound on remembered manager-applied routes. Held independently of
|
|
57
|
+
* `strategy.historyLimit` on purpose, so lowering that diagnostic limit can
|
|
58
|
+
* never cause the manager to forget a route it assigned.
|
|
59
|
+
*/
|
|
60
|
+
const MANAGER_APPLIED_LIMIT = 4096;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Provider/model failures eligible for failover.
|
|
64
|
+
*
|
|
65
|
+
* Deliberately excludes:
|
|
66
|
+
* - `ABORTED` — a user or parent cancellation, never a model problem; failing
|
|
67
|
+
* over would silently change the route the next request uses.
|
|
68
|
+
* - `INVALID_REQUEST` — a 400 is a request-content problem that another model
|
|
69
|
+
* will almost certainly reject identically, so switching just burns budget.
|
|
70
|
+
* - `IMAGE_OFFLOAD_REQUIRED` — owned by `dsh-compaction-image-offload`, which
|
|
71
|
+
* offloads images and retries in place.
|
|
72
|
+
*/
|
|
73
|
+
const FAILOVER_CODES = new Set([
|
|
74
|
+
'SERVER', 'RATE_LIMIT', 'TIMEOUT', 'TRANSPORT', 'EMPTY_RESPONSE', 'STREAM_CLOSED',
|
|
75
|
+
'MALFORMED_RESPONSE', 'PI_AI_ERROR', 'UNKNOWN', 'NO_ADAPTER',
|
|
76
|
+
'INVALID_MODEL_INFO', 'INVALID_MODEL_CONTEXT', 'INVALID_MODEL_MAX_TOKENS',
|
|
77
|
+
'AUTH', 'QUOTA', 'ACCOUNT_QUOTA', 'INVALID_CREDENTIAL',
|
|
78
|
+
'CONTEXT_WINDOW_EXCEEDED', 'UNSUPPORTED_CONTENT', 'UNSUPPORTED_REASONING_EFFORT',
|
|
79
|
+
]);
|
|
80
|
+
|
|
81
|
+
/** `HTTP_5xx` fallback codes are provider failures too. */
|
|
82
|
+
const isFailoverCode = (code) => typeof code === 'string'
|
|
83
|
+
&& (FAILOVER_CODES.has(code) || code.startsWith('HTTP_5'));
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Bound on model switches within one step.
|
|
87
|
+
*
|
|
88
|
+
* The harness's attempt loop has no global cap — it exits only on success,
|
|
89
|
+
* terminal failure, or abort — so without this a route that always fails could
|
|
90
|
+
* ping-pong indefinitely.
|
|
91
|
+
*/
|
|
92
|
+
const MAX_SWITCHES_PER_STEP = 3;
|
|
93
|
+
|
|
94
|
+
/** Package name the browser module table keys this plugin's client half by. */
|
|
95
|
+
const PACKAGE_NAME = '@darkbear9494/dsh-model-manager';
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Loader row id this plugin is mounted as.
|
|
99
|
+
*
|
|
100
|
+
* Also the settings namespace the client half binds (`configForms`/`settings`
|
|
101
|
+
* are keyed by row id — the shipped Subagent settings card binds its own row id
|
|
102
|
+
* `subagent-model-selection-settings` the same way).
|
|
103
|
+
*/
|
|
104
|
+
const ROW_ID = 'model-manager';
|
|
105
|
+
|
|
106
|
+
const DEFAULT_VISION_KEYWORDS = [
|
|
107
|
+
'vision', 'visual', 'image', 'images', 'screenshot', 'screen shot', 'ocr',
|
|
108
|
+
'figure', 'diagram', 'chart', 'plot', 'photo', 'picture', 'png', 'jpg',
|
|
109
|
+
'jpeg', 'webp', 'gif', 'ui mock', 'render',
|
|
110
|
+
];
|
|
111
|
+
|
|
112
|
+
const DEFAULT_PLANNING_KEYWORDS = [
|
|
113
|
+
'plan', 'planning', 'design', 'architect', 'architecture', 'analyse',
|
|
114
|
+
'analyze', 'analysis', 'research', 'investigate', 'review', 'critique',
|
|
115
|
+
'strategy', 'reasoning', 'reason', 'compare', 'evaluate', 'assess',
|
|
116
|
+
'spec', 'specification', 'decompose', 'breakdown', 'proposal', 'root cause',
|
|
117
|
+
];
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Config
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Build the row schema.
|
|
125
|
+
*
|
|
126
|
+
* Kept inside a function so that nothing touches `z` unless the optional
|
|
127
|
+
* dependency actually loaded.
|
|
128
|
+
*/
|
|
129
|
+
function buildConfigSchema(z) {
|
|
130
|
+
const RouteSchema = z.object({
|
|
131
|
+
provider: z.string().required(),
|
|
132
|
+
model: z.string().required(),
|
|
133
|
+
reasoningEffort: z.string(),
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const RoleSchema = z.object({
|
|
137
|
+
models: z.array(RouteSchema).default([]),
|
|
138
|
+
pick: z.union([z.const('first'), z.const('round-robin')]).default('first'),
|
|
139
|
+
note: z.string(),
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const StrategySchema = z.object({
|
|
143
|
+
mode: z.union([z.const('hybrid'), z.const('managed'), z.const('advisory')]).default('hybrid'),
|
|
144
|
+
visionKeywords: z.array(z.string()).default(DEFAULT_VISION_KEYWORDS),
|
|
145
|
+
planningKeywords: z.array(z.string()).default(DEFAULT_PLANNING_KEYWORDS),
|
|
146
|
+
historyLimit: z.number().default(300),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Row config.
|
|
151
|
+
*
|
|
152
|
+
* Every field is volatile so the client card can edit it through the shared
|
|
153
|
+
* settings form and have the change apply without a remount. A volatile-only
|
|
154
|
+
* save is committed in place *without* re-running `apply`, which is why
|
|
155
|
+
* `attach()` listens on `loader/volatile-update` to re-read this config.
|
|
156
|
+
*/
|
|
157
|
+
return z.object({
|
|
158
|
+
/** Master switch: when false the manager observes and reports but never rewrites a route. */
|
|
159
|
+
enabled: z.boolean().default(true).volatile(),
|
|
160
|
+
roles: z.object({
|
|
161
|
+
main: RoleSchema.default({}),
|
|
162
|
+
planning: RoleSchema.default({}),
|
|
163
|
+
execution: RoleSchema.default({}),
|
|
164
|
+
vision: RoleSchema.default({}),
|
|
165
|
+
}).default({}).volatile(),
|
|
166
|
+
strategy: StrategySchema.default({}).volatile(),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Row schema, or `undefined` when the optional schema dependency is missing or
|
|
172
|
+
* incompatible.
|
|
173
|
+
*
|
|
174
|
+
* Built inside a guard on purpose: a module-evaluation failure here would fail
|
|
175
|
+
* the loader entry and therefore startup, which is the one failure this plugin
|
|
176
|
+
* must never cause. Without a schema cordis's `resolveConfig` passes the raw
|
|
177
|
+
* config through and `readConfig` normalizes it — routing still works, only
|
|
178
|
+
* schema validation and the auto-generated Settings page are skipped.
|
|
179
|
+
*/
|
|
180
|
+
let Config;
|
|
181
|
+
try {
|
|
182
|
+
Config = z === undefined ? undefined : buildConfigSchema(z);
|
|
183
|
+
} catch {
|
|
184
|
+
Config = undefined;
|
|
185
|
+
}
|
|
186
|
+
export { Config };
|
|
187
|
+
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
// Small helpers
|
|
190
|
+
// ---------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
/** Unwrap a volatile ref if the loader gave us one, else return the value. */
|
|
193
|
+
function readVal(value) {
|
|
194
|
+
if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
|
|
195
|
+
try {
|
|
196
|
+
return value.get();
|
|
197
|
+
} catch {
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return value;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Normalize a keyword list.
|
|
206
|
+
*
|
|
207
|
+
* An absent list takes the built-in default; an explicit `[]` is honoured and
|
|
208
|
+
* disables that classifier, which is the only way to switch one off.
|
|
209
|
+
*/
|
|
210
|
+
function asStringArray(value, fallback) {
|
|
211
|
+
const raw = readVal(value);
|
|
212
|
+
if (!Array.isArray(raw)) return fallback;
|
|
213
|
+
return raw
|
|
214
|
+
.filter((item) => typeof item === 'string')
|
|
215
|
+
.map((item) => item.trim())
|
|
216
|
+
.filter((item) => item !== '');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function normalizeRoute(raw) {
|
|
220
|
+
const value = readVal(raw);
|
|
221
|
+
if (value === null || typeof value !== 'object') return undefined;
|
|
222
|
+
const provider = typeof value.provider === 'string' ? value.provider.trim() : '';
|
|
223
|
+
const model = typeof value.model === 'string' ? value.model.trim() : '';
|
|
224
|
+
if (provider === '' || model === '') return undefined;
|
|
225
|
+
const effort = typeof value.reasoningEffort === 'string' ? value.reasoningEffort.trim() : '';
|
|
226
|
+
return { provider, model, ...(effort === '' ? {} : { reasoningEffort: effort }) };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function unknownKeys(source, known) {
|
|
230
|
+
const value = readVal(source);
|
|
231
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return [];
|
|
232
|
+
return Object.keys(value).filter((key) => !known.includes(key));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Coerce raw row config into a total, always-usable shape. */
|
|
236
|
+
function readConfig(raw) {
|
|
237
|
+
const warnings = [];
|
|
238
|
+
const rolesRaw = readVal(raw?.roles) ?? {};
|
|
239
|
+
const strategyRaw = readVal(raw?.strategy) ?? {};
|
|
240
|
+
|
|
241
|
+
for (const key of unknownKeys(raw, KNOWN_TOP_KEYS)) warnings.push(`unknown config key "${key}" ignored`);
|
|
242
|
+
for (const key of unknownKeys(rolesRaw, ROLE_NAMES)) warnings.push(`unknown role "${key}" ignored`);
|
|
243
|
+
for (const key of ROLE_NAMES) {
|
|
244
|
+
for (const bad of unknownKeys(readVal(rolesRaw?.[key]), KNOWN_ROLE_KEYS)) {
|
|
245
|
+
warnings.push(`unknown key "roles.${key}.${bad}" ignored`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
for (const key of unknownKeys(strategyRaw, KNOWN_STRATEGY_KEYS)) warnings.push(`unknown key "strategy.${key}" ignored`);
|
|
249
|
+
|
|
250
|
+
const readRole = (key) => {
|
|
251
|
+
const role = readVal(rolesRaw?.[key]) ?? {};
|
|
252
|
+
const rawModels = Array.isArray(role.models) ? role.models : [];
|
|
253
|
+
const models = rawModels.map(normalizeRoute).filter((route) => route !== undefined);
|
|
254
|
+
for (const rawModel of rawModels) {
|
|
255
|
+
for (const bad of unknownKeys(rawModel, KNOWN_ROUTE_KEYS)) {
|
|
256
|
+
warnings.push(`unknown key "roles.${key}.models[].${bad}" ignored`
|
|
257
|
+
+ (bad === 'reasoning_effort' ? ' — the key is "reasoningEffort"' : ''));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
models,
|
|
262
|
+
pick: role.pick === 'round-robin' ? 'round-robin' : 'first',
|
|
263
|
+
note: typeof role.note === 'string' && role.note.trim() !== '' ? role.note.trim() : undefined,
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const mode = strategyRaw.mode;
|
|
268
|
+
const limit = strategyRaw.historyLimit;
|
|
269
|
+
return {
|
|
270
|
+
// Only an explicit `false` switches the manager off. A missing or malformed
|
|
271
|
+
// value keeps it on, so a typo can never silently disable routing.
|
|
272
|
+
enabled: readVal(raw?.enabled) !== false,
|
|
273
|
+
roles: Object.fromEntries(ROLE_NAMES.map((key) => [key, readRole(key)])),
|
|
274
|
+
strategy: {
|
|
275
|
+
mode: mode === 'managed' || mode === 'advisory' ? mode : 'hybrid',
|
|
276
|
+
visionKeywords: asStringArray(strategyRaw.visionKeywords, DEFAULT_VISION_KEYWORDS),
|
|
277
|
+
planningKeywords: asStringArray(strategyRaw.planningKeywords, DEFAULT_PLANNING_KEYWORDS),
|
|
278
|
+
// Guard against a positive fraction flooring to 0, which would evict every
|
|
279
|
+
// record immediately and silently disable usage tracking.
|
|
280
|
+
historyLimit: Number.isFinite(limit) && limit > 0 ? Math.max(1, Math.floor(limit)) : 300,
|
|
281
|
+
},
|
|
282
|
+
warnings,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Best-effort logger; never throws, whatever the host provides. */
|
|
287
|
+
function makeLogger(ctx) {
|
|
288
|
+
let logger;
|
|
289
|
+
try {
|
|
290
|
+
logger = typeof ctx?.logger === 'function' ? ctx.logger('model-manager') : undefined;
|
|
291
|
+
} catch {
|
|
292
|
+
logger = undefined;
|
|
293
|
+
}
|
|
294
|
+
return (level, message) => {
|
|
295
|
+
const text = `[model-manager] ${message}`;
|
|
296
|
+
try {
|
|
297
|
+
if (logger && typeof logger[level] === 'function') {
|
|
298
|
+
logger[level](text);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
} catch {
|
|
302
|
+
/* fall through to console */
|
|
303
|
+
}
|
|
304
|
+
try {
|
|
305
|
+
if (level === 'error') console.error(text);
|
|
306
|
+
else if (level === 'warn') console.warn(text);
|
|
307
|
+
else console.log(text);
|
|
308
|
+
} catch {
|
|
309
|
+
/* nothing else we can do */
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Run a probe against the live context, returning undefined instead of throwing. */
|
|
315
|
+
function probe(fn) {
|
|
316
|
+
try {
|
|
317
|
+
return fn();
|
|
318
|
+
} catch {
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Whether plan mode is currently in force for an agent. Never throws. */
|
|
324
|
+
function planActive(ctx, agent) {
|
|
325
|
+
const live = probe(() => {
|
|
326
|
+
const controller = ctx.get('planMode');
|
|
327
|
+
if (controller === undefined || typeof controller.get !== 'function') return undefined;
|
|
328
|
+
const state = controller.get(agent);
|
|
329
|
+
return state === undefined ? undefined : Boolean(state.pending ?? state.active);
|
|
330
|
+
});
|
|
331
|
+
if (live !== undefined) return live;
|
|
332
|
+
const projected = probe(() => {
|
|
333
|
+
const projections = ctx.get('sessionProjections');
|
|
334
|
+
if (projections === undefined || typeof projections.stateOf !== 'function') return undefined;
|
|
335
|
+
const state = projections.stateOf(agent.session, 'plan');
|
|
336
|
+
return state === undefined ? undefined : Boolean(state.active);
|
|
337
|
+
});
|
|
338
|
+
return projected === undefined ? false : projected;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Find the delegating parent of a child session. */
|
|
342
|
+
function findParent(ctx, childId) {
|
|
343
|
+
return probe(() => {
|
|
344
|
+
const agents = ctx.get('agents');
|
|
345
|
+
if (agents === undefined || typeof agents.list !== 'function') return undefined;
|
|
346
|
+
if (typeof agents.isOwnedBy !== 'function') return undefined;
|
|
347
|
+
return agents.list().find((candidate) => {
|
|
348
|
+
if (candidate.id === childId) return false;
|
|
349
|
+
try {
|
|
350
|
+
return agents.isOwnedBy(childId, candidate) === true;
|
|
351
|
+
} catch {
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* The route a delegating parent actually passes to a child.
|
|
360
|
+
*
|
|
361
|
+
* Mirrors DSH's own `parentAgentOptionsForDelegation`: after request-time
|
|
362
|
+
* selection the parent's **latest request header** owns provider and model, and
|
|
363
|
+
* creation options are only the pre-first-request fallback. Comparing against
|
|
364
|
+
* `parent.options` instead would misread a manager-rewritten parent as an
|
|
365
|
+
* explicit child choice and silently disable routing.
|
|
366
|
+
*/
|
|
367
|
+
function effectiveRouteOf(agent) {
|
|
368
|
+
const fromHeader = probe(() => {
|
|
369
|
+
const config = agent.session?.requestHeader?.()?.config;
|
|
370
|
+
if (config === undefined) return undefined;
|
|
371
|
+
return config.provider !== undefined && config.model !== undefined
|
|
372
|
+
? { provider: config.provider, model: config.model }
|
|
373
|
+
: undefined;
|
|
374
|
+
});
|
|
375
|
+
if (fromHeader !== undefined) return fromHeader;
|
|
376
|
+
return probe(() => {
|
|
377
|
+
const options = agent.options;
|
|
378
|
+
if (options === undefined) return undefined;
|
|
379
|
+
return options.provider !== undefined && options.model !== undefined
|
|
380
|
+
? { provider: options.provider, model: options.model }
|
|
381
|
+
: undefined;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Read the routes the delegation tool will accept.
|
|
387
|
+
*
|
|
388
|
+
* Returns `{ unavailable: true }` when the composition has no such service, or
|
|
389
|
+
* `{ error }` when the settings owner refuses to report — importantly, its
|
|
390
|
+
* `current()` *throws* when model selection is enabled with an empty allow-list,
|
|
391
|
+
* which is a configuration problem and must not be reported as a missing service.
|
|
392
|
+
*/
|
|
393
|
+
function readAllowList(ctx) {
|
|
394
|
+
const selection = probe(() => ctx.get('subagentModelSelection'));
|
|
395
|
+
if (selection === undefined || typeof selection.current !== 'function') return { unavailable: true };
|
|
396
|
+
let current;
|
|
397
|
+
try {
|
|
398
|
+
current = selection.current();
|
|
399
|
+
} catch (error) {
|
|
400
|
+
return { error: String(error?.message ?? error) };
|
|
401
|
+
}
|
|
402
|
+
if (current === null || typeof current !== 'object') return { unavailable: true };
|
|
403
|
+
const routes = Array.isArray(current.allowedModels) ? current.allowedModels : [];
|
|
404
|
+
return {
|
|
405
|
+
enabled: current.enabled === true,
|
|
406
|
+
allowed: routes
|
|
407
|
+
.filter((route) => route && typeof route.provider === 'string' && typeof route.model === 'string')
|
|
408
|
+
.map((route) => ({ provider: route.provider, model: route.model })),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const routeKey = (route) => `${route.provider}\u0000${route.model}`;
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Apply a role route to a resolved call config.
|
|
416
|
+
*
|
|
417
|
+
* Switching route drops an inherited adapter-owned reasoning effort, because the
|
|
418
|
+
* destination model may not accept the previous one and `prepareCall` rejects
|
|
419
|
+
* unsupported explicit efforts rather than clamping. An effort named by the role
|
|
420
|
+
* is applied instead.
|
|
421
|
+
*/
|
|
422
|
+
function applyRoute(resolved, route) {
|
|
423
|
+
const sameRoute = resolved.provider === route.provider && resolved.model === route.model;
|
|
424
|
+
const effort = route.reasoningEffort;
|
|
425
|
+
if (sameRoute && effort === undefined) return resolved;
|
|
426
|
+
const { reasoningEffort: inherited, ...rest } = resolved;
|
|
427
|
+
void inherited;
|
|
428
|
+
return {
|
|
429
|
+
...(sameRoute ? resolved : rest),
|
|
430
|
+
provider: route.provider,
|
|
431
|
+
model: route.model,
|
|
432
|
+
...(effort === undefined ? {} : { reasoningEffort: effort }),
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const shortId = (id) => String(id ?? '').slice(0, 10).padEnd(10);
|
|
437
|
+
|
|
438
|
+
const quoteLabel = (label) => {
|
|
439
|
+
if (typeof label !== 'string' || label.trim() === '') return '(unlabelled)';
|
|
440
|
+
const text = label.trim().replace(/\s+/g, ' ').replace(/"/g, "'");
|
|
441
|
+
return text.length > 42 ? `"${text.slice(0, 41)}…"` : `"${text}"`;
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Build a keyword matcher.
|
|
446
|
+
*
|
|
447
|
+
* Anchored with a **leading** word boundary only: that stops `spec` matching
|
|
448
|
+
* `inspect`, while still letting `screenshot` match `screenshots`.
|
|
449
|
+
*/
|
|
450
|
+
function keywordMatcher(keywords) {
|
|
451
|
+
const patterns = [];
|
|
452
|
+
for (const keyword of keywords) {
|
|
453
|
+
const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
454
|
+
const pattern = new RegExp(`\\b${escaped}`, 'i');
|
|
455
|
+
patterns.push(pattern);
|
|
456
|
+
}
|
|
457
|
+
return (text) => patterns.some((pattern) => pattern.test(text));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ---------------------------------------------------------------------------
|
|
461
|
+
// Engine
|
|
462
|
+
// ---------------------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
465
|
+
/**
|
|
466
|
+
* Live config. Reassigned when the harness commits a volatile-only Settings
|
|
467
|
+
* edit: the loader applies those in place and returns *before* re-running
|
|
468
|
+
* `apply`, so without this re-read the Settings page would save successfully
|
|
469
|
+
* while routing kept its boot-time values until the next restart.
|
|
470
|
+
*/
|
|
471
|
+
let config = initialConfig;
|
|
472
|
+
/** child session id -> catalog facts */
|
|
473
|
+
const catalog = new Map();
|
|
474
|
+
/** session id -> last observed route decision (insertion-ordered, LRU-refreshed) */
|
|
475
|
+
const usage = new Map();
|
|
476
|
+
/**
|
|
477
|
+
* session id -> route key this manager itself applied.
|
|
478
|
+
*
|
|
479
|
+
* Deliberately separate from `usage`, which is LRU-capped by `historyLimit`.
|
|
480
|
+
* If ownership lived only there, lowering the limit would evict a record and
|
|
481
|
+
* the manager would afterwards misreport its own route as an explicit caller
|
|
482
|
+
* choice and stop managing that child permanently.
|
|
483
|
+
*/
|
|
484
|
+
const managerApplied = new Map();
|
|
485
|
+
const roundRobin = new Map();
|
|
486
|
+
/** child session id -> in-flight single-child lookup, to coalesce bursts */
|
|
487
|
+
const childLookups = new Map();
|
|
488
|
+
/**
|
|
489
|
+
* session id -> how far down its role's ordered model list a failure has
|
|
490
|
+
* pushed it.
|
|
491
|
+
*
|
|
492
|
+
* Only `agent/request-error` advances this, so a request can never
|
|
493
|
+
* double-advance. The list order IS the failover order: index 0 is tried
|
|
494
|
+
* first, and each genuine provider failure moves one step down.
|
|
495
|
+
*/
|
|
496
|
+
const failover = new Map();
|
|
497
|
+
/** session id -> `{ key: '<turn>:<step>', switches }`, the per-step budget. */
|
|
498
|
+
const stepSwitches = new Map();
|
|
499
|
+
|
|
500
|
+
const roleOf = (key) => config.roles[key];
|
|
501
|
+
|
|
502
|
+
let visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
503
|
+
let planningMatch = keywordMatcher(config.strategy.planningKeywords);
|
|
504
|
+
|
|
505
|
+
/** The model list a role actually resolves to, including the vision fallback. */
|
|
506
|
+
function effectiveModels(key) {
|
|
507
|
+
const role = roleOf(key);
|
|
508
|
+
if (role && role.models.length > 0) return role.models;
|
|
509
|
+
if (key === 'vision') return roleOf('execution')?.models ?? [];
|
|
510
|
+
return [];
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Choose a route for a role without committing a round-robin advance.
|
|
515
|
+
*
|
|
516
|
+
* The counter is committed only when the route is actually applied, so an
|
|
517
|
+
* advisory pass or a respected explicit choice does not consume a turn of the
|
|
518
|
+
* rotation.
|
|
519
|
+
*
|
|
520
|
+
* `sessionId` selects the failover position for `pick: 'first'`, where the
|
|
521
|
+
* ordered list is a failover chain rather than a rotation.
|
|
522
|
+
*/
|
|
523
|
+
function routeCandidate(key, sessionId) {
|
|
524
|
+
const models = effectiveModels(key);
|
|
525
|
+
if (models.length === 0) return undefined;
|
|
526
|
+
if (models.length === 1) return { route: models[0], commit() {} };
|
|
527
|
+
const owner = roleOf(key)?.models.length > 0 ? key : 'execution';
|
|
528
|
+
if (roleOf(owner)?.pick === 'round-robin') {
|
|
529
|
+
const index = roundRobin.get(owner) ?? 0;
|
|
530
|
+
return {
|
|
531
|
+
route: models[index],
|
|
532
|
+
commit() {
|
|
533
|
+
roundRobin.set(owner, (index + 1) % models.length);
|
|
534
|
+
},
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
const at = Math.min(failover.get(sessionId) ?? 0, models.length - 1);
|
|
538
|
+
return { route: models[at], commit() {} };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Which role owns a delegated child, from its delegation label. */
|
|
542
|
+
function classifySubagent(label) {
|
|
543
|
+
const text = String(label ?? '');
|
|
544
|
+
if (text === '') return 'execution';
|
|
545
|
+
if (visionMatch(text)) return 'vision';
|
|
546
|
+
if (planningMatch(text)) return 'planning';
|
|
547
|
+
return 'execution';
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function remember(sessionId, entry) {
|
|
551
|
+
const previous = usage.get(sessionId);
|
|
552
|
+
// Re-insert so the map stays in least-recently-used order for eviction.
|
|
553
|
+
if (previous !== undefined) usage.delete(sessionId);
|
|
554
|
+
usage.set(sessionId, {
|
|
555
|
+
...(previous ?? {}),
|
|
556
|
+
...entry,
|
|
557
|
+
requests: (previous?.requests ?? 0) + 1,
|
|
558
|
+
at: Date.now(),
|
|
559
|
+
});
|
|
560
|
+
while (usage.size > config.strategy.historyLimit) {
|
|
561
|
+
const oldest = usage.keys().next().value;
|
|
562
|
+
if (oldest === undefined) break;
|
|
563
|
+
usage.delete(oldest);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Cache one parent's direct children. */
|
|
568
|
+
async function cacheChildrenOf(parentId) {
|
|
569
|
+
const subagents = probe(() => ctx.get('subagents'));
|
|
570
|
+
if (!subagents || typeof subagents.listChildren !== 'function') return false;
|
|
571
|
+
let children;
|
|
572
|
+
try {
|
|
573
|
+
children = await subagents.listChildren(parentId);
|
|
574
|
+
} catch {
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
if (!Array.isArray(children)) return false;
|
|
578
|
+
for (const child of children) {
|
|
579
|
+
if (!child || child.id === undefined) continue;
|
|
580
|
+
catalog.set(child.id, {
|
|
581
|
+
label: typeof child.label === 'string' ? child.label : undefined,
|
|
582
|
+
parentId,
|
|
583
|
+
mode: child.mode,
|
|
584
|
+
createdAt: child.createdAt,
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
return true;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Refresh the child catalog for every live agent (used by reporting). */
|
|
591
|
+
async function refreshCatalog() {
|
|
592
|
+
const agents = probe(() => ctx.get('agents'));
|
|
593
|
+
if (!agents || typeof agents.list !== 'function') return false;
|
|
594
|
+
let found = false;
|
|
595
|
+
for (const agent of agents.list()) {
|
|
596
|
+
if (await cacheChildrenOf(agent.id)) found = true;
|
|
597
|
+
}
|
|
598
|
+
return found;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Resolve one child's catalog facts on demand.
|
|
603
|
+
*
|
|
604
|
+
* Deliberately not latched behind a one-shot "catalog loaded" flag: a child
|
|
605
|
+
* created after the first lookup must still be resolvable on its first
|
|
606
|
+
* request, otherwise the very delegations the manager exists to route would
|
|
607
|
+
* fall through to the default role.
|
|
608
|
+
*/
|
|
609
|
+
function lookupChild(childId) {
|
|
610
|
+
const known = catalog.get(childId);
|
|
611
|
+
if (known !== undefined) return Promise.resolve(known);
|
|
612
|
+
const inFlight = childLookups.get(childId);
|
|
613
|
+
if (inFlight !== undefined) return inFlight;
|
|
614
|
+
const pending = (async () => {
|
|
615
|
+
const parent = findParent(ctx, childId);
|
|
616
|
+
if (parent !== undefined) await cacheChildrenOf(parent.id);
|
|
617
|
+
// Fall back to a full sweep when lineage could not be resolved.
|
|
618
|
+
if (!catalog.has(childId)) await refreshCatalog();
|
|
619
|
+
return catalog.get(childId);
|
|
620
|
+
})().catch(() => undefined).finally(() => {
|
|
621
|
+
childLookups.delete(childId);
|
|
622
|
+
});
|
|
623
|
+
childLookups.set(childId, pending);
|
|
624
|
+
return pending;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
async function factsFor(childId) {
|
|
628
|
+
return catalog.get(childId) ?? (await lookupChild(childId));
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// -- request routing ------------------------------------------------------
|
|
632
|
+
|
|
633
|
+
async function onAgentRequest(payload, next) {
|
|
634
|
+
const resolved = await next();
|
|
635
|
+
try {
|
|
636
|
+
const agent = payload?.agent;
|
|
637
|
+
if (agent === undefined) return resolved;
|
|
638
|
+
const isSubagent = probe(() => agent.session?.header?.origin === 'subagent') === true;
|
|
639
|
+
|
|
640
|
+
let role;
|
|
641
|
+
let label;
|
|
642
|
+
if (isSubagent) {
|
|
643
|
+
const facts = await factsFor(agent.id);
|
|
644
|
+
label = facts?.label;
|
|
645
|
+
role = classifySubagent(label);
|
|
646
|
+
} else {
|
|
647
|
+
role = planActive(ctx, agent) ? 'planning' : 'main';
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Master switch off: observe and record, but never rewrite a route. The
|
|
651
|
+
// record is what makes `model_manager report` useful even with routing
|
|
652
|
+
// disabled — "which model did this subagent use" is a question the user
|
|
653
|
+
// still wants answered.
|
|
654
|
+
if (!config.enabled) {
|
|
655
|
+
remember(agent.id, {
|
|
656
|
+
role,
|
|
657
|
+
label,
|
|
658
|
+
isSubagent,
|
|
659
|
+
provider: resolved.provider,
|
|
660
|
+
model: resolved.model,
|
|
661
|
+
reasoningEffort: resolved.reasoningEffort,
|
|
662
|
+
reason: 'manager disabled (observed only)',
|
|
663
|
+
applied: false,
|
|
664
|
+
parentId: catalog.get(agent.id)?.parentId,
|
|
665
|
+
});
|
|
666
|
+
return resolved;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// Record the attempt group, so the failover budget is per (turn, step).
|
|
670
|
+
// `agent/request` re-fires for every attempt of the same step, so this
|
|
671
|
+
// resets only when the step actually changes.
|
|
672
|
+
const stepKey = `${payload?.turn}:${payload?.step}`;
|
|
673
|
+
const tracked = stepSwitches.get(agent.id);
|
|
674
|
+
if (tracked === undefined || tracked.key !== stepKey) {
|
|
675
|
+
stepSwitches.set(agent.id, { key: stepKey, switches: 0 });
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const candidate = routeCandidate(role, agent.id);
|
|
679
|
+
if (candidate === undefined) {
|
|
680
|
+
remember(agent.id, {
|
|
681
|
+
role,
|
|
682
|
+
provider: resolved.provider,
|
|
683
|
+
model: resolved.model,
|
|
684
|
+
reason: 'passthrough (role unconfigured)',
|
|
685
|
+
applied: false,
|
|
686
|
+
isSubagent,
|
|
687
|
+
label,
|
|
688
|
+
});
|
|
689
|
+
return resolved;
|
|
690
|
+
}
|
|
691
|
+
const route = candidate.route;
|
|
692
|
+
|
|
693
|
+
const mode = config.strategy.mode;
|
|
694
|
+
let reason = 'applied';
|
|
695
|
+
let didApply = false;
|
|
696
|
+
let output;
|
|
697
|
+
|
|
698
|
+
if (mode === 'advisory') {
|
|
699
|
+
reason = 'advisory (not applied)';
|
|
700
|
+
output = resolved;
|
|
701
|
+
} else {
|
|
702
|
+
let inherited = true;
|
|
703
|
+
if (mode === 'hybrid' && !isSubagent && selectionWasExplicit(agent)) {
|
|
704
|
+
// `main` replaces a route the user never chose; it does not overrule
|
|
705
|
+
// one they did choose. The proof is a durable log event, so a real
|
|
706
|
+
// composer pick survives restart, resume and fork, while a session
|
|
707
|
+
// still riding the deployment default is rewritten as before.
|
|
708
|
+
// `managed` is the mode for "the manager owns every route", including a
|
|
709
|
+
// session the user already picked, and is left untouched here.
|
|
710
|
+
inherited = false;
|
|
711
|
+
reason = 'explicit session selection (respected)';
|
|
712
|
+
} else if (mode === 'hybrid' && isSubagent) {
|
|
713
|
+
// Respect an explicit delegation choice. A child counts as inheriting
|
|
714
|
+
// when its resolved route is either the delegating parent's *effective*
|
|
715
|
+
// route (mirroring DSH's own parentAgentOptionsForDelegation) or the
|
|
716
|
+
// route this manager itself assigned earlier — the latter keeps a
|
|
717
|
+
// long-running child manager-owned instead of letting the first route
|
|
718
|
+
// it applied masquerade as a choice the caller made.
|
|
719
|
+
const previous = usage.get(agent.id);
|
|
720
|
+
const managerOwned = managerApplied.get(agent.id) === routeKey({ provider: resolved.provider, model: resolved.model })
|
|
721
|
+
|| (previous?.applied === true
|
|
722
|
+
&& previous.provider === resolved.provider
|
|
723
|
+
&& previous.model === resolved.model);
|
|
724
|
+
if (managerOwned) {
|
|
725
|
+
reason = 'applied (manager-owned)';
|
|
726
|
+
} else {
|
|
727
|
+
const parent = findParent(ctx, agent.id);
|
|
728
|
+
const parentRoute = parent === undefined ? undefined : effectiveRouteOf(parent);
|
|
729
|
+
if (parentRoute === undefined) {
|
|
730
|
+
// Lineage unresolvable (parent disposed, resumed descendant). Do
|
|
731
|
+
// not overwrite a route the manager cannot prove it inherited.
|
|
732
|
+
inherited = false;
|
|
733
|
+
reason = 'lineage unresolved (child route respected)';
|
|
734
|
+
} else if (parentRoute.provider !== resolved.provider || parentRoute.model !== resolved.model) {
|
|
735
|
+
inherited = false;
|
|
736
|
+
reason = 'explicit child route (respected)';
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
output = inherited ? applyRoute(resolved, route) : resolved;
|
|
741
|
+
didApply = inherited;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// Commit the rotation only when a route was actually applied, and record
|
|
745
|
+
// ownership in a map the usage LRU cap cannot evict.
|
|
746
|
+
if (didApply) {
|
|
747
|
+
candidate.commit();
|
|
748
|
+
managerApplied.delete(agent.id);
|
|
749
|
+
managerApplied.set(agent.id, routeKey({ provider: output.provider, model: output.model }));
|
|
750
|
+
while (managerApplied.size > MANAGER_APPLIED_LIMIT) {
|
|
751
|
+
const oldest = managerApplied.keys().next().value;
|
|
752
|
+
if (oldest === undefined) break;
|
|
753
|
+
managerApplied.delete(oldest);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
remember(agent.id, {
|
|
758
|
+
role,
|
|
759
|
+
label,
|
|
760
|
+
isSubagent,
|
|
761
|
+
provider: output.provider,
|
|
762
|
+
model: output.model,
|
|
763
|
+
reasoningEffort: output.reasoningEffort,
|
|
764
|
+
reason,
|
|
765
|
+
applied: didApply,
|
|
766
|
+
parentId: catalog.get(agent.id)?.parentId,
|
|
767
|
+
});
|
|
768
|
+
return output;
|
|
769
|
+
} catch (error) {
|
|
770
|
+
log('warn', `routing skipped for one request: ${error?.message ?? error}`);
|
|
771
|
+
return resolved;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* In-step model failover.
|
|
777
|
+
*
|
|
778
|
+
* `agent/request-error` is the harness's recovery seam: it fires once per
|
|
779
|
+
* genuinely failed model-request attempt. Downstream is asked first, so
|
|
780
|
+
* `dsh-llm-retry` (same-model backoff), `dsh-compaction-basic` (context
|
|
781
|
+
* overflow) and `dsh-compaction-image-offload` (image offload) stay
|
|
782
|
+
* authoritative. Only when they all decline does this advance the role's
|
|
783
|
+
* failover pointer and ask the loop to re-run the SAME step; re-running
|
|
784
|
+
* re-enters `agent/request`, which then picks the next model. The failed
|
|
785
|
+
* attempt was already settled as a non-surface `assistant/attempt` event, so
|
|
786
|
+
* nothing enters model-visible history and the step's user messages are not
|
|
787
|
+
* re-appended.
|
|
788
|
+
*/
|
|
789
|
+
async function onRequestError(payload, next) {
|
|
790
|
+
const decision = await next();
|
|
791
|
+
if (decision !== undefined && decision !== null) return decision;
|
|
792
|
+
try {
|
|
793
|
+
if (!config.enabled) return undefined;
|
|
794
|
+
const agent = payload?.agent;
|
|
795
|
+
const failure = payload?.failure;
|
|
796
|
+
if (agent === undefined || failure === null || typeof failure !== 'object') return undefined;
|
|
797
|
+
|
|
798
|
+
// A user or parent cancellation is not a model problem, and advancing the
|
|
799
|
+
// pointer here would silently change the route the next request uses.
|
|
800
|
+
if (payload.signal?.aborted === true || failure.code === 'ABORTED') return undefined;
|
|
801
|
+
if (!isFailoverCode(failure.code)) return undefined;
|
|
802
|
+
|
|
803
|
+
// The role is the one this manager routed the failed request as; with no
|
|
804
|
+
// such record there is no chain to fail over within.
|
|
805
|
+
const role = usage.get(agent.id)?.role;
|
|
806
|
+
if (role === undefined) return undefined;
|
|
807
|
+
const models = effectiveModels(role);
|
|
808
|
+
if (models.length < 2) return undefined;
|
|
809
|
+
|
|
810
|
+
const stepKey = `${payload?.turn}:${payload?.step}`;
|
|
811
|
+
let budget = stepSwitches.get(agent.id);
|
|
812
|
+
if (budget === undefined || budget.key !== stepKey) {
|
|
813
|
+
budget = { key: stepKey, switches: 0 };
|
|
814
|
+
stepSwitches.set(agent.id, budget);
|
|
815
|
+
}
|
|
816
|
+
if (budget.switches >= MAX_SWITCHES_PER_STEP) return undefined;
|
|
817
|
+
|
|
818
|
+
// Anchor on the failed attempt's own logged header rather than on a guess,
|
|
819
|
+
// so the pointer moves from where the failure actually was. A header
|
|
820
|
+
// naming a route outside this role's list means the failure was not ours
|
|
821
|
+
// to recover.
|
|
822
|
+
const header = probe(() => agent.session?.requestHeader?.()?.config);
|
|
823
|
+
const failedAt = header === undefined
|
|
824
|
+
? Math.min(failover.get(agent.id) ?? 0, models.length - 1)
|
|
825
|
+
: models.findIndex((route) => route.provider === header.provider && route.model === header.model);
|
|
826
|
+
if (failedAt < 0) return undefined;
|
|
827
|
+
|
|
828
|
+
const owner = roleOf(role)?.models.length > 0 ? role : 'execution';
|
|
829
|
+
const rotating = roleOf(owner)?.pick === 'round-robin';
|
|
830
|
+
const nextIndex = rotating
|
|
831
|
+
? (failedAt + 1) % models.length
|
|
832
|
+
: Math.min(failedAt + 1, models.length - 1);
|
|
833
|
+
// `first` mode: the end of the chain is a terminal failure, not a wrap.
|
|
834
|
+
if (!rotating && nextIndex === failedAt) return undefined;
|
|
835
|
+
|
|
836
|
+
if (rotating) roundRobin.set(owner, nextIndex);
|
|
837
|
+
else failover.set(agent.id, nextIndex);
|
|
838
|
+
budget.switches += 1;
|
|
839
|
+
|
|
840
|
+
const from = models[failedAt];
|
|
841
|
+
const to = models[nextIndex];
|
|
842
|
+
log('warn', `failover: ${role} ${from.provider}/${from.model} failed (${failure.code}); `
|
|
843
|
+
+ `re-running the step on ${to.provider}/${to.model} `
|
|
844
|
+
+ `(${budget.switches}/${MAX_SWITCHES_PER_STEP} switches this step)`);
|
|
845
|
+
return { kind: 'retry' };
|
|
846
|
+
} catch (error) {
|
|
847
|
+
log('warn', `failover skipped: ${error?.message ?? error}`);
|
|
848
|
+
return undefined;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// -- reporting ------------------------------------------------------------
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* Check whether the vision role's models can actually accept images.
|
|
856
|
+
*
|
|
857
|
+
* `inputModalities` is authoritative when present: absent means unknown, an
|
|
858
|
+
* explicit list without `image` is a negative capability. Routing image work
|
|
859
|
+
* to a model that declares no image input fails at request time, so this is
|
|
860
|
+
* worth surfacing before it is discovered mid-task.
|
|
861
|
+
*/
|
|
862
|
+
async function visionReport() {
|
|
863
|
+
const models = effectiveModels('vision');
|
|
864
|
+
if (models.length === 0) return { reason: 'no-routes', rows: [] };
|
|
865
|
+
const llm = probe(() => ctx.get('llm'));
|
|
866
|
+
if (llm === undefined || typeof llm.resolveModelInfo !== 'function') return { reason: 'no-service', rows: [] };
|
|
867
|
+
const rows = [];
|
|
868
|
+
for (const route of models) {
|
|
869
|
+
const label = `${route.provider}/${route.model}`;
|
|
870
|
+
let info;
|
|
871
|
+
try {
|
|
872
|
+
info = await llm.resolveModelInfo(route.provider, route.model);
|
|
873
|
+
} catch (error) {
|
|
874
|
+
rows.push({ label, verdict: 'unresolved', detail: `could not resolve (${error?.message ?? error})` });
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
const modalities = info?.inputModalities;
|
|
878
|
+
if (!Array.isArray(modalities)) rows.push({ label, verdict: 'unknown', detail: 'image support not declared' });
|
|
879
|
+
else if (modalities.includes('image')) rows.push({ label, verdict: 'ok', detail: 'accepts images' });
|
|
880
|
+
else rows.push({
|
|
881
|
+
label,
|
|
882
|
+
verdict: 'no-images',
|
|
883
|
+
detail: `declares ${modalities.join(', ') || 'nothing'} — image work routed here will fail`,
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
return { reason: 'checked', rows };
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Whether the Host composed this plugin's Web client half into the browser
|
|
891
|
+
* boot graph.
|
|
892
|
+
*
|
|
893
|
+
* The configuration card is contributed at runtime by the client half, so a
|
|
894
|
+
* missing card is either a composition problem — which this reports exactly —
|
|
895
|
+
* or a browser page that predates the current composition, which this cannot
|
|
896
|
+
* see and which a reload fixes.
|
|
897
|
+
*/
|
|
898
|
+
async function clientStatus() {
|
|
899
|
+
const modules = probe(() => ctx.get('clientModules'));
|
|
900
|
+
if (modules === undefined) {
|
|
901
|
+
return 'Web client half\n\n unavailable — this composition has no clientModules service, so no\n'
|
|
902
|
+
+ ' Web client half can be mounted at all.';
|
|
903
|
+
}
|
|
904
|
+
const graph = probe(() => (typeof modules.graph === 'function' ? modules.graph() : undefined));
|
|
905
|
+
const entries = Array.isArray(graph?.entries) ? graph.entries : [];
|
|
906
|
+
const ids = entries.map((entry) => entry?.id).filter((id) => typeof id === 'string');
|
|
907
|
+
const mine = ids.filter((id) => id === PACKAGE_NAME || id.startsWith(`${PACKAGE_NAME}/`));
|
|
908
|
+
const served = probe(() => (typeof modules.clientPath === 'function' ? modules.clientPath(PACKAGE_NAME) : undefined));
|
|
909
|
+
const lines = [
|
|
910
|
+
'Web client half',
|
|
911
|
+
'',
|
|
912
|
+
` graph revision : ${typeof graph?.rev === 'string' ? graph.rev : '(unknown)'}`,
|
|
913
|
+
` graph rows : ${ids.length}`,
|
|
914
|
+
` this package : ${mine.length > 0 ? `PRESENT (${mine.join(', ')})` : 'ABSENT'}`,
|
|
915
|
+
` bundle route : ${typeof served === 'string' ? served : '(not served)'}`,
|
|
916
|
+
` row id / ns : ${ROW_ID}`,
|
|
917
|
+
// The Host's settings.describe() skips any entry without a Config schema,
|
|
918
|
+
// and a namespace it does not serve can never satisfy whileServed — so an
|
|
919
|
+
// undefined Config would silently remove both the auto form and the
|
|
920
|
+
// Settings card while routing kept working. Report it explicitly.
|
|
921
|
+
` Config schema : ${Config === undefined
|
|
922
|
+
? 'UNDEFINED — no settings namespace is served for this row, so neither the auto-generated form nor the Settings card can appear (schemastery did not resolve)'
|
|
923
|
+
: 'exported'}`,
|
|
924
|
+
` settings svc : ${probe(() => ctx.get('settings')) === undefined ? 'absent' : 'present'}`,
|
|
925
|
+
];
|
|
926
|
+
|
|
927
|
+
// Serve the graph row's own URL through the Host's bundle handler. This is
|
|
928
|
+
// the same fetch the browser makes (minus auth), so it settles whether the
|
|
929
|
+
// bundle is reachable and intact without needing the browser console.
|
|
930
|
+
const row = entries.find((entry) => entry !== null && typeof entry === 'object'
|
|
931
|
+
&& typeof entry.id === 'string'
|
|
932
|
+
&& (entry.id === PACKAGE_NAME || entry.id.startsWith(`${PACKAGE_NAME}/`)));
|
|
933
|
+
const url = typeof row?.url === 'string' ? row.url : undefined;
|
|
934
|
+
lines.push(` graph url : ${url ?? '(none)'}`);
|
|
935
|
+
if (url !== undefined && typeof modules.fetchBundle === 'function') {
|
|
936
|
+
try {
|
|
937
|
+
const absolute = url.startsWith('http') ? url : `http://localhost/${url.replace(/^\/+/, '')}`;
|
|
938
|
+
const response = await modules.fetchBundle(new Request(absolute));
|
|
939
|
+
const body = typeof response.text === 'function' ? await response.text() : '';
|
|
940
|
+
const registers = body.includes(`'${PACKAGE_NAME}'`) || body.includes(`"${PACKAGE_NAME}"`);
|
|
941
|
+
lines.push(` self-fetch : HTTP ${response.status}, ${body.length} bytes`);
|
|
942
|
+
lines.push(` module loader : ${body.includes('__ModuleLoader__') ? 'present' : 'MISSING'}`);
|
|
943
|
+
lines.push(` registers id : ${registers ? 'yes' : 'NO'}`);
|
|
944
|
+
if (response.status !== 200 || !registers) {
|
|
945
|
+
lines.push('', ' The Host did not serve a usable bundle, so the browser cannot load this');
|
|
946
|
+
lines.push(' client half. That is a packaging problem, not a page-cache problem.');
|
|
947
|
+
} else {
|
|
948
|
+
lines.push('', ' The Host serves a usable bundle. If no card appears, the open page');
|
|
949
|
+
lines.push(' predates this composition, or the client half threw while applying —');
|
|
950
|
+
lines.push(' check the browser console for lines starting with "[model-manager]".');
|
|
951
|
+
}
|
|
952
|
+
} catch (error) {
|
|
953
|
+
lines.push(` self-fetch : FAILED (${error?.message ?? error})`);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
// Whether the settings namespace this plugin writes to is actually served,
|
|
958
|
+
// which is the gate the Settings card registers behind.
|
|
959
|
+
const namespaces = probe(() => {
|
|
960
|
+
const settings = ctx.get('settings');
|
|
961
|
+
if (settings === undefined || typeof settings.describe !== 'function') return undefined;
|
|
962
|
+
const described = settings.describe({ redactSecrets: true });
|
|
963
|
+
return Array.isArray(described)
|
|
964
|
+
? described.map((item) => item?.ns).filter((ns) => typeof ns === 'string')
|
|
965
|
+
: undefined;
|
|
966
|
+
});
|
|
967
|
+
if (namespaces === undefined) {
|
|
968
|
+
lines.push('', ' settings namespaces: unavailable (no settings service).');
|
|
969
|
+
} else {
|
|
970
|
+
lines.push('', ` settings namespaces served (${namespaces.length}): ${namespaces.join(', ') || '(none)'}`);
|
|
971
|
+
lines.push(` ours (${ROW_ID}) served: ${namespaces.includes(ROW_ID) ? 'YES' : 'NO — the Settings card cannot register'}`);
|
|
972
|
+
}
|
|
973
|
+
return lines.join('\n');
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
function roleTable() {
|
|
977
|
+
const lines = ['Role pick effective model(s)'];
|
|
978
|
+
lines.push('------------ ------------ ------------------------------------------');
|
|
979
|
+
for (const key of ROLE_NAMES) {
|
|
980
|
+
const role = roleOf(key);
|
|
981
|
+
const models = effectiveModels(key);
|
|
982
|
+
const via = role.models.length === 0 && models.length > 0 ? ' (via execution)' : '';
|
|
983
|
+
const detail = models.length === 0
|
|
984
|
+
? '(unconfigured — passes through)'
|
|
985
|
+
: models.map((route) => `${route.provider}/${route.model}${route.reasoningEffort ? ` (${route.reasoningEffort})` : ''}`).join(', ');
|
|
986
|
+
lines.push(`${key.padEnd(12)} ${role.pick.padEnd(12)} ${detail}${via}`);
|
|
987
|
+
if (role.note !== undefined) lines.push(`${' '.repeat(28)}note: ${role.note}`);
|
|
988
|
+
}
|
|
989
|
+
return lines.join('\n');
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function allowListBlock() {
|
|
993
|
+
const selection = readAllowList(ctx);
|
|
994
|
+
if (selection.error !== undefined) {
|
|
995
|
+
return 'Allow-list: the subagent model-selection settings refused to report its routes:\n'
|
|
996
|
+
+ ` ${selection.error}\n`
|
|
997
|
+
+ 'Fix `subagent-model-selection-settings` in the profile patch (an enabled policy needs a\n'
|
|
998
|
+
+ 'non-empty `allowedModels`), then reload.';
|
|
999
|
+
}
|
|
1000
|
+
if (selection.unavailable === true) {
|
|
1001
|
+
return 'Allow-list: unavailable (no subagent model-selection settings service in this composition).';
|
|
1002
|
+
}
|
|
1003
|
+
if (!selection.enabled) {
|
|
1004
|
+
return 'Allow-list: model selection is DISABLED — subagents cannot select a model at all.\n'
|
|
1005
|
+
+ 'Enable `subagent-model-selection-settings` in the profile patch to use role routing.';
|
|
1006
|
+
}
|
|
1007
|
+
const allowed = new Set(selection.allowed.map(routeKey));
|
|
1008
|
+
const rows = [];
|
|
1009
|
+
const missing = [];
|
|
1010
|
+
const seenMissing = new Set();
|
|
1011
|
+
for (const key of ROLE_NAMES) {
|
|
1012
|
+
// Audit the route the role will actually use, including the vision
|
|
1013
|
+
// fallback onto execution. Per-role rows stay, but the missing-route list
|
|
1014
|
+
// is deduplicated: the fallback would otherwise emit the same route twice,
|
|
1015
|
+
// and a repeated `allowedModels` entry is rejected by the harness.
|
|
1016
|
+
for (const route of effectiveModels(key)) {
|
|
1017
|
+
const ok = allowed.has(routeKey(route));
|
|
1018
|
+
rows.push(` ${ok ? 'allowed ' : 'BLOCKED '} ${key.padEnd(10)} ${route.provider}/${route.model}`);
|
|
1019
|
+
const id = routeKey(route);
|
|
1020
|
+
if (!ok && !seenMissing.has(id)) {
|
|
1021
|
+
seenMissing.add(id);
|
|
1022
|
+
missing.push({ key, route });
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
const head = `Allow-list: enabled, ${selection.allowed.length} route(s) currently dispatchable`;
|
|
1027
|
+
if (rows.length === 0) return `${head}\n (no role routes configured)`;
|
|
1028
|
+
if (missing.length === 0) return `${head}\n${rows.join('\n')}\n All role routes are allow-listed.`;
|
|
1029
|
+
const yaml = missing
|
|
1030
|
+
.map(({ route }) => ` - provider: ${route.provider}\n model: ${route.model}`)
|
|
1031
|
+
.join('\n');
|
|
1032
|
+
return `${head}\n${rows.join('\n')}\n\n`
|
|
1033
|
+
+ `${missing.length} role route(s) are not in the subagent allow-list.\n`
|
|
1034
|
+
+ 'This does NOT block role routing: the harness gates only *explicit* model-facing\n'
|
|
1035
|
+
+ 'choices, and the manager routes pure-inheritance delegations at request time. What\n'
|
|
1036
|
+
+ 'it does affect: an agent that names one of these routes explicitly will be refused,\n'
|
|
1037
|
+
+ 'and the route will not appear in `list_subagent_models`. Add them to\n'
|
|
1038
|
+
+ '`subagent-model-selection-settings` (`.allowedModels`) — in the profile patch, or on\n'
|
|
1039
|
+
+ 'the Subagent settings page — to make them selectable:\n\n'
|
|
1040
|
+
+ `${yaml}`;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
async function report() {
|
|
1044
|
+
await refreshCatalog();
|
|
1045
|
+
const rows = [];
|
|
1046
|
+
for (const [childId, facts] of catalog) {
|
|
1047
|
+
rows.push({ childId, facts, seen: usage.get(childId) });
|
|
1048
|
+
}
|
|
1049
|
+
// Include any routed subagent the catalog did not surface.
|
|
1050
|
+
for (const [sessionId, seen] of usage) {
|
|
1051
|
+
if (!seen?.isSubagent) continue;
|
|
1052
|
+
if (rows.some((row) => row.childId === sessionId)) continue;
|
|
1053
|
+
rows.push({ childId: sessionId, facts: undefined, seen });
|
|
1054
|
+
}
|
|
1055
|
+
// The top-level agents: the only place the manager's decision about the main
|
|
1056
|
+
// role is visible at all. Without it this report answers which model each
|
|
1057
|
+
// child got and never says what served the conversation you are typing in —
|
|
1058
|
+
// exactly the question the explicit-selection rule raises.
|
|
1059
|
+
const topRows = [];
|
|
1060
|
+
for (const [sessionId, seen] of usage) {
|
|
1061
|
+
// A missing `seen` would take the whole report down on the first field
|
|
1062
|
+
// read below, and the subagent loop above already guards for it.
|
|
1063
|
+
if (!seen || seen.isSubagent) continue;
|
|
1064
|
+
topRows.push({ sessionId, seen });
|
|
1065
|
+
}
|
|
1066
|
+
if (rows.length === 0 && topRows.length === 0) {
|
|
1067
|
+
return 'No subagents observed yet in this process.\n\n'
|
|
1068
|
+
+ 'Delegate some work, then run this report again. Model usage is recorded per\n'
|
|
1069
|
+
+ 'delegation at request time, so it works whether routing applied or passed through.\n\n'
|
|
1070
|
+
+ roleTable();
|
|
1071
|
+
}
|
|
1072
|
+
rows.sort((a, b) => String(a.childId).localeCompare(String(b.childId)));
|
|
1073
|
+
const lines = [];
|
|
1074
|
+
if (topRows.length > 0) {
|
|
1075
|
+
topRows.sort((a, b) => String(a.sessionId).localeCompare(String(b.sessionId)));
|
|
1076
|
+
lines.push(`Top-level agents — ${topRows.length}`, '');
|
|
1077
|
+
lines.push('session role model reason status the session model was');
|
|
1078
|
+
lines.push('----------- --------- ------------------------------- ------------------------------------------- -------- --------------------------------');
|
|
1079
|
+
for (const row of topRows) {
|
|
1080
|
+
const live = probe(() => ctx.get('agents')?.get?.(row.sessionId));
|
|
1081
|
+
const status = live === undefined ? 'inactive' : String(live.status ?? 'live');
|
|
1082
|
+
// Read the durable fold rather than this turn's decision, so the answer
|
|
1083
|
+
// does not depend on whether the manager happened to be enabled.
|
|
1084
|
+
const origin = live === undefined
|
|
1085
|
+
? 'unknown, agent no longer live'
|
|
1086
|
+
: selectionWasExplicit(live)
|
|
1087
|
+
? 'picked by hand, so main yields'
|
|
1088
|
+
: 'the deployment default, so main applies';
|
|
1089
|
+
lines.push([
|
|
1090
|
+
shortId(row.sessionId),
|
|
1091
|
+
String(row.seen.role ?? '?').padEnd(9),
|
|
1092
|
+
`${row.seen.provider}/${row.seen.model}`.padEnd(31),
|
|
1093
|
+
String(row.seen.reason ?? '-').padEnd(43),
|
|
1094
|
+
status.padEnd(8),
|
|
1095
|
+
origin,
|
|
1096
|
+
].join(' '));
|
|
1097
|
+
}
|
|
1098
|
+
lines.push('');
|
|
1099
|
+
lines.push('A reason ending in (respected) is the verdict itself: a human choice won and the');
|
|
1100
|
+
lines.push('manager stepped back. Under managed it never does, and a session that never had');
|
|
1101
|
+
lines.push('a manual pick is rewritten by the main role.');
|
|
1102
|
+
lines.push('');
|
|
1103
|
+
}
|
|
1104
|
+
if (rows.length > 0) {
|
|
1105
|
+
lines.push(`Subagent model report — ${rows.length} subagent(s)`, '');
|
|
1106
|
+
lines.push('child role model reason status label');
|
|
1107
|
+
lines.push('---------- --------- ------------------------------- ------------------------------------------- -------- --------------------');
|
|
1108
|
+
}
|
|
1109
|
+
for (const row of rows) {
|
|
1110
|
+
const model = row.seen ? `${row.seen.provider}/${row.seen.model}` : '(not yet routed)';
|
|
1111
|
+
const live = probe(() => ctx.get('agents')?.get?.(row.childId));
|
|
1112
|
+
const status = live === undefined ? 'inactive' : String(live.status ?? 'live');
|
|
1113
|
+
lines.push([
|
|
1114
|
+
shortId(row.childId),
|
|
1115
|
+
String(row.seen?.role ?? '?').padEnd(9),
|
|
1116
|
+
model.padEnd(31),
|
|
1117
|
+
String(row.seen?.reason ?? '-').padEnd(43),
|
|
1118
|
+
status.padEnd(8),
|
|
1119
|
+
quoteLabel(row.facts?.label ?? row.seen?.label),
|
|
1120
|
+
].join(' '));
|
|
1121
|
+
}
|
|
1122
|
+
lines.push('');
|
|
1123
|
+
lines.push(`mode: ${config.strategy.mode}`);
|
|
1124
|
+
lines.push('');
|
|
1125
|
+
lines.push('Subagent requests by role/model:');
|
|
1126
|
+
const totals = new Map();
|
|
1127
|
+
for (const [, seen] of usage) {
|
|
1128
|
+
if (!seen?.isSubagent) continue;
|
|
1129
|
+
const key = `${seen.role ?? '?'} ${seen.provider}/${seen.model}`;
|
|
1130
|
+
const entry = totals.get(key) ?? { requests: 0, children: 0 };
|
|
1131
|
+
entry.requests += seen.requests ?? 1;
|
|
1132
|
+
entry.children += 1;
|
|
1133
|
+
totals.set(key, entry);
|
|
1134
|
+
}
|
|
1135
|
+
if (totals.size === 0) lines.push(' (nothing routed yet)');
|
|
1136
|
+
else {
|
|
1137
|
+
for (const [key, entry] of [...totals].sort()) {
|
|
1138
|
+
lines.push(` ${String(entry.requests).padStart(4)} req / ${String(entry.children).padStart(2)} subagent(s) ${key}`);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
return lines.join('\n');
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
async function routes() {
|
|
1145
|
+
const vision = await visionReport();
|
|
1146
|
+
const visionBlock = vision.reason === 'no-service'
|
|
1147
|
+
? 'Vision role: not checked (no llm service in this composition).'
|
|
1148
|
+
: vision.reason === 'no-routes'
|
|
1149
|
+
? 'Vision role: no route configured, so image-labelled delegations have no dedicated model\n'
|
|
1150
|
+
+ ' and will simply inherit the delegating parent\'s route.'
|
|
1151
|
+
: [
|
|
1152
|
+
'Vision role (image capability):',
|
|
1153
|
+
...vision.rows.map((row) => {
|
|
1154
|
+
const tag = row.verdict === 'ok' ? 'ok '
|
|
1155
|
+
: row.verdict === 'no-images' ? 'NO IMAGES '
|
|
1156
|
+
: row.verdict === 'unknown' ? 'unknown ' : 'unresolved';
|
|
1157
|
+
return ` ${tag} ${row.label} — ${row.detail}`;
|
|
1158
|
+
}),
|
|
1159
|
+
].join('\n');
|
|
1160
|
+
return [
|
|
1161
|
+
'Model manager roles',
|
|
1162
|
+
'',
|
|
1163
|
+
`Enabled: ${config.enabled ? 'yes' : 'NO — observing and reporting only, no route is rewritten'}`,
|
|
1164
|
+
'',
|
|
1165
|
+
roleTable(),
|
|
1166
|
+
'',
|
|
1167
|
+
`Strategy mode: ${config.strategy.mode}`
|
|
1168
|
+
+ (config.strategy.mode === 'hybrid' ? ' (apply when the child inherited the parent route)' : '')
|
|
1169
|
+
+ (config.strategy.mode === 'managed' ? ' (always apply the role route)' : '')
|
|
1170
|
+
+ (config.strategy.mode === 'advisory' ? ' (never rewrite — report only)' : ''),
|
|
1171
|
+
'',
|
|
1172
|
+
allowListBlock(),
|
|
1173
|
+
'',
|
|
1174
|
+
visionBlock,
|
|
1175
|
+
'',
|
|
1176
|
+
'Delegation labels select the tier. The `description` you pass to a delegation',
|
|
1177
|
+
'becomes the child label, which the manager matches against (word-anchored):',
|
|
1178
|
+
` vision : ${config.strategy.visionKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.visionKeywords.length > 8 ? ', …' : ''}`,
|
|
1179
|
+
` planning : ${config.strategy.planningKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.planningKeywords.length > 8 ? ', …' : ''}`,
|
|
1180
|
+
' else : execution',
|
|
1181
|
+
].join('\n');
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
function cheatSheet() {
|
|
1185
|
+
const summary = ROLE_NAMES
|
|
1186
|
+
.map((key) => {
|
|
1187
|
+
const models = effectiveModels(key);
|
|
1188
|
+
if (models.length === 0) return undefined;
|
|
1189
|
+
return ` ${key}: ${models.map((route) => `${route.provider}/${route.model}`).join(', ')}`;
|
|
1190
|
+
})
|
|
1191
|
+
.filter(Boolean);
|
|
1192
|
+
if (summary.length === 0) return '';
|
|
1193
|
+
return [
|
|
1194
|
+
'## Model manager',
|
|
1195
|
+
'Delegated work is routed by the label you give each delegation:',
|
|
1196
|
+
...summary,
|
|
1197
|
+
'Start a delegation `description` with "plan:" for reasoning work, "vision:" for',
|
|
1198
|
+
'image/screenshot work, or leave it plain for execution. Call `model_manager` with',
|
|
1199
|
+
'action "report" to see which model each subagent actually used.',
|
|
1200
|
+
].join('\n');
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// -- wiring ---------------------------------------------------------------
|
|
1204
|
+
|
|
1205
|
+
// ---- session-level usage by model ----------------------------------------
|
|
1206
|
+
//
|
|
1207
|
+
// The harness already attributes every completed Turn to the exact
|
|
1208
|
+
// provider/model that served it and shows that in the Turn's own usage dialog,
|
|
1209
|
+
// but nothing aggregates usage *by model* for a whole session: its
|
|
1210
|
+
// session-level projections accumulate four token buckets with no route split.
|
|
1211
|
+
// This unit fills that gap.
|
|
1212
|
+
//
|
|
1213
|
+
// It folds the DURABLE LOG rather than keeping a live counter, so the numbers
|
|
1214
|
+
// survive a restart and are byte-identical after fork, resume, and replay —
|
|
1215
|
+
// unlike the process-local state `model_manager report` reads.
|
|
1216
|
+
//
|
|
1217
|
+
// Only attempts carrying an exact usage sample are counted, and only those with
|
|
1218
|
+
// a provider/model on the committed message. A failed attempt that reported no
|
|
1219
|
+
// usage contributes nothing, which is the same refusal the per-Turn dialog
|
|
1220
|
+
// makes: never present a total that cannot be proven.
|
|
1221
|
+
const USAGE_PROJECTION_KEY = 'modelManagerUsage';
|
|
1222
|
+
const USAGE_BUCKETS = [
|
|
1223
|
+
'uncachedInputTokens',
|
|
1224
|
+
'outputTokens',
|
|
1225
|
+
'cacheReadTokens',
|
|
1226
|
+
'cacheWriteTokens',
|
|
1227
|
+
'totalTokens',
|
|
1228
|
+
];
|
|
1229
|
+
|
|
1230
|
+
const countField = (value, label) => {
|
|
1231
|
+
if (value === undefined || value === null) return 0;
|
|
1232
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
1233
|
+
throw new Error(`${label}: expected a non-negative safe integer, got ${String(value)}`);
|
|
1234
|
+
}
|
|
1235
|
+
return value;
|
|
1236
|
+
};
|
|
1237
|
+
|
|
1238
|
+
const parseUsageRoute = (value, label) => {
|
|
1239
|
+
if (value === null || typeof value !== 'object') throw new Error(`${label}: expected an object`);
|
|
1240
|
+
const record = value;
|
|
1241
|
+
if (typeof record.provider !== 'string' || typeof record.model !== 'string') {
|
|
1242
|
+
throw new Error(`${label}: provider and model must be strings`);
|
|
1243
|
+
}
|
|
1244
|
+
const route = {
|
|
1245
|
+
provider: record.provider,
|
|
1246
|
+
model: record.model,
|
|
1247
|
+
requests: countField(record.requests, `${label}.requests`),
|
|
1248
|
+
};
|
|
1249
|
+
for (const bucket of USAGE_BUCKETS) route[bucket] = countField(record[bucket], `${label}.${bucket}`);
|
|
1250
|
+
return route;
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* cordis calls only `.parse()` on `stateSchema` and `viewSchema`, so a
|
|
1255
|
+
* hand-written canonicalizer satisfies the contract and this package keeps no
|
|
1256
|
+
* `zod` dependency of its own. Rebuilding each route is the point: nothing
|
|
1257
|
+
* that is not a proven count can reach the wire.
|
|
1258
|
+
*/
|
|
1259
|
+
const usageProjectionSchema = {
|
|
1260
|
+
parse: (value) => {
|
|
1261
|
+
if (value === null || typeof value !== 'object' || !Array.isArray(value.routes)) {
|
|
1262
|
+
throw new Error(`${USAGE_PROJECTION_KEY}: expected { routes: [] }`);
|
|
1263
|
+
}
|
|
1264
|
+
return { routes: value.routes.map((route, index) => parseUsageRoute(route, `routes[${index}]`)) };
|
|
1265
|
+
},
|
|
1266
|
+
};
|
|
1267
|
+
|
|
1268
|
+
const usageSampleOf = (event) => {
|
|
1269
|
+
if (event.type === 'assistant/message' && event.data.usage !== undefined) return event.data.usage;
|
|
1270
|
+
if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return undefined;
|
|
1271
|
+
const stream = event.data.stream;
|
|
1272
|
+
if (!Array.isArray(stream)) return undefined;
|
|
1273
|
+
for (let index = stream.length - 1; index >= 0; index -= 1) {
|
|
1274
|
+
const frame = stream[index];
|
|
1275
|
+
if (frame !== null && typeof frame === 'object' && frame.type === 'usage' && frame.usage !== null && typeof frame.usage === 'object') {
|
|
1276
|
+
return frame.usage;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
return undefined;
|
|
1280
|
+
};
|
|
1281
|
+
|
|
1282
|
+
const routeOfMessage = (message) => {
|
|
1283
|
+
const source = message === null || typeof message !== 'object' ? undefined : message.source;
|
|
1284
|
+
if (source === null || typeof source !== 'object') return undefined;
|
|
1285
|
+
const { provider, model } = source;
|
|
1286
|
+
if (typeof provider !== 'string' || provider.length === 0) return undefined;
|
|
1287
|
+
if (typeof model !== 'string' || model.length === 0) return undefined;
|
|
1288
|
+
return { provider, model };
|
|
1289
|
+
};
|
|
1290
|
+
|
|
1291
|
+
const usageProjectionDefinition = {
|
|
1292
|
+
key: USAGE_PROJECTION_KEY,
|
|
1293
|
+
stateVersion: 1,
|
|
1294
|
+
stateSchema: usageProjectionSchema,
|
|
1295
|
+
init: () => ({ routes: [] }),
|
|
1296
|
+
apply: (state, event) => {
|
|
1297
|
+
if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return state;
|
|
1298
|
+
const sample = usageSampleOf(event);
|
|
1299
|
+
if (sample === undefined) return state;
|
|
1300
|
+
// `assistant/attempt` carries no message, so its route is unknown here;
|
|
1301
|
+
// counting it under a guessed model would corrupt the split.
|
|
1302
|
+
const route = event.type === 'assistant/message' ? routeOfMessage(event.data.message) : undefined;
|
|
1303
|
+
if (route === undefined) return state;
|
|
1304
|
+
const key = `${route.provider}\u0000${route.model}`;
|
|
1305
|
+
const index = state.routes.findIndex((entry) => entry.provider === route.provider && entry.model === route.model);
|
|
1306
|
+
const previous = index < 0
|
|
1307
|
+
? { ...route, requests: 0, uncachedInputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, totalTokens: 0 }
|
|
1308
|
+
: state.routes[index];
|
|
1309
|
+
let next;
|
|
1310
|
+
try {
|
|
1311
|
+
next = parseUsageRoute({
|
|
1312
|
+
...previous,
|
|
1313
|
+
requests: previous.requests + 1,
|
|
1314
|
+
uncachedInputTokens: previous.uncachedInputTokens + countField(sample.inputTokens, 'usage.inputTokens'),
|
|
1315
|
+
outputTokens: previous.outputTokens + countField(sample.outputTokens, 'usage.outputTokens'),
|
|
1316
|
+
cacheReadTokens: previous.cacheReadTokens + countField(sample.cacheReadTokens, 'usage.cacheReadTokens'),
|
|
1317
|
+
cacheWriteTokens: previous.cacheWriteTokens + countField(sample.cacheWriteTokens, 'usage.cacheWriteTokens'),
|
|
1318
|
+
totalTokens: previous.totalTokens + countField(sample.totalTokens, 'usage.totalTokens'),
|
|
1319
|
+
}, `route ${key}`);
|
|
1320
|
+
} catch (error) {
|
|
1321
|
+
// An unusable sample must never abort the fold: the log is authoritative
|
|
1322
|
+
// and every later event still has to be applied.
|
|
1323
|
+
log('warn', `usage sample skipped: ${error?.message ?? error}`);
|
|
1324
|
+
return state;
|
|
1325
|
+
}
|
|
1326
|
+
const routes = index < 0
|
|
1327
|
+
? [...state.routes, next]
|
|
1328
|
+
: state.routes.map((entry, position) => (position === index ? next : entry));
|
|
1329
|
+
return { routes };
|
|
1330
|
+
},
|
|
1331
|
+
// Returning the state itself keeps the view reference stable whenever the
|
|
1332
|
+
// fold produced no change, which is what suppresses a publication.
|
|
1333
|
+
wire: { viewSchema: usageProjectionSchema, view: (state) => state },
|
|
1334
|
+
};
|
|
1335
|
+
|
|
1336
|
+
/**
|
|
1337
|
+
* Whether this Session ever recorded an *explicit* model selection.
|
|
1338
|
+
*
|
|
1339
|
+
* `selectForNextRequest()` (dsh-api-session-controller/lib/index.js:319-322)
|
|
1340
|
+
* appends a durable `model/selection` event, and that is the only append site
|
|
1341
|
+
* in the install, so the event is proof that a person chose this session's
|
|
1342
|
+
* model — through the composer seat or `/model`. A session that never got one
|
|
1343
|
+
* runs on the deployment default, and *that* is the route `main` exists to
|
|
1344
|
+
* replace.
|
|
1345
|
+
*
|
|
1346
|
+
* The host's own `modelSelection` projection cannot answer this question: its
|
|
1347
|
+
* `lastUsed` is filled from `request/header`, so a default-written request
|
|
1348
|
+
* populates it too, and `pending` is cleared the moment a request consumes it.
|
|
1349
|
+
* One is default-polluted, the other transient; only the event's presence is
|
|
1350
|
+
* both durable and unambiguous.
|
|
1351
|
+
*/
|
|
1352
|
+
const SELECTION_PROJECTION_KEY = 'modelManagerSelection';
|
|
1353
|
+
const selectionProjectionSchema = {
|
|
1354
|
+
parse: (value) => {
|
|
1355
|
+
if (value === null || typeof value !== 'object') throw new Error('expected an object');
|
|
1356
|
+
if (typeof value.explicit !== 'boolean') throw new Error('explicit: expected a boolean');
|
|
1357
|
+
return { explicit: value.explicit };
|
|
1358
|
+
},
|
|
1359
|
+
};
|
|
1360
|
+
const selectionProjectionDefinition = {
|
|
1361
|
+
key: SELECTION_PROJECTION_KEY,
|
|
1362
|
+
stateVersion: 1,
|
|
1363
|
+
stateSchema: selectionProjectionSchema,
|
|
1364
|
+
init: () => ({ explicit: false }),
|
|
1365
|
+
apply: (state, event) => {
|
|
1366
|
+
// Monotone: an explicit selection cannot be taken back, and a fold that
|
|
1367
|
+
// changed nothing must return the same reference to suppress publication.
|
|
1368
|
+
if (event.type !== 'model/selection' || state.explicit === true) return state;
|
|
1369
|
+
return { explicit: true };
|
|
1370
|
+
},
|
|
1371
|
+
wire: { viewSchema: selectionProjectionSchema, view: (state) => state },
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
/** The projection registry, captured when this composition provides one. */
|
|
1375
|
+
let projections;
|
|
1376
|
+
|
|
1377
|
+
/**
|
|
1378
|
+
* Whether the user explicitly chose this agent's session model.
|
|
1379
|
+
*
|
|
1380
|
+
* Never throws. Answers `false` when no registry is reachable, which keeps the
|
|
1381
|
+
* previous behaviour — `main` rewrites the route — instead of quietly turning
|
|
1382
|
+
* the manager off; the missing registration is logged at apply time.
|
|
1383
|
+
*/
|
|
1384
|
+
function selectionWasExplicit(agent) {
|
|
1385
|
+
if (projections === undefined || typeof projections.stateOf !== 'function') return false;
|
|
1386
|
+
const state = probe(() => projections.stateOf(agent.session, SELECTION_PROJECTION_KEY));
|
|
1387
|
+
return state?.explicit === true;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
function attach() {
|
|
1391
|
+
ctx.on('agent/request', onAgentRequest);
|
|
1392
|
+
ctx.on('agent/request-error', onRequestError);
|
|
1393
|
+
|
|
1394
|
+
// Drop per-session failover state when its agent goes away, so a long-lived
|
|
1395
|
+
// process does not accumulate entries for sessions that can no longer run.
|
|
1396
|
+
ctx.on('agent/disposed', (payload) => {
|
|
1397
|
+
const id = payload?.agent?.id ?? (typeof payload === 'string' ? payload : payload?.id);
|
|
1398
|
+
if (typeof id !== 'string') return;
|
|
1399
|
+
failover.delete(id);
|
|
1400
|
+
stepSwitches.delete(id);
|
|
1401
|
+
});
|
|
1402
|
+
|
|
1403
|
+
// Resolve a newly published child's label immediately, and targeted rather
|
|
1404
|
+
// than by sweeping every live agent.
|
|
1405
|
+
ctx.on('subagent/start', (info) => {
|
|
1406
|
+
const childId = info?.id;
|
|
1407
|
+
if (childId !== undefined) void lookupChild(childId).catch(() => {});
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
// A volatile-only Settings edit is committed in place: the loader returns
|
|
1411
|
+
// before re-running `apply`, so the config must be re-read here. Without
|
|
1412
|
+
// this the page would save and display the new value while routing kept the
|
|
1413
|
+
// boot-time one until restart. DSH's own volatile plugins do the same.
|
|
1414
|
+
ctx.on('loader/volatile-update', () => {
|
|
1415
|
+
try {
|
|
1416
|
+
const next = readConfig(rawConfig);
|
|
1417
|
+
config = { enabled: next.enabled, roles: next.roles, strategy: next.strategy, warnings: next.warnings };
|
|
1418
|
+
visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
1419
|
+
planningMatch = keywordMatcher(config.strategy.planningKeywords);
|
|
1420
|
+
for (const warning of config.warnings) log('warn', warning);
|
|
1421
|
+
log('info', `settings reloaded — mode ${config.strategy.mode}; `
|
|
1422
|
+
+ ROLE_NAMES
|
|
1423
|
+
.map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
|
|
1424
|
+
.join(' '));
|
|
1425
|
+
} catch (error) {
|
|
1426
|
+
log('warn', `could not reload settings; routing keeps the previous config: ${error?.message ?? error}`);
|
|
1427
|
+
}
|
|
1428
|
+
});
|
|
1429
|
+
|
|
1430
|
+
if (typeof ctx.inject === 'function') {
|
|
1431
|
+
ctx.inject(['tools'], (scoped) => {
|
|
1432
|
+
try {
|
|
1433
|
+
scoped.tools.register({
|
|
1434
|
+
name: 'model_manager',
|
|
1435
|
+
description: 'Inspect and explain the role-based model routing configured for this harness. '
|
|
1436
|
+
+ 'action "report": a Top-level agents section naming which model served each '
|
|
1437
|
+
+ 'conversation and whether the manager yielded to a model a person picked in the '
|
|
1438
|
+
+ 'composer, then one row per subagent with its label, role, reason, live status and '
|
|
1439
|
+
+ 'totals. action "routes": the four role assignments '
|
|
1440
|
+
+ '(including the vision->execution fallback), the active distribution mode, and whether each '
|
|
1441
|
+
+ 'route is dispatchable by the delegation tool, with the YAML to add any that are not. '
|
|
1442
|
+
+ 'action "usage": request and subagent counts by role and model across the whole process. '
|
|
1443
|
+
+ 'action "client": whether the Host composed this plugin\'s Web client half into the browser '
|
|
1444
|
+
+ 'boot graph, the route serving its bundle, and the current graph revision — use it when the '
|
|
1445
|
+
+ 'configuration card does not appear in the Web UI. '
|
|
1446
|
+
+ 'Read-only; it never changes routing.',
|
|
1447
|
+
parameters: {
|
|
1448
|
+
type: 'object',
|
|
1449
|
+
properties: {
|
|
1450
|
+
action: {
|
|
1451
|
+
type: 'string',
|
|
1452
|
+
enum: ['report', 'routes', 'usage', 'client'],
|
|
1453
|
+
description: 'What to return. Defaults to "report".',
|
|
1454
|
+
},
|
|
1455
|
+
},
|
|
1456
|
+
additionalProperties: false,
|
|
1457
|
+
},
|
|
1458
|
+
output: {
|
|
1459
|
+
schema: { type: 'string' },
|
|
1460
|
+
render: (_args, result) => [{ type: 'text', text: String(result) }],
|
|
1461
|
+
},
|
|
1462
|
+
async execute(args) {
|
|
1463
|
+
const action = args?.action ?? 'report';
|
|
1464
|
+
if (action === 'routes') return routes();
|
|
1465
|
+
if (action === 'client') return clientStatus();
|
|
1466
|
+
if (action === 'usage') {
|
|
1467
|
+
await refreshCatalog();
|
|
1468
|
+
const totals = new Map();
|
|
1469
|
+
for (const [, seen] of usage) {
|
|
1470
|
+
const key = `${seen.role ?? '?'} ${seen.provider}/${seen.model}`;
|
|
1471
|
+
const entry = totals.get(key) ?? { requests: 0, subagents: 0 };
|
|
1472
|
+
entry.requests += seen.requests ?? 1;
|
|
1473
|
+
if (seen.isSubagent) entry.subagents += 1;
|
|
1474
|
+
totals.set(key, entry);
|
|
1475
|
+
}
|
|
1476
|
+
if (totals.size === 0) return 'No model usage recorded yet.\n\n' + roleTable();
|
|
1477
|
+
const lines = [
|
|
1478
|
+
'Requests by role/model (whole process, including top-level turns)',
|
|
1479
|
+
'',
|
|
1480
|
+
];
|
|
1481
|
+
for (const [key, entry] of [...totals].sort()) {
|
|
1482
|
+
lines.push(` ${String(entry.requests).padStart(4)} req ${String(entry.subagents).padStart(3)} subagent(s) ${key}`);
|
|
1483
|
+
}
|
|
1484
|
+
return lines.join('\n');
|
|
1485
|
+
}
|
|
1486
|
+
return report();
|
|
1487
|
+
},
|
|
1488
|
+
});
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
log('warn', `model_manager tool not registered: ${error?.message ?? error}`);
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
|
|
1494
|
+
// Optional service: a profile without the projection subsystem simply
|
|
1495
|
+
// gets no per-session model usage surface, instead of a throwing plugin.
|
|
1496
|
+
ctx.inject(['sessionProjections'], (scoped) => {
|
|
1497
|
+
try {
|
|
1498
|
+
const registry = scoped.sessionProjections;
|
|
1499
|
+
if (registry === undefined || typeof registry.register !== 'function') {
|
|
1500
|
+
log('warn', 'sessionProjections is present but exposes no register(); per-session model usage is unavailable');
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
registry.register(usageProjectionDefinition);
|
|
1504
|
+
registry.register(selectionProjectionDefinition);
|
|
1505
|
+
projections = registry;
|
|
1506
|
+
log('info', `registered the ${USAGE_PROJECTION_KEY} and ${SELECTION_PROJECTION_KEY} session projections`);
|
|
1507
|
+
} catch (error) {
|
|
1508
|
+
log('warn', `could not register the usage projection: ${error?.message ?? error}`);
|
|
1509
|
+
}
|
|
1510
|
+
});
|
|
1511
|
+
|
|
1512
|
+
ctx.inject(['systemPrompt'], (scoped) => {
|
|
1513
|
+
try {
|
|
1514
|
+
const register = () => scoped.systemPrompt.section({
|
|
1515
|
+
name: 'model-manager',
|
|
1516
|
+
order: 60,
|
|
1517
|
+
text: () => cheatSheet(),
|
|
1518
|
+
});
|
|
1519
|
+
if (typeof scoped.effect === 'function') scoped.effect(register);
|
|
1520
|
+
else register();
|
|
1521
|
+
} catch (error) {
|
|
1522
|
+
log('warn', `system prompt section not registered: ${error?.message ?? error}`);
|
|
1523
|
+
}
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// Boot diagnostic: tell the operator about role routes the delegation tool
|
|
1528
|
+
// would refuse, before they hit the error mid-task.
|
|
1529
|
+
const selection = readAllowList(ctx);
|
|
1530
|
+
if (selection.error !== undefined) {
|
|
1531
|
+
log('warn', `subagent model-selection settings refused to report its routes: ${selection.error}`);
|
|
1532
|
+
} else if (selection.unavailable !== true && selection.enabled) {
|
|
1533
|
+
const allowed = new Set(selection.allowed.map(routeKey));
|
|
1534
|
+
const missing = [];
|
|
1535
|
+
const seen = new Set();
|
|
1536
|
+
for (const key of ROLE_NAMES) {
|
|
1537
|
+
for (const route of effectiveModels(key)) {
|
|
1538
|
+
const id = routeKey(route);
|
|
1539
|
+
if (allowed.has(id) || seen.has(id)) continue;
|
|
1540
|
+
seen.add(id);
|
|
1541
|
+
missing.push(`${route.provider}/${route.model} (needed by ${key})`);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
if (missing.length > 0) {
|
|
1545
|
+
log('warn', `${missing.length} role route(s) are not in the subagent allow-list: ${missing.join('; ')}. `
|
|
1546
|
+
+ 'Role routing still works for inherited delegations (the harness gates only explicit '
|
|
1547
|
+
+ 'model-facing choices), but an agent naming one of these explicitly will be refused and '
|
|
1548
|
+
+ 'it will not appear in list_subagent_models. Run the model_manager tool with action '
|
|
1549
|
+
+ '"routes" for the exact snippet to add.');
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
// The vision role only helps if its models actually declare image input.
|
|
1554
|
+
void (async () => {
|
|
1555
|
+
const vision = await visionReport();
|
|
1556
|
+
const broken = vision.rows.filter((row) => row.verdict === 'no-images');
|
|
1557
|
+
if (broken.length > 0) {
|
|
1558
|
+
log('warn', `vision role route(s) declare no image input and image work routed to them will fail: `
|
|
1559
|
+
+ `${broken.map((row) => row.label).join(', ')}. Point roles.vision.models at an image-capable model.`);
|
|
1560
|
+
}
|
|
1561
|
+
})().catch(() => {});
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
return { attach, classifySubagent, classifyAndRoute: routeCandidate, roleTable, routes, report };
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
// ---------------------------------------------------------------------------
|
|
1568
|
+
// Entry point
|
|
1569
|
+
// ---------------------------------------------------------------------------
|
|
1570
|
+
|
|
1571
|
+
/**
|
|
1572
|
+
* Activate the model manager.
|
|
1573
|
+
*
|
|
1574
|
+
* A throw here would fail the loader entry and therefore startup, so the whole
|
|
1575
|
+
* body is guarded: any failure disables routing and logs, never propagates.
|
|
1576
|
+
*/
|
|
1577
|
+
export function apply(ctx, rawConfig) {
|
|
1578
|
+
const log = makeLogger(ctx);
|
|
1579
|
+
try {
|
|
1580
|
+
const config = readConfig(rawConfig);
|
|
1581
|
+
for (const warning of config.warnings) log('warn', warning);
|
|
1582
|
+
const engine = createEngine(config, ctx, log, rawConfig);
|
|
1583
|
+
engine.attach();
|
|
1584
|
+
log('info', `active — mode ${config.strategy.mode}; `
|
|
1585
|
+
+ ROLE_NAMES
|
|
1586
|
+
.map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
|
|
1587
|
+
.join(' '));
|
|
1588
|
+
} catch (error) {
|
|
1589
|
+
log('error', `failed to initialise; model routing is disabled: ${error?.stack ?? error}`);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
export { readConfig, applyRoute, effectiveRouteOf, DEFAULT_PLANNING_KEYWORDS, DEFAULT_VISION_KEYWORDS };
|