@darkbear9494/dsh-model-manager 0.1.0 → 0.4.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/README.md +314 -80
- package/client.js +277 -23
- package/cordis.patch.yml +15 -0
- package/lib/index.js +759 -37
- package/package.json +6 -4
package/lib/index.js
CHANGED
|
@@ -25,6 +25,8 @@
|
|
|
25
25
|
* @module @darkbear9494/dsh-model-manager
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
|
+
import { readFileSync } from 'node:fs';
|
|
29
|
+
|
|
28
30
|
/**
|
|
29
31
|
* Optional schema dependency.
|
|
30
32
|
*
|
|
@@ -47,10 +49,51 @@ export const name = 'model-manager';
|
|
|
47
49
|
|
|
48
50
|
const ROLE_NAMES = ['main', 'planning', 'execution', 'vision'];
|
|
49
51
|
|
|
50
|
-
const KNOWN_TOP_KEYS = ['enabled', 'roles', 'strategy'];
|
|
51
|
-
const KNOWN_ROLE_KEYS = ['models', '
|
|
52
|
+
const KNOWN_TOP_KEYS = ['enabled', 'pick', 'roles', 'strategy', 'update'];
|
|
53
|
+
const KNOWN_ROLE_KEYS = ['models', 'note'];
|
|
52
54
|
const KNOWN_ROUTE_KEYS = ['provider', 'model', 'reasoningEffort'];
|
|
53
|
-
const KNOWN_STRATEGY_KEYS = ['mode', 'visionKeywords', 'planningKeywords', 'historyLimit'];
|
|
55
|
+
const KNOWN_STRATEGY_KEYS = ['mode', 'visionKeywords', 'planningKeywords', 'historyLimit', 'autoDelegate'];
|
|
56
|
+
const KNOWN_UPDATE_KEYS = ['enabled', 'registry', 'intervalHours'];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Delegation-policy levels for `strategy.autoDelegate`.
|
|
60
|
+
*
|
|
61
|
+
* off — no policy section is rendered at all.
|
|
62
|
+
* balanced — the default: prefer subagents for multi-step and independent work.
|
|
63
|
+
* eager — the top-level agent is instructed to orchestrate: nearly all
|
|
64
|
+
* substantive work goes to delegations.
|
|
65
|
+
*/
|
|
66
|
+
const DELEGATION_LEVELS = ['off', 'balanced', 'eager'];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Delegation tools the policy may name. The text function checks each against
|
|
70
|
+
* the assembly's scope (`tools.get(name, scope)`, the same probe
|
|
71
|
+
* dsh-tool-subagent itself uses) so the policy never tells an agent to call a
|
|
72
|
+
* tool it does not have.
|
|
73
|
+
*/
|
|
74
|
+
const DELEGATION_TOOL_NAMES = ['subagent', 'subagent_fork'];
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Order of the delegation-policy prompt section. Sits between the harness's
|
|
78
|
+
* PLAN_POLICY (500) and TEAM_POLICY (600) placements, i.e. with the other
|
|
79
|
+
* behavioural policy rows rather than with this plugin's routing cheat sheet.
|
|
80
|
+
*/
|
|
81
|
+
const DELEGATION_SECTION_ORDER = 550;
|
|
82
|
+
|
|
83
|
+
/** Registry path of this package on any npm-compatible registry. */
|
|
84
|
+
const UPDATE_PACKAGE_PATH = '@darkbear9494%2fdsh-model-manager';
|
|
85
|
+
|
|
86
|
+
/** Default registry consulted for the latest published version. */
|
|
87
|
+
const UPDATE_REGISTRY_DEFAULT = 'https://registry.npmjs.org';
|
|
88
|
+
|
|
89
|
+
/** Delay before the first update check, so boot is never blocked by it. */
|
|
90
|
+
const UPDATE_FIRST_CHECK_DELAY_MS = 10_000;
|
|
91
|
+
|
|
92
|
+
/** Per-request timeout for the registry fetch. */
|
|
93
|
+
const UPDATE_FETCH_TIMEOUT_MS = 10_000;
|
|
94
|
+
|
|
95
|
+
/** Floor for the re-check interval, so a mis-typed hour cannot hammer a registry. */
|
|
96
|
+
const UPDATE_MIN_INTERVAL_MS = 60_000;
|
|
54
97
|
|
|
55
98
|
/**
|
|
56
99
|
* Bound on remembered manager-applied routes. Held independently of
|
|
@@ -103,9 +146,13 @@ const PACKAGE_NAME = '@darkbear9494/dsh-model-manager';
|
|
|
103
146
|
*/
|
|
104
147
|
const ROW_ID = 'model-manager';
|
|
105
148
|
|
|
149
|
+
// No 'figure' here on purpose: in coding labels "figure out the bug" is far more
|
|
150
|
+
// common than "read figure 3", and a genuine figure-reading unit can always say
|
|
151
|
+
// so with a leading `vision:` prefix (which outranks every keyword). Anyone who
|
|
152
|
+
// wants it back can re-add it via `strategy.visionKeywords`.
|
|
106
153
|
const DEFAULT_VISION_KEYWORDS = [
|
|
107
154
|
'vision', 'visual', 'image', 'images', 'screenshot', 'screen shot', 'ocr',
|
|
108
|
-
'
|
|
155
|
+
'diagram', 'chart', 'plot', 'photo', 'picture', 'png', 'jpg',
|
|
109
156
|
'jpeg', 'webp', 'gif', 'ui mock', 'render',
|
|
110
157
|
];
|
|
111
158
|
|
|
@@ -135,7 +182,6 @@ function buildConfigSchema(z) {
|
|
|
135
182
|
|
|
136
183
|
const RoleSchema = z.object({
|
|
137
184
|
models: z.array(RouteSchema).default([]),
|
|
138
|
-
pick: z.union([z.const('first'), z.const('round-robin')]).default('first'),
|
|
139
185
|
note: z.string(),
|
|
140
186
|
});
|
|
141
187
|
|
|
@@ -144,6 +190,13 @@ function buildConfigSchema(z) {
|
|
|
144
190
|
visionKeywords: z.array(z.string()).default(DEFAULT_VISION_KEYWORDS),
|
|
145
191
|
planningKeywords: z.array(z.string()).default(DEFAULT_PLANNING_KEYWORDS),
|
|
146
192
|
historyLimit: z.number().default(300),
|
|
193
|
+
autoDelegate: z.union([z.const('off'), z.const('balanced'), z.const('eager')]).default('balanced'),
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
const UpdateSchema = z.object({
|
|
197
|
+
enabled: z.boolean().default(true),
|
|
198
|
+
registry: z.string().default(UPDATE_REGISTRY_DEFAULT),
|
|
199
|
+
intervalHours: z.number().default(24),
|
|
147
200
|
});
|
|
148
201
|
|
|
149
202
|
/**
|
|
@@ -157,6 +210,12 @@ function buildConfigSchema(z) {
|
|
|
157
210
|
return z.object({
|
|
158
211
|
/** Master switch: when false the manager observes and reports but never rewrites a route. */
|
|
159
212
|
enabled: z.boolean().default(true).volatile(),
|
|
213
|
+
/**
|
|
214
|
+
* One selection strategy for every role (0.2.0). `first` treats each role's
|
|
215
|
+
* ordered list as a failover chain: index 0 first, failures move down.
|
|
216
|
+
* `round-robin` rotates across each role's list instead.
|
|
217
|
+
*/
|
|
218
|
+
pick: z.union([z.const('first'), z.const('round-robin')]).default('first').volatile(),
|
|
160
219
|
roles: z.object({
|
|
161
220
|
main: RoleSchema.default({}),
|
|
162
221
|
planning: RoleSchema.default({}),
|
|
@@ -164,6 +223,12 @@ function buildConfigSchema(z) {
|
|
|
164
223
|
vision: RoleSchema.default({}),
|
|
165
224
|
}).default({}).volatile(),
|
|
166
225
|
strategy: StrategySchema.default({}).volatile(),
|
|
226
|
+
/**
|
|
227
|
+
* Automatic update check against the package registry. Checked once shortly
|
|
228
|
+
* after boot, then on the interval; a newer release is logged, surfaced by
|
|
229
|
+
* the `model_manager` tool (action "update") and reported by `routes`.
|
|
230
|
+
*/
|
|
231
|
+
update: UpdateSchema.default({}).volatile(),
|
|
167
232
|
});
|
|
168
233
|
}
|
|
169
234
|
|
|
@@ -232,20 +297,182 @@ function unknownKeys(source, known) {
|
|
|
232
297
|
return Object.keys(value).filter((key) => !known.includes(key));
|
|
233
298
|
}
|
|
234
299
|
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
// Versions
|
|
302
|
+
// ---------------------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
/** A strict semver-shaped version: `v?MAJOR.MINOR.PATCH[-prerelease][+build]`. */
|
|
305
|
+
const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-((?:[0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Parse a semver-shaped version string.
|
|
309
|
+
*
|
|
310
|
+
* Both sides of the update comparison come from `package.json` fields (this
|
|
311
|
+
* package's own and the registry packument's `dist-tags.latest`), so a strict
|
|
312
|
+
* shape check is enough: anything else is reported unparseable rather than
|
|
313
|
+
* guessed at.
|
|
314
|
+
* @returns `{ major, minor, patch, prerelease }` or `undefined`.
|
|
315
|
+
*/
|
|
316
|
+
function parseVersion(input) {
|
|
317
|
+
if (typeof input !== 'string') return undefined;
|
|
318
|
+
const match = VERSION_RE.exec(input.trim());
|
|
319
|
+
if (match === null) return undefined;
|
|
320
|
+
const major = Number(match[1]);
|
|
321
|
+
const minor = Number(match[2]);
|
|
322
|
+
const patch = Number(match[3]);
|
|
323
|
+
if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
const prerelease = match[4] === undefined || match[4] === '' ? [] : match[4].split('.');
|
|
327
|
+
return { major, minor, patch, prerelease };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Compare two prerelease identifier lists per semver: numeric identifiers
|
|
332
|
+
* compare numerically and sort below alphanumeric ones, alphanumeric compare
|
|
333
|
+
* in ASCII order, and a shorter list sorts below a longer one when it is a
|
|
334
|
+
* prefix of it. An empty list (no prerelease) sorts ABOVE any prerelease.
|
|
335
|
+
*/
|
|
336
|
+
function comparePrerelease(a, b) {
|
|
337
|
+
if (a.length === 0 && b.length === 0) return 0;
|
|
338
|
+
if (a.length === 0) return 1;
|
|
339
|
+
if (b.length === 0) return -1;
|
|
340
|
+
for (let index = 0; index < a.length || index < b.length; index += 1) {
|
|
341
|
+
const x = a[index];
|
|
342
|
+
const y = b[index];
|
|
343
|
+
if (x === undefined) return -1;
|
|
344
|
+
if (y === undefined) return 1;
|
|
345
|
+
const xNumeric = /^\d+$/.test(x);
|
|
346
|
+
const yNumeric = /^\d+$/.test(y);
|
|
347
|
+
if (xNumeric && yNumeric) {
|
|
348
|
+
if (Number(x) !== Number(y)) return Number(x) < Number(y) ? -1 : 1;
|
|
349
|
+
} else if (xNumeric) return -1;
|
|
350
|
+
else if (yNumeric) return 1;
|
|
351
|
+
else if (x !== y) return x < y ? -1 : 1;
|
|
352
|
+
}
|
|
353
|
+
return 0;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Compare two version strings, semver-style including prereleases.
|
|
358
|
+
* @returns `-1 | 0 | 1`, or `undefined` when either side does not parse.
|
|
359
|
+
*/
|
|
360
|
+
function compareVersions(a, b) {
|
|
361
|
+
const left = parseVersion(a);
|
|
362
|
+
const right = parseVersion(b);
|
|
363
|
+
if (left === undefined || right === undefined) return undefined;
|
|
364
|
+
if (left.major !== right.major) return left.major < right.major ? -1 : 1;
|
|
365
|
+
if (left.minor !== right.minor) return left.minor < right.minor ? -1 : 1;
|
|
366
|
+
if (left.patch !== right.patch) return left.patch < right.patch ? -1 : 1;
|
|
367
|
+
return comparePrerelease(left.prerelease, right.prerelease);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Cached own version, read from this package's `package.json`. `null` = unreadable. */
|
|
371
|
+
let cachedInstalledVersion;
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* This package's own version, straight from its `package.json`.
|
|
375
|
+
*
|
|
376
|
+
* Read from the manifest next to `lib/index.js` rather than hardcoded, so a
|
|
377
|
+
* git checkout, an npm install and a tarball install all report what actually
|
|
378
|
+
* shipped — the version in `client.js` is a pinned fallback for the browser
|
|
379
|
+
* only, and a packaging test keeps the two equal.
|
|
380
|
+
* @returns {string | null}
|
|
381
|
+
*/
|
|
382
|
+
function installedVersion() {
|
|
383
|
+
if (cachedInstalledVersion !== undefined) return cachedInstalledVersion;
|
|
384
|
+
let version;
|
|
385
|
+
try {
|
|
386
|
+
const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
387
|
+
if (typeof manifest.version === 'string' && manifest.version.trim() !== '') {
|
|
388
|
+
version = manifest.version.trim();
|
|
389
|
+
}
|
|
390
|
+
} catch {
|
|
391
|
+
version = undefined;
|
|
392
|
+
}
|
|
393
|
+
cachedInstalledVersion = version ?? null;
|
|
394
|
+
return cachedInstalledVersion;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* The profile name this process booted, from the host's working directory
|
|
399
|
+
* (`$DSH_HOME/profiles/<name>` per the harness's own docs), so the upgrade
|
|
400
|
+
* command can be printed ready to paste. `undefined` when the layout does not
|
|
401
|
+
* match; the command then shows a `<profile>` placeholder instead.
|
|
402
|
+
*/
|
|
403
|
+
function profileHint() {
|
|
404
|
+
try {
|
|
405
|
+
const segments = process.cwd().split(/[\\/]/).filter((segment) => segment !== '');
|
|
406
|
+
const at = segments.lastIndexOf('profiles');
|
|
407
|
+
if (at >= 0 && at + 1 < segments.length) return segments[at + 1];
|
|
408
|
+
} catch {
|
|
409
|
+
/* fall through to the placeholder */
|
|
410
|
+
}
|
|
411
|
+
return undefined;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** An abort signal that fires after `ms`, on whatever abort API exists. */
|
|
415
|
+
function timeoutSignal(ms) {
|
|
416
|
+
try {
|
|
417
|
+
if (typeof AbortSignal?.timeout === 'function') return AbortSignal.timeout(ms);
|
|
418
|
+
} catch {
|
|
419
|
+
/* fall through to the manual controller */
|
|
420
|
+
}
|
|
421
|
+
if (typeof AbortController !== 'function') return undefined;
|
|
422
|
+
const controller = new AbortController();
|
|
423
|
+
const timer = setTimeout(() => {
|
|
424
|
+
try {
|
|
425
|
+
controller.abort(new Error(`timed out after ${ms}ms`));
|
|
426
|
+
} catch {
|
|
427
|
+
controller.abort();
|
|
428
|
+
}
|
|
429
|
+
}, ms);
|
|
430
|
+
if (typeof timer?.unref === 'function') timer.unref();
|
|
431
|
+
return controller.signal;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Sanitize a configured registry URL: trim, drop trailing slashes, and keep
|
|
436
|
+
* only http(s) origins. Anything else falls back to the npm default.
|
|
437
|
+
*/
|
|
438
|
+
function sanitizeRegistry(value) {
|
|
439
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
440
|
+
if (!/^https?:\/\//i.test(text)) return UPDATE_REGISTRY_DEFAULT;
|
|
441
|
+
return text.replace(/\/+$/, '');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Normalize `update.intervalHours`.
|
|
446
|
+
*
|
|
447
|
+
* Absent, malformed or negative values mean the 24h default; an explicit `0`
|
|
448
|
+
* is honoured as "check at boot only" — `enabled: false` is the off switch.
|
|
449
|
+
*/
|
|
450
|
+
function normalizeIntervalHours(value) {
|
|
451
|
+
const raw = readVal(value);
|
|
452
|
+
if (typeof raw !== 'number' || !Number.isFinite(raw)) return 24;
|
|
453
|
+
if (raw === 0) return 0;
|
|
454
|
+
if (raw < 0) return 24;
|
|
455
|
+
return raw;
|
|
456
|
+
}
|
|
457
|
+
|
|
235
458
|
/** Coerce raw row config into a total, always-usable shape. */
|
|
236
459
|
function readConfig(raw) {
|
|
237
460
|
const warnings = [];
|
|
238
461
|
const rolesRaw = readVal(raw?.roles) ?? {};
|
|
239
462
|
const strategyRaw = readVal(raw?.strategy) ?? {};
|
|
463
|
+
const updateRaw = readVal(raw?.update) ?? {};
|
|
240
464
|
|
|
241
465
|
for (const key of unknownKeys(raw, KNOWN_TOP_KEYS)) warnings.push(`unknown config key "${key}" ignored`);
|
|
242
466
|
for (const key of unknownKeys(rolesRaw, ROLE_NAMES)) warnings.push(`unknown role "${key}" ignored`);
|
|
243
467
|
for (const key of ROLE_NAMES) {
|
|
244
468
|
for (const bad of unknownKeys(readVal(rolesRaw?.[key]), KNOWN_ROLE_KEYS)) {
|
|
245
|
-
warnings.push(
|
|
469
|
+
warnings.push(bad === 'pick'
|
|
470
|
+
? `"roles.${key}.pick" moved to the top-level "pick" in 0.2.0; the per-role value is ignored`
|
|
471
|
+
: `unknown key "roles.${key}.${bad}" ignored`);
|
|
246
472
|
}
|
|
247
473
|
}
|
|
248
474
|
for (const key of unknownKeys(strategyRaw, KNOWN_STRATEGY_KEYS)) warnings.push(`unknown key "strategy.${key}" ignored`);
|
|
475
|
+
for (const key of unknownKeys(updateRaw, KNOWN_UPDATE_KEYS)) warnings.push(`unknown key "update.${key}" ignored`);
|
|
249
476
|
|
|
250
477
|
const readRole = (key) => {
|
|
251
478
|
const role = readVal(rolesRaw?.[key]) ?? {};
|
|
@@ -259,17 +486,19 @@ function readConfig(raw) {
|
|
|
259
486
|
}
|
|
260
487
|
return {
|
|
261
488
|
models,
|
|
262
|
-
pick: role.pick === 'round-robin' ? 'round-robin' : 'first',
|
|
263
489
|
note: typeof role.note === 'string' && role.note.trim() !== '' ? role.note.trim() : undefined,
|
|
264
490
|
};
|
|
265
491
|
};
|
|
266
492
|
|
|
267
493
|
const mode = strategyRaw.mode;
|
|
268
494
|
const limit = strategyRaw.historyLimit;
|
|
495
|
+
const autoDelegate = strategyRaw.autoDelegate;
|
|
269
496
|
return {
|
|
270
497
|
// Only an explicit `false` switches the manager off. A missing or malformed
|
|
271
498
|
// value keeps it on, so a typo can never silently disable routing.
|
|
272
499
|
enabled: readVal(raw?.enabled) !== false,
|
|
500
|
+
// One strategy for every role; anything that is not 'round-robin' is 'first'.
|
|
501
|
+
pick: readVal(raw?.pick) === 'round-robin' ? 'round-robin' : 'first',
|
|
273
502
|
roles: Object.fromEntries(ROLE_NAMES.map((key) => [key, readRole(key)])),
|
|
274
503
|
strategy: {
|
|
275
504
|
mode: mode === 'managed' || mode === 'advisory' ? mode : 'hybrid',
|
|
@@ -278,6 +507,19 @@ function readConfig(raw) {
|
|
|
278
507
|
// Guard against a positive fraction flooring to 0, which would evict every
|
|
279
508
|
// record immediately and silently disable usage tracking.
|
|
280
509
|
historyLimit: Number.isFinite(limit) && limit > 0 ? Math.max(1, Math.floor(limit)) : 300,
|
|
510
|
+
// The delegation-policy level; anything unrecognised falls back to the
|
|
511
|
+
// default level rather than silently switching the policy off.
|
|
512
|
+
autoDelegate: autoDelegate === 'off' || autoDelegate === 'eager' || autoDelegate === 'balanced'
|
|
513
|
+
? autoDelegate
|
|
514
|
+
: 'balanced',
|
|
515
|
+
},
|
|
516
|
+
update: {
|
|
517
|
+
// Same fail-on philosophy as the master switch: only explicit `false`
|
|
518
|
+
// stops the checks.
|
|
519
|
+
enabled: readVal(updateRaw.enabled) !== false,
|
|
520
|
+
registry: sanitizeRegistry(readVal(updateRaw.registry)),
|
|
521
|
+
// Absent/malformed -> 24h; explicit 0 -> boot-only checks.
|
|
522
|
+
intervalHours: normalizeIntervalHours(updateRaw.intervalHours),
|
|
281
523
|
},
|
|
282
524
|
warnings,
|
|
283
525
|
};
|
|
@@ -441,6 +683,16 @@ const quoteLabel = (label) => {
|
|
|
441
683
|
return text.length > 42 ? `"${text.slice(0, 41)}…"` : `"${text}"`;
|
|
442
684
|
};
|
|
443
685
|
|
|
686
|
+
/**
|
|
687
|
+
* Key of a failover cursor: per (session, role), never per session alone.
|
|
688
|
+
*
|
|
689
|
+
* A session can serve different roles over its life — plan mode moves the
|
|
690
|
+
* top-level agent between `main` and `planning` on every request — and the
|
|
691
|
+
* roles' chains are independent lists. Keying by session only let one role's
|
|
692
|
+
* wear push every other role off its first model.
|
|
693
|
+
*/
|
|
694
|
+
const failoverKey = (sessionId, role) => `${sessionId}::${role}`;
|
|
695
|
+
|
|
444
696
|
/**
|
|
445
697
|
* Build a keyword matcher.
|
|
446
698
|
*
|
|
@@ -457,6 +709,110 @@ function keywordMatcher(keywords) {
|
|
|
457
709
|
return (text) => patterns.some((pattern) => pattern.test(text));
|
|
458
710
|
}
|
|
459
711
|
|
|
712
|
+
// ---------------------------------------------------------------------------
|
|
713
|
+
// Delegation policy text
|
|
714
|
+
// ---------------------------------------------------------------------------
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* Render the model-facing delegation policy for one level.
|
|
718
|
+
*
|
|
719
|
+
* Pure on purpose: the decision *whether* to render (config, agent lineage,
|
|
720
|
+
* tool availability) lives in the engine's `delegationPolicy`, so this text is
|
|
721
|
+
* directly unit-testable and the engine only ever swaps the level, the
|
|
722
|
+
* available tool names, and which tiers actually have models behind the labels
|
|
723
|
+
* it teaches — a tier with no configured route is never advertised.
|
|
724
|
+
*
|
|
725
|
+
* @param {'balanced' | 'eager'} level - the policy level.
|
|
726
|
+
* @param {string[]} toolNames - delegation tools the target agent actually has.
|
|
727
|
+
* @param {{ planning?: boolean, vision?: boolean, routed?: boolean }} [opts]
|
|
728
|
+
* `planning` / `vision`: whether that tier has models to route to (both
|
|
729
|
+
* default to true, so a bare caller keeps the full text). `routed`:
|
|
730
|
+
* whether a label can actually change the model — false under
|
|
731
|
+
* `advisory`, where warning about `provider`/`model` would be noise
|
|
732
|
+
* because nothing is routed at all.
|
|
733
|
+
* @returns {string} the policy, or `''` when there is nothing to say.
|
|
734
|
+
*/
|
|
735
|
+
function delegationPolicyText(level, toolNames, opts) {
|
|
736
|
+
const has = (name) => toolNames.includes(name);
|
|
737
|
+
const subagent = has('subagent') || has('subagent_fork');
|
|
738
|
+
if (!subagent) return '';
|
|
739
|
+
const planning = opts?.planning !== false;
|
|
740
|
+
const vision = opts?.vision !== false;
|
|
741
|
+
const routed = opts?.routed !== false;
|
|
742
|
+
const fork = has('subagent_fork')
|
|
743
|
+
? ' Prefer `subagent_fork` when a unit needs this conversation\'s own context.'
|
|
744
|
+
: '';
|
|
745
|
+
const subagentTool = has('subagent') ? '`subagent`' : '`subagent_fork`';
|
|
746
|
+
const planTag = planning ? ' as a `plan:` unit' : ' to a delegation';
|
|
747
|
+
const head = level === 'eager'
|
|
748
|
+
? [
|
|
749
|
+
'## Delegation policy (model-manager, eager)',
|
|
750
|
+
'',
|
|
751
|
+
'You are the orchestrator: decomposition, dispatch, and synthesis are your job, and',
|
|
752
|
+
'nearly all substantive work — research, analysis, implementation, review, verification —',
|
|
753
|
+
'belongs in delegations.',
|
|
754
|
+
'',
|
|
755
|
+
`- Decompose the request into self-contained units before doing anything else, the`,
|
|
756
|
+
` decomposition itself going out${planTag}, and dispatch them as ${subagentTool}`,
|
|
757
|
+
` delegations, several in a single message when they are independent.${fork}`,
|
|
758
|
+
'- Do work yourself only when no delegation can carry it: a single trivial step, or an',
|
|
759
|
+
' action that requires this session\'s interactive tools (approvals, user questions).',
|
|
760
|
+
'- Collect results as delegations finish, verify each one, re-delegate what missed, and',
|
|
761
|
+
' synthesize the final answer from what came back.',
|
|
762
|
+
]
|
|
763
|
+
: [
|
|
764
|
+
'## Delegation policy (model-manager, balanced)',
|
|
765
|
+
'',
|
|
766
|
+
'Default to solving substantive work through subagents instead of doing it all yourself.',
|
|
767
|
+
'',
|
|
768
|
+
'- Plan first: when a task needs more than a few steps, delegate the decomposition',
|
|
769
|
+
` itself${planTag}, then dispatch the units it returned — research, analysis,`,
|
|
770
|
+
' implementation of separate areas, review, verification — together.',
|
|
771
|
+
`- Dispatch each unit as a ${subagentTool} delegation — independent units go together in`,
|
|
772
|
+
` a single message — and continue useful work while they run.${fork}`,
|
|
773
|
+
'- Keep for yourself what does not pay to delegate: coordination, single-step reads or',
|
|
774
|
+
' tiny edits, decisions that need the user, and the final synthesis of every result.',
|
|
775
|
+
'- Verify what delegations return before presenting it as done; re-delegate or fix',
|
|
776
|
+
' yourself when a result misses.',
|
|
777
|
+
];
|
|
778
|
+
const tierLines = [
|
|
779
|
+
planning
|
|
780
|
+
? '- `plan:` — the unit has to be thought through before it is done: design, analysis,'
|
|
781
|
+
+ '\n research, decomposition, review, trade-offs.'
|
|
782
|
+
: '',
|
|
783
|
+
vision
|
|
784
|
+
? '- `vision:` — the unit reads images, screenshots, diagrams, or OCRs a picture.'
|
|
785
|
+
: '',
|
|
786
|
+
'- plain — mechanical execution: edits, lookups, formatting, straightforward commands.',
|
|
787
|
+
].filter(Boolean);
|
|
788
|
+
const taught = [planning ? '`plan:`' : '', vision ? '`vision:`' : ''].filter(Boolean).join('/');
|
|
789
|
+
const matchLines = [];
|
|
790
|
+
if (planning && vision) {
|
|
791
|
+
matchLines.push(
|
|
792
|
+
'- A leading prefix decides the tier; a label without one falls back to keyword',
|
|
793
|
+
' matching, and a keyword label that fits both tiers goes to `vision`.',
|
|
794
|
+
);
|
|
795
|
+
} else if (planning || vision) {
|
|
796
|
+
matchLines.push(
|
|
797
|
+
'- A leading prefix decides the tier; a label without one falls back to keyword matching.',
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
if ((planning || vision) && routed) {
|
|
801
|
+
matchLines.push(
|
|
802
|
+
`- Omit \`provider\` and \`model\` on ${taught} units — a route named explicitly`,
|
|
803
|
+
' on the delegation overrides the tier.',
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
return [
|
|
807
|
+
...head,
|
|
808
|
+
'',
|
|
809
|
+
'Label each delegation by the kind of work it carries — the label picks the model:',
|
|
810
|
+
...tierLines,
|
|
811
|
+
...matchLines,
|
|
812
|
+
'- Never invent results for delegations that have not answered; wait for or collect them.',
|
|
813
|
+
].join('\n');
|
|
814
|
+
}
|
|
815
|
+
|
|
460
816
|
// ---------------------------------------------------------------------------
|
|
461
817
|
// Engine
|
|
462
818
|
// ---------------------------------------------------------------------------
|
|
@@ -497,6 +853,27 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
497
853
|
/** session id -> `{ key: '<turn>:<step>', switches }`, the per-step budget. */
|
|
498
854
|
const stepSwitches = new Map();
|
|
499
855
|
|
|
856
|
+
/**
|
|
857
|
+
* The `tools` service, captured when its injection resolves, so the
|
|
858
|
+
* delegation-policy section can ask which delegation tools an assembly's
|
|
859
|
+
* scope actually sees (`tools.get(name, scope)`) — the same probe
|
|
860
|
+
* dsh-tool-subagent's own prompt section uses.
|
|
861
|
+
*/
|
|
862
|
+
let toolsService;
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* Latest update-check outcome. Statuses: `idle` (not yet checked), `checking`,
|
|
866
|
+
* `ok` (up to date), `available` (a newer release exists), `error` (the check
|
|
867
|
+
* failed), `disabled` (checks switched off in config).
|
|
868
|
+
*/
|
|
869
|
+
let updateState = { status: 'idle' };
|
|
870
|
+
|
|
871
|
+
/** Coalesces concurrent update checks. */
|
|
872
|
+
let updateInFlight;
|
|
873
|
+
|
|
874
|
+
/** Fallback timer handles for the update schedule, cleared when re-armed. */
|
|
875
|
+
let updateTimers = [];
|
|
876
|
+
|
|
500
877
|
const roleOf = (key) => config.roles[key];
|
|
501
878
|
|
|
502
879
|
let visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
@@ -515,17 +892,21 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
515
892
|
*
|
|
516
893
|
* The counter is committed only when the route is actually applied, so an
|
|
517
894
|
* advisory pass or a respected explicit choice does not consume a turn of the
|
|
518
|
-
* rotation.
|
|
895
|
+
* rotation. One strategy (`config.pick`) governs every role; the rotation
|
|
896
|
+
* counter itself stays per-role so each list rotates independently.
|
|
519
897
|
*
|
|
520
898
|
* `sessionId` selects the failover position for `pick: 'first'`, where the
|
|
521
|
-
* ordered list is a failover chain rather than a rotation.
|
|
899
|
+
* ordered list is a failover chain rather than a rotation. The cursor is
|
|
900
|
+
* keyed per (session, role): a session that failed over while it was serving
|
|
901
|
+
* `planning` (say, in plan mode) must not come back to `main` already pushed
|
|
902
|
+
* off `main`'s first model — each tier's chain wears down independently.
|
|
522
903
|
*/
|
|
523
904
|
function routeCandidate(key, sessionId) {
|
|
524
905
|
const models = effectiveModels(key);
|
|
525
906
|
if (models.length === 0) return undefined;
|
|
526
907
|
if (models.length === 1) return { route: models[0], commit() {} };
|
|
527
908
|
const owner = roleOf(key)?.models.length > 0 ? key : 'execution';
|
|
528
|
-
if (
|
|
909
|
+
if (config.pick === 'round-robin') {
|
|
529
910
|
const index = roundRobin.get(owner) ?? 0;
|
|
530
911
|
return {
|
|
531
912
|
route: models[index],
|
|
@@ -534,19 +915,74 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
534
915
|
},
|
|
535
916
|
};
|
|
536
917
|
}
|
|
537
|
-
const at = Math.min(failover.get(sessionId) ?? 0, models.length - 1);
|
|
918
|
+
const at = Math.min(failover.get(failoverKey(sessionId, key)) ?? 0, models.length - 1);
|
|
538
919
|
return { route: models[at], commit() {} };
|
|
539
920
|
}
|
|
540
921
|
|
|
541
|
-
/**
|
|
922
|
+
/**
|
|
923
|
+
* Which role owns a delegated child, from its delegation label.
|
|
924
|
+
*
|
|
925
|
+
* A leading `plan:` / `vision:` prefix is authoritative — it is the one signal
|
|
926
|
+
* the delegating model writes *on purpose*, so it must beat the keyword scan.
|
|
927
|
+
* That is what the policy text teaches, so honouring it makes the documented
|
|
928
|
+
* rule true: "plan: analyse the screenshots" is planning work even though a
|
|
929
|
+
* bare keyword label fitting both tiers goes to vision.
|
|
930
|
+
*/
|
|
542
931
|
function classifySubagent(label) {
|
|
543
|
-
const text = String(label ?? '');
|
|
932
|
+
const text = String(label ?? '').trim();
|
|
544
933
|
if (text === '') return 'execution';
|
|
934
|
+
const lower = text.toLowerCase();
|
|
935
|
+
if (lower.startsWith('plan:')) return 'planning';
|
|
936
|
+
if (lower.startsWith('vision:')) return 'vision';
|
|
545
937
|
if (visionMatch(text)) return 'vision';
|
|
546
938
|
if (planningMatch(text)) return 'planning';
|
|
547
939
|
return 'execution';
|
|
548
940
|
}
|
|
549
941
|
|
|
942
|
+
/**
|
|
943
|
+
* The delegation policy for one prompt assembly, or `''` when none applies.
|
|
944
|
+
*
|
|
945
|
+
* Rendered only for the *orchestrating* top-level agent: a delegated child
|
|
946
|
+
* already carries the harness's fixed `subagent:delegation` runtime context,
|
|
947
|
+
* and encouraging a child to delegate further would push every unit one more
|
|
948
|
+
* depth level down for no benefit. Depth is read from the session header the
|
|
949
|
+
* same way `delegationDepthOf` does (`header.delegationDepth ?? 0`).
|
|
950
|
+
*
|
|
951
|
+
* Tool availability is verified against the assembly's own scope, so an agent
|
|
952
|
+
* whose composition restricted the delegation tools never sees a policy
|
|
953
|
+
* naming a tool it cannot call. Tier availability is passed through too, so
|
|
954
|
+
* the text never advertises a `plan:` or `vision:` tier that has no models
|
|
955
|
+
* behind it, and never warns about `provider`/`model` overrides in `advisory`
|
|
956
|
+
* mode where nothing is routed at all.
|
|
957
|
+
*/
|
|
958
|
+
function delegationPolicy(context) {
|
|
959
|
+
try {
|
|
960
|
+
if (!config.enabled) return '';
|
|
961
|
+
const level = config.strategy.autoDelegate;
|
|
962
|
+
if (level === 'off') return '';
|
|
963
|
+
const agent = context?.agent;
|
|
964
|
+
if (agent !== undefined) {
|
|
965
|
+
const header = agent.session?.header;
|
|
966
|
+
if (header?.origin === 'subagent') return '';
|
|
967
|
+
const depth = header?.delegationDepth;
|
|
968
|
+
if (typeof depth === 'number' && depth > 0) return '';
|
|
969
|
+
}
|
|
970
|
+
if (toolsService === undefined || typeof toolsService.get !== 'function') return '';
|
|
971
|
+
const scope = context?.scope;
|
|
972
|
+
const available = DELEGATION_TOOL_NAMES
|
|
973
|
+
.filter((name) => probe(() => toolsService.get(name, scope)) !== undefined);
|
|
974
|
+
return delegationPolicyText(level, available, {
|
|
975
|
+
planning: effectiveModels('planning').length > 0,
|
|
976
|
+
vision: effectiveModels('vision').length > 0,
|
|
977
|
+
routed: config.strategy.mode !== 'advisory',
|
|
978
|
+
});
|
|
979
|
+
} catch {
|
|
980
|
+
// A prompt section must never throw: an empty policy degrades to the
|
|
981
|
+
// harness's own behaviour, which is exactly the pre-0.3.0 state.
|
|
982
|
+
return '';
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
550
986
|
function remember(sessionId, entry) {
|
|
551
987
|
const previous = usage.get(sessionId);
|
|
552
988
|
// Re-insert so the map stays in least-recently-used order for eviction.
|
|
@@ -821,12 +1257,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
821
1257
|
// to recover.
|
|
822
1258
|
const header = probe(() => agent.session?.requestHeader?.()?.config);
|
|
823
1259
|
const failedAt = header === undefined
|
|
824
|
-
? Math.min(failover.get(agent.id) ?? 0, models.length - 1)
|
|
1260
|
+
? Math.min(failover.get(failoverKey(agent.id, role)) ?? 0, models.length - 1)
|
|
825
1261
|
: models.findIndex((route) => route.provider === header.provider && route.model === header.model);
|
|
826
1262
|
if (failedAt < 0) return undefined;
|
|
827
1263
|
|
|
828
1264
|
const owner = roleOf(role)?.models.length > 0 ? role : 'execution';
|
|
829
|
-
const rotating =
|
|
1265
|
+
const rotating = config.pick === 'round-robin';
|
|
830
1266
|
const nextIndex = rotating
|
|
831
1267
|
? (failedAt + 1) % models.length
|
|
832
1268
|
: Math.min(failedAt + 1, models.length - 1);
|
|
@@ -834,7 +1270,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
834
1270
|
if (!rotating && nextIndex === failedAt) return undefined;
|
|
835
1271
|
|
|
836
1272
|
if (rotating) roundRobin.set(owner, nextIndex);
|
|
837
|
-
else failover.set(agent.id, nextIndex);
|
|
1273
|
+
else failover.set(failoverKey(agent.id, role), nextIndex);
|
|
838
1274
|
budget.switches += 1;
|
|
839
1275
|
|
|
840
1276
|
const from = models[failedAt];
|
|
@@ -849,6 +1285,174 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
849
1285
|
}
|
|
850
1286
|
}
|
|
851
1287
|
|
|
1288
|
+
// -- update check ---------------------------------------------------------
|
|
1289
|
+
|
|
1290
|
+
/** Drop every fallback timer the schedule armed; never throws. */
|
|
1291
|
+
function clearUpdateTimers() {
|
|
1292
|
+
const timers = updateTimers;
|
|
1293
|
+
updateTimers = [];
|
|
1294
|
+
for (const timer of timers) {
|
|
1295
|
+
try {
|
|
1296
|
+
clearTimeout(timer);
|
|
1297
|
+
clearInterval(timer);
|
|
1298
|
+
} catch {
|
|
1299
|
+
/* a half-cleared timer is already harmless */
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/**
|
|
1305
|
+
* Arm the update-check schedule from the live config.
|
|
1306
|
+
*
|
|
1307
|
+
* The first check runs shortly after boot (never on the boot path itself),
|
|
1308
|
+
* then once per `update.intervalHours`; an explicit `0` means "boot only".
|
|
1309
|
+
* Prefers the cordis timer service when the composition provides one — those
|
|
1310
|
+
* timers are context-effect-managed and dispose with the plugin fiber — and
|
|
1311
|
+
* falls back to unref'd globals otherwise, so a test process can still exit.
|
|
1312
|
+
*/
|
|
1313
|
+
function scheduleUpdateChecks() {
|
|
1314
|
+
clearUpdateTimers();
|
|
1315
|
+
if (!config.update.enabled) {
|
|
1316
|
+
if (updateState.status !== 'available') updateState = { status: 'disabled', at: Date.now() };
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
const arm = (repeat, delay) => {
|
|
1320
|
+
const run = () => void checkForUpdate().catch(() => {});
|
|
1321
|
+
const viaCordis = probe(() => (repeat
|
|
1322
|
+
? (typeof ctx.interval === 'function' ? ctx.interval : undefined)
|
|
1323
|
+
: (typeof ctx.timeout === 'function' ? ctx.timeout : undefined)));
|
|
1324
|
+
if (viaCordis !== undefined) {
|
|
1325
|
+
viaCordis(run, delay);
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
const timer = repeat ? setInterval(run, delay) : setTimeout(run, delay);
|
|
1329
|
+
if (typeof timer?.unref === 'function') timer.unref();
|
|
1330
|
+
updateTimers.push(timer);
|
|
1331
|
+
};
|
|
1332
|
+
arm(false, UPDATE_FIRST_CHECK_DELAY_MS);
|
|
1333
|
+
const hours = config.update.intervalHours;
|
|
1334
|
+
if (hours > 0) {
|
|
1335
|
+
arm(true, Math.max(UPDATE_MIN_INTERVAL_MS, hours * 3_600_000));
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/**
|
|
1340
|
+
* Run one update check against the configured registry.
|
|
1341
|
+
*
|
|
1342
|
+
* Fetches the abbreviated packument, reads `dist-tags.latest`, and compares
|
|
1343
|
+
* it with this package's own version. Every failure path lands in
|
|
1344
|
+
* `updateState.status === 'error'` with a reason; none of them throws, and
|
|
1345
|
+
* none of them can touch routing.
|
|
1346
|
+
*/
|
|
1347
|
+
function checkForUpdate() {
|
|
1348
|
+
if (updateInFlight !== undefined) return updateInFlight;
|
|
1349
|
+
updateInFlight = (async () => {
|
|
1350
|
+
if (!config.update.enabled) {
|
|
1351
|
+
updateState = { status: 'disabled', at: Date.now() };
|
|
1352
|
+
return updateState;
|
|
1353
|
+
}
|
|
1354
|
+
const registry = config.update.registry;
|
|
1355
|
+
const current = installedVersion();
|
|
1356
|
+
updateState = { status: 'checking', at: Date.now(), registry, current: current ?? undefined };
|
|
1357
|
+
try {
|
|
1358
|
+
if (current === null) throw new Error('this installation\'s version could not be read');
|
|
1359
|
+
if (typeof fetch !== 'function') throw new Error('no fetch in this runtime');
|
|
1360
|
+
const signal = timeoutSignal(UPDATE_FETCH_TIMEOUT_MS);
|
|
1361
|
+
const response = await fetch(`${registry}/${UPDATE_PACKAGE_PATH}`, {
|
|
1362
|
+
headers: { accept: 'application/vnd.npm.install-v1+json' },
|
|
1363
|
+
redirect: 'follow',
|
|
1364
|
+
...(signal === undefined ? {} : { signal }),
|
|
1365
|
+
});
|
|
1366
|
+
if (response?.ok !== true) throw new Error(`HTTP ${response?.status ?? '(no status)'}`);
|
|
1367
|
+
const packument = await response.json();
|
|
1368
|
+
const latest = packument?.['dist-tags']?.latest;
|
|
1369
|
+
if (typeof latest !== 'string' || latest === '') {
|
|
1370
|
+
throw new Error('the packument carries no dist-tags.latest');
|
|
1371
|
+
}
|
|
1372
|
+
const order = compareVersions(latest, current);
|
|
1373
|
+
if (order === undefined) throw new Error(`unparseable version pair "${latest}" / "${current}"`);
|
|
1374
|
+
if (order > 0) {
|
|
1375
|
+
updateState = { status: 'available', at: Date.now(), current, latest, registry };
|
|
1376
|
+
log('warn', `update available: ${PACKAGE_NAME} ${current} -> ${latest} (checked ${registry}). `
|
|
1377
|
+
+ `Run the model_manager tool with action "update" for the upgrade command, then restart. `
|
|
1378
|
+
+ 'The settings card and the session-header chip show the same notice.');
|
|
1379
|
+
} else {
|
|
1380
|
+
updateState = { status: 'ok', at: Date.now(), current, latest, registry };
|
|
1381
|
+
}
|
|
1382
|
+
} catch (error) {
|
|
1383
|
+
updateState = {
|
|
1384
|
+
status: 'error',
|
|
1385
|
+
at: Date.now(),
|
|
1386
|
+
registry,
|
|
1387
|
+
current: current ?? undefined,
|
|
1388
|
+
reason: String(error?.message ?? error),
|
|
1389
|
+
};
|
|
1390
|
+
// A failed check is a diagnostic, not an alarm: offline deployments hit
|
|
1391
|
+
// this on every interval and a warn-per-hour would be noise.
|
|
1392
|
+
log('info', `update check failed (will retry on the interval): ${updateState.reason}`);
|
|
1393
|
+
}
|
|
1394
|
+
return updateState;
|
|
1395
|
+
})().finally(() => {
|
|
1396
|
+
updateInFlight = undefined;
|
|
1397
|
+
});
|
|
1398
|
+
return updateInFlight;
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
/** One compact status line for `routes`/`report`. */
|
|
1402
|
+
function updateStatusLine() {
|
|
1403
|
+
const state = updateState;
|
|
1404
|
+
const at = state.at === undefined ? '' : new Date(state.at).toISOString();
|
|
1405
|
+
switch (state.status) {
|
|
1406
|
+
case 'available':
|
|
1407
|
+
return `Update check: ${state.latest} AVAILABLE (installed ${state.current}, checked ${at}, ${state.registry}). `
|
|
1408
|
+
+ 'Run model_manager with action "update" for the upgrade command.';
|
|
1409
|
+
case 'ok':
|
|
1410
|
+
return `Update check: up to date — ${state.current} (checked ${at}, ${state.registry}).`;
|
|
1411
|
+
case 'checking':
|
|
1412
|
+
return `Update check: in progress (since ${at}, ${state.registry}).`;
|
|
1413
|
+
case 'error':
|
|
1414
|
+
return `Update check: failed — ${state.reason} (checked ${at}). `
|
|
1415
|
+
+ 'Run model_manager with action "update" to retry now.';
|
|
1416
|
+
case 'disabled':
|
|
1417
|
+
return 'Update check: disabled in config (update.enabled: false).';
|
|
1418
|
+
default:
|
|
1419
|
+
return 'Update check: not run yet in this process.';
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/** The full `model_manager` action-"update" report, forcing a fresh check. */
|
|
1424
|
+
async function updateAction() {
|
|
1425
|
+
await checkForUpdate();
|
|
1426
|
+
const state = updateState;
|
|
1427
|
+
const current = installedVersion();
|
|
1428
|
+
const lines = [
|
|
1429
|
+
'Model manager update check',
|
|
1430
|
+
'',
|
|
1431
|
+
` installed : ${current ?? '(unreadable)'}`,
|
|
1432
|
+
` latest : ${state.latest ?? '(unknown)'}`,
|
|
1433
|
+
` registry : ${config.update.registry}`,
|
|
1434
|
+
` checked : ${state.at === undefined ? 'not yet' : new Date(state.at).toISOString()}`,
|
|
1435
|
+
];
|
|
1436
|
+
if (state.status === 'available') {
|
|
1437
|
+
lines.push(` verdict : UPDATE AVAILABLE (${current} -> ${state.latest})`, '',
|
|
1438
|
+
'To upgrade, run in a terminal:', '',
|
|
1439
|
+
` dsh plugin --profile ${profileHint() ?? '<profile>'} add ${PACKAGE_NAME}@latest`, '',
|
|
1440
|
+
'then restart the harness so the new version mounts. The Plugins page can reinstall',
|
|
1441
|
+
'the same package instead; both paths run the same installer. Tell the user this',
|
|
1442
|
+
'upgrade is available and what command to run.');
|
|
1443
|
+
} else if (state.status === 'error') {
|
|
1444
|
+
lines.push(` verdict : CHECK FAILED — ${state.reason}`, '',
|
|
1445
|
+
'The check is retried on its interval; offline deployments keep this verdict.');
|
|
1446
|
+
} else if (state.status === 'disabled') {
|
|
1447
|
+
lines.push(' verdict : DISABLED — set update.enabled: true to check.');
|
|
1448
|
+
} else if (state.status === 'checking') {
|
|
1449
|
+
lines.push(' verdict : a concurrent check is in flight; re-run this action shortly.');
|
|
1450
|
+
} else {
|
|
1451
|
+
lines.push(` verdict : up to date (${current}).`);
|
|
1452
|
+
}
|
|
1453
|
+
return lines.join('\n');
|
|
1454
|
+
}
|
|
1455
|
+
|
|
852
1456
|
// -- reporting ------------------------------------------------------------
|
|
853
1457
|
|
|
854
1458
|
/**
|
|
@@ -974,8 +1578,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
974
1578
|
}
|
|
975
1579
|
|
|
976
1580
|
function roleTable() {
|
|
977
|
-
const lines = ['Role
|
|
978
|
-
lines.push('
|
|
1581
|
+
const lines = ['Role effective model(s)'];
|
|
1582
|
+
lines.push('---------- ------------------------------------------');
|
|
979
1583
|
for (const key of ROLE_NAMES) {
|
|
980
1584
|
const role = roleOf(key);
|
|
981
1585
|
const models = effectiveModels(key);
|
|
@@ -983,8 +1587,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
983
1587
|
const detail = models.length === 0
|
|
984
1588
|
? '(unconfigured — passes through)'
|
|
985
1589
|
: models.map((route) => `${route.provider}/${route.model}${route.reasoningEffort ? ` (${route.reasoningEffort})` : ''}`).join(', ');
|
|
986
|
-
lines.push(`${key.padEnd(12)} ${
|
|
987
|
-
if (role.note !== undefined) lines.push(`${' '.repeat(
|
|
1590
|
+
lines.push(`${key.padEnd(12)} ${detail}${via}`);
|
|
1591
|
+
if (role.note !== undefined) lines.push(`${' '.repeat(14)}note: ${role.note}`);
|
|
988
1592
|
}
|
|
989
1593
|
return lines.join('\n');
|
|
990
1594
|
}
|
|
@@ -1067,7 +1671,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1067
1671
|
return 'No subagents observed yet in this process.\n\n'
|
|
1068
1672
|
+ 'Delegate some work, then run this report again. Model usage is recorded per\n'
|
|
1069
1673
|
+ 'delegation at request time, so it works whether routing applied or passed through.\n\n'
|
|
1070
|
-
+ roleTable()
|
|
1674
|
+
+ roleTable()
|
|
1675
|
+
// The empty report still carries an available-update notice: it is the
|
|
1676
|
+
// one line a model reading this report should relay unprompted.
|
|
1677
|
+
+ (updateState.status === 'available' ? `\n${updateStatusLine()}` : '');
|
|
1071
1678
|
}
|
|
1072
1679
|
rows.sort((a, b) => String(a.childId).localeCompare(String(b.childId)));
|
|
1073
1680
|
const lines = [];
|
|
@@ -1138,6 +1745,11 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1138
1745
|
lines.push(` ${String(entry.requests).padStart(4)} req / ${String(entry.children).padStart(2)} subagent(s) ${key}`);
|
|
1139
1746
|
}
|
|
1140
1747
|
}
|
|
1748
|
+
// Only an AVAILABLE update is worth a report line: the full status lives in
|
|
1749
|
+
// `routes` and action "update", and a per-report "up to date" would be noise.
|
|
1750
|
+
if (updateState.status === 'available') {
|
|
1751
|
+
lines.push('', updateStatusLine());
|
|
1752
|
+
}
|
|
1141
1753
|
return lines.join('\n');
|
|
1142
1754
|
}
|
|
1143
1755
|
|
|
@@ -1162,6 +1774,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1162
1774
|
'',
|
|
1163
1775
|
`Enabled: ${config.enabled ? 'yes' : 'NO — observing and reporting only, no route is rewritten'}`,
|
|
1164
1776
|
'',
|
|
1777
|
+
`Selection: ${config.pick === 'round-robin'
|
|
1778
|
+
? 'round-robin — every role rotates across its own list'
|
|
1779
|
+
: 'first — every role starts at its top model and fails over down its list'} (one strategy for all roles)`,
|
|
1780
|
+
'',
|
|
1165
1781
|
roleTable(),
|
|
1166
1782
|
'',
|
|
1167
1783
|
`Strategy mode: ${config.strategy.mode}`
|
|
@@ -1169,6 +1785,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1169
1785
|
+ (config.strategy.mode === 'managed' ? ' (always apply the role route)' : '')
|
|
1170
1786
|
+ (config.strategy.mode === 'advisory' ? ' (never rewrite — report only)' : ''),
|
|
1171
1787
|
'',
|
|
1788
|
+
`Auto-delegation: ${config.strategy.autoDelegate === 'off'
|
|
1789
|
+
? 'off — no delegation policy is added to the system prompt'
|
|
1790
|
+
: `${config.strategy.autoDelegate} — the top-level agent is prompted to ${config.strategy.autoDelegate === 'eager'
|
|
1791
|
+
? 'orchestrate: nearly all substantive work goes to delegations'
|
|
1792
|
+
: 'plan and dispatch subagents for multi-step and independent work'}`}`,
|
|
1793
|
+
'',
|
|
1172
1794
|
allowListBlock(),
|
|
1173
1795
|
'',
|
|
1174
1796
|
visionBlock,
|
|
@@ -1178,6 +1800,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1178
1800
|
` vision : ${config.strategy.visionKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.visionKeywords.length > 8 ? ', …' : ''}`,
|
|
1179
1801
|
` planning : ${config.strategy.planningKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.planningKeywords.length > 8 ? ', …' : ''}`,
|
|
1180
1802
|
' else : execution',
|
|
1803
|
+
'',
|
|
1804
|
+
updateStatusLine(),
|
|
1181
1805
|
].join('\n');
|
|
1182
1806
|
}
|
|
1183
1807
|
|
|
@@ -1190,13 +1814,22 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1190
1814
|
})
|
|
1191
1815
|
.filter(Boolean);
|
|
1192
1816
|
if (summary.length === 0) return '';
|
|
1817
|
+
const routing = config.strategy.mode === 'advisory'
|
|
1818
|
+
? 'The manager is observing only (advisory), so labels classify but never rewrite a route.'
|
|
1819
|
+
: [
|
|
1820
|
+
'Label a delegation `description` with "plan:" for thinking work, "vision:" for image',
|
|
1821
|
+
'work, or leave it plain for execution; a leading prefix wins over keyword matches.',
|
|
1822
|
+
'Leave `provider` and `model` unset on those units so the role route applies.',
|
|
1823
|
+
].join('\n');
|
|
1824
|
+
const planningGap = effectiveModels('planning').length === 0
|
|
1825
|
+
? '\nThe planning tier has no models, so "plan:" labels keep the inherited route.'
|
|
1826
|
+
: '';
|
|
1193
1827
|
return [
|
|
1194
1828
|
'## Model manager',
|
|
1195
1829
|
'Delegated work is routed by the label you give each delegation:',
|
|
1196
1830
|
...summary,
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
'action "report" to see which model each subagent actually used.',
|
|
1831
|
+
routing,
|
|
1832
|
+
`Call \`model_manager\` with action "report" to see which model each subagent actually used.${planningGap}`,
|
|
1200
1833
|
].join('\n');
|
|
1201
1834
|
}
|
|
1202
1835
|
|
|
@@ -1393,10 +2026,15 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1393
2026
|
|
|
1394
2027
|
// Drop per-session failover state when its agent goes away, so a long-lived
|
|
1395
2028
|
// process does not accumulate entries for sessions that can no longer run.
|
|
2029
|
+
// The cursors are keyed `${id}::${role}`, so every role's cursor goes too.
|
|
1396
2030
|
ctx.on('agent/disposed', (payload) => {
|
|
1397
2031
|
const id = payload?.agent?.id ?? (typeof payload === 'string' ? payload : payload?.id);
|
|
1398
2032
|
if (typeof id !== 'string') return;
|
|
1399
2033
|
failover.delete(id);
|
|
2034
|
+
const prefix = `${id}::`;
|
|
2035
|
+
for (const key of [...failover.keys()]) {
|
|
2036
|
+
if (key.startsWith(prefix)) failover.delete(key);
|
|
2037
|
+
}
|
|
1400
2038
|
stepSwitches.delete(id);
|
|
1401
2039
|
});
|
|
1402
2040
|
|
|
@@ -1413,12 +2051,25 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1413
2051
|
// boot-time one until restart. DSH's own volatile plugins do the same.
|
|
1414
2052
|
ctx.on('loader/volatile-update', () => {
|
|
1415
2053
|
try {
|
|
2054
|
+
const previousUpdate = config.update;
|
|
1416
2055
|
const next = readConfig(rawConfig);
|
|
1417
|
-
config = {
|
|
2056
|
+
config = {
|
|
2057
|
+
enabled: next.enabled,
|
|
2058
|
+
pick: next.pick,
|
|
2059
|
+
roles: next.roles,
|
|
2060
|
+
strategy: next.strategy,
|
|
2061
|
+
update: next.update,
|
|
2062
|
+
warnings: next.warnings,
|
|
2063
|
+
};
|
|
1418
2064
|
visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
1419
2065
|
planningMatch = keywordMatcher(config.strategy.planningKeywords);
|
|
1420
2066
|
for (const warning of config.warnings) log('warn', warning);
|
|
1421
|
-
|
|
2067
|
+
// The delegation policy and the update schedule both read the live
|
|
2068
|
+
// config through this closure, so they follow a save with no restart.
|
|
2069
|
+
scheduleUpdateChecks();
|
|
2070
|
+
const updateChanged = JSON.stringify(previousUpdate) !== JSON.stringify(config.update);
|
|
2071
|
+
if (updateChanged) void checkForUpdate().catch(() => {});
|
|
2072
|
+
log('info', `settings reloaded — mode ${config.strategy.mode}, pick ${config.pick}, autoDelegate ${config.strategy.autoDelegate}; `
|
|
1422
2073
|
+ ROLE_NAMES
|
|
1423
2074
|
.map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
|
|
1424
2075
|
.join(' '));
|
|
@@ -1429,6 +2080,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1429
2080
|
|
|
1430
2081
|
if (typeof ctx.inject === 'function') {
|
|
1431
2082
|
ctx.inject(['tools'], (scoped) => {
|
|
2083
|
+
// Captured for the delegation-policy section, which asks this service
|
|
2084
|
+
// which delegation tools an assembly's scope actually exposes.
|
|
2085
|
+
toolsService = scoped.tools;
|
|
1432
2086
|
try {
|
|
1433
2087
|
scoped.tools.register({
|
|
1434
2088
|
name: 'model_manager',
|
|
@@ -1437,19 +2091,25 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1437
2091
|
+ 'conversation and whether the manager yielded to a model a person picked in the '
|
|
1438
2092
|
+ 'composer, then one row per subagent with its label, role, reason, live status and '
|
|
1439
2093
|
+ 'totals. action "routes": the four role assignments '
|
|
1440
|
-
+ '(including the vision->execution fallback), the
|
|
2094
|
+
+ '(including the vision->execution fallback), the shared selection strategy (first or round-robin), '
|
|
2095
|
+
+ 'the active distribution mode, the auto-delegation level, the update-check status, '
|
|
2096
|
+
+ 'and whether each '
|
|
1441
2097
|
+ 'route is dispatchable by the delegation tool, with the YAML to add any that are not. '
|
|
1442
2098
|
+ 'action "usage": request and subagent counts by role and model across the whole process. '
|
|
1443
2099
|
+ 'action "client": whether the Host composed this plugin\'s Web client half into the browser '
|
|
1444
2100
|
+ 'boot graph, the route serving its bundle, and the current graph revision — use it when the '
|
|
1445
2101
|
+ 'configuration card does not appear in the Web UI. '
|
|
2102
|
+
+ 'action "update": force a fresh update check against the package registry and return the '
|
|
2103
|
+
+ 'installed version, the latest published version, and the exact upgrade command to run '
|
|
2104
|
+
+ 'when a newer release exists — use it whenever the report or routes output says an update '
|
|
2105
|
+
+ 'is available, and tell the user. '
|
|
1446
2106
|
+ 'Read-only; it never changes routing.',
|
|
1447
2107
|
parameters: {
|
|
1448
2108
|
type: 'object',
|
|
1449
2109
|
properties: {
|
|
1450
2110
|
action: {
|
|
1451
2111
|
type: 'string',
|
|
1452
|
-
enum: ['report', 'routes', 'usage', 'client'],
|
|
2112
|
+
enum: ['report', 'routes', 'usage', 'client', 'update'],
|
|
1453
2113
|
description: 'What to return. Defaults to "report".',
|
|
1454
2114
|
},
|
|
1455
2115
|
},
|
|
@@ -1463,6 +2123,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1463
2123
|
const action = args?.action ?? 'report';
|
|
1464
2124
|
if (action === 'routes') return routes();
|
|
1465
2125
|
if (action === 'client') return clientStatus();
|
|
2126
|
+
if (action === 'update') return updateAction();
|
|
1466
2127
|
if (action === 'usage') {
|
|
1467
2128
|
await refreshCatalog();
|
|
1468
2129
|
const totals = new Map();
|
|
@@ -1511,11 +2172,42 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1511
2172
|
|
|
1512
2173
|
ctx.inject(['systemPrompt'], (scoped) => {
|
|
1513
2174
|
try {
|
|
1514
|
-
const register = () =>
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
2175
|
+
const register = () => {
|
|
2176
|
+
const disposers = [];
|
|
2177
|
+
try {
|
|
2178
|
+
disposers.push(scoped.systemPrompt.section({
|
|
2179
|
+
name: 'model-manager',
|
|
2180
|
+
order: 60,
|
|
2181
|
+
text: () => cheatSheet(),
|
|
2182
|
+
}));
|
|
2183
|
+
// The delegation policy: rendered per assembly, only for the
|
|
2184
|
+
// top-level orchestrator, and only while it actually has the
|
|
2185
|
+
// delegation tools — see delegationPolicy().
|
|
2186
|
+
disposers.push(scoped.systemPrompt.section({
|
|
2187
|
+
name: 'model-manager:delegation',
|
|
2188
|
+
order: DELEGATION_SECTION_ORDER,
|
|
2189
|
+
text: (context) => delegationPolicy(context),
|
|
2190
|
+
}));
|
|
2191
|
+
} catch (error) {
|
|
2192
|
+
for (const dispose of disposers) {
|
|
2193
|
+
try {
|
|
2194
|
+
dispose();
|
|
2195
|
+
} catch {
|
|
2196
|
+
/* a failed partial registration must not leak the rest */
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
throw error;
|
|
2200
|
+
}
|
|
2201
|
+
return () => {
|
|
2202
|
+
for (const dispose of disposers) {
|
|
2203
|
+
try {
|
|
2204
|
+
dispose();
|
|
2205
|
+
} catch {
|
|
2206
|
+
/* disposal is best-effort */
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
};
|
|
2210
|
+
};
|
|
1519
2211
|
if (typeof scoped.effect === 'function') scoped.effect(register);
|
|
1520
2212
|
else register();
|
|
1521
2213
|
} catch (error) {
|
|
@@ -1559,9 +2251,23 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1559
2251
|
+ `${broken.map((row) => row.label).join(', ')}. Point roles.vision.models at an image-capable model.`);
|
|
1560
2252
|
}
|
|
1561
2253
|
})().catch(() => {});
|
|
2254
|
+
|
|
2255
|
+
// Automatic update checks: the first run is delayed past the boot path,
|
|
2256
|
+
// and every failure path inside degrades to a logged diagnostic.
|
|
2257
|
+
scheduleUpdateChecks();
|
|
1562
2258
|
}
|
|
1563
2259
|
|
|
1564
|
-
return {
|
|
2260
|
+
return {
|
|
2261
|
+
attach,
|
|
2262
|
+
classifySubagent,
|
|
2263
|
+
classifyAndRoute: routeCandidate,
|
|
2264
|
+
roleTable,
|
|
2265
|
+
routes,
|
|
2266
|
+
report,
|
|
2267
|
+
delegationPolicy,
|
|
2268
|
+
checkForUpdate,
|
|
2269
|
+
updateStatusLine,
|
|
2270
|
+
};
|
|
1565
2271
|
}
|
|
1566
2272
|
|
|
1567
2273
|
// ---------------------------------------------------------------------------
|
|
@@ -1581,13 +2287,29 @@ export function apply(ctx, rawConfig) {
|
|
|
1581
2287
|
for (const warning of config.warnings) log('warn', warning);
|
|
1582
2288
|
const engine = createEngine(config, ctx, log, rawConfig);
|
|
1583
2289
|
engine.attach();
|
|
1584
|
-
log('info', `active — mode ${config.strategy.mode}; `
|
|
2290
|
+
log('info', `active — mode ${config.strategy.mode}, pick ${config.pick}, autoDelegate ${config.strategy.autoDelegate}; `
|
|
1585
2291
|
+ ROLE_NAMES
|
|
1586
2292
|
.map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
|
|
1587
|
-
.join(' ')
|
|
2293
|
+
.join(' ')
|
|
2294
|
+
+ (config.update.enabled
|
|
2295
|
+
? `; update check every ${config.update.intervalHours === 0
|
|
2296
|
+
? 'boot (interval disabled)'
|
|
2297
|
+
: `${config.update.intervalHours}h against ${config.update.registry}`}`
|
|
2298
|
+
: '; update check disabled'));
|
|
1588
2299
|
} catch (error) {
|
|
1589
2300
|
log('error', `failed to initialise; model routing is disabled: ${error?.stack ?? error}`);
|
|
1590
2301
|
}
|
|
1591
2302
|
}
|
|
1592
2303
|
|
|
1593
|
-
export {
|
|
2304
|
+
export {
|
|
2305
|
+
readConfig,
|
|
2306
|
+
applyRoute,
|
|
2307
|
+
effectiveRouteOf,
|
|
2308
|
+
parseVersion,
|
|
2309
|
+
compareVersions,
|
|
2310
|
+
installedVersion,
|
|
2311
|
+
profileHint,
|
|
2312
|
+
delegationPolicyText,
|
|
2313
|
+
DEFAULT_PLANNING_KEYWORDS,
|
|
2314
|
+
DEFAULT_VISION_KEYWORDS,
|
|
2315
|
+
};
|