@darkbear9494/dsh-model-manager 0.2.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 +261 -39
- package/client.js +255 -1
- package/cordis.patch.yml +11 -0
- package/lib/index.js +734 -26
- 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', 'pick', 'roles', 'strategy'];
|
|
52
|
+
const KNOWN_TOP_KEYS = ['enabled', 'pick', 'roles', 'strategy', 'update'];
|
|
51
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
|
|
|
@@ -143,6 +190,13 @@ function buildConfigSchema(z) {
|
|
|
143
190
|
visionKeywords: z.array(z.string()).default(DEFAULT_VISION_KEYWORDS),
|
|
144
191
|
planningKeywords: z.array(z.string()).default(DEFAULT_PLANNING_KEYWORDS),
|
|
145
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),
|
|
146
200
|
});
|
|
147
201
|
|
|
148
202
|
/**
|
|
@@ -169,6 +223,12 @@ function buildConfigSchema(z) {
|
|
|
169
223
|
vision: RoleSchema.default({}),
|
|
170
224
|
}).default({}).volatile(),
|
|
171
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(),
|
|
172
232
|
});
|
|
173
233
|
}
|
|
174
234
|
|
|
@@ -237,11 +297,170 @@ function unknownKeys(source, known) {
|
|
|
237
297
|
return Object.keys(value).filter((key) => !known.includes(key));
|
|
238
298
|
}
|
|
239
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
|
+
|
|
240
458
|
/** Coerce raw row config into a total, always-usable shape. */
|
|
241
459
|
function readConfig(raw) {
|
|
242
460
|
const warnings = [];
|
|
243
461
|
const rolesRaw = readVal(raw?.roles) ?? {};
|
|
244
462
|
const strategyRaw = readVal(raw?.strategy) ?? {};
|
|
463
|
+
const updateRaw = readVal(raw?.update) ?? {};
|
|
245
464
|
|
|
246
465
|
for (const key of unknownKeys(raw, KNOWN_TOP_KEYS)) warnings.push(`unknown config key "${key}" ignored`);
|
|
247
466
|
for (const key of unknownKeys(rolesRaw, ROLE_NAMES)) warnings.push(`unknown role "${key}" ignored`);
|
|
@@ -253,6 +472,7 @@ function readConfig(raw) {
|
|
|
253
472
|
}
|
|
254
473
|
}
|
|
255
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`);
|
|
256
476
|
|
|
257
477
|
const readRole = (key) => {
|
|
258
478
|
const role = readVal(rolesRaw?.[key]) ?? {};
|
|
@@ -272,6 +492,7 @@ function readConfig(raw) {
|
|
|
272
492
|
|
|
273
493
|
const mode = strategyRaw.mode;
|
|
274
494
|
const limit = strategyRaw.historyLimit;
|
|
495
|
+
const autoDelegate = strategyRaw.autoDelegate;
|
|
275
496
|
return {
|
|
276
497
|
// Only an explicit `false` switches the manager off. A missing or malformed
|
|
277
498
|
// value keeps it on, so a typo can never silently disable routing.
|
|
@@ -286,6 +507,19 @@ function readConfig(raw) {
|
|
|
286
507
|
// Guard against a positive fraction flooring to 0, which would evict every
|
|
287
508
|
// record immediately and silently disable usage tracking.
|
|
288
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),
|
|
289
523
|
},
|
|
290
524
|
warnings,
|
|
291
525
|
};
|
|
@@ -449,6 +683,16 @@ const quoteLabel = (label) => {
|
|
|
449
683
|
return text.length > 42 ? `"${text.slice(0, 41)}…"` : `"${text}"`;
|
|
450
684
|
};
|
|
451
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
|
+
|
|
452
696
|
/**
|
|
453
697
|
* Build a keyword matcher.
|
|
454
698
|
*
|
|
@@ -465,6 +709,110 @@ function keywordMatcher(keywords) {
|
|
|
465
709
|
return (text) => patterns.some((pattern) => pattern.test(text));
|
|
466
710
|
}
|
|
467
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
|
+
|
|
468
816
|
// ---------------------------------------------------------------------------
|
|
469
817
|
// Engine
|
|
470
818
|
// ---------------------------------------------------------------------------
|
|
@@ -505,6 +853,27 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
505
853
|
/** session id -> `{ key: '<turn>:<step>', switches }`, the per-step budget. */
|
|
506
854
|
const stepSwitches = new Map();
|
|
507
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
|
+
|
|
508
877
|
const roleOf = (key) => config.roles[key];
|
|
509
878
|
|
|
510
879
|
let visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
@@ -527,7 +896,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
527
896
|
* counter itself stays per-role so each list rotates independently.
|
|
528
897
|
*
|
|
529
898
|
* `sessionId` selects the failover position for `pick: 'first'`, where the
|
|
530
|
-
* 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.
|
|
531
903
|
*/
|
|
532
904
|
function routeCandidate(key, sessionId) {
|
|
533
905
|
const models = effectiveModels(key);
|
|
@@ -543,19 +915,74 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
543
915
|
},
|
|
544
916
|
};
|
|
545
917
|
}
|
|
546
|
-
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);
|
|
547
919
|
return { route: models[at], commit() {} };
|
|
548
920
|
}
|
|
549
921
|
|
|
550
|
-
/**
|
|
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
|
+
*/
|
|
551
931
|
function classifySubagent(label) {
|
|
552
|
-
const text = String(label ?? '');
|
|
932
|
+
const text = String(label ?? '').trim();
|
|
553
933
|
if (text === '') return 'execution';
|
|
934
|
+
const lower = text.toLowerCase();
|
|
935
|
+
if (lower.startsWith('plan:')) return 'planning';
|
|
936
|
+
if (lower.startsWith('vision:')) return 'vision';
|
|
554
937
|
if (visionMatch(text)) return 'vision';
|
|
555
938
|
if (planningMatch(text)) return 'planning';
|
|
556
939
|
return 'execution';
|
|
557
940
|
}
|
|
558
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
|
+
|
|
559
986
|
function remember(sessionId, entry) {
|
|
560
987
|
const previous = usage.get(sessionId);
|
|
561
988
|
// Re-insert so the map stays in least-recently-used order for eviction.
|
|
@@ -830,7 +1257,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
830
1257
|
// to recover.
|
|
831
1258
|
const header = probe(() => agent.session?.requestHeader?.()?.config);
|
|
832
1259
|
const failedAt = header === undefined
|
|
833
|
-
? Math.min(failover.get(agent.id) ?? 0, models.length - 1)
|
|
1260
|
+
? Math.min(failover.get(failoverKey(agent.id, role)) ?? 0, models.length - 1)
|
|
834
1261
|
: models.findIndex((route) => route.provider === header.provider && route.model === header.model);
|
|
835
1262
|
if (failedAt < 0) return undefined;
|
|
836
1263
|
|
|
@@ -843,7 +1270,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
843
1270
|
if (!rotating && nextIndex === failedAt) return undefined;
|
|
844
1271
|
|
|
845
1272
|
if (rotating) roundRobin.set(owner, nextIndex);
|
|
846
|
-
else failover.set(agent.id, nextIndex);
|
|
1273
|
+
else failover.set(failoverKey(agent.id, role), nextIndex);
|
|
847
1274
|
budget.switches += 1;
|
|
848
1275
|
|
|
849
1276
|
const from = models[failedAt];
|
|
@@ -858,6 +1285,174 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
858
1285
|
}
|
|
859
1286
|
}
|
|
860
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
|
+
|
|
861
1456
|
// -- reporting ------------------------------------------------------------
|
|
862
1457
|
|
|
863
1458
|
/**
|
|
@@ -1076,7 +1671,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1076
1671
|
return 'No subagents observed yet in this process.\n\n'
|
|
1077
1672
|
+ 'Delegate some work, then run this report again. Model usage is recorded per\n'
|
|
1078
1673
|
+ 'delegation at request time, so it works whether routing applied or passed through.\n\n'
|
|
1079
|
-
+ 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()}` : '');
|
|
1080
1678
|
}
|
|
1081
1679
|
rows.sort((a, b) => String(a.childId).localeCompare(String(b.childId)));
|
|
1082
1680
|
const lines = [];
|
|
@@ -1147,6 +1745,11 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1147
1745
|
lines.push(` ${String(entry.requests).padStart(4)} req / ${String(entry.children).padStart(2)} subagent(s) ${key}`);
|
|
1148
1746
|
}
|
|
1149
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
|
+
}
|
|
1150
1753
|
return lines.join('\n');
|
|
1151
1754
|
}
|
|
1152
1755
|
|
|
@@ -1182,6 +1785,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1182
1785
|
+ (config.strategy.mode === 'managed' ? ' (always apply the role route)' : '')
|
|
1183
1786
|
+ (config.strategy.mode === 'advisory' ? ' (never rewrite — report only)' : ''),
|
|
1184
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
|
+
'',
|
|
1185
1794
|
allowListBlock(),
|
|
1186
1795
|
'',
|
|
1187
1796
|
visionBlock,
|
|
@@ -1191,6 +1800,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1191
1800
|
` vision : ${config.strategy.visionKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.visionKeywords.length > 8 ? ', …' : ''}`,
|
|
1192
1801
|
` planning : ${config.strategy.planningKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.planningKeywords.length > 8 ? ', …' : ''}`,
|
|
1193
1802
|
' else : execution',
|
|
1803
|
+
'',
|
|
1804
|
+
updateStatusLine(),
|
|
1194
1805
|
].join('\n');
|
|
1195
1806
|
}
|
|
1196
1807
|
|
|
@@ -1203,13 +1814,22 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1203
1814
|
})
|
|
1204
1815
|
.filter(Boolean);
|
|
1205
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
|
+
: '';
|
|
1206
1827
|
return [
|
|
1207
1828
|
'## Model manager',
|
|
1208
1829
|
'Delegated work is routed by the label you give each delegation:',
|
|
1209
1830
|
...summary,
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
'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}`,
|
|
1213
1833
|
].join('\n');
|
|
1214
1834
|
}
|
|
1215
1835
|
|
|
@@ -1406,10 +2026,15 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1406
2026
|
|
|
1407
2027
|
// Drop per-session failover state when its agent goes away, so a long-lived
|
|
1408
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.
|
|
1409
2030
|
ctx.on('agent/disposed', (payload) => {
|
|
1410
2031
|
const id = payload?.agent?.id ?? (typeof payload === 'string' ? payload : payload?.id);
|
|
1411
2032
|
if (typeof id !== 'string') return;
|
|
1412
2033
|
failover.delete(id);
|
|
2034
|
+
const prefix = `${id}::`;
|
|
2035
|
+
for (const key of [...failover.keys()]) {
|
|
2036
|
+
if (key.startsWith(prefix)) failover.delete(key);
|
|
2037
|
+
}
|
|
1413
2038
|
stepSwitches.delete(id);
|
|
1414
2039
|
});
|
|
1415
2040
|
|
|
@@ -1426,12 +2051,25 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1426
2051
|
// boot-time one until restart. DSH's own volatile plugins do the same.
|
|
1427
2052
|
ctx.on('loader/volatile-update', () => {
|
|
1428
2053
|
try {
|
|
2054
|
+
const previousUpdate = config.update;
|
|
1429
2055
|
const next = readConfig(rawConfig);
|
|
1430
|
-
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
|
+
};
|
|
1431
2064
|
visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
1432
2065
|
planningMatch = keywordMatcher(config.strategy.planningKeywords);
|
|
1433
2066
|
for (const warning of config.warnings) log('warn', warning);
|
|
1434
|
-
|
|
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}; `
|
|
1435
2073
|
+ ROLE_NAMES
|
|
1436
2074
|
.map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
|
|
1437
2075
|
.join(' '));
|
|
@@ -1442,6 +2080,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1442
2080
|
|
|
1443
2081
|
if (typeof ctx.inject === 'function') {
|
|
1444
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;
|
|
1445
2086
|
try {
|
|
1446
2087
|
scoped.tools.register({
|
|
1447
2088
|
name: 'model_manager',
|
|
@@ -1451,19 +2092,24 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1451
2092
|
+ 'composer, then one row per subagent with its label, role, reason, live status and '
|
|
1452
2093
|
+ 'totals. action "routes": the four role assignments '
|
|
1453
2094
|
+ '(including the vision->execution fallback), the shared selection strategy (first or round-robin), '
|
|
1454
|
-
+ 'the active distribution mode,
|
|
2095
|
+
+ 'the active distribution mode, the auto-delegation level, the update-check status, '
|
|
2096
|
+
+ 'and whether each '
|
|
1455
2097
|
+ 'route is dispatchable by the delegation tool, with the YAML to add any that are not. '
|
|
1456
2098
|
+ 'action "usage": request and subagent counts by role and model across the whole process. '
|
|
1457
2099
|
+ 'action "client": whether the Host composed this plugin\'s Web client half into the browser '
|
|
1458
2100
|
+ 'boot graph, the route serving its bundle, and the current graph revision — use it when the '
|
|
1459
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. '
|
|
1460
2106
|
+ 'Read-only; it never changes routing.',
|
|
1461
2107
|
parameters: {
|
|
1462
2108
|
type: 'object',
|
|
1463
2109
|
properties: {
|
|
1464
2110
|
action: {
|
|
1465
2111
|
type: 'string',
|
|
1466
|
-
enum: ['report', 'routes', 'usage', 'client'],
|
|
2112
|
+
enum: ['report', 'routes', 'usage', 'client', 'update'],
|
|
1467
2113
|
description: 'What to return. Defaults to "report".',
|
|
1468
2114
|
},
|
|
1469
2115
|
},
|
|
@@ -1477,6 +2123,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1477
2123
|
const action = args?.action ?? 'report';
|
|
1478
2124
|
if (action === 'routes') return routes();
|
|
1479
2125
|
if (action === 'client') return clientStatus();
|
|
2126
|
+
if (action === 'update') return updateAction();
|
|
1480
2127
|
if (action === 'usage') {
|
|
1481
2128
|
await refreshCatalog();
|
|
1482
2129
|
const totals = new Map();
|
|
@@ -1525,11 +2172,42 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1525
2172
|
|
|
1526
2173
|
ctx.inject(['systemPrompt'], (scoped) => {
|
|
1527
2174
|
try {
|
|
1528
|
-
const register = () =>
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
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
|
+
};
|
|
1533
2211
|
if (typeof scoped.effect === 'function') scoped.effect(register);
|
|
1534
2212
|
else register();
|
|
1535
2213
|
} catch (error) {
|
|
@@ -1573,9 +2251,23 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1573
2251
|
+ `${broken.map((row) => row.label).join(', ')}. Point roles.vision.models at an image-capable model.`);
|
|
1574
2252
|
}
|
|
1575
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();
|
|
1576
2258
|
}
|
|
1577
2259
|
|
|
1578
|
-
return {
|
|
2260
|
+
return {
|
|
2261
|
+
attach,
|
|
2262
|
+
classifySubagent,
|
|
2263
|
+
classifyAndRoute: routeCandidate,
|
|
2264
|
+
roleTable,
|
|
2265
|
+
routes,
|
|
2266
|
+
report,
|
|
2267
|
+
delegationPolicy,
|
|
2268
|
+
checkForUpdate,
|
|
2269
|
+
updateStatusLine,
|
|
2270
|
+
};
|
|
1579
2271
|
}
|
|
1580
2272
|
|
|
1581
2273
|
// ---------------------------------------------------------------------------
|
|
@@ -1595,13 +2287,29 @@ export function apply(ctx, rawConfig) {
|
|
|
1595
2287
|
for (const warning of config.warnings) log('warn', warning);
|
|
1596
2288
|
const engine = createEngine(config, ctx, log, rawConfig);
|
|
1597
2289
|
engine.attach();
|
|
1598
|
-
log('info', `active — mode ${config.strategy.mode}, pick ${config.pick}; `
|
|
2290
|
+
log('info', `active — mode ${config.strategy.mode}, pick ${config.pick}, autoDelegate ${config.strategy.autoDelegate}; `
|
|
1599
2291
|
+ ROLE_NAMES
|
|
1600
2292
|
.map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
|
|
1601
|
-
.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'));
|
|
1602
2299
|
} catch (error) {
|
|
1603
2300
|
log('error', `failed to initialise; model routing is disabled: ${error?.stack ?? error}`);
|
|
1604
2301
|
}
|
|
1605
2302
|
}
|
|
1606
2303
|
|
|
1607
|
-
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
|
+
};
|