@darkbear9494/dsh-model-manager 0.6.0 → 0.6.1

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 CHANGED
@@ -12,7 +12,9 @@ decides the tier outright, and each role's failover chain wears down on its own.
12
12
  alias people type — puts the top-level session on the `planning` role for the rest of the session,
13
13
  exactly as plan mode does. Since 0.6.0 it ships one skill of its own: **`/autoplan`** turns the two
14
14
  tiers into a workflow — the plan is designed by a `plan:`-labelled fork on the planning model, and
15
- the main model implements the returned plan immediately, without stopping for approval.
15
+ the main model implements the returned plan immediately, without stopping for approval. Since 0.6.1
16
+ it also follows DSH 0.2's model-selection contract: a route is assigned with `agent.model.select()`
17
+ before the step is prepared, instead of being rewritten at request time (which 0.2 aborts).
16
18
 
17
19
  ## What it is
18
20
 
@@ -705,6 +707,44 @@ an `Autoplan skill: registered` / `not registered (…)` line so you can tell wh
705
707
  Registering the skill is not routing: it happens even with `enabled: false`, where only the model
706
708
  switch stops.
707
709
 
710
+ ### Switching models on DSH 0.2.x
711
+
712
+ DSH 0.2 moved model selection out of the request waterfall. The loop reads
713
+ `agent.model.current()` at the start of step preparation and fixes
714
+ provider/model/reasoningEffort for that step; an `agent/request` listener that proposes another
715
+ route now **aborts the turn** with
716
+ `agent/request proposed "…" after step preparation fixed "…"; use agent.model.select() before step
717
+ preparation`. 0.6.1 follows the new contract while keeping the 0.1.x path:
718
+
719
+ | Harness | How a route is applied | `agent/request` |
720
+ | --- | --- | --- |
721
+ | 0.1.x (no `agent.model.select`) | the manager rewrites the proposed route | routing |
722
+ | 0.2.x (`agent.model.select` present) | `agent.model.select()` **before** the step is prepared | observe-only |
723
+
724
+ On 0.2.x the selection is made at `agent/inbox/claimed`, which is the one moment that beats the
725
+ fix without fighting it: the loop claims a step's input and only then reads the model, and the
726
+ claim notifications are emitted outside the session append being published — a selection made
727
+ there is accepted and lands on the request that is about to run. (A `session/event` listener
728
+ cannot do this: it runs inside the append, where a nested append is refused as reentrant.) A
729
+ second selection at `agent/pre-step` keeps later steps correct — plan mode toggled mid-turn, a
730
+ skill invoked on a later step, a child whose label was not yet known — at the price of landing on
731
+ the *next* step, which is the best any pre-step hook can do.
732
+
733
+ Consequences worth knowing:
734
+
735
+ - **A hand-picked model still wins under `hybrid`.** A route is the manager's own when it
736
+ selected it (`managerSelected`), and the deployment default when it equals the agent's creation
737
+ options; anything else is a recorded choice and is respected. Ownership is in-process, so after
738
+ a restart a session whose route the manager had selected reads as hand-picked and is left alone
739
+ until a turn actually routes it again — `managed` overrides it as always.
740
+ - **Failover cannot retry the same step on another model.** The step's route is fixed, so a
741
+ failure advances the role's cursor, selects the next model for the next request, and the failing
742
+ step ends instead of retrying a model already known to be down. The log says so; on 0.1.x the
743
+ old same-step retry is unchanged.
744
+ - **`routes` reports the transport** on its `Routing transport:` line — `agent.model.select()
745
+ before step preparation (DSH ≥ 0.2)` or `agent/request route rewrite (DSH 0.1.x)` — read from
746
+ the live agents, so it states what the running composition is actually doing.
747
+
708
748
  ### The vision → execution fallback
709
749
 
710
750
  If `vision.models` is empty when a vision request is routed, the plugin serves it from the
@@ -1507,7 +1547,7 @@ degrades to a notice or a log line.
1507
1547
  npm test
1508
1548
  ```
1509
1549
 
1510
- Runs twelve suites in child processes and aggregates the result — **993 assertions** at the time
1550
+ Runs thirteen suites in child processes and aggregates the result — **1019 assertions** at the time
1511
1551
  of writing. Each suite also runs on its own: `node test/<name>.test.mjs`.
1512
1552
 
1513
1553
  | Suite | Assertions | What it pins |
@@ -1525,6 +1565,7 @@ of writing. Each suite also runs on its own: `node test/<name>.test.mjs`.
1525
1565
  | `autoplan-skill.test.mjs` | 42 | New in 0.6.0. The bundled `/autoplan` skill: the pure frontmatter parser (`parseSkillMarkdown`) accepting exactly a well-formed SKILL.md — CRLF, edge-trimming, a `---` line inside the body preserved, a `name:` line in the body not mistaken for frontmatter — and returning `undefined` for a missing/unclosed fence, an empty body, an empty description, an invalid name, and every hostile input without throwing; the shipped definition satisfying the runtime contract `dsh-skill` validates on `get()` (kebab name, non-empty description/content, both invocation flags, a string source) and its body carrying the load-bearing instructions (the `plan:`-labelled `subagent_fork`, the no-approval rule, the plan-mode boundary, the `subagent` fallback, the main-tier implementation phase) so it cannot be silently gutted; registration through a mock skills service — exactly once, the shipped definition, an info log naming the skill — and every degradation: a throwing `register()` and a composition with no skills service both leave `apply()` working with a warning, and `routes()` distinguishing registered from not; registration independent of `config.enabled`; and the routing invariant that `/autoplan` is not a planning skill — a top-level session that invoked it stays on the `main` tier, with `/grilling` as the escalating control. The packaging suite additionally pins that `skills/` is in `files` and the body ships. |
1526
1566
  | `planning-skills.test.mjs` | 100 | New in 0.5.0. The skill → top-level `planning` escalation, in eight blocks: the pure event fold `skillNamesOfEvent` over all three records — the `skill-invocation` injection, the `/name` gesture in direct user text, and a model's `skill` `tool/call` with JSON arguments — including the gesture-boundary rules, hostile payloads that record nothing and never throw, and the grammar pinned **byte-identical against the real `dsh-tool-skill`** when a DSH install resolves; `planningSkills` configuration (absent → `grill-me`/`grilling`, explicit `[]` honoured, lowercasing/trimming/de-duplication, invalid names dropped, volatile refs unwrapped, no unknown-key warning either way, and the schema union accepting an array / rejecting anything else); the `modelManagerPlanningSkill` projection (key, `stateVersion`, `init`, folding all three event shapes, mixed-case canonicalization, same-reference returns that suppress republishing, `.parse` rejecting junk); the **live** `agent/pre-step` signal — registered prepended, routing the FIRST request of a gesture step, stickiness across later turns, non-listed skills left on `main`, `[]` disabling it, the enter/reject decision returned by identity, a dozen hostile payloads, a subagent never escalated, `agent/disposed` dropping the live signal, a volatile reload of `[]` applying to the next request, and the info notice firing once per switch; the **durable** signal (a resumed session routing planning from a logged invocation, gesture, or model tool call, a durable name inert under `[]`, and no throw when the projection service is absent); plan mode keeping its own behaviour and owning the trigger when both apply; an explicit composer pick still winning the route while the row records role `planning`; and both diagnostic surfaces — the `Planning skills:` line in `routes` and the `Planning skill trigger:` line in `report`, each in its enabled and disabled form. |
1527
1567
 
1568
+ | `model-select.test.mjs` | 26 | New in 0.6.1. DSH 0.2's selection contract: the pure helpers (`sameSelection`, `planningSkillInMessages`, `selectionModelOf`); a claimed user message selects the role's route before the step is prepared — plain prompt → `main`, `/grilling` → `planning`, `/autoplan` → `main`, plan mode → `planning`, round-robin committing only on an applied selection, and a hand-picked composer model respected under `hybrid` while `managed` overrides it; the manager's own selection is not mistaken for a hand-picked one on the next turn; `agent/request` returns the step's fixed route untouched (the 0.2 crash path); `agent/pre-step` corrects the next step; failover selects the next model and does not retry the fixed step; and a 0.1.x agent without a selection surface keeps request-time rewriting. |
1528
1569
  The suites are plain Node scripts — no test framework, and no dependency beyond Node itself.
1529
1570
 
1530
1571
  Two of them optionally pin their expectations against the **real** harness internals rather
@@ -1556,6 +1597,13 @@ outside the repository.
1556
1597
  out. A skill the **model** invoked (through its `skill` tool) escalates only from the next
1557
1598
  request of that session onward — the `tool/call` event exists only once the model has emitted
1558
1599
  it, so the step that asked for the skill still runs on the route already chosen.
1600
+ - **Failover is per request, not per step, on DSH 0.2.x.** The route is fixed when a step is
1601
+ prepared, so a provider failure advances the role's cursor and selects the next model for the
1602
+ next request; the failing step ends rather than being retried on another model. On 0.1.x the
1603
+ same-step retry is unchanged. See [Switching models on DSH 0.2.x](#switching-models-on-dsh-02x).
1604
+ - **Selection ownership is in-process.** A route the manager selected reads as hand-picked after a
1605
+ restart, because 0.2 records every selection in the same durable event; `managed` overrides it,
1606
+ and the next turn that routes the session re-establishes ownership.
1559
1607
  - **`/autoplan` is a workflow, not enforcement.** The body is injected as instructions, so the
1560
1608
  model decides how faithfully to follow it: nothing forces the fork, and nothing stops a model
1561
1609
  from asking a question anyway. What the plugin does guarantee is the tiers — the `plan:` label
package/client.js CHANGED
@@ -64,7 +64,7 @@ window.__ModuleLoader__.load({
64
64
  * test/packaging.test.mjs pins it equal to package.json, so a release that
65
65
  * forgets to bump both fails the suite instead of shipping a wrong banner.
66
66
  */
67
- const VERSION = '0.6.0';
67
+ const VERSION = '0.6.1';
68
68
  /**
69
69
  * Registry path of this package. The scoped name is percent-encoded the
70
70
  * way npm serves scoped packuments.
package/lib/index.js CHANGED
@@ -753,6 +753,54 @@ function planActive(ctx, agent) {
753
753
  return projected === undefined ? false : projected;
754
754
  }
755
755
 
756
+ /**
757
+ * The agent's model-selection surface, or `undefined`.
758
+ *
759
+ * DSH 0.2.x replaced the request-time model rewrite with an explicit selection
760
+ * API: `agent.model.select()` assigns the route for the next step whose
761
+ * preparation has not begun, while `agent/request` must preserve the route the
762
+ * step already fixed — proposing another one aborts the turn. Feature-detecting
763
+ * the surface keeps the 0.1.x rewrite path working on harnesses that never
764
+ * shipped it.
765
+ */
766
+ function selectionModelOf(agent) {
767
+ const model = probe(() => agent?.model);
768
+ return model !== undefined && typeof model.select === 'function' ? model : undefined;
769
+ }
770
+
771
+ /** Whether two route selections name the same provider, model and effort. */
772
+ function sameSelection(left, right) {
773
+ if (left === undefined || right === undefined) return false;
774
+ return left.provider === right.provider
775
+ && left.model === right.model
776
+ && (left.reasoningEffort ?? undefined) === (right.reasoningEffort ?? undefined);
777
+ }
778
+
779
+ /**
780
+ * The planning skill named by a batch of pending user messages, or `undefined`.
781
+ *
782
+ * The inbox is the only place a new turn's text exists before its first step is
783
+ * prepared — the harness appends `user/message` only when the step admits it,
784
+ * which is after the route is fixed. Scanning the pending messages is therefore
785
+ * what lets a `/grilling` gesture reach the FIRST request of its turn on a
786
+ * harness that fixes the route at step preparation. Recognition uses the
787
+ * harness's own `/name` grammar and only the configured planning skills match.
788
+ */
789
+ function planningSkillInMessages(messages, wanted) {
790
+ if (wanted.length === 0) return undefined;
791
+ for (const message of Array.isArray(messages) ? messages : []) {
792
+ if (message?.source?.kind !== 'user') continue;
793
+ for (const block of Array.isArray(message.content) ? message.content : []) {
794
+ if (block?.type !== 'text' || typeof block.text !== 'string') continue;
795
+ for (const match of block.text.matchAll(SKILL_GESTURE)) {
796
+ const name = match[2];
797
+ if (name !== undefined && wanted.includes(name)) return name;
798
+ }
799
+ }
800
+ }
801
+ return undefined;
802
+ }
803
+
756
804
  /** Find the delegating parent of a child session. */
757
805
  function findParent(ctx, childId) {
758
806
  return probe(() => {
@@ -1011,6 +1059,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1011
1059
  * choice and stop managing that child permanently.
1012
1060
  */
1013
1061
  const managerApplied = new Map();
1062
+
1063
+ /**
1064
+ * session id -> route key this manager last assigned through
1065
+ * `agent.model.select()` (the DSH 0.2.x selection path).
1066
+ *
1067
+ * A selected route is recorded in the session log exactly like a composer
1068
+ * pick, so ownership has to be remembered here: without it the manager would
1069
+ * read back its own selection as a hand-picked model and stop routing the
1070
+ * session under `hybrid`.
1071
+ */
1072
+ const managerSelected = new Map();
1014
1073
  const roundRobin = new Map();
1015
1074
  /** child session id -> in-flight single-child lookup, to coalesce bursts */
1016
1075
  const childLookups = new Map();
@@ -1139,7 +1198,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1139
1198
  async function onPreStep(payload, next) {
1140
1199
  const decision = await next();
1141
1200
  try {
1142
- const id = typeof payload?.agent?.id === 'string' ? payload.agent.id : undefined;
1201
+ const agent = payload?.agent;
1202
+ const id = typeof agent?.id === 'string' ? agent.id : undefined;
1143
1203
  if (id !== undefined && decision?.kind !== 'reject') {
1144
1204
  for (const batch of [payload?.messages, decision?.messages]) {
1145
1205
  if (!Array.isArray(batch)) continue;
@@ -1148,6 +1208,27 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1148
1208
  }
1149
1209
  }
1150
1210
  }
1211
+ // On a harness that fixes the route at step preparation, keep the
1212
+ // selection correct from step to step: this call lands on the NEXT step,
1213
+ // because the current step's route was read before this hook ran. The
1214
+ // claim-boundary selection in `onInboxClaimed` is what covers the request
1215
+ // that is about to run.
1216
+ if (agent !== undefined && decision?.kind !== 'reject'
1217
+ && selectionModelOf(agent) !== undefined && config.enabled) {
1218
+ const isSubagent = probe(() => agent.session?.header?.origin === 'subagent') === true;
1219
+ if (isSubagent) {
1220
+ const facts = catalog.get(agent.id);
1221
+ if (facts !== undefined) {
1222
+ applySelection(agent, classifySubagent(facts.label), undefined, facts.label, true);
1223
+ }
1224
+ } else {
1225
+ const plan = planActive(ctx, agent);
1226
+ const skill = plan ? undefined : planningSkillFor(agent);
1227
+ const trigger = skill === undefined ? (plan ? 'plan-mode' : 'main') : `skill:${skill}`;
1228
+ noteTopTrigger(agent, trigger);
1229
+ applySelection(agent, plan || skill !== undefined ? 'planning' : 'main', trigger, undefined, false);
1230
+ }
1231
+ }
1151
1232
  } catch {
1152
1233
  // Observe-only: a hostile message shape must never fail the step.
1153
1234
  }
@@ -1206,6 +1287,184 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1206
1287
  return { route: models[at], commit() {} };
1207
1288
  }
1208
1289
 
1290
+ // -- model selection (DSH 0.2.x) ------------------------------------------
1291
+
1292
+ /**
1293
+ * Whether the agent's current selection was recorded by somebody else.
1294
+ *
1295
+ * A route the manager selected is its own; a route equal to the agent's
1296
+ * creation options is the deployment default (or the inherited parent route),
1297
+ * which the manager is allowed to replace. Anything else is a recorded choice
1298
+ * — a composer pick, a resume override, an explicit child route — and
1299
+ * `hybrid` leaves it alone, exactly when it is neither manager-owned nor the
1300
+ * deployment default.
1301
+ */
1302
+ function selectionIsForeign(agent, current) {
1303
+ if (current === undefined) return false;
1304
+ if (managerSelected.get(agent.id) === routeKey(current)) return false;
1305
+ const options = probe(() => agent?.options);
1306
+ if (options !== undefined && options.provider === current.provider && options.model === current.model) return false;
1307
+ return true;
1308
+ }
1309
+
1310
+ /**
1311
+ * The hybrid gate for a subagent's current route.
1312
+ *
1313
+ * Mirrors the request-path rule the 0.1.x engine implements: a child is
1314
+ * routed when the route is manager-owned or provably inherited from the
1315
+ * delegating parent, and respected when it names a route nobody can prove was
1316
+ * inherited (an explicit child choice, or unresolvable lineage).
1317
+ */
1318
+ function childRouteIsInherited(agent, current) {
1319
+ if (current === undefined) return true;
1320
+ if (managerSelected.get(agent.id) === routeKey(current)) return true;
1321
+ const previous = usage.get(agent.id);
1322
+ if (previous?.applied === true
1323
+ && previous.provider === current.provider
1324
+ && previous.model === current.model) return true;
1325
+ const parent = findParent(ctx, agent.id);
1326
+ const parentRoute = parent === undefined ? undefined : effectiveRouteOf(parent);
1327
+ if (parentRoute === undefined) return false;
1328
+ return parentRoute.provider === current.provider && parentRoute.model === current.model;
1329
+ }
1330
+
1331
+ /** Whether `hybrid` permits replacing the agent's current route with `route`. */
1332
+ function selectionAllowed(agent, current, isSubagent) {
1333
+ if (config.strategy.mode !== 'hybrid') return true;
1334
+ if (!isSubagent) return !selectionIsForeign(agent, current);
1335
+ return childRouteIsInherited(agent, current);
1336
+ }
1337
+
1338
+ /**
1339
+ * Assign a role's route through `agent.model.select()`.
1340
+ *
1341
+ * This is the only legal way to change a model on DSH 0.2.x: the loop fixes
1342
+ * provider/model/reasoningEffort at step preparation and rejects an
1343
+ * `agent/request` that proposes another route. Selection applies to the next
1344
+ * step whose preparation has not begun, so callers run it at `turn/start`
1345
+ * (before the first step) and at `agent/pre-step` (for the step after the one
1346
+ * in flight). Returns whether a selection was recorded; every failure is
1347
+ * contained.
1348
+ */
1349
+ function applySelection(agent, role, trigger, label, isSubagent) {
1350
+ const model = selectionModelOf(agent);
1351
+ if (model === undefined || !config.enabled) return false;
1352
+ try {
1353
+ if (config.strategy.mode === 'advisory') return false;
1354
+ const candidate = routeCandidate(role, agent.id);
1355
+ if (candidate === undefined) return false;
1356
+ const route = candidate.route;
1357
+ const current = probe(() => model.current());
1358
+ if (!selectionAllowed(agent, current, isSubagent)) {
1359
+ if (!isSubagent && current !== undefined) {
1360
+ log('info', `session ${shortId(agent.id)} keeps ${current.provider}/${current.model}: `
1361
+ + 'a hand-picked model is respected under hybrid');
1362
+ }
1363
+ return false;
1364
+ }
1365
+ if (sameSelection(current, route)) {
1366
+ managerSelected.set(agent.id, routeKey(route));
1367
+ return false;
1368
+ }
1369
+ model.select({
1370
+ provider: route.provider,
1371
+ model: route.model,
1372
+ ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }),
1373
+ });
1374
+ candidate.commit();
1375
+ managerSelected.delete(agent.id);
1376
+ managerSelected.set(agent.id, routeKey(route));
1377
+ while (managerSelected.size > MANAGER_APPLIED_LIMIT) {
1378
+ const oldest = managerSelected.keys().next().value;
1379
+ if (oldest === undefined) break;
1380
+ managerSelected.delete(oldest);
1381
+ }
1382
+ log('info', `selected ${route.provider}/${route.model} for ${shortId(agent.id)} (${role}) `
1383
+ + `before step preparation${trigger === undefined ? '' : ` — ${trigger}`}`);
1384
+ return true;
1385
+ } catch (error) {
1386
+ log('warn', `model selection skipped: ${error?.message ?? error}`);
1387
+ return false;
1388
+ }
1389
+ }
1390
+
1391
+ /**
1392
+ * One line describing how this harness accepts a route change.
1393
+ *
1394
+ * The two supported contracts differ enough that an operator has to be able
1395
+ * to tell which one is in force: 0.1.x rewrites the `agent/request` proposal,
1396
+ * 0.2.x fixes the route at step preparation and only accepts
1397
+ * `agent.model.select()` before it. Capability is read from the live agents,
1398
+ * so this reports what the running composition actually does.
1399
+ */
1400
+ function selectionTransport() {
1401
+ const agents = probe(() => ctx.get('agents'));
1402
+ const list = typeof agents?.list === 'function' ? probe(() => agents.list()) : undefined;
1403
+ const live = Array.isArray(list) ? list : [];
1404
+ if (live.length === 0) return 'not decided yet (no live agent has been observed)';
1405
+ if (live.some((agent) => selectionModelOf(agent) !== undefined)) {
1406
+ return 'agent.model.select() before step preparation (DSH ≥ 0.2)';
1407
+ }
1408
+ return 'agent/request route rewrite (DSH 0.1.x)';
1409
+ }
1410
+
1411
+ /** The live agent a session belongs to, or `undefined`. */
1412
+ function agentForSession(session) {
1413
+ const agents = probe(() => ctx.get('agents'));
1414
+ if (agents === undefined || session === undefined) return undefined;
1415
+ const direct = typeof agents.get === 'function' ? probe(() => agents.get(session.id)) : undefined;
1416
+ if (direct !== undefined) return direct;
1417
+ if (typeof agents.list !== 'function') return undefined;
1418
+ return probe(() => agents.list().find((candidate) => candidate.session === session));
1419
+ }
1420
+
1421
+ /**
1422
+ * Decide the role for a step that is claiming its input.
1423
+ *
1424
+ * `agent/inbox/claimed` is the one moment that beats the route fix without
1425
+ * fighting it: the loop's `preStep()` claims the batch first and reads
1426
+ * `agent.model.current()` straight after, and the claim notifications are
1427
+ * emitted outside any session append — so a selection made here is accepted
1428
+ * and lands on the step that is about to run. (`session/event` cannot do
1429
+ * this: its listeners run inside the append that is being published, where a
1430
+ * nested append is refused as reentrant.)
1431
+ *
1432
+ * The claimed message is what names the intent — the `/grilling` gesture, or
1433
+ * the plain prompt that leaves the session on `main` — so this is also where
1434
+ * a turn's FIRST request gets its role. Everything is wrapped: a selection
1435
+ * hook must never fail a step.
1436
+ */
1437
+ function onInboxClaimed(payload) {
1438
+ try {
1439
+ if (!config.enabled) return;
1440
+ const agent = payload?.agent;
1441
+ const message = payload?.message;
1442
+ if (agent === undefined || selectionModelOf(agent) === undefined) return;
1443
+ const isSubagent = probe(() => agent.session?.header?.origin === 'subagent') === true;
1444
+ if (isSubagent) {
1445
+ const facts = catalog.get(agent.id);
1446
+ // The label only exists behind an async listing. A child whose facts are
1447
+ // not cached yet runs its first step on the inherited route; the
1448
+ // pre-step hook then corrects it from the second step on. The eager
1449
+ // lookup in `subagent/start` usually wins that race.
1450
+ if (facts !== undefined) {
1451
+ applySelection(agent, classifySubagent(facts.label), undefined, facts.label, true);
1452
+ }
1453
+ return;
1454
+ }
1455
+ const plan = planActive(ctx, agent);
1456
+ const skill = plan
1457
+ ? undefined
1458
+ : (planningSkillFor(agent)
1459
+ ?? planningSkillInMessages([message], config.strategy.planningSkills));
1460
+ const trigger = skill === undefined ? (plan ? 'plan-mode' : 'main') : `skill:${skill}`;
1461
+ noteTopTrigger(agent, trigger);
1462
+ applySelection(agent, plan || skill !== undefined ? 'planning' : 'main', trigger, undefined, false);
1463
+ } catch {
1464
+ /* observe-only at the claim boundary */
1465
+ }
1466
+ }
1467
+
1209
1468
  /**
1210
1469
  * Which role owns a delegated child, from its delegation label.
1211
1470
  *
@@ -1400,6 +1659,34 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1400
1659
  return resolved;
1401
1660
  }
1402
1661
 
1662
+ // DSH 0.2.x fixes provider/model/reasoningEffort at step preparation and
1663
+ // aborts the turn when this waterfall proposes another route. Routing
1664
+ // therefore happens through `agent.model.select()` at `turn/start` and
1665
+ // `agent/pre-step`; here the manager only records what the step fixed and
1666
+ // returns it untouched.
1667
+ if (selectionModelOf(agent) !== undefined) {
1668
+ const candidate = routeCandidate(role, agent.id);
1669
+ const matches = managerSelected.get(agent.id) === routeKey(resolved)
1670
+ || (candidate !== undefined
1671
+ && candidate.route.provider === resolved.provider
1672
+ && candidate.route.model === resolved.model);
1673
+ remember(agent.id, {
1674
+ role,
1675
+ trigger,
1676
+ label,
1677
+ isSubagent,
1678
+ provider: resolved.provider,
1679
+ model: resolved.model,
1680
+ reasoningEffort: resolved.reasoningEffort,
1681
+ reason: matches
1682
+ ? 'step route selected before preparation'
1683
+ : 'step route fixed by the session',
1684
+ applied: matches,
1685
+ parentId: catalog.get(agent.id)?.parentId,
1686
+ });
1687
+ return resolved;
1688
+ }
1689
+
1403
1690
  // Record the attempt group, so the failover budget is per (turn, step).
1404
1691
  // `agent/request` re-fires for every attempt of the same step, so this
1405
1692
  // resets only when the step actually changes.
@@ -1575,6 +1862,28 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1575
1862
 
1576
1863
  const from = models[failedAt];
1577
1864
  const to = models[nextIndex];
1865
+ // DSH 0.2.x fixes the route at step preparation, so a retry of THIS step
1866
+ // always reuses the failed model. Select the next route instead: it is
1867
+ // what the next request will use, and this step ends with its failure
1868
+ // rather than retrying a model that is already known to be down.
1869
+ const model = selectionModelOf(agent);
1870
+ if (model !== undefined) {
1871
+ try {
1872
+ model.select({
1873
+ provider: to.provider,
1874
+ model: to.model,
1875
+ ...(to.reasoningEffort === undefined ? {} : { reasoningEffort: to.reasoningEffort }),
1876
+ });
1877
+ managerSelected.delete(agent.id);
1878
+ managerSelected.set(agent.id, routeKey(to));
1879
+ } catch (error) {
1880
+ log('warn', `failover could not select the next route: ${error?.message ?? error}`);
1881
+ }
1882
+ log('warn', `failover: ${role} ${from.provider}/${from.model} failed (${failure.code}); `
1883
+ + `the step route is fixed at preparation, so nothing is retried — the next request uses `
1884
+ + `${to.provider}/${to.model} (${budget.switches}/${MAX_SWITCHES_PER_STEP} this step)`);
1885
+ return undefined;
1886
+ }
1578
1887
  log('warn', `failover: ${role} ${from.provider}/${from.model} failed (${failure.code}); `
1579
1888
  + `re-running the step on ${to.provider}/${to.model} `
1580
1889
  + `(${budget.switches}/${MAX_SWITCHES_PER_STEP} switches this step)`);
@@ -2113,6 +2422,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2113
2422
  : 'not registered (no skills service in this composition, or skills/autoplan/SKILL.md '
2114
2423
  + 'is missing or invalid in this install)'}`,
2115
2424
  '',
2425
+ `Routing transport: ${selectionTransport()}`,
2426
+ '',
2116
2427
  allowListBlock(),
2117
2428
  '',
2118
2429
  visionBlock,
@@ -2391,6 +2702,15 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2391
2702
  * the manager off; the missing registration is logged at apply time.
2392
2703
  */
2393
2704
  function selectionWasExplicit(agent) {
2705
+ // On DSH 0.2.x a selection is a durable `model/selection` event regardless
2706
+ // of who wrote it, so the durable fold alone cannot tell a composer pick
2707
+ // from a route the manager itself selected. Ownership lives in
2708
+ // `managerSelected`: a route the manager does not own and that differs from
2709
+ // the agent's creation route is a hand-picked one.
2710
+ const model = selectionModelOf(agent);
2711
+ if (model !== undefined) {
2712
+ return selectionIsForeign(agent, probe(() => model.current()));
2713
+ }
2394
2714
  if (projections === undefined || typeof projections.stateOf !== 'function') return false;
2395
2715
  const state = probe(() => projections.stateOf(agent.session, SELECTION_PROJECTION_KEY));
2396
2716
  return state?.explicit === true;
@@ -2419,13 +2739,31 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2419
2739
  stepSwitches.delete(id);
2420
2740
  liveSkills.delete(id);
2421
2741
  topTriggers.delete(id);
2742
+ managerSelected.delete(id);
2422
2743
  });
2423
2744
 
2745
+ // Claim-boundary selection (DSH 0.2.x): the loop claims a step's input and
2746
+ // only then reads `agent.model.current()`, and the claim notifications are
2747
+ // emitted outside any session append — the one moment a role change can
2748
+ // reach the request that is about to run.
2749
+ ctx.on('agent/inbox/claimed', onInboxClaimed);
2750
+
2424
2751
  // Resolve a newly published child's label immediately, and targeted rather
2425
2752
  // than by sweeping every live agent.
2426
2753
  ctx.on('subagent/start', (info) => {
2427
2754
  const childId = info?.id;
2428
- if (childId !== undefined) void lookupChild(childId).catch(() => {});
2755
+ if (childId === undefined) return;
2756
+ void lookupChild(childId).then(() => {
2757
+ // DSH 0.2.x: the child's route has to be selected before its first
2758
+ // step is prepared, and the label only exists behind that async
2759
+ // listing. If this loses the race, the pre-step hook corrects the
2760
+ // route from the child's second step.
2761
+ const agent = agentForSession({ id: childId });
2762
+ const facts = catalog.get(childId);
2763
+ if (agent !== undefined && facts !== undefined) {
2764
+ applySelection(agent, classifySubagent(facts.label), undefined, facts.label, true);
2765
+ }
2766
+ }).catch(() => {});
2429
2767
  });
2430
2768
 
2431
2769
  // A volatile-only Settings edit is committed in place: the loader returns
@@ -2733,6 +3071,9 @@ export {
2733
3071
  skillNamesOfEvent,
2734
3072
  parseSkillMarkdown,
2735
3073
  autoplanSkillDefinition,
3074
+ selectionModelOf,
3075
+ sameSelection,
3076
+ planningSkillInMessages,
2736
3077
  DEFAULT_PLANNING_KEYWORDS,
2737
3078
  DEFAULT_PLANNING_SKILLS,
2738
3079
  DEFAULT_VISION_KEYWORDS,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@darkbear9494/dsh-model-manager",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
- "description": "Role-based model manager for DeepSeek Harness: assign models to planning, execution, vision and main roles, route subagent work by role, escalate sessions that invoke a planning skill (grilling / grill-me) to the planning role, report which model every subagent used, prompt the top-level agent to delegate, ship a /autoplan skill that plans on the planning tier then implements on main without stopping for approval, and check npm for updates.",
5
+ "description": "Role-based model manager for DeepSeek Harness: assign models to planning, execution, vision and main roles, route subagent work by role, escalate sessions that invoke a planning skill (grilling / grill-me) to the planning role, report which model every subagent used, prompt the top-level agent to delegate, ship a /autoplan skill that plans on the planning tier then implements on main without stopping for approval, and switch models through agent.model.select() on DSH 0.2.x, and check npm for updates.",
6
6
  "license": "MIT",
7
7
  "keywords": [
8
8
  "dsh",