@darkbear9494/dsh-model-manager 0.2.0 → 0.5.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/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', 'planningSkills', '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
- 'figure', 'diagram', 'chart', 'plot', 'photo', 'picture', 'png', 'jpg',
155
+ 'diagram', 'chart', 'plot', 'photo', 'picture', 'png', 'jpg',
109
156
  'jpeg', 'webp', 'gif', 'ui mock', 'render',
110
157
  ];
111
158
 
@@ -116,6 +163,85 @@ const DEFAULT_PLANNING_KEYWORDS = [
116
163
  'spec', 'specification', 'decompose', 'breakdown', 'proposal', 'root cause',
117
164
  ];
118
165
 
166
+ /**
167
+ * Skills that put a top-level session on the planning tier.
168
+ *
169
+ * These are interactive thinking skills: a session that invokes one is doing
170
+ * design/review work for its whole life, exactly like a session in plan mode,
171
+ * so it should run on the planning role's more capable models rather than
172
+ * `main`. `grill-me` is the user-facing alias that loads `grilling`, so both
173
+ * names are listed. An empty list disables the trigger.
174
+ */
175
+ const DEFAULT_PLANNING_SKILLS = ['grill-me', 'grilling'];
176
+
177
+ /**
178
+ * The public DSH skill-name grammar and the `/name` gesture the harness scans
179
+ * for in direct user text.
180
+ *
181
+ * Kept byte-identical to `@deepseek-ai/dsh-tool-skill`'s `SKILL_NAME` and
182
+ * `SKILL_GESTURE` (dsh-tool-skill/lib/index.js): the manager must recognise
183
+ * exactly the gestures the harness itself turns into a skill invocation.
184
+ */
185
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
186
+ const SKILL_GESTURE = /(^|\s)\/([a-z0-9]+(?:-[a-z0-9]+)*)(?=\s|$)/g;
187
+
188
+ /**
189
+ * Names of the skills one user message records, in order. Pure.
190
+ *
191
+ * `source.kind === 'skill-invocation'` is the canonical record of a user's
192
+ * `/name` invocation (DSH's own validated injection). The `/name` gesture in
193
+ * direct user text is scanned too, with the harness's exact grammar, so the
194
+ * intent is visible to `agent/pre-step` in the same step that carries it —
195
+ * before the injection exists and before any event is committed.
196
+ */
197
+ function skillNamesOfMessage(message) {
198
+ if (message === null || typeof message !== 'object') return [];
199
+ const source = message.source;
200
+ if (source?.kind === 'skill-invocation') {
201
+ return typeof source.name === 'string' ? [source.name] : [];
202
+ }
203
+ if (source?.kind !== 'user') return [];
204
+ const names = [];
205
+ for (const block of Array.isArray(message.content) ? message.content : []) {
206
+ if (block === null || typeof block !== 'object') continue;
207
+ if (block.type !== 'text' || typeof block.text !== 'string') continue;
208
+ for (const match of block.text.matchAll(SKILL_GESTURE)) {
209
+ if (match[2] !== undefined) names.push(match[2]);
210
+ }
211
+ }
212
+ return names;
213
+ }
214
+
215
+ /**
216
+ * Names of the skills one durable event records, in event order. Pure, so both
217
+ * the projection fold and the pre-step scan are unit-testable without a session.
218
+ *
219
+ * Three records count, because DSH writes each of them before the request it
220
+ * influences:
221
+ * - a user-invoked skill's injected `user/message` (`source.kind ===
222
+ * 'skill-invocation'`, `source.name`) — the canonical record;
223
+ * - the `/name` gesture in direct user text (the same message helper);
224
+ * - a model-invoked `skill` tool call (`tool/call`, name `skill`, JSON
225
+ * arguments), so "grill me on this" without a slash escalates on the next
226
+ * request of the same session.
227
+ */
228
+ function skillNamesOfEvent(event) {
229
+ if (event === null || typeof event !== 'object') return [];
230
+ if (event.type === 'user/message') return skillNamesOfMessage(event.data);
231
+ if (event.type === 'tool/call') {
232
+ const data = event.data;
233
+ if (data?.name !== 'skill' || typeof data.arguments !== 'string') return [];
234
+ let args;
235
+ try {
236
+ args = JSON.parse(data.arguments);
237
+ } catch {
238
+ return [];
239
+ }
240
+ return typeof args?.name === 'string' ? [args.name] : [];
241
+ }
242
+ return [];
243
+ }
244
+
119
245
  // ---------------------------------------------------------------------------
120
246
  // Config
121
247
  // ---------------------------------------------------------------------------
@@ -142,7 +268,15 @@ function buildConfigSchema(z) {
142
268
  mode: z.union([z.const('hybrid'), z.const('managed'), z.const('advisory')]).default('hybrid'),
143
269
  visionKeywords: z.array(z.string()).default(DEFAULT_VISION_KEYWORDS),
144
270
  planningKeywords: z.array(z.string()).default(DEFAULT_PLANNING_KEYWORDS),
271
+ planningSkills: z.array(z.string()).default(DEFAULT_PLANNING_SKILLS),
145
272
  historyLimit: z.number().default(300),
273
+ autoDelegate: z.union([z.const('off'), z.const('balanced'), z.const('eager')]).default('balanced'),
274
+ });
275
+
276
+ const UpdateSchema = z.object({
277
+ enabled: z.boolean().default(true),
278
+ registry: z.string().default(UPDATE_REGISTRY_DEFAULT),
279
+ intervalHours: z.number().default(24),
146
280
  });
147
281
 
148
282
  /**
@@ -169,6 +303,12 @@ function buildConfigSchema(z) {
169
303
  vision: RoleSchema.default({}),
170
304
  }).default({}).volatile(),
171
305
  strategy: StrategySchema.default({}).volatile(),
306
+ /**
307
+ * Automatic update check against the package registry. Checked once shortly
308
+ * after boot, then on the interval; a newer release is logged, surfaced by
309
+ * the `model_manager` tool (action "update") and reported by `routes`.
310
+ */
311
+ update: UpdateSchema.default({}).volatile(),
172
312
  });
173
313
  }
174
314
 
@@ -221,6 +361,28 @@ function asStringArray(value, fallback) {
221
361
  .filter((item) => item !== '');
222
362
  }
223
363
 
364
+ /**
365
+ * Normalize the `planningSkills` list.
366
+ *
367
+ * Same shape as the keyword lists: an absent or malformed value takes the
368
+ * built-in default, while an explicit `[]` is honoured and disables the
369
+ * trigger. Names are lowercased (the DSH skill grammar is lowercase) and
370
+ * non-kebab entries are dropped, so a typo can never match a session by
371
+ * accident.
372
+ */
373
+ function normalizeSkillNames(value) {
374
+ const raw = readVal(value);
375
+ if (!Array.isArray(raw)) return [...DEFAULT_PLANNING_SKILLS];
376
+ const names = [];
377
+ for (const item of raw) {
378
+ if (typeof item !== 'string') continue;
379
+ const name = item.trim().toLowerCase();
380
+ if (name === '' || !SKILL_NAME.test(name) || names.includes(name)) continue;
381
+ names.push(name);
382
+ }
383
+ return names;
384
+ }
385
+
224
386
  function normalizeRoute(raw) {
225
387
  const value = readVal(raw);
226
388
  if (value === null || typeof value !== 'object') return undefined;
@@ -237,11 +399,170 @@ function unknownKeys(source, known) {
237
399
  return Object.keys(value).filter((key) => !known.includes(key));
238
400
  }
239
401
 
402
+ // ---------------------------------------------------------------------------
403
+ // Versions
404
+ // ---------------------------------------------------------------------------
405
+
406
+ /** A strict semver-shaped version: `v?MAJOR.MINOR.PATCH[-prerelease][+build]`. */
407
+ const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-((?:[0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/;
408
+
409
+ /**
410
+ * Parse a semver-shaped version string.
411
+ *
412
+ * Both sides of the update comparison come from `package.json` fields (this
413
+ * package's own and the registry packument's `dist-tags.latest`), so a strict
414
+ * shape check is enough: anything else is reported unparseable rather than
415
+ * guessed at.
416
+ * @returns `{ major, minor, patch, prerelease }` or `undefined`.
417
+ */
418
+ function parseVersion(input) {
419
+ if (typeof input !== 'string') return undefined;
420
+ const match = VERSION_RE.exec(input.trim());
421
+ if (match === null) return undefined;
422
+ const major = Number(match[1]);
423
+ const minor = Number(match[2]);
424
+ const patch = Number(match[3]);
425
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
426
+ return undefined;
427
+ }
428
+ const prerelease = match[4] === undefined || match[4] === '' ? [] : match[4].split('.');
429
+ return { major, minor, patch, prerelease };
430
+ }
431
+
432
+ /**
433
+ * Compare two prerelease identifier lists per semver: numeric identifiers
434
+ * compare numerically and sort below alphanumeric ones, alphanumeric compare
435
+ * in ASCII order, and a shorter list sorts below a longer one when it is a
436
+ * prefix of it. An empty list (no prerelease) sorts ABOVE any prerelease.
437
+ */
438
+ function comparePrerelease(a, b) {
439
+ if (a.length === 0 && b.length === 0) return 0;
440
+ if (a.length === 0) return 1;
441
+ if (b.length === 0) return -1;
442
+ for (let index = 0; index < a.length || index < b.length; index += 1) {
443
+ const x = a[index];
444
+ const y = b[index];
445
+ if (x === undefined) return -1;
446
+ if (y === undefined) return 1;
447
+ const xNumeric = /^\d+$/.test(x);
448
+ const yNumeric = /^\d+$/.test(y);
449
+ if (xNumeric && yNumeric) {
450
+ if (Number(x) !== Number(y)) return Number(x) < Number(y) ? -1 : 1;
451
+ } else if (xNumeric) return -1;
452
+ else if (yNumeric) return 1;
453
+ else if (x !== y) return x < y ? -1 : 1;
454
+ }
455
+ return 0;
456
+ }
457
+
458
+ /**
459
+ * Compare two version strings, semver-style including prereleases.
460
+ * @returns `-1 | 0 | 1`, or `undefined` when either side does not parse.
461
+ */
462
+ function compareVersions(a, b) {
463
+ const left = parseVersion(a);
464
+ const right = parseVersion(b);
465
+ if (left === undefined || right === undefined) return undefined;
466
+ if (left.major !== right.major) return left.major < right.major ? -1 : 1;
467
+ if (left.minor !== right.minor) return left.minor < right.minor ? -1 : 1;
468
+ if (left.patch !== right.patch) return left.patch < right.patch ? -1 : 1;
469
+ return comparePrerelease(left.prerelease, right.prerelease);
470
+ }
471
+
472
+ /** Cached own version, read from this package's `package.json`. `null` = unreadable. */
473
+ let cachedInstalledVersion;
474
+
475
+ /**
476
+ * This package's own version, straight from its `package.json`.
477
+ *
478
+ * Read from the manifest next to `lib/index.js` rather than hardcoded, so a
479
+ * git checkout, an npm install and a tarball install all report what actually
480
+ * shipped — the version in `client.js` is a pinned fallback for the browser
481
+ * only, and a packaging test keeps the two equal.
482
+ * @returns {string | null}
483
+ */
484
+ function installedVersion() {
485
+ if (cachedInstalledVersion !== undefined) return cachedInstalledVersion;
486
+ let version;
487
+ try {
488
+ const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
489
+ if (typeof manifest.version === 'string' && manifest.version.trim() !== '') {
490
+ version = manifest.version.trim();
491
+ }
492
+ } catch {
493
+ version = undefined;
494
+ }
495
+ cachedInstalledVersion = version ?? null;
496
+ return cachedInstalledVersion;
497
+ }
498
+
499
+ /**
500
+ * The profile name this process booted, from the host's working directory
501
+ * (`$DSH_HOME/profiles/<name>` per the harness's own docs), so the upgrade
502
+ * command can be printed ready to paste. `undefined` when the layout does not
503
+ * match; the command then shows a `<profile>` placeholder instead.
504
+ */
505
+ function profileHint() {
506
+ try {
507
+ const segments = process.cwd().split(/[\\/]/).filter((segment) => segment !== '');
508
+ const at = segments.lastIndexOf('profiles');
509
+ if (at >= 0 && at + 1 < segments.length) return segments[at + 1];
510
+ } catch {
511
+ /* fall through to the placeholder */
512
+ }
513
+ return undefined;
514
+ }
515
+
516
+ /** An abort signal that fires after `ms`, on whatever abort API exists. */
517
+ function timeoutSignal(ms) {
518
+ try {
519
+ if (typeof AbortSignal?.timeout === 'function') return AbortSignal.timeout(ms);
520
+ } catch {
521
+ /* fall through to the manual controller */
522
+ }
523
+ if (typeof AbortController !== 'function') return undefined;
524
+ const controller = new AbortController();
525
+ const timer = setTimeout(() => {
526
+ try {
527
+ controller.abort(new Error(`timed out after ${ms}ms`));
528
+ } catch {
529
+ controller.abort();
530
+ }
531
+ }, ms);
532
+ if (typeof timer?.unref === 'function') timer.unref();
533
+ return controller.signal;
534
+ }
535
+
536
+ /**
537
+ * Sanitize a configured registry URL: trim, drop trailing slashes, and keep
538
+ * only http(s) origins. Anything else falls back to the npm default.
539
+ */
540
+ function sanitizeRegistry(value) {
541
+ const text = typeof value === 'string' ? value.trim() : '';
542
+ if (!/^https?:\/\//i.test(text)) return UPDATE_REGISTRY_DEFAULT;
543
+ return text.replace(/\/+$/, '');
544
+ }
545
+
546
+ /**
547
+ * Normalize `update.intervalHours`.
548
+ *
549
+ * Absent, malformed or negative values mean the 24h default; an explicit `0`
550
+ * is honoured as "check at boot only" — `enabled: false` is the off switch.
551
+ */
552
+ function normalizeIntervalHours(value) {
553
+ const raw = readVal(value);
554
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return 24;
555
+ if (raw === 0) return 0;
556
+ if (raw < 0) return 24;
557
+ return raw;
558
+ }
559
+
240
560
  /** Coerce raw row config into a total, always-usable shape. */
241
561
  function readConfig(raw) {
242
562
  const warnings = [];
243
563
  const rolesRaw = readVal(raw?.roles) ?? {};
244
564
  const strategyRaw = readVal(raw?.strategy) ?? {};
565
+ const updateRaw = readVal(raw?.update) ?? {};
245
566
 
246
567
  for (const key of unknownKeys(raw, KNOWN_TOP_KEYS)) warnings.push(`unknown config key "${key}" ignored`);
247
568
  for (const key of unknownKeys(rolesRaw, ROLE_NAMES)) warnings.push(`unknown role "${key}" ignored`);
@@ -253,6 +574,7 @@ function readConfig(raw) {
253
574
  }
254
575
  }
255
576
  for (const key of unknownKeys(strategyRaw, KNOWN_STRATEGY_KEYS)) warnings.push(`unknown key "strategy.${key}" ignored`);
577
+ for (const key of unknownKeys(updateRaw, KNOWN_UPDATE_KEYS)) warnings.push(`unknown key "update.${key}" ignored`);
256
578
 
257
579
  const readRole = (key) => {
258
580
  const role = readVal(rolesRaw?.[key]) ?? {};
@@ -272,6 +594,7 @@ function readConfig(raw) {
272
594
 
273
595
  const mode = strategyRaw.mode;
274
596
  const limit = strategyRaw.historyLimit;
597
+ const autoDelegate = strategyRaw.autoDelegate;
275
598
  return {
276
599
  // Only an explicit `false` switches the manager off. A missing or malformed
277
600
  // value keeps it on, so a typo can never silently disable routing.
@@ -283,9 +606,25 @@ function readConfig(raw) {
283
606
  mode: mode === 'managed' || mode === 'advisory' ? mode : 'hybrid',
284
607
  visionKeywords: asStringArray(strategyRaw.visionKeywords, DEFAULT_VISION_KEYWORDS),
285
608
  planningKeywords: asStringArray(strategyRaw.planningKeywords, DEFAULT_PLANNING_KEYWORDS),
609
+ // Absent/malformed -> the grill defaults; explicit [] switches the
610
+ // skill-to-planning escalation off.
611
+ planningSkills: normalizeSkillNames(strategyRaw.planningSkills),
286
612
  // Guard against a positive fraction flooring to 0, which would evict every
287
613
  // record immediately and silently disable usage tracking.
288
614
  historyLimit: Number.isFinite(limit) && limit > 0 ? Math.max(1, Math.floor(limit)) : 300,
615
+ // The delegation-policy level; anything unrecognised falls back to the
616
+ // default level rather than silently switching the policy off.
617
+ autoDelegate: autoDelegate === 'off' || autoDelegate === 'eager' || autoDelegate === 'balanced'
618
+ ? autoDelegate
619
+ : 'balanced',
620
+ },
621
+ update: {
622
+ // Same fail-on philosophy as the master switch: only explicit `false`
623
+ // stops the checks.
624
+ enabled: readVal(updateRaw.enabled) !== false,
625
+ registry: sanitizeRegistry(readVal(updateRaw.registry)),
626
+ // Absent/malformed -> 24h; explicit 0 -> boot-only checks.
627
+ intervalHours: normalizeIntervalHours(updateRaw.intervalHours),
289
628
  },
290
629
  warnings,
291
630
  };
@@ -449,6 +788,16 @@ const quoteLabel = (label) => {
449
788
  return text.length > 42 ? `"${text.slice(0, 41)}…"` : `"${text}"`;
450
789
  };
451
790
 
791
+ /**
792
+ * Key of a failover cursor: per (session, role), never per session alone.
793
+ *
794
+ * A session can serve different roles over its life — plan mode moves the
795
+ * top-level agent between `main` and `planning` on every request — and the
796
+ * roles' chains are independent lists. Keying by session only let one role's
797
+ * wear push every other role off its first model.
798
+ */
799
+ const failoverKey = (sessionId, role) => `${sessionId}::${role}`;
800
+
452
801
  /**
453
802
  * Build a keyword matcher.
454
803
  *
@@ -465,6 +814,110 @@ function keywordMatcher(keywords) {
465
814
  return (text) => patterns.some((pattern) => pattern.test(text));
466
815
  }
467
816
 
817
+ // ---------------------------------------------------------------------------
818
+ // Delegation policy text
819
+ // ---------------------------------------------------------------------------
820
+
821
+ /**
822
+ * Render the model-facing delegation policy for one level.
823
+ *
824
+ * Pure on purpose: the decision *whether* to render (config, agent lineage,
825
+ * tool availability) lives in the engine's `delegationPolicy`, so this text is
826
+ * directly unit-testable and the engine only ever swaps the level, the
827
+ * available tool names, and which tiers actually have models behind the labels
828
+ * it teaches — a tier with no configured route is never advertised.
829
+ *
830
+ * @param {'balanced' | 'eager'} level - the policy level.
831
+ * @param {string[]} toolNames - delegation tools the target agent actually has.
832
+ * @param {{ planning?: boolean, vision?: boolean, routed?: boolean }} [opts]
833
+ * `planning` / `vision`: whether that tier has models to route to (both
834
+ * default to true, so a bare caller keeps the full text). `routed`:
835
+ * whether a label can actually change the model — false under
836
+ * `advisory`, where warning about `provider`/`model` would be noise
837
+ * because nothing is routed at all.
838
+ * @returns {string} the policy, or `''` when there is nothing to say.
839
+ */
840
+ function delegationPolicyText(level, toolNames, opts) {
841
+ const has = (name) => toolNames.includes(name);
842
+ const subagent = has('subagent') || has('subagent_fork');
843
+ if (!subagent) return '';
844
+ const planning = opts?.planning !== false;
845
+ const vision = opts?.vision !== false;
846
+ const routed = opts?.routed !== false;
847
+ const fork = has('subagent_fork')
848
+ ? ' Prefer `subagent_fork` when a unit needs this conversation\'s own context.'
849
+ : '';
850
+ const subagentTool = has('subagent') ? '`subagent`' : '`subagent_fork`';
851
+ const planTag = planning ? ' as a `plan:` unit' : ' to a delegation';
852
+ const head = level === 'eager'
853
+ ? [
854
+ '## Delegation policy (model-manager, eager)',
855
+ '',
856
+ 'You are the orchestrator: decomposition, dispatch, and synthesis are your job, and',
857
+ 'nearly all substantive work — research, analysis, implementation, review, verification —',
858
+ 'belongs in delegations.',
859
+ '',
860
+ `- Decompose the request into self-contained units before doing anything else, the`,
861
+ ` decomposition itself going out${planTag}, and dispatch them as ${subagentTool}`,
862
+ ` delegations, several in a single message when they are independent.${fork}`,
863
+ '- Do work yourself only when no delegation can carry it: a single trivial step, or an',
864
+ ' action that requires this session\'s interactive tools (approvals, user questions).',
865
+ '- Collect results as delegations finish, verify each one, re-delegate what missed, and',
866
+ ' synthesize the final answer from what came back.',
867
+ ]
868
+ : [
869
+ '## Delegation policy (model-manager, balanced)',
870
+ '',
871
+ 'Default to solving substantive work through subagents instead of doing it all yourself.',
872
+ '',
873
+ '- Plan first: when a task needs more than a few steps, delegate the decomposition',
874
+ ` itself${planTag}, then dispatch the units it returned — research, analysis,`,
875
+ ' implementation of separate areas, review, verification — together.',
876
+ `- Dispatch each unit as a ${subagentTool} delegation — independent units go together in`,
877
+ ` a single message — and continue useful work while they run.${fork}`,
878
+ '- Keep for yourself what does not pay to delegate: coordination, single-step reads or',
879
+ ' tiny edits, decisions that need the user, and the final synthesis of every result.',
880
+ '- Verify what delegations return before presenting it as done; re-delegate or fix',
881
+ ' yourself when a result misses.',
882
+ ];
883
+ const tierLines = [
884
+ planning
885
+ ? '- `plan:` — the unit has to be thought through before it is done: design, analysis,'
886
+ + '\n research, decomposition, review, trade-offs.'
887
+ : '',
888
+ vision
889
+ ? '- `vision:` — the unit reads images, screenshots, diagrams, or OCRs a picture.'
890
+ : '',
891
+ '- plain — mechanical execution: edits, lookups, formatting, straightforward commands.',
892
+ ].filter(Boolean);
893
+ const taught = [planning ? '`plan:`' : '', vision ? '`vision:`' : ''].filter(Boolean).join('/');
894
+ const matchLines = [];
895
+ if (planning && vision) {
896
+ matchLines.push(
897
+ '- A leading prefix decides the tier; a label without one falls back to keyword',
898
+ ' matching, and a keyword label that fits both tiers goes to `vision`.',
899
+ );
900
+ } else if (planning || vision) {
901
+ matchLines.push(
902
+ '- A leading prefix decides the tier; a label without one falls back to keyword matching.',
903
+ );
904
+ }
905
+ if ((planning || vision) && routed) {
906
+ matchLines.push(
907
+ `- Omit \`provider\` and \`model\` on ${taught} units — a route named explicitly`,
908
+ ' on the delegation overrides the tier.',
909
+ );
910
+ }
911
+ return [
912
+ ...head,
913
+ '',
914
+ 'Label each delegation by the kind of work it carries — the label picks the model:',
915
+ ...tierLines,
916
+ ...matchLines,
917
+ '- Never invent results for delegations that have not answered; wait for or collect them.',
918
+ ].join('\n');
919
+ }
920
+
468
921
  // ---------------------------------------------------------------------------
469
922
  // Engine
470
923
  // ---------------------------------------------------------------------------
@@ -505,11 +958,139 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
505
958
  /** session id -> `{ key: '<turn>:<step>', switches }`, the per-step budget. */
506
959
  const stepSwitches = new Map();
507
960
 
961
+ /**
962
+ * The `tools` service, captured when its injection resolves, so the
963
+ * delegation-policy section can ask which delegation tools an assembly's
964
+ * scope actually sees (`tools.get(name, scope)`) — the same probe
965
+ * dsh-tool-subagent's own prompt section uses.
966
+ */
967
+ let toolsService;
968
+
969
+ /**
970
+ * Latest update-check outcome. Statuses: `idle` (not yet checked), `checking`,
971
+ * `ok` (up to date), `available` (a newer release exists), `error` (the check
972
+ * failed), `disabled` (checks switched off in config).
973
+ */
974
+ let updateState = { status: 'idle' };
975
+
976
+ /** Coalesces concurrent update checks. */
977
+ let updateInFlight;
978
+
979
+ /** Fallback timer handles for the update schedule, cleared when re-armed. */
980
+ let updateTimers = [];
981
+
508
982
  const roleOf = (key) => config.roles[key];
509
983
 
510
984
  let visionMatch = keywordMatcher(config.strategy.visionKeywords);
511
985
  let planningMatch = keywordMatcher(config.strategy.planningKeywords);
512
986
 
987
+ /**
988
+ * How many sessions' live skill names are remembered, and how many names one
989
+ * session keeps. Both are backstops: `agent/disposed` is the normal cleanup,
990
+ * and a session only ever invokes a handful of skills.
991
+ */
992
+ const LIVE_SKILL_LIMIT = 1024;
993
+ const SKILL_NAME_LIMIT = 64;
994
+
995
+ /**
996
+ * session id -> skill names seen in `agent/pre-step` batches this process.
997
+ *
998
+ * This is the signal that makes the FIRST request of a `/grilling` step route
999
+ * as planning. The harness fires `agent/pre-step` before `agent/request` but
1000
+ * commits the step's user batch (including the skill injection) only after
1001
+ * `agent/request` returns (`dsh-agent-loop`: `preStep()` → `prepareRequest()`
1002
+ * → `session.append('user/message')`), so a log-only fold would serve the
1003
+ * first — and most important — request of the grilling turn on `main`.
1004
+ */
1005
+ const liveSkills = new Map();
1006
+
1007
+ /** session id -> the last top-level trigger, so the info log fires once per switch. */
1008
+ const topTriggers = new Map();
1009
+
1010
+ /** Add one skill name to a session's live list, bounded and de-duplicated. */
1011
+ function addLiveSkill(id, name) {
1012
+ const normalized = typeof name === 'string' ? name.trim().toLowerCase() : '';
1013
+ if (normalized === '' || !SKILL_NAME.test(normalized)) return;
1014
+ let names = liveSkills.get(id);
1015
+ if (names === undefined) {
1016
+ names = [];
1017
+ liveSkills.set(id, names);
1018
+ while (liveSkills.size > LIVE_SKILL_LIMIT) {
1019
+ const oldest = liveSkills.keys().next().value;
1020
+ if (oldest === undefined) break;
1021
+ liveSkills.delete(oldest);
1022
+ }
1023
+ }
1024
+ if (names.length >= SKILL_NAME_LIMIT || names.includes(normalized)) return;
1025
+ names.push(normalized);
1026
+ }
1027
+
1028
+ /**
1029
+ * The planning skill currently in force for this agent, or `undefined`.
1030
+ *
1031
+ * Two sources are consulted. The live map covers the request that carries the
1032
+ * gesture itself; the `modelManagerPlanningSkill` projection is folded from
1033
+ * the durable log, so the trigger survives restart, resume and fork, and also
1034
+ * catches a model-invoked `skill` tool call on a later request. A skill stays
1035
+ * in force for the rest of the session: its instructions remain in context,
1036
+ * and the grilling interview spans many turns. Membership is read from the
1037
+ * live config on every request, so a Settings edit (or `[]`) applies to the
1038
+ * next request with no restart.
1039
+ */
1040
+ function planningSkillFor(agent) {
1041
+ const wanted = config.strategy.planningSkills;
1042
+ if (wanted.length === 0) return undefined;
1043
+ const names = [];
1044
+ const live = typeof agent?.id === 'string' ? liveSkills.get(agent.id) : undefined;
1045
+ if (Array.isArray(live)) names.push(...live);
1046
+ const state = probe(() => projections?.stateOf?.(agent?.session, PLANNING_SKILL_PROJECTION_KEY));
1047
+ if (Array.isArray(state?.skills)) names.push(...state.skills);
1048
+ for (let index = names.length - 1; index >= 0; index -= 1) {
1049
+ const name = names[index];
1050
+ if (name !== undefined && wanted.includes(name)) return name;
1051
+ }
1052
+ return undefined;
1053
+ }
1054
+
1055
+ /**
1056
+ * Observe every pre-step batch and remember any skill it names.
1057
+ *
1058
+ * Registered with `{ prepend: true }` so its `await next()` returns the
1059
+ * decision *with* the harness's own skill injections (tool-skill registers as
1060
+ * an inner hook), and so the claimed direct user text — the `/grilling`
1061
+ * gesture — is visible even if that injection is unavailable. The decision is
1062
+ * returned untouched; anything this observer does must never fail a step.
1063
+ */
1064
+ async function onPreStep(payload, next) {
1065
+ const decision = await next();
1066
+ try {
1067
+ const id = typeof payload?.agent?.id === 'string' ? payload.agent.id : undefined;
1068
+ if (id !== undefined && decision?.kind !== 'reject') {
1069
+ for (const batch of [payload?.messages, decision?.messages]) {
1070
+ if (!Array.isArray(batch)) continue;
1071
+ for (const message of batch) {
1072
+ for (const name of skillNamesOfMessage(message)) addLiveSkill(id, name);
1073
+ }
1074
+ }
1075
+ }
1076
+ } catch {
1077
+ // Observe-only: a hostile message shape must never fail the step.
1078
+ }
1079
+ return decision;
1080
+ }
1081
+
1082
+ /** Log a top-level trigger once per switch, never once per request. */
1083
+ function noteTopTrigger(agent, trigger) {
1084
+ const id = typeof agent?.id === 'string' ? agent.id : undefined;
1085
+ if (id === undefined) return;
1086
+ if (topTriggers.get(id) === trigger) return;
1087
+ topTriggers.set(id, trigger);
1088
+ if (trigger.startsWith('skill:')) {
1089
+ log('info', `planning skill "${trigger.slice('skill:'.length)}" is active in this session; `
1090
+ + 'top-level requests route as planning');
1091
+ }
1092
+ }
1093
+
513
1094
  /** The model list a role actually resolves to, including the vision fallback. */
514
1095
  function effectiveModels(key) {
515
1096
  const role = roleOf(key);
@@ -527,7 +1108,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
527
1108
  * counter itself stays per-role so each list rotates independently.
528
1109
  *
529
1110
  * `sessionId` selects the failover position for `pick: 'first'`, where the
530
- * ordered list is a failover chain rather than a rotation.
1111
+ * ordered list is a failover chain rather than a rotation. The cursor is
1112
+ * keyed per (session, role): a session that failed over while it was serving
1113
+ * `planning` (say, in plan mode) must not come back to `main` already pushed
1114
+ * off `main`'s first model — each tier's chain wears down independently.
531
1115
  */
532
1116
  function routeCandidate(key, sessionId) {
533
1117
  const models = effectiveModels(key);
@@ -543,19 +1127,74 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
543
1127
  },
544
1128
  };
545
1129
  }
546
- const at = Math.min(failover.get(sessionId) ?? 0, models.length - 1);
1130
+ const at = Math.min(failover.get(failoverKey(sessionId, key)) ?? 0, models.length - 1);
547
1131
  return { route: models[at], commit() {} };
548
1132
  }
549
1133
 
550
- /** Which role owns a delegated child, from its delegation label. */
1134
+ /**
1135
+ * Which role owns a delegated child, from its delegation label.
1136
+ *
1137
+ * A leading `plan:` / `vision:` prefix is authoritative — it is the one signal
1138
+ * the delegating model writes *on purpose*, so it must beat the keyword scan.
1139
+ * That is what the policy text teaches, so honouring it makes the documented
1140
+ * rule true: "plan: analyse the screenshots" is planning work even though a
1141
+ * bare keyword label fitting both tiers goes to vision.
1142
+ */
551
1143
  function classifySubagent(label) {
552
- const text = String(label ?? '');
1144
+ const text = String(label ?? '').trim();
553
1145
  if (text === '') return 'execution';
1146
+ const lower = text.toLowerCase();
1147
+ if (lower.startsWith('plan:')) return 'planning';
1148
+ if (lower.startsWith('vision:')) return 'vision';
554
1149
  if (visionMatch(text)) return 'vision';
555
1150
  if (planningMatch(text)) return 'planning';
556
1151
  return 'execution';
557
1152
  }
558
1153
 
1154
+ /**
1155
+ * The delegation policy for one prompt assembly, or `''` when none applies.
1156
+ *
1157
+ * Rendered only for the *orchestrating* top-level agent: a delegated child
1158
+ * already carries the harness's fixed `subagent:delegation` runtime context,
1159
+ * and encouraging a child to delegate further would push every unit one more
1160
+ * depth level down for no benefit. Depth is read from the session header the
1161
+ * same way `delegationDepthOf` does (`header.delegationDepth ?? 0`).
1162
+ *
1163
+ * Tool availability is verified against the assembly's own scope, so an agent
1164
+ * whose composition restricted the delegation tools never sees a policy
1165
+ * naming a tool it cannot call. Tier availability is passed through too, so
1166
+ * the text never advertises a `plan:` or `vision:` tier that has no models
1167
+ * behind it, and never warns about `provider`/`model` overrides in `advisory`
1168
+ * mode where nothing is routed at all.
1169
+ */
1170
+ function delegationPolicy(context) {
1171
+ try {
1172
+ if (!config.enabled) return '';
1173
+ const level = config.strategy.autoDelegate;
1174
+ if (level === 'off') return '';
1175
+ const agent = context?.agent;
1176
+ if (agent !== undefined) {
1177
+ const header = agent.session?.header;
1178
+ if (header?.origin === 'subagent') return '';
1179
+ const depth = header?.delegationDepth;
1180
+ if (typeof depth === 'number' && depth > 0) return '';
1181
+ }
1182
+ if (toolsService === undefined || typeof toolsService.get !== 'function') return '';
1183
+ const scope = context?.scope;
1184
+ const available = DELEGATION_TOOL_NAMES
1185
+ .filter((name) => probe(() => toolsService.get(name, scope)) !== undefined);
1186
+ return delegationPolicyText(level, available, {
1187
+ planning: effectiveModels('planning').length > 0,
1188
+ vision: effectiveModels('vision').length > 0,
1189
+ routed: config.strategy.mode !== 'advisory',
1190
+ });
1191
+ } catch {
1192
+ // A prompt section must never throw: an empty policy degrades to the
1193
+ // harness's own behaviour, which is exactly the pre-0.3.0 state.
1194
+ return '';
1195
+ }
1196
+ }
1197
+
559
1198
  function remember(sessionId, entry) {
560
1199
  const previous = usage.get(sessionId);
561
1200
  // Re-insert so the map stays in least-recently-used order for eviction.
@@ -648,12 +1287,22 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
648
1287
 
649
1288
  let role;
650
1289
  let label;
1290
+ let trigger;
651
1291
  if (isSubagent) {
652
1292
  const facts = await factsFor(agent.id);
653
1293
  label = facts?.label;
654
1294
  role = classifySubagent(label);
655
1295
  } else {
656
- role = planActive(ctx, agent) ? 'planning' : 'main';
1296
+ // Plan mode is the harness's own "thinking work" mode; a planning skill
1297
+ // (`grilling` / `grill-me`) is the user's own version of the same
1298
+ // intent, so both put the top-level session on the planning tier.
1299
+ const plan = planActive(ctx, agent);
1300
+ const skill = plan ? undefined : planningSkillFor(agent);
1301
+ trigger = skill === undefined ? (plan ? 'plan-mode' : 'main') : `skill:${skill}`;
1302
+ // Only claim routing when routing is on; a disabled manager still records
1303
+ // the trigger in its observed rows, but must not log that requests route.
1304
+ if (config.enabled) noteTopTrigger(agent, trigger);
1305
+ role = plan || skill !== undefined ? 'planning' : 'main';
657
1306
  }
658
1307
 
659
1308
  // Master switch off: observe and record, but never rewrite a route. The
@@ -663,6 +1312,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
663
1312
  if (!config.enabled) {
664
1313
  remember(agent.id, {
665
1314
  role,
1315
+ trigger,
666
1316
  label,
667
1317
  isSubagent,
668
1318
  provider: resolved.provider,
@@ -688,6 +1338,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
688
1338
  if (candidate === undefined) {
689
1339
  remember(agent.id, {
690
1340
  role,
1341
+ trigger,
691
1342
  provider: resolved.provider,
692
1343
  model: resolved.model,
693
1344
  reason: 'passthrough (role unconfigured)',
@@ -765,6 +1416,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
765
1416
 
766
1417
  remember(agent.id, {
767
1418
  role,
1419
+ trigger,
768
1420
  label,
769
1421
  isSubagent,
770
1422
  provider: output.provider,
@@ -830,7 +1482,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
830
1482
  // to recover.
831
1483
  const header = probe(() => agent.session?.requestHeader?.()?.config);
832
1484
  const failedAt = header === undefined
833
- ? Math.min(failover.get(agent.id) ?? 0, models.length - 1)
1485
+ ? Math.min(failover.get(failoverKey(agent.id, role)) ?? 0, models.length - 1)
834
1486
  : models.findIndex((route) => route.provider === header.provider && route.model === header.model);
835
1487
  if (failedAt < 0) return undefined;
836
1488
 
@@ -843,7 +1495,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
843
1495
  if (!rotating && nextIndex === failedAt) return undefined;
844
1496
 
845
1497
  if (rotating) roundRobin.set(owner, nextIndex);
846
- else failover.set(agent.id, nextIndex);
1498
+ else failover.set(failoverKey(agent.id, role), nextIndex);
847
1499
  budget.switches += 1;
848
1500
 
849
1501
  const from = models[failedAt];
@@ -858,6 +1510,174 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
858
1510
  }
859
1511
  }
860
1512
 
1513
+ // -- update check ---------------------------------------------------------
1514
+
1515
+ /** Drop every fallback timer the schedule armed; never throws. */
1516
+ function clearUpdateTimers() {
1517
+ const timers = updateTimers;
1518
+ updateTimers = [];
1519
+ for (const timer of timers) {
1520
+ try {
1521
+ clearTimeout(timer);
1522
+ clearInterval(timer);
1523
+ } catch {
1524
+ /* a half-cleared timer is already harmless */
1525
+ }
1526
+ }
1527
+ }
1528
+
1529
+ /**
1530
+ * Arm the update-check schedule from the live config.
1531
+ *
1532
+ * The first check runs shortly after boot (never on the boot path itself),
1533
+ * then once per `update.intervalHours`; an explicit `0` means "boot only".
1534
+ * Prefers the cordis timer service when the composition provides one — those
1535
+ * timers are context-effect-managed and dispose with the plugin fiber — and
1536
+ * falls back to unref'd globals otherwise, so a test process can still exit.
1537
+ */
1538
+ function scheduleUpdateChecks() {
1539
+ clearUpdateTimers();
1540
+ if (!config.update.enabled) {
1541
+ if (updateState.status !== 'available') updateState = { status: 'disabled', at: Date.now() };
1542
+ return;
1543
+ }
1544
+ const arm = (repeat, delay) => {
1545
+ const run = () => void checkForUpdate().catch(() => {});
1546
+ const viaCordis = probe(() => (repeat
1547
+ ? (typeof ctx.interval === 'function' ? ctx.interval : undefined)
1548
+ : (typeof ctx.timeout === 'function' ? ctx.timeout : undefined)));
1549
+ if (viaCordis !== undefined) {
1550
+ viaCordis(run, delay);
1551
+ return;
1552
+ }
1553
+ const timer = repeat ? setInterval(run, delay) : setTimeout(run, delay);
1554
+ if (typeof timer?.unref === 'function') timer.unref();
1555
+ updateTimers.push(timer);
1556
+ };
1557
+ arm(false, UPDATE_FIRST_CHECK_DELAY_MS);
1558
+ const hours = config.update.intervalHours;
1559
+ if (hours > 0) {
1560
+ arm(true, Math.max(UPDATE_MIN_INTERVAL_MS, hours * 3_600_000));
1561
+ }
1562
+ }
1563
+
1564
+ /**
1565
+ * Run one update check against the configured registry.
1566
+ *
1567
+ * Fetches the abbreviated packument, reads `dist-tags.latest`, and compares
1568
+ * it with this package's own version. Every failure path lands in
1569
+ * `updateState.status === 'error'` with a reason; none of them throws, and
1570
+ * none of them can touch routing.
1571
+ */
1572
+ function checkForUpdate() {
1573
+ if (updateInFlight !== undefined) return updateInFlight;
1574
+ updateInFlight = (async () => {
1575
+ if (!config.update.enabled) {
1576
+ updateState = { status: 'disabled', at: Date.now() };
1577
+ return updateState;
1578
+ }
1579
+ const registry = config.update.registry;
1580
+ const current = installedVersion();
1581
+ updateState = { status: 'checking', at: Date.now(), registry, current: current ?? undefined };
1582
+ try {
1583
+ if (current === null) throw new Error('this installation\'s version could not be read');
1584
+ if (typeof fetch !== 'function') throw new Error('no fetch in this runtime');
1585
+ const signal = timeoutSignal(UPDATE_FETCH_TIMEOUT_MS);
1586
+ const response = await fetch(`${registry}/${UPDATE_PACKAGE_PATH}`, {
1587
+ headers: { accept: 'application/vnd.npm.install-v1+json' },
1588
+ redirect: 'follow',
1589
+ ...(signal === undefined ? {} : { signal }),
1590
+ });
1591
+ if (response?.ok !== true) throw new Error(`HTTP ${response?.status ?? '(no status)'}`);
1592
+ const packument = await response.json();
1593
+ const latest = packument?.['dist-tags']?.latest;
1594
+ if (typeof latest !== 'string' || latest === '') {
1595
+ throw new Error('the packument carries no dist-tags.latest');
1596
+ }
1597
+ const order = compareVersions(latest, current);
1598
+ if (order === undefined) throw new Error(`unparseable version pair "${latest}" / "${current}"`);
1599
+ if (order > 0) {
1600
+ updateState = { status: 'available', at: Date.now(), current, latest, registry };
1601
+ log('warn', `update available: ${PACKAGE_NAME} ${current} -> ${latest} (checked ${registry}). `
1602
+ + `Run the model_manager tool with action "update" for the upgrade command, then restart. `
1603
+ + 'The settings card and the session-header chip show the same notice.');
1604
+ } else {
1605
+ updateState = { status: 'ok', at: Date.now(), current, latest, registry };
1606
+ }
1607
+ } catch (error) {
1608
+ updateState = {
1609
+ status: 'error',
1610
+ at: Date.now(),
1611
+ registry,
1612
+ current: current ?? undefined,
1613
+ reason: String(error?.message ?? error),
1614
+ };
1615
+ // A failed check is a diagnostic, not an alarm: offline deployments hit
1616
+ // this on every interval and a warn-per-hour would be noise.
1617
+ log('info', `update check failed (will retry on the interval): ${updateState.reason}`);
1618
+ }
1619
+ return updateState;
1620
+ })().finally(() => {
1621
+ updateInFlight = undefined;
1622
+ });
1623
+ return updateInFlight;
1624
+ }
1625
+
1626
+ /** One compact status line for `routes`/`report`. */
1627
+ function updateStatusLine() {
1628
+ const state = updateState;
1629
+ const at = state.at === undefined ? '' : new Date(state.at).toISOString();
1630
+ switch (state.status) {
1631
+ case 'available':
1632
+ return `Update check: ${state.latest} AVAILABLE (installed ${state.current}, checked ${at}, ${state.registry}). `
1633
+ + 'Run model_manager with action "update" for the upgrade command.';
1634
+ case 'ok':
1635
+ return `Update check: up to date — ${state.current} (checked ${at}, ${state.registry}).`;
1636
+ case 'checking':
1637
+ return `Update check: in progress (since ${at}, ${state.registry}).`;
1638
+ case 'error':
1639
+ return `Update check: failed — ${state.reason} (checked ${at}). `
1640
+ + 'Run model_manager with action "update" to retry now.';
1641
+ case 'disabled':
1642
+ return 'Update check: disabled in config (update.enabled: false).';
1643
+ default:
1644
+ return 'Update check: not run yet in this process.';
1645
+ }
1646
+ }
1647
+
1648
+ /** The full `model_manager` action-"update" report, forcing a fresh check. */
1649
+ async function updateAction() {
1650
+ await checkForUpdate();
1651
+ const state = updateState;
1652
+ const current = installedVersion();
1653
+ const lines = [
1654
+ 'Model manager update check',
1655
+ '',
1656
+ ` installed : ${current ?? '(unreadable)'}`,
1657
+ ` latest : ${state.latest ?? '(unknown)'}`,
1658
+ ` registry : ${config.update.registry}`,
1659
+ ` checked : ${state.at === undefined ? 'not yet' : new Date(state.at).toISOString()}`,
1660
+ ];
1661
+ if (state.status === 'available') {
1662
+ lines.push(` verdict : UPDATE AVAILABLE (${current} -> ${state.latest})`, '',
1663
+ 'To upgrade, run in a terminal:', '',
1664
+ ` dsh plugin --profile ${profileHint() ?? '<profile>'} add ${PACKAGE_NAME}@latest`, '',
1665
+ 'then restart the harness so the new version mounts. The Plugins page can reinstall',
1666
+ 'the same package instead; both paths run the same installer. Tell the user this',
1667
+ 'upgrade is available and what command to run.');
1668
+ } else if (state.status === 'error') {
1669
+ lines.push(` verdict : CHECK FAILED — ${state.reason}`, '',
1670
+ 'The check is retried on its interval; offline deployments keep this verdict.');
1671
+ } else if (state.status === 'disabled') {
1672
+ lines.push(' verdict : DISABLED — set update.enabled: true to check.');
1673
+ } else if (state.status === 'checking') {
1674
+ lines.push(' verdict : a concurrent check is in flight; re-run this action shortly.');
1675
+ } else {
1676
+ lines.push(` verdict : up to date (${current}).`);
1677
+ }
1678
+ return lines.join('\n');
1679
+ }
1680
+
861
1681
  // -- reporting ------------------------------------------------------------
862
1682
 
863
1683
  /**
@@ -1076,7 +1896,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1076
1896
  return 'No subagents observed yet in this process.\n\n'
1077
1897
  + 'Delegate some work, then run this report again. Model usage is recorded per\n'
1078
1898
  + 'delegation at request time, so it works whether routing applied or passed through.\n\n'
1079
- + roleTable();
1899
+ + roleTable()
1900
+ // The empty report still carries an available-update notice: it is the
1901
+ // one line a model reading this report should relay unprompted.
1902
+ + (updateState.status === 'available' ? `\n${updateStatusLine()}` : '');
1080
1903
  }
1081
1904
  rows.sort((a, b) => String(a.childId).localeCompare(String(b.childId)));
1082
1905
  const lines = [];
@@ -1108,6 +1931,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1108
1931
  lines.push('A reason ending in (respected) is the verdict itself: a human choice won and the');
1109
1932
  lines.push('manager stepped back. Under managed it never does, and a session that never had');
1110
1933
  lines.push('a manual pick is rewritten by the main role.');
1934
+ const skillTriggers = topRows.filter((row) => typeof row.seen.trigger === 'string'
1935
+ && row.seen.trigger.startsWith('skill:')
1936
+ && row.seen.reason !== 'manager disabled (observed only)');
1937
+ if (skillTriggers.length > 0) {
1938
+ lines.push('');
1939
+ lines.push('Planning skill trigger: ' + skillTriggers
1940
+ .map((row) => `${shortId(row.sessionId)} → ${row.seen.trigger.slice('skill:'.length)}`)
1941
+ .join(', '));
1942
+ lines.push('These sessions invoked a planning skill, so they route to the planning tier for');
1943
+ lines.push('the rest of the session, like plan mode; a hand-picked composer model still wins.');
1944
+ }
1111
1945
  lines.push('');
1112
1946
  }
1113
1947
  if (rows.length > 0) {
@@ -1147,6 +1981,11 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1147
1981
  lines.push(` ${String(entry.requests).padStart(4)} req / ${String(entry.children).padStart(2)} subagent(s) ${key}`);
1148
1982
  }
1149
1983
  }
1984
+ // Only an AVAILABLE update is worth a report line: the full status lives in
1985
+ // `routes` and action "update", and a per-report "up to date" would be noise.
1986
+ if (updateState.status === 'available') {
1987
+ lines.push('', updateStatusLine());
1988
+ }
1150
1989
  return lines.join('\n');
1151
1990
  }
1152
1991
 
@@ -1182,6 +2021,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1182
2021
  + (config.strategy.mode === 'managed' ? ' (always apply the role route)' : '')
1183
2022
  + (config.strategy.mode === 'advisory' ? ' (never rewrite — report only)' : ''),
1184
2023
  '',
2024
+ `Auto-delegation: ${config.strategy.autoDelegate === 'off'
2025
+ ? 'off — no delegation policy is added to the system prompt'
2026
+ : `${config.strategy.autoDelegate} — the top-level agent is prompted to ${config.strategy.autoDelegate === 'eager'
2027
+ ? 'orchestrate: nearly all substantive work goes to delegations'
2028
+ : 'plan and dispatch subagents for multi-step and independent work'}`}`,
2029
+ '',
2030
+ `Planning skills: ${config.strategy.planningSkills.length === 0
2031
+ ? '(disabled) — skills never change the top-level role'
2032
+ : `${config.strategy.planningSkills.join(', ')} — a top-level session that invoked one routes as `
2033
+ + 'planning for the rest of the session, like plan mode'}`,
2034
+ '',
1185
2035
  allowListBlock(),
1186
2036
  '',
1187
2037
  visionBlock,
@@ -1191,6 +2041,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1191
2041
  ` vision : ${config.strategy.visionKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.visionKeywords.length > 8 ? ', …' : ''}`,
1192
2042
  ` planning : ${config.strategy.planningKeywords.slice(0, 8).join(', ') || '(disabled)'}${config.strategy.planningKeywords.length > 8 ? ', …' : ''}`,
1193
2043
  ' else : execution',
2044
+ '',
2045
+ updateStatusLine(),
1194
2046
  ].join('\n');
1195
2047
  }
1196
2048
 
@@ -1203,13 +2055,26 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1203
2055
  })
1204
2056
  .filter(Boolean);
1205
2057
  if (summary.length === 0) return '';
2058
+ const routing = config.strategy.mode === 'advisory'
2059
+ ? 'The manager is observing only (advisory), so labels classify but never rewrite a route.'
2060
+ : [
2061
+ 'Label a delegation `description` with "plan:" for thinking work, "vision:" for image',
2062
+ 'work, or leave it plain for execution; a leading prefix wins over keyword matches.',
2063
+ 'Leave `provider` and `model` unset on those units so the role route applies.',
2064
+ ].join('\n');
2065
+ const planningGap = effectiveModels('planning').length === 0
2066
+ ? '\nThe planning tier has no models, so "plan:" labels keep the inherited route.'
2067
+ : '';
2068
+ const skillNote = config.strategy.planningSkills.length > 0 && effectiveModels('planning').length > 0
2069
+ ? '\nA top-level session that invoked '
2070
+ + `${config.strategy.planningSkills.join(' / ')} runs on the planning tier, like plan mode.`
2071
+ : '';
1206
2072
  return [
1207
2073
  '## Model manager',
1208
2074
  'Delegated work is routed by the label you give each delegation:',
1209
2075
  ...summary,
1210
- 'Start a delegation `description` with "plan:" for reasoning work, "vision:" for',
1211
- 'image/screenshot work, or leave it plain for execution. Call `model_manager` with',
1212
- 'action "report" to see which model each subagent actually used.',
2076
+ routing,
2077
+ `Call \`model_manager\` with action "report" to see which model each subagent actually used.${planningGap}${skillNote}`,
1213
2078
  ].join('\n');
1214
2079
  }
1215
2080
 
@@ -1384,6 +2249,56 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1384
2249
  wire: { viewSchema: selectionProjectionSchema, view: (state) => state },
1385
2250
  };
1386
2251
 
2252
+ /**
2253
+ * Skills invoked anywhere in one session, folded from the durable log.
2254
+ *
2255
+ * The projection is the durable half of the planning-skill trigger: the live
2256
+ * pre-step map only covers this process, while this fold survives restart,
2257
+ * resume and fork. It records every skill name (not just the configured
2258
+ * planning ones), because membership is decided against the LIVE config at
2259
+ * request time — adding a skill to `strategy.planningSkills` must apply to a
2260
+ * session that invoked it earlier in the same process, and `[]` must switch
2261
+ * the trigger off immediately.
2262
+ *
2263
+ * Only the append-only log feeds it (compaction shadows surface nodes but
2264
+ * never deletes events), and a fold that adds nothing returns the same state
2265
+ * reference so the projection layer does not republish.
2266
+ */
2267
+ const PLANNING_SKILL_PROJECTION_KEY = 'modelManagerPlanningSkill';
2268
+ const planningSkillProjectionSchema = {
2269
+ parse: (value) => {
2270
+ if (value === null || typeof value !== 'object') throw new Error('expected an object');
2271
+ if (!Array.isArray(value.skills)) throw new Error('skills: expected an array');
2272
+ const skills = [];
2273
+ for (const item of value.skills) {
2274
+ if (typeof item !== 'string') throw new Error('skills: expected strings');
2275
+ const name = item.trim().toLowerCase();
2276
+ if (!SKILL_NAME.test(name)) throw new Error(`skills: invalid skill name "${item}"`);
2277
+ if (!skills.includes(name) && skills.length < SKILL_NAME_LIMIT) skills.push(name);
2278
+ }
2279
+ return { skills };
2280
+ },
2281
+ };
2282
+ const planningSkillProjectionDefinition = {
2283
+ key: PLANNING_SKILL_PROJECTION_KEY,
2284
+ stateVersion: 1,
2285
+ stateSchema: planningSkillProjectionSchema,
2286
+ init: () => ({ skills: [] }),
2287
+ apply: (state, event) => {
2288
+ let added;
2289
+ for (const name of skillNamesOfEvent(event)) {
2290
+ const normalized = typeof name === 'string' ? name.trim().toLowerCase() : '';
2291
+ if (normalized === '' || !SKILL_NAME.test(normalized)) continue;
2292
+ if (state.skills.includes(normalized)) continue;
2293
+ if (added !== undefined && added.includes(normalized)) continue;
2294
+ if (state.skills.length + (added?.length ?? 0) >= SKILL_NAME_LIMIT) break;
2295
+ (added ??= []).push(normalized);
2296
+ }
2297
+ if (added === undefined) return state;
2298
+ return { skills: [...state.skills, ...added] };
2299
+ },
2300
+ };
2301
+
1387
2302
  /** The projection registry, captured when this composition provides one. */
1388
2303
  let projections;
1389
2304
 
@@ -1403,14 +2318,26 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1403
2318
  function attach() {
1404
2319
  ctx.on('agent/request', onAgentRequest);
1405
2320
  ctx.on('agent/request-error', onRequestError);
2321
+ // Prepend so `next()` returns the decision WITH the harness's own skill
2322
+ // injections; a normally-registered listener would run inside tool-skill's
2323
+ // hook and never see them. The listener is observe-only and returns the
2324
+ // decision untouched.
2325
+ ctx.on('agent/pre-step', onPreStep, { prepend: true });
1406
2326
 
1407
2327
  // Drop per-session failover state when its agent goes away, so a long-lived
1408
2328
  // process does not accumulate entries for sessions that can no longer run.
2329
+ // The cursors are keyed `${id}::${role}`, so every role's cursor goes too.
1409
2330
  ctx.on('agent/disposed', (payload) => {
1410
2331
  const id = payload?.agent?.id ?? (typeof payload === 'string' ? payload : payload?.id);
1411
2332
  if (typeof id !== 'string') return;
1412
2333
  failover.delete(id);
2334
+ const prefix = `${id}::`;
2335
+ for (const key of [...failover.keys()]) {
2336
+ if (key.startsWith(prefix)) failover.delete(key);
2337
+ }
1413
2338
  stepSwitches.delete(id);
2339
+ liveSkills.delete(id);
2340
+ topTriggers.delete(id);
1414
2341
  });
1415
2342
 
1416
2343
  // Resolve a newly published child's label immediately, and targeted rather
@@ -1426,12 +2353,26 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1426
2353
  // boot-time one until restart. DSH's own volatile plugins do the same.
1427
2354
  ctx.on('loader/volatile-update', () => {
1428
2355
  try {
2356
+ const previousUpdate = config.update;
1429
2357
  const next = readConfig(rawConfig);
1430
- config = { enabled: next.enabled, pick: next.pick, roles: next.roles, strategy: next.strategy, warnings: next.warnings };
2358
+ config = {
2359
+ enabled: next.enabled,
2360
+ pick: next.pick,
2361
+ roles: next.roles,
2362
+ strategy: next.strategy,
2363
+ update: next.update,
2364
+ warnings: next.warnings,
2365
+ };
1431
2366
  visionMatch = keywordMatcher(config.strategy.visionKeywords);
1432
2367
  planningMatch = keywordMatcher(config.strategy.planningKeywords);
1433
2368
  for (const warning of config.warnings) log('warn', warning);
1434
- log('info', `settings reloaded — mode ${config.strategy.mode}, pick ${config.pick}; `
2369
+ // The delegation policy and the update schedule both read the live
2370
+ // config through this closure, so they follow a save with no restart.
2371
+ scheduleUpdateChecks();
2372
+ const updateChanged = JSON.stringify(previousUpdate) !== JSON.stringify(config.update);
2373
+ if (updateChanged) void checkForUpdate().catch(() => {});
2374
+ log('info', `settings reloaded — mode ${config.strategy.mode}, pick ${config.pick}, autoDelegate ${config.strategy.autoDelegate}, `
2375
+ + `planningSkills ${config.strategy.planningSkills.join('|') || '-'}; `
1435
2376
  + ROLE_NAMES
1436
2377
  .map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
1437
2378
  .join(' '));
@@ -1442,28 +2383,38 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1442
2383
 
1443
2384
  if (typeof ctx.inject === 'function') {
1444
2385
  ctx.inject(['tools'], (scoped) => {
2386
+ // Captured for the delegation-policy section, which asks this service
2387
+ // which delegation tools an assembly's scope actually exposes.
2388
+ toolsService = scoped.tools;
1445
2389
  try {
1446
2390
  scoped.tools.register({
1447
2391
  name: 'model_manager',
1448
2392
  description: 'Inspect and explain the role-based model routing configured for this harness. '
1449
2393
  + 'action "report": a Top-level agents section naming which model served each '
1450
- + 'conversation and whether the manager yielded to a model a person picked in the '
1451
- + 'composer, then one row per subagent with its label, role, reason, live status and '
2394
+ + 'conversation, whether the manager yielded to a model a person picked in the '
2395
+ + 'composer, and which planning skill (if any) put a session on the planning tier, '
2396
+ + 'then one row per subagent with its label, role, reason, live status and '
1452
2397
  + 'totals. action "routes": the four role assignments '
1453
2398
  + '(including the vision->execution fallback), the shared selection strategy (first or round-robin), '
1454
- + 'the active distribution mode, and whether each '
2399
+ + 'the active distribution mode, the auto-delegation level, the planning-skill trigger, '
2400
+ + 'the update-check status, '
2401
+ + 'and whether each '
1455
2402
  + 'route is dispatchable by the delegation tool, with the YAML to add any that are not. '
1456
2403
  + 'action "usage": request and subagent counts by role and model across the whole process. '
1457
2404
  + 'action "client": whether the Host composed this plugin\'s Web client half into the browser '
1458
2405
  + 'boot graph, the route serving its bundle, and the current graph revision — use it when the '
1459
2406
  + 'configuration card does not appear in the Web UI. '
2407
+ + 'action "update": force a fresh update check against the package registry and return the '
2408
+ + 'installed version, the latest published version, and the exact upgrade command to run '
2409
+ + 'when a newer release exists — use it whenever the report or routes output says an update '
2410
+ + 'is available, and tell the user. '
1460
2411
  + 'Read-only; it never changes routing.',
1461
2412
  parameters: {
1462
2413
  type: 'object',
1463
2414
  properties: {
1464
2415
  action: {
1465
2416
  type: 'string',
1466
- enum: ['report', 'routes', 'usage', 'client'],
2417
+ enum: ['report', 'routes', 'usage', 'client', 'update'],
1467
2418
  description: 'What to return. Defaults to "report".',
1468
2419
  },
1469
2420
  },
@@ -1477,6 +2428,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1477
2428
  const action = args?.action ?? 'report';
1478
2429
  if (action === 'routes') return routes();
1479
2430
  if (action === 'client') return clientStatus();
2431
+ if (action === 'update') return updateAction();
1480
2432
  if (action === 'usage') {
1481
2433
  await refreshCatalog();
1482
2434
  const totals = new Map();
@@ -1516,8 +2468,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1516
2468
  }
1517
2469
  registry.register(usageProjectionDefinition);
1518
2470
  registry.register(selectionProjectionDefinition);
2471
+ registry.register(planningSkillProjectionDefinition);
1519
2472
  projections = registry;
1520
- log('info', `registered the ${USAGE_PROJECTION_KEY} and ${SELECTION_PROJECTION_KEY} session projections`);
2473
+ log('info', `registered the ${USAGE_PROJECTION_KEY}, ${SELECTION_PROJECTION_KEY} and `
2474
+ + `${PLANNING_SKILL_PROJECTION_KEY} session projections`);
1521
2475
  } catch (error) {
1522
2476
  log('warn', `could not register the usage projection: ${error?.message ?? error}`);
1523
2477
  }
@@ -1525,11 +2479,42 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1525
2479
 
1526
2480
  ctx.inject(['systemPrompt'], (scoped) => {
1527
2481
  try {
1528
- const register = () => scoped.systemPrompt.section({
1529
- name: 'model-manager',
1530
- order: 60,
1531
- text: () => cheatSheet(),
1532
- });
2482
+ const register = () => {
2483
+ const disposers = [];
2484
+ try {
2485
+ disposers.push(scoped.systemPrompt.section({
2486
+ name: 'model-manager',
2487
+ order: 60,
2488
+ text: () => cheatSheet(),
2489
+ }));
2490
+ // The delegation policy: rendered per assembly, only for the
2491
+ // top-level orchestrator, and only while it actually has the
2492
+ // delegation tools — see delegationPolicy().
2493
+ disposers.push(scoped.systemPrompt.section({
2494
+ name: 'model-manager:delegation',
2495
+ order: DELEGATION_SECTION_ORDER,
2496
+ text: (context) => delegationPolicy(context),
2497
+ }));
2498
+ } catch (error) {
2499
+ for (const dispose of disposers) {
2500
+ try {
2501
+ dispose();
2502
+ } catch {
2503
+ /* a failed partial registration must not leak the rest */
2504
+ }
2505
+ }
2506
+ throw error;
2507
+ }
2508
+ return () => {
2509
+ for (const dispose of disposers) {
2510
+ try {
2511
+ dispose();
2512
+ } catch {
2513
+ /* disposal is best-effort */
2514
+ }
2515
+ }
2516
+ };
2517
+ };
1533
2518
  if (typeof scoped.effect === 'function') scoped.effect(register);
1534
2519
  else register();
1535
2520
  } catch (error) {
@@ -1573,9 +2558,23 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1573
2558
  + `${broken.map((row) => row.label).join(', ')}. Point roles.vision.models at an image-capable model.`);
1574
2559
  }
1575
2560
  })().catch(() => {});
2561
+
2562
+ // Automatic update checks: the first run is delayed past the boot path,
2563
+ // and every failure path inside degrades to a logged diagnostic.
2564
+ scheduleUpdateChecks();
1576
2565
  }
1577
2566
 
1578
- return { attach, classifySubagent, classifyAndRoute: routeCandidate, roleTable, routes, report };
2567
+ return {
2568
+ attach,
2569
+ classifySubagent,
2570
+ classifyAndRoute: routeCandidate,
2571
+ roleTable,
2572
+ routes,
2573
+ report,
2574
+ delegationPolicy,
2575
+ checkForUpdate,
2576
+ updateStatusLine,
2577
+ };
1579
2578
  }
1580
2579
 
1581
2580
  // ---------------------------------------------------------------------------
@@ -1595,13 +2594,31 @@ export function apply(ctx, rawConfig) {
1595
2594
  for (const warning of config.warnings) log('warn', warning);
1596
2595
  const engine = createEngine(config, ctx, log, rawConfig);
1597
2596
  engine.attach();
1598
- log('info', `active — mode ${config.strategy.mode}, pick ${config.pick}; `
2597
+ log('info', `active — mode ${config.strategy.mode}, pick ${config.pick}, autoDelegate ${config.strategy.autoDelegate}; `
1599
2598
  + ROLE_NAMES
1600
2599
  .map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
1601
- .join(' '));
2600
+ .join(' ')
2601
+ + (config.update.enabled
2602
+ ? `; update check every ${config.update.intervalHours === 0
2603
+ ? 'boot (interval disabled)'
2604
+ : `${config.update.intervalHours}h against ${config.update.registry}`}`
2605
+ : '; update check disabled'));
1602
2606
  } catch (error) {
1603
2607
  log('error', `failed to initialise; model routing is disabled: ${error?.stack ?? error}`);
1604
2608
  }
1605
2609
  }
1606
2610
 
1607
- export { readConfig, applyRoute, effectiveRouteOf, DEFAULT_PLANNING_KEYWORDS, DEFAULT_VISION_KEYWORDS };
2611
+ export {
2612
+ readConfig,
2613
+ applyRoute,
2614
+ effectiveRouteOf,
2615
+ parseVersion,
2616
+ compareVersions,
2617
+ installedVersion,
2618
+ profileHint,
2619
+ delegationPolicyText,
2620
+ skillNamesOfEvent,
2621
+ DEFAULT_PLANNING_KEYWORDS,
2622
+ DEFAULT_PLANNING_SKILLS,
2623
+ DEFAULT_VISION_KEYWORDS,
2624
+ };