@darkbear9494/dsh-model-manager 0.7.1 → 0.7.2
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 +516 -1741
- package/client.js +5 -5
- package/lib/index.js +631 -85
- package/package.json +4 -3
- package/skills/autoplan/SKILL.md +4 -3
package/lib/index.js
CHANGED
|
@@ -274,6 +274,28 @@ const TURN_COMMANDS = [
|
|
|
274
274
|
const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
275
275
|
const SKILL_GESTURE = /(^|\s)\/([a-z0-9]+(?:-[a-z0-9]+)*)(?=\s|$)/g;
|
|
276
276
|
|
|
277
|
+
/**
|
|
278
|
+
* Message-authored model directives.
|
|
279
|
+
*
|
|
280
|
+
* A mention is deliberately ASCII-only: model and provider ids are ASCII in
|
|
281
|
+
* the LLM catalog, and stopping before a non-ASCII character is what makes the
|
|
282
|
+
* natural Chinese form `@kimi-k3.1-pro来执行` parse as `kimi-k3.1-pro`, not as
|
|
283
|
+
* a different, non-existent id. The first slash separates an optional explicit
|
|
284
|
+
* provider; later slashes belong to the model id.
|
|
285
|
+
*/
|
|
286
|
+
const MODEL_REFERENCE_SOURCE = '[A-Za-z0-9](?:[A-Za-z0-9._/-]*[A-Za-z0-9])?';
|
|
287
|
+
const MODEL_REFERENCE = new RegExp(`^${MODEL_REFERENCE_SOURCE}$`);
|
|
288
|
+
const MODEL_MENTION = new RegExp(`@(${MODEL_REFERENCE_SOURCE})`, 'g');
|
|
289
|
+
const DIRECTIVE_PROJECTION_KEY = 'modelManagerDirectives';
|
|
290
|
+
const DIRECTIVE_MESSAGE_LIMIT = 128;
|
|
291
|
+
|
|
292
|
+
/** Role aliases accepted in direct user prose. English aliases require "model"
|
|
293
|
+
* where a bare word such as "main" would be too easy to hit accidentally. */
|
|
294
|
+
const DIRECTIVE_ROLE_ALIAS = /(主模型|主要模型|理解模型|规划与推理|规划模型|推理模型|执行模型|视觉模型|图像识别模型|图像模型|\bmain\s+model\b|\bplanning(?:\s+model)?\b|\breasoning(?:\s+model)?\b|\bunderstanding\s+model\b|\bexecution(?:\s+model)?\b|\bvision(?:\s+model)?\b|\bimage\s+model\b)/gi;
|
|
295
|
+
const DIRECTIVE_USE_WORD = /使用|用|选用|指定|设置|设为|换成|切换为|改用|\buse\b|\bset\b|\bassign\b/i;
|
|
296
|
+
const DIRECTIVE_NEGATION = /不|别|勿|\bnot\b|\bdo\s+not\b|\bdon't\b/i;
|
|
297
|
+
const DIRECTIVE_CLEAR = /取消[^,。;,;.!?]*(?:固定|指定)|恢复(?:为|到|至)?自动(?:分配|路由)|(?:改|切)?回自动(?:分配|路由)|使用自动(?:分配|路由)|\bclear\b[^.!?]*\bpin\b|\b(?:use|return\s+to)\s+automatic(?:\s+role)?\s+routing\b|\breset\b[^.!?]*\bautomatic\b/i;
|
|
298
|
+
|
|
277
299
|
/**
|
|
278
300
|
* Names of the skills one user message records, in order. Pure.
|
|
279
301
|
*
|
|
@@ -935,6 +957,198 @@ function planningSkillInMessages(messages, wanted) {
|
|
|
935
957
|
return undefined;
|
|
936
958
|
}
|
|
937
959
|
|
|
960
|
+
/** Remove code examples before directive recognition, preserving non-code prose. */
|
|
961
|
+
function directiveVisibleText(text) {
|
|
962
|
+
return text
|
|
963
|
+
.replace(/```[\s\S]*?(?:```|$)/g, ' ')
|
|
964
|
+
.replace(/`[^`\r\n]*`/g, ' ');
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/** Map one recognised alias to its existing routing role. */
|
|
968
|
+
function directiveRoleOf(alias) {
|
|
969
|
+
const value = alias.toLowerCase();
|
|
970
|
+
if (value.includes('main')) return 'main';
|
|
971
|
+
if (value.includes('planning') || value.includes('reasoning') || value.includes('understanding')) return 'planning';
|
|
972
|
+
if (value.includes('execution')) return 'execution';
|
|
973
|
+
if (value.includes('vision') || value.includes('image')) return 'vision';
|
|
974
|
+
if (value.includes('主')) return 'main';
|
|
975
|
+
if (value.includes('理解') || value.includes('规划') || value.includes('推理')) return 'planning';
|
|
976
|
+
if (value.includes('执行')) return 'execution';
|
|
977
|
+
return 'vision';
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/**
|
|
981
|
+
* Parse model assignments from direct user messages.
|
|
982
|
+
*
|
|
983
|
+
* The accepted shape is role + an explicit assignment verb + `@model` (a colon
|
|
984
|
+
* also works), for example `主模型请使用@kimi-k3.1-pro来执行`. Splitting at each
|
|
985
|
+
* role alias keeps `主模型…@a,理解模型…@b` unambiguous. A later assignment to
|
|
986
|
+
* the same role wins in the caller's fold. Plain `@file` references, quoted
|
|
987
|
+
* code, runtime messages, and delegation prompts have no effect.
|
|
988
|
+
*
|
|
989
|
+
* Returns patches in prose order: `{ role, reference }` or `{ role, clear: true }`.
|
|
990
|
+
*/
|
|
991
|
+
function modelDirectivesInMessages(messages) {
|
|
992
|
+
const patches = [];
|
|
993
|
+
for (const message of Array.isArray(messages) ? messages : []) {
|
|
994
|
+
// Only a person at the top-level composer is authoritative. In particular,
|
|
995
|
+
// a model-authored subagent brief also uses source.kind=user in DSH and must
|
|
996
|
+
// never silently create a session-level routing lock.
|
|
997
|
+
if (message?.source?.kind !== 'user') continue;
|
|
998
|
+
for (const block of Array.isArray(message.content) ? message.content : []) {
|
|
999
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue;
|
|
1000
|
+
const text = directiveVisibleText(block.text);
|
|
1001
|
+
// Mask mentions before finding role aliases: @vision-cn and
|
|
1002
|
+
// @block-execution are model ids, not new role clauses. Replacement with
|
|
1003
|
+
// equal-width spaces preserves every original string index.
|
|
1004
|
+
const aliasText = text.replace(MODEL_MENTION, (mention) => ' '.repeat(mention.length));
|
|
1005
|
+
const aliases = [...aliasText.matchAll(DIRECTIVE_ROLE_ALIAS)];
|
|
1006
|
+
for (let index = 0; index < aliases.length; index += 1) {
|
|
1007
|
+
const match = aliases[index];
|
|
1008
|
+
const role = directiveRoleOf(match[1]);
|
|
1009
|
+
const start = (match.index ?? 0) + match[0].length;
|
|
1010
|
+
const end = aliases[index + 1]?.index ?? text.length;
|
|
1011
|
+
const segment = text.slice(start, end);
|
|
1012
|
+
const prefix = text.slice(0, match.index ?? 0);
|
|
1013
|
+
const clausePrefix = prefix.split(/[\n。;,,.!?;]/).at(-1) ?? '';
|
|
1014
|
+
MODEL_MENTION.lastIndex = 0;
|
|
1015
|
+
const mention = MODEL_MENTION.exec(segment);
|
|
1016
|
+
if (mention !== null) {
|
|
1017
|
+
const before = segment.slice(0, mention.index);
|
|
1018
|
+
// Chinese and English role-first forms: "主模型请使用@x",
|
|
1019
|
+
// "set the main model to @x", "main model: @x". If the mention
|
|
1020
|
+
// actually introduces the NEXT role ("… and @y as the planning
|
|
1021
|
+
// model"), fall through to this role's mention-first check instead.
|
|
1022
|
+
const roleFirst = DIRECTIVE_USE_WORD.test(before) || /[::]\s*$/.test(before)
|
|
1023
|
+
|| /\b(?:to|be|is|as)\s*$/i.test(before);
|
|
1024
|
+
if (roleFirst) {
|
|
1025
|
+
if (DIRECTIVE_NEGATION.test(before) || DIRECTIVE_NEGATION.test(clausePrefix)) continue;
|
|
1026
|
+
patches.push({ role, reference: mention[1] });
|
|
1027
|
+
continue;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
// English also commonly puts the mention first: "use @x as the main
|
|
1031
|
+
// model". Only a short connector may separate mention and role, so an
|
|
1032
|
+
// earlier role's @assignment can never be captured by the next role.
|
|
1033
|
+
MODEL_MENTION.lastIndex = 0;
|
|
1034
|
+
let earlier;
|
|
1035
|
+
let candidate;
|
|
1036
|
+
while ((candidate = MODEL_MENTION.exec(prefix)) !== null) earlier = candidate;
|
|
1037
|
+
if (earlier !== undefined) {
|
|
1038
|
+
const connector = prefix.slice(earlier.index + earlier[0].length);
|
|
1039
|
+
const before = prefix.slice(0, earlier.index);
|
|
1040
|
+
if (/^\s*(?:as|for|to)(?:\s+the)?\s*$/i.test(connector)
|
|
1041
|
+
&& DIRECTIVE_USE_WORD.test(before) && !DIRECTIVE_NEGATION.test(before)) {
|
|
1042
|
+
patches.push({ role, reference: earlier[1] });
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
if (DIRECTIVE_CLEAR.test(segment)) patches.push({ role, clear: true });
|
|
1047
|
+
}
|
|
1048
|
+
if (aliases.length === 0 && /所有模型|全部模型|\ball\s+models\b/i.test(text)
|
|
1049
|
+
&& DIRECTIVE_CLEAR.test(text)) {
|
|
1050
|
+
for (const role of ROLE_NAMES) patches.push({ role, clear: true });
|
|
1051
|
+
}
|
|
1052
|
+
if (patches.length >= DIRECTIVE_MESSAGE_LIMIT) return patches.slice(0, DIRECTIVE_MESSAGE_LIMIT);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return patches;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/** Canonical, projection-safe directive state. */
|
|
1059
|
+
function normalizeDirectiveState(value) {
|
|
1060
|
+
if (value === null || typeof value !== 'object' || value.pins === null || typeof value.pins !== 'object') {
|
|
1061
|
+
throw new Error('expected an object with a pins object');
|
|
1062
|
+
}
|
|
1063
|
+
const pins = {};
|
|
1064
|
+
for (const role of ROLE_NAMES) {
|
|
1065
|
+
const candidate = value.pins[role];
|
|
1066
|
+
if (candidate === undefined) continue;
|
|
1067
|
+
if (candidate === null || typeof candidate !== 'object'
|
|
1068
|
+
|| typeof candidate.reference !== 'string' || !MODEL_REFERENCE.test(candidate.reference)) {
|
|
1069
|
+
throw new Error(`pins.${role}: expected a valid model reference`);
|
|
1070
|
+
}
|
|
1071
|
+
pins[role] = { reference: candidate.reference };
|
|
1072
|
+
}
|
|
1073
|
+
return {
|
|
1074
|
+
pins,
|
|
1075
|
+
// Projection-only provenance: delegated prompts are not user-authoritative,
|
|
1076
|
+
// except for the inherited prefix of a fork, which contains the person's
|
|
1077
|
+
// original session messages and must replay its directives.
|
|
1078
|
+
topLevel: value.topLevel !== false,
|
|
1079
|
+
inherited: Number.isSafeInteger(value.inherited) && value.inherited >= 0 ? value.inherited : 0,
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/** Apply live or durable patches without mutating the input state. */
|
|
1084
|
+
function applyDirectivePatches(state, patches) {
|
|
1085
|
+
let next = state;
|
|
1086
|
+
for (const patch of patches) {
|
|
1087
|
+
if (!ROLE_NAMES.includes(patch?.role)) continue;
|
|
1088
|
+
const previous = next.pins[patch.role];
|
|
1089
|
+
if (patch.clear === true) {
|
|
1090
|
+
if (previous === undefined) continue;
|
|
1091
|
+
const pins = { ...next.pins };
|
|
1092
|
+
delete pins[patch.role];
|
|
1093
|
+
next = { ...next, pins };
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
if (typeof patch.reference !== 'string' || !MODEL_REFERENCE.test(patch.reference)) continue;
|
|
1097
|
+
if (previous?.reference === patch.reference) continue;
|
|
1098
|
+
next = { ...next, pins: { ...next.pins, [patch.role]: { reference: patch.reference } } };
|
|
1099
|
+
}
|
|
1100
|
+
return next;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** Split `@provider/model`; a bare reference has no provider component. */
|
|
1104
|
+
function directiveReferenceParts(reference) {
|
|
1105
|
+
const slash = reference.indexOf('/');
|
|
1106
|
+
if (slash <= 0 || slash === reference.length - 1) return { model: reference };
|
|
1107
|
+
return { provider: reference.slice(0, slash), model: reference.slice(slash + 1) };
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/**
|
|
1111
|
+
* Resolve one raw reference against the synchronous catalog snapshot.
|
|
1112
|
+
*
|
|
1113
|
+
* Qualified references are exact and never need a model-list request. Bare ids
|
|
1114
|
+
* must be unique. While discovery is incomplete, a configured role route is a
|
|
1115
|
+
* deterministic provider hint; a catalog-only match waits for a complete scan
|
|
1116
|
+
* rather than guessing. No branch ever picks the first of several providers.
|
|
1117
|
+
*/
|
|
1118
|
+
function resolveModelDirective(directive, snapshot) {
|
|
1119
|
+
const reference = directive.reference;
|
|
1120
|
+
const { provider, model } = directiveReferenceParts(reference);
|
|
1121
|
+
const routes = Array.isArray(snapshot?.routes) ? snapshot.routes : [];
|
|
1122
|
+
const providers = snapshot?.providers;
|
|
1123
|
+
if (provider !== undefined) {
|
|
1124
|
+
if (providers instanceof Set && !providers.has(provider)) {
|
|
1125
|
+
return { status: 'unknown-provider', reference };
|
|
1126
|
+
}
|
|
1127
|
+
const configured = routes.find((route) => route.provider === provider && route.model === model);
|
|
1128
|
+
return { status: 'ok', reference, route: configured ?? { provider, model } };
|
|
1129
|
+
}
|
|
1130
|
+
const matches = [];
|
|
1131
|
+
const seen = new Set();
|
|
1132
|
+
for (const route of routes) {
|
|
1133
|
+
if (route.model !== model) continue;
|
|
1134
|
+
const key = routeKey(route);
|
|
1135
|
+
if (seen.has(key)) continue;
|
|
1136
|
+
seen.add(key);
|
|
1137
|
+
matches.push(route);
|
|
1138
|
+
}
|
|
1139
|
+
if (matches.length > 1) return { status: 'ambiguous', reference, matches };
|
|
1140
|
+
if (matches.length === 1) {
|
|
1141
|
+
if (providers instanceof Set && !providers.has(matches[0].provider)) {
|
|
1142
|
+
return { status: 'unknown-provider', reference };
|
|
1143
|
+
}
|
|
1144
|
+
if (snapshot?.complete === true || snapshot?.configured?.has?.(routeKey(matches[0]))) {
|
|
1145
|
+
return { status: 'ok', reference, route: matches[0] };
|
|
1146
|
+
}
|
|
1147
|
+
return { status: 'unresolved', reference, matches };
|
|
1148
|
+
}
|
|
1149
|
+
return { status: snapshot?.complete === true ? 'unknown' : 'unresolved', reference, matches: [] };
|
|
1150
|
+
}
|
|
1151
|
+
|
|
938
1152
|
/**
|
|
939
1153
|
* Whether a batch of user messages carries a given command's gesture. Pure.
|
|
940
1154
|
*
|
|
@@ -1125,7 +1339,13 @@ function delegationPolicyText(level, toolNames, opts) {
|
|
|
1125
1339
|
const vision = opts?.vision !== false;
|
|
1126
1340
|
const routed = opts?.routed !== false;
|
|
1127
1341
|
const fork = has('subagent_fork')
|
|
1128
|
-
? '
|
|
1342
|
+
? (has('subagent')
|
|
1343
|
+
? ' Prefer `subagent` with a self-contained brief for units that only need a few'
|
|
1344
|
+
+ ' facts — a fork re-reads the entire conversation on every one of its steps, so in a'
|
|
1345
|
+
+ ' long session it costs far more input tokens than a tight brief. Reserve'
|
|
1346
|
+
+ ' `subagent_fork` for units that genuinely need the whole discussion (e.g. an'
|
|
1347
|
+
+ ' initial plan).'
|
|
1348
|
+
: ' Prefer `subagent_fork` when a unit needs this conversation\'s own context.')
|
|
1129
1349
|
: '';
|
|
1130
1350
|
const subagentTool = has('subagent') ? '`subagent`' : '`subagent_fork`';
|
|
1131
1351
|
const planTag = planning ? ' as a `plan:` unit' : ' to a delegation';
|
|
@@ -1150,13 +1370,14 @@ function delegationPolicyText(level, toolNames, opts) {
|
|
|
1150
1370
|
'',
|
|
1151
1371
|
'Default to solving substantive work through subagents instead of doing it all yourself.',
|
|
1152
1372
|
'',
|
|
1153
|
-
'- Plan first: when a task
|
|
1154
|
-
`
|
|
1155
|
-
'
|
|
1156
|
-
`- Dispatch each unit as a ${subagentTool} delegation
|
|
1157
|
-
`
|
|
1158
|
-
'
|
|
1159
|
-
'
|
|
1373
|
+
'- Plan first: when a task touches 3 or more files, spans 2 or more independent areas,',
|
|
1374
|
+
` or needs 4 or more tool calls, delegate the decomposition itself${planTag}, then`,
|
|
1375
|
+
' dispatch the units it returned together in a single message.',
|
|
1376
|
+
`- Dispatch each independent unit as a ${subagentTool} delegation, all of them together`,
|
|
1377
|
+
` in one message — and continue useful work while they run.${fork}`,
|
|
1378
|
+
' If you are about to edit a second independent area yourself, delegate it instead.',
|
|
1379
|
+
'- Keep for yourself only: coordination, edits confined to a single file, decisions that',
|
|
1380
|
+
' need the user, and the final synthesis of every result.',
|
|
1160
1381
|
'- Verify what delegations return before presenting it as done; re-delegate or fix',
|
|
1161
1382
|
' yourself when a result misses.',
|
|
1162
1383
|
];
|
|
@@ -1229,9 +1450,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1229
1450
|
* `agent.model.select()` (the DSH 0.2.x selection path).
|
|
1230
1451
|
*
|
|
1231
1452
|
* A selected route is recorded in the session log exactly like a composer
|
|
1232
|
-
* pick, so ownership has to be remembered here
|
|
1233
|
-
*
|
|
1234
|
-
* session under `hybrid`.
|
|
1453
|
+
* pick, so ownership has to be remembered here for report origin and for the
|
|
1454
|
+
* separate explicit-child inheritance safeguard. It is not a top-level veto.
|
|
1235
1455
|
*/
|
|
1236
1456
|
const managerSelected = new Map();
|
|
1237
1457
|
const roundRobin = new Map();
|
|
@@ -1249,6 +1469,24 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1249
1469
|
/** session id -> `{ key: '<turn>:<step>', switches }`, the per-step budget. */
|
|
1250
1470
|
const stepSwitches = new Map();
|
|
1251
1471
|
|
|
1472
|
+
/**
|
|
1473
|
+
* Direct user patches not yet guaranteed to be in the durable projection.
|
|
1474
|
+
* Rebased onto the latest projection on every read, so replay cannot erase a
|
|
1475
|
+
* newer live choice and a restart reconstructs exactly the same raw intent.
|
|
1476
|
+
*/
|
|
1477
|
+
const liveDirectivePatches = new Map();
|
|
1478
|
+
/** child session id -> last inherited state, for a child outliving its parent. */
|
|
1479
|
+
const inheritedDirectiveFallbacks = new Map();
|
|
1480
|
+
/** Throttle unresolved/ambiguous directive warnings per session and role. */
|
|
1481
|
+
const directiveWarnings = new Map();
|
|
1482
|
+
|
|
1483
|
+
/** Synchronous model-catalog snapshot used at the claim boundary. */
|
|
1484
|
+
let discoveredRoutes = [];
|
|
1485
|
+
let discoveredProviders;
|
|
1486
|
+
let catalogComplete = false;
|
|
1487
|
+
let catalogGeneration = 0;
|
|
1488
|
+
let catalogRefresh;
|
|
1489
|
+
|
|
1252
1490
|
/**
|
|
1253
1491
|
* The `tools` service, captured when its injection resolves, so the
|
|
1254
1492
|
* delegation-policy section can ask which delegation tools an assembly's
|
|
@@ -1298,6 +1536,201 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1298
1536
|
let visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
1299
1537
|
let planningMatch = keywordMatcher(config.strategy.planningKeywords);
|
|
1300
1538
|
|
|
1539
|
+
/** Refresh the asynchronous half of the bare-model resolver. */
|
|
1540
|
+
function refreshModelCatalog(force = false) {
|
|
1541
|
+
if (catalogRefresh !== undefined && !force) return catalogRefresh;
|
|
1542
|
+
const generation = ++catalogGeneration;
|
|
1543
|
+
catalogComplete = false;
|
|
1544
|
+
catalogRefresh = (async () => {
|
|
1545
|
+
const llm = probe(() => ctx.get('llm'));
|
|
1546
|
+
if (llm === undefined || typeof llm.listProviders !== 'function'
|
|
1547
|
+
|| typeof llm.listModels !== 'function') return;
|
|
1548
|
+
const providers = probe(() => llm.listProviders());
|
|
1549
|
+
if (!Array.isArray(providers)) return;
|
|
1550
|
+
// Publish provider ownership synchronously with the refresh, so a
|
|
1551
|
+
// qualified route for a removed provider stops resolving immediately.
|
|
1552
|
+
discoveredProviders = new Set(providers.map((provider) => provider?.id).filter((id) => typeof id === 'string'));
|
|
1553
|
+
const results = await Promise.all(providers.map(async (provider) => {
|
|
1554
|
+
try {
|
|
1555
|
+
const models = await llm.listModels(provider.id);
|
|
1556
|
+
return {
|
|
1557
|
+
ok: true,
|
|
1558
|
+
routes: (Array.isArray(models) ? models : [])
|
|
1559
|
+
.filter((model) => typeof model?.id === 'string' && model.id !== '')
|
|
1560
|
+
.map((model) => ({ provider: provider.id, model: model.id })),
|
|
1561
|
+
};
|
|
1562
|
+
} catch (error) {
|
|
1563
|
+
return { ok: false, provider: provider.id, error };
|
|
1564
|
+
}
|
|
1565
|
+
}));
|
|
1566
|
+
// A slower, older discovery must never overwrite a newer adapter event.
|
|
1567
|
+
if (generation !== catalogGeneration) return;
|
|
1568
|
+
discoveredRoutes = results.filter((result) => result.ok).flatMap((result) => result.routes);
|
|
1569
|
+
catalogComplete = results.every((result) => result.ok);
|
|
1570
|
+
const failures = results.filter((result) => !result.ok);
|
|
1571
|
+
if (failures.length > 0) {
|
|
1572
|
+
log('warn', `model catalog incomplete; bare @model directives in unresolved providers will not be guessed: `
|
|
1573
|
+
+ failures.map((result) => `${result.provider} (${result.error?.message ?? result.error})`).join('; '));
|
|
1574
|
+
}
|
|
1575
|
+
})().catch((error) => {
|
|
1576
|
+
if (generation === catalogGeneration) {
|
|
1577
|
+
catalogComplete = false;
|
|
1578
|
+
log('warn', `model catalog refresh failed: ${error?.message ?? error}`);
|
|
1579
|
+
}
|
|
1580
|
+
}).finally(() => {
|
|
1581
|
+
if (generation === catalogGeneration) catalogRefresh = undefined;
|
|
1582
|
+
});
|
|
1583
|
+
return catalogRefresh;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
/** All synchronously known routes, plus which ones came from role config. */
|
|
1587
|
+
function directiveCatalogSnapshot(agent) {
|
|
1588
|
+
const configured = new Set();
|
|
1589
|
+
const byKey = new Map();
|
|
1590
|
+
for (const role of ROLE_NAMES) {
|
|
1591
|
+
for (const route of config.roles[role]?.models ?? []) {
|
|
1592
|
+
configured.add(routeKey(route));
|
|
1593
|
+
byKey.set(routeKey(route), route);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
for (const route of discoveredRoutes) {
|
|
1597
|
+
// Role config is more specific than discovery: it may carry an explicit
|
|
1598
|
+
// reasoningEffort that the catalog does not advertise on this entry.
|
|
1599
|
+
if (!byKey.has(routeKey(route))) byKey.set(routeKey(route), route);
|
|
1600
|
+
}
|
|
1601
|
+
// A route already running in this session is also a safe, exact hint when
|
|
1602
|
+
// the catalog is cold. It is not marked configured, so a partial discovery
|
|
1603
|
+
// still cannot turn it into an arbitrary bare-id choice.
|
|
1604
|
+
for (const route of [probe(() => agent?.options), effectiveRouteOf(agent)]) {
|
|
1605
|
+
if (route?.provider !== undefined && route?.model !== undefined) {
|
|
1606
|
+
byKey.set(routeKey(route), { provider: route.provider, model: route.model,
|
|
1607
|
+
...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }) });
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
return {
|
|
1611
|
+
routes: [...byKey.values()],
|
|
1612
|
+
providers: discoveredProviders,
|
|
1613
|
+
configured,
|
|
1614
|
+
complete: catalogComplete,
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
/** This session's own directives, before inheritance from a parent. */
|
|
1619
|
+
function ownDirectiveState(agent) {
|
|
1620
|
+
const projected = probe(() => projections?.stateOf?.(agent?.session, DIRECTIVE_PROJECTION_KEY));
|
|
1621
|
+
let state = projected === undefined ? { pins: {} } : normalizeDirectiveState(projected);
|
|
1622
|
+
const patches = liveDirectivePatches.get(agent?.id);
|
|
1623
|
+
if (patches !== undefined) state = applyDirectivePatches(state, [...patches.values()]);
|
|
1624
|
+
return state;
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
/**
|
|
1628
|
+
* Merge root-to-child directive state. A child inherits its parent's pins;
|
|
1629
|
+
* the inherited event prefix of a fork also replays the person's original
|
|
1630
|
+
* directives. Model-authored child prompts add no new pins. Lookup is bounded
|
|
1631
|
+
* and cycle-safe.
|
|
1632
|
+
*/
|
|
1633
|
+
function directiveStateFor(agent) {
|
|
1634
|
+
const isSubagent = probe(() => agent?.session?.header?.origin === 'subagent') === true;
|
|
1635
|
+
const directParent = isSubagent && typeof agent?.id === 'string' ? findParent(ctx, agent.id) : undefined;
|
|
1636
|
+
const chain = [];
|
|
1637
|
+
const seen = new Set();
|
|
1638
|
+
let current = agent;
|
|
1639
|
+
for (let depth = 0; current !== undefined && depth < 32; depth += 1) {
|
|
1640
|
+
const id = typeof current?.id === 'string' ? current.id : undefined;
|
|
1641
|
+
if (id === undefined || seen.has(id)) break;
|
|
1642
|
+
seen.add(id);
|
|
1643
|
+
chain.unshift(ownDirectiveState(current));
|
|
1644
|
+
if (probe(() => current?.session?.header?.origin === 'subagent') !== true) break;
|
|
1645
|
+
current = findParent(ctx, id);
|
|
1646
|
+
}
|
|
1647
|
+
if (directParent !== undefined) {
|
|
1648
|
+
// chain is root → … → parent → child. The live ancestors are authoritative:
|
|
1649
|
+
// a fork's replayed older pin must not override a later parent update/clear.
|
|
1650
|
+
const inherited = { pins: {} };
|
|
1651
|
+
for (const state of chain.slice(0, -1)) {
|
|
1652
|
+
Object.assign(inherited.pins, state.pins);
|
|
1653
|
+
}
|
|
1654
|
+
inheritedDirectiveFallbacks.set(agent.id, inherited);
|
|
1655
|
+
return inherited;
|
|
1656
|
+
}
|
|
1657
|
+
if (isSubagent) {
|
|
1658
|
+
const inherited = inheritedDirectiveFallbacks.get(agent.id);
|
|
1659
|
+
if (inherited !== undefined) {
|
|
1660
|
+
// The last live-parent snapshot also outranks the fork's older replay,
|
|
1661
|
+
// and unlike a merge it preserves a parent's later CLEAR (absence).
|
|
1662
|
+
return inherited;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
// No live parent and no snapshot: a fork can still reconstruct its original
|
|
1666
|
+
// inherited prefix. Ordinary top-level sessions take this path as well.
|
|
1667
|
+
const merged = { pins: {} };
|
|
1668
|
+
for (const state of chain) {
|
|
1669
|
+
Object.assign(merged.pins, state.pins);
|
|
1670
|
+
}
|
|
1671
|
+
return merged;
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
/** Resolve the active pin for one role, or undefined when it is automatic. */
|
|
1675
|
+
function directiveForRole(agent, role) {
|
|
1676
|
+
const directive = directiveStateFor(agent).pins[role];
|
|
1677
|
+
if (directive === undefined) return undefined;
|
|
1678
|
+
return resolveModelDirective(directive, directiveCatalogSnapshot(agent));
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
/** Explain a bad directive without throwing or selecting another model. */
|
|
1682
|
+
function noteDirectiveProblem(agent, role, directive) {
|
|
1683
|
+
if (directive === undefined || directive.status === 'ok') return;
|
|
1684
|
+
const detail = directive.status === 'ambiguous'
|
|
1685
|
+
? `ambiguous; use @provider/model (${directive.matches.map((route) => `${route.provider}/${route.model}`).join(', ')})`
|
|
1686
|
+
: directive.status === 'unknown-provider'
|
|
1687
|
+
? 'provider is not registered'
|
|
1688
|
+
: directive.status === 'unknown'
|
|
1689
|
+
? 'model id is not advertised; use an exact catalog id or @provider/model'
|
|
1690
|
+
: 'model catalog is incomplete; use @provider/model or retry after discovery';
|
|
1691
|
+
const key = `${agent?.id}::${role}::${directive.reference}::${directive.status}`;
|
|
1692
|
+
if (directiveWarnings.get(key) === true) return;
|
|
1693
|
+
directiveWarnings.set(key, true);
|
|
1694
|
+
while (directiveWarnings.size > MANAGER_APPLIED_LIMIT) {
|
|
1695
|
+
const oldest = directiveWarnings.keys().next().value;
|
|
1696
|
+
if (oldest === undefined) break;
|
|
1697
|
+
directiveWarnings.delete(oldest);
|
|
1698
|
+
}
|
|
1699
|
+
log('warn', `message directive ${role}=@${directive.reference} cannot be applied: ${detail}; `
|
|
1700
|
+
+ 'the current route is preserved and no automatic failover is attempted for that role');
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
/** Record direct-user patches before the first request of their step. */
|
|
1704
|
+
function observeModelDirectives(agent, messages) {
|
|
1705
|
+
const patches = modelDirectivesInMessages(messages);
|
|
1706
|
+
if (patches.length === 0 || typeof agent?.id !== 'string') return;
|
|
1707
|
+
let owned = liveDirectivePatches.get(agent.id);
|
|
1708
|
+
if (owned === undefined) {
|
|
1709
|
+
owned = new Map();
|
|
1710
|
+
liveDirectivePatches.set(agent.id, owned);
|
|
1711
|
+
}
|
|
1712
|
+
for (const patch of patches) {
|
|
1713
|
+
const previous = owned.get(patch.role);
|
|
1714
|
+
if (previous?.clear === patch.clear && previous?.reference === patch.reference) continue;
|
|
1715
|
+
owned.set(patch.role, patch);
|
|
1716
|
+
log('info', `message directive for ${shortId(agent.id)}: ${patch.role} `
|
|
1717
|
+
+ (patch.clear === true ? 'returns to automatic role routing' : `pinned to @${patch.reference}`));
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
/** Human/model-facing active-pin summary for diagnostics and prompt context. */
|
|
1722
|
+
function directiveSummary(agent) {
|
|
1723
|
+
const lines = [];
|
|
1724
|
+
for (const role of ROLE_NAMES) {
|
|
1725
|
+
const directive = directiveForRole(agent, role);
|
|
1726
|
+
if (directive === undefined) continue;
|
|
1727
|
+
lines.push(directive.status === 'ok'
|
|
1728
|
+
? `${role}=@${directive.reference} → ${directive.route.provider}/${directive.route.model} (pinned; no rotation or failover)`
|
|
1729
|
+
: `${role}=@${directive.reference} (${directive.status}; current route preserved, no manager failover)`);
|
|
1730
|
+
}
|
|
1731
|
+
return lines;
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1301
1734
|
/**
|
|
1302
1735
|
* How many sessions' live skill names are remembered, and how many names one
|
|
1303
1736
|
* session keeps. Both are backstops: `agent/disposed` is the normal cleanup,
|
|
@@ -1399,15 +1832,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1399
1832
|
try {
|
|
1400
1833
|
const agent = payload?.agent;
|
|
1401
1834
|
const id = typeof agent?.id === 'string' ? agent.id : undefined;
|
|
1402
|
-
const isSubagent = agent ===
|
|
1403
|
-
? false
|
|
1404
|
-
: probe(() => agent.session?.header?.origin === 'subagent') === true;
|
|
1835
|
+
const isSubagent = probe(() => agent?.session?.header?.origin === 'subagent') === true;
|
|
1405
1836
|
if (id !== undefined && decision?.kind !== 'reject') {
|
|
1406
1837
|
for (const batch of [payload?.messages, decision?.messages]) {
|
|
1407
1838
|
if (!Array.isArray(batch)) continue;
|
|
1408
1839
|
for (const message of batch) {
|
|
1409
1840
|
for (const name of skillNamesOfMessage(message)) addLiveSkill(id, name);
|
|
1410
1841
|
}
|
|
1842
|
+
// The claim hook covers DSH 0.2's first request. This second scan is
|
|
1843
|
+
// the 0.1 fallback (and a resilience path if a claim was missed);
|
|
1844
|
+
// identical patches are deduplicated by observeModelDirectives.
|
|
1845
|
+
if (!isSubagent) observeModelDirectives(agent, batch);
|
|
1411
1846
|
}
|
|
1412
1847
|
// The one-turn command override binds here too, on every transport:
|
|
1413
1848
|
// the claim boundary covers the first step, and this scan covers a
|
|
@@ -1540,12 +1975,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1540
1975
|
* End the override when a DIFFERENT turn claims input, handing a remembered
|
|
1541
1976
|
* composer pick back.
|
|
1542
1977
|
*
|
|
1543
|
-
* The restore is selected before the normal role decision runs
|
|
1544
|
-
*
|
|
1545
|
-
*
|
|
1546
|
-
*
|
|
1547
|
-
*
|
|
1548
|
-
*
|
|
1978
|
+
* The restore is selected before the normal role decision runs. It is a UI
|
|
1979
|
+
* courtesy, not a routing veto: a composer pick no longer locks the route,
|
|
1980
|
+
* so the next plain turn applies the active role's route again (a message
|
|
1981
|
+
* pin, if any, still wins). Ownership is dropped on purpose so the restored
|
|
1982
|
+
* pick is never mistaken for a manager-applied route. On the 0.1.x rewrite
|
|
1983
|
+
* path nothing was ever durably selected, so there is nothing to restore.
|
|
1549
1984
|
*/
|
|
1550
1985
|
function endCommandTurn(agent, turn) {
|
|
1551
1986
|
const id = typeof agent?.id === 'string' ? agent.id : undefined;
|
|
@@ -1559,9 +1994,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1559
1994
|
if (model === undefined) return;
|
|
1560
1995
|
try {
|
|
1561
1996
|
// A hand pick made AFTER the commanded turn is newer than the one
|
|
1562
|
-
// remembered at command time. Keep it and drop ownership
|
|
1563
|
-
//
|
|
1564
|
-
//
|
|
1997
|
+
// remembered at command time. Keep it and drop ownership — restoring
|
|
1998
|
+
// the stale memory would eat the user's latest choice, which is exactly
|
|
1999
|
+
// what the hand-back exists to protect.
|
|
1565
2000
|
const current = probe(() => model.current());
|
|
1566
2001
|
if (selectionIsForeign(agent, current)) {
|
|
1567
2002
|
managerSelected.delete(id);
|
|
@@ -1645,17 +2080,28 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1645
2080
|
return { route: models[at], commit() {} };
|
|
1646
2081
|
}
|
|
1647
2082
|
|
|
2083
|
+
/**
|
|
2084
|
+
* Resolve a role for one agent. A valid message pin bypasses every automatic
|
|
2085
|
+
* cursor; an unresolved pin fails closed and preserves the current route.
|
|
2086
|
+
* In neither case is round-robin or failover state consumed.
|
|
2087
|
+
*/
|
|
2088
|
+
function candidateForAgent(agent, role) {
|
|
2089
|
+
const directive = directiveForRole(agent, role);
|
|
2090
|
+
if (directive === undefined) return routeCandidate(role, agent?.id);
|
|
2091
|
+
noteDirectiveProblem(agent, role, directive);
|
|
2092
|
+
if (directive.status !== 'ok') return { route: undefined, directive, commit() {} };
|
|
2093
|
+
return { route: directive.route, directive, commit() {} };
|
|
2094
|
+
}
|
|
2095
|
+
|
|
1648
2096
|
// -- model selection (DSH 0.2.x) ------------------------------------------
|
|
1649
2097
|
|
|
1650
2098
|
/**
|
|
1651
2099
|
* Whether the agent's current selection was recorded by somebody else.
|
|
1652
2100
|
*
|
|
1653
2101
|
* A route the manager selected is its own; a route equal to the agent's
|
|
1654
|
-
* creation options is the deployment default (or the inherited parent route)
|
|
1655
|
-
*
|
|
1656
|
-
*
|
|
1657
|
-
* `hybrid` leaves it alone, exactly when it is neither manager-owned nor the
|
|
1658
|
-
* deployment default.
|
|
2102
|
+
* creation options is the deployment default (or the inherited parent route).
|
|
2103
|
+
* Anything else is a foreign origin — a composer pick, resume override, or
|
|
2104
|
+
* explicit child route. This is report/lineage metadata, not a top-level veto.
|
|
1659
2105
|
*/
|
|
1660
2106
|
function selectionIsForeign(agent, current) {
|
|
1661
2107
|
if (current === undefined) return false;
|
|
@@ -1689,7 +2135,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1689
2135
|
/** Whether `hybrid` permits replacing the agent's current route with `route`. */
|
|
1690
2136
|
function selectionAllowed(agent, current, isSubagent) {
|
|
1691
2137
|
if (config.strategy.mode !== 'hybrid') return true;
|
|
1692
|
-
|
|
2138
|
+
// A composer pick is no longer a routing lock. Only a direct @model message
|
|
2139
|
+
// pins a top-level role; otherwise its configured role route always applies.
|
|
2140
|
+
if (!isSubagent) return true;
|
|
1693
2141
|
return childRouteIsInherited(agent, current);
|
|
1694
2142
|
}
|
|
1695
2143
|
|
|
@@ -1705,26 +2153,25 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1705
2153
|
* contained.
|
|
1706
2154
|
*
|
|
1707
2155
|
* `force` is the one-turn commands' authority (`/readimage`, `/quicktask`):
|
|
1708
|
-
* an explicit user instruction for THIS message outranks
|
|
1709
|
-
*
|
|
1710
|
-
*
|
|
1711
|
-
*
|
|
1712
|
-
* all.
|
|
2156
|
+
* an explicit user instruction for THIS message outranks the child
|
|
2157
|
+
* inheritance safeguard for the turn it commands. A composer pick is no
|
|
2158
|
+
* longer a routing lock, but `endCommandTurn` still hands the pick back to
|
|
2159
|
+
* the UI afterwards. `force` never bypasses the master switch or advisory
|
|
2160
|
+
* mode — those mean the manager does not move routes at all.
|
|
1713
2161
|
*/
|
|
1714
2162
|
function applySelection(agent, role, trigger, label, isSubagent, force = false) {
|
|
1715
2163
|
const model = selectionModelOf(agent);
|
|
1716
2164
|
if (model === undefined || !config.enabled) return false;
|
|
1717
2165
|
try {
|
|
1718
2166
|
if (config.strategy.mode === 'advisory') return false;
|
|
1719
|
-
const candidate =
|
|
1720
|
-
if (candidate === undefined) return false;
|
|
2167
|
+
const candidate = candidateForAgent(agent, role);
|
|
2168
|
+
if (candidate?.route === undefined) return false;
|
|
1721
2169
|
const route = candidate.route;
|
|
1722
2170
|
const current = probe(() => model.current());
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
}
|
|
2171
|
+
// Message pins are user-authoritative even for an explicitly delegated
|
|
2172
|
+
// child route, and a one-turn command forces its role for this turn.
|
|
2173
|
+
// Unpinned, unforced children keep the existing inheritance safeguard.
|
|
2174
|
+
if (!force && candidate.directive === undefined && !selectionAllowed(agent, current, isSubagent)) {
|
|
1728
2175
|
return false;
|
|
1729
2176
|
}
|
|
1730
2177
|
if (sameSelection(current, route)) {
|
|
@@ -1804,8 +2251,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
1804
2251
|
if (!config.enabled) return;
|
|
1805
2252
|
const agent = payload?.agent;
|
|
1806
2253
|
const message = payload?.message;
|
|
1807
|
-
if (agent === undefined
|
|
2254
|
+
if (agent === undefined) return;
|
|
1808
2255
|
const isSubagent = probe(() => agent.session?.header?.origin === 'subagent') === true;
|
|
2256
|
+
// Only top-level human input is authoritative. Subagents inherit these
|
|
2257
|
+
// pins through directiveStateFor rather than promoting their own briefs.
|
|
2258
|
+
if (!isSubagent) observeModelDirectives(agent, [message]);
|
|
2259
|
+
if (selectionModelOf(agent) === undefined) return;
|
|
1809
2260
|
if (isSubagent) {
|
|
1810
2261
|
const facts = catalog.get(agent.id);
|
|
1811
2262
|
// The label only exists behind an async listing. A child whose facts are
|
|
@@ -2048,11 +2499,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2048
2499
|
// `agent/pre-step`; here the manager only records what the step fixed and
|
|
2049
2500
|
// returns it untouched.
|
|
2050
2501
|
if (selectionModelOf(agent) !== undefined) {
|
|
2051
|
-
const candidate =
|
|
2052
|
-
const
|
|
2053
|
-
|
|
2502
|
+
const candidate = candidateForAgent(agent, role);
|
|
2503
|
+
const invalidDirective = candidate?.directive !== undefined && candidate.route === undefined;
|
|
2504
|
+
const matches = !invalidDirective && (managerSelected.get(agent.id) === routeKey(resolved)
|
|
2505
|
+
|| (candidate?.route !== undefined
|
|
2054
2506
|
&& candidate.route.provider === resolved.provider
|
|
2055
|
-
&& candidate.route.model === resolved.model);
|
|
2507
|
+
&& candidate.route.model === resolved.model));
|
|
2056
2508
|
remember(agent.id, {
|
|
2057
2509
|
role,
|
|
2058
2510
|
trigger,
|
|
@@ -2061,10 +2513,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2061
2513
|
provider: resolved.provider,
|
|
2062
2514
|
model: resolved.model,
|
|
2063
2515
|
reasoningEffort: resolved.reasoningEffort,
|
|
2064
|
-
reason:
|
|
2065
|
-
? '
|
|
2066
|
-
:
|
|
2516
|
+
reason: invalidDirective
|
|
2517
|
+
? 'message directive unresolved'
|
|
2518
|
+
: candidate?.directive !== undefined && matches
|
|
2519
|
+
? 'message directive (pinned)'
|
|
2520
|
+
: matches
|
|
2521
|
+
? 'step route selected before preparation'
|
|
2522
|
+
: 'step route fixed by the session',
|
|
2067
2523
|
applied: matches,
|
|
2524
|
+
pinned: candidate?.directive !== undefined,
|
|
2525
|
+
pinRoute: candidate?.directive?.status === 'ok' && matches
|
|
2526
|
+
? { provider: resolved.provider, model: resolved.model } : undefined,
|
|
2068
2527
|
parentId: catalog.get(agent.id)?.parentId,
|
|
2069
2528
|
});
|
|
2070
2529
|
return resolved;
|
|
@@ -2079,15 +2538,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2079
2538
|
stepSwitches.set(agent.id, { key: stepKey, switches: 0 });
|
|
2080
2539
|
}
|
|
2081
2540
|
|
|
2082
|
-
const candidate =
|
|
2083
|
-
if (candidate === undefined) {
|
|
2541
|
+
const candidate = candidateForAgent(agent, role);
|
|
2542
|
+
if (candidate?.route === undefined) {
|
|
2084
2543
|
remember(agent.id, {
|
|
2085
2544
|
role,
|
|
2086
2545
|
trigger,
|
|
2087
2546
|
provider: resolved.provider,
|
|
2088
2547
|
model: resolved.model,
|
|
2089
|
-
reason:
|
|
2548
|
+
reason: candidate?.directive !== undefined
|
|
2549
|
+
? 'message directive unresolved' : 'passthrough (role unconfigured)',
|
|
2090
2550
|
applied: false,
|
|
2551
|
+
pinned: candidate?.directive !== undefined,
|
|
2091
2552
|
isSubagent,
|
|
2092
2553
|
label,
|
|
2093
2554
|
});
|
|
@@ -2103,22 +2564,20 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2103
2564
|
if (mode === 'advisory') {
|
|
2104
2565
|
reason = 'advisory (not applied)';
|
|
2105
2566
|
output = resolved;
|
|
2567
|
+
} else if (candidate.directive !== undefined) {
|
|
2568
|
+
// A direct user pin outranks composer and delegation choices. Its
|
|
2569
|
+
// candidate has a no-op commit, so rotation/failover cursors stay put.
|
|
2570
|
+
reason = 'message directive (pinned)';
|
|
2571
|
+
output = applyRoute(resolved, route);
|
|
2572
|
+
didApply = true;
|
|
2106
2573
|
} else {
|
|
2107
2574
|
let inherited = true;
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
// session the user already picked, and is left untouched here.
|
|
2115
|
-
// The one-turn commands are the one exception: each is an explicit
|
|
2116
|
-
// user instruction for THIS turn, newer than the pick, so it rewrites
|
|
2117
|
-
// for that turn only — the durable selection is untouched on this
|
|
2118
|
-
// path, and the next turn respects the pick again by itself.
|
|
2119
|
-
inherited = false;
|
|
2120
|
-
reason = 'explicit session selection (respected)';
|
|
2121
|
-
} else if (mode === 'hybrid' && isSubagent) {
|
|
2575
|
+
// Composer selections deliberately have no branch here: under hybrid
|
|
2576
|
+
// the top-level role route applies whether or not a person picked a
|
|
2577
|
+
// model in the main UI. Only a message directive creates a lasting pin.
|
|
2578
|
+
// The one-turn commands still force their role for the commanded turn
|
|
2579
|
+
// (see `command` above); the turn after it routes by role again.
|
|
2580
|
+
if (mode === 'hybrid' && isSubagent) {
|
|
2122
2581
|
// Respect an explicit delegation choice. A child counts as inheriting
|
|
2123
2582
|
// when its resolved route is either the delegating parent's *effective*
|
|
2124
2583
|
// route (mirroring DSH's own parentAgentOptionsForDelegation) or the
|
|
@@ -2174,6 +2633,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2174
2633
|
reasoningEffort: output.reasoningEffort,
|
|
2175
2634
|
reason,
|
|
2176
2635
|
applied: didApply,
|
|
2636
|
+
pinned: candidate.directive !== undefined,
|
|
2637
|
+
pinRoute: candidate.directive?.status === 'ok' && didApply
|
|
2638
|
+
? { provider: output.provider, model: output.model } : undefined,
|
|
2177
2639
|
parentId: catalog.get(agent.id)?.parentId,
|
|
2178
2640
|
});
|
|
2179
2641
|
return output;
|
|
@@ -2213,8 +2675,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2213
2675
|
|
|
2214
2676
|
// The role is the one this manager routed the failed request as; with no
|
|
2215
2677
|
// such record there is no chain to fail over within.
|
|
2216
|
-
const
|
|
2678
|
+
const seen = usage.get(agent.id);
|
|
2679
|
+
const role = seen?.role;
|
|
2217
2680
|
if (role === undefined) return undefined;
|
|
2681
|
+
// A pin belongs to the failed ATTEMPT, not merely to current live state.
|
|
2682
|
+
// This check precedes every cursor mutation and model.select(), while a
|
|
2683
|
+
// downstream same-model retry/compaction decision has already won above.
|
|
2684
|
+
if (seen.pinned === true || directiveForRole(agent, role) !== undefined) {
|
|
2685
|
+
log('info', `failover suppressed for ${shortId(agent.id)} (${role}): `
|
|
2686
|
+
+ 'a direct message directive requires the specified model to remain unchanged');
|
|
2687
|
+
return undefined;
|
|
2688
|
+
}
|
|
2218
2689
|
const models = effectiveModels(role);
|
|
2219
2690
|
if (models.length < 2) return undefined;
|
|
2220
2691
|
|
|
@@ -2683,13 +3154,13 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2683
3154
|
for (const row of topRows) {
|
|
2684
3155
|
const live = probe(() => ctx.get('agents')?.get?.(row.sessionId));
|
|
2685
3156
|
const status = live === undefined ? 'inactive' : String(live.status ?? 'live');
|
|
2686
|
-
//
|
|
2687
|
-
//
|
|
3157
|
+
// A composer selection is an origin fact, not a routing veto. Lasting
|
|
3158
|
+
// pins come only from direct user messages and are listed separately.
|
|
2688
3159
|
const origin = live === undefined
|
|
2689
3160
|
? 'unknown, agent no longer live'
|
|
2690
3161
|
: selectionWasExplicit(live)
|
|
2691
|
-
? '
|
|
2692
|
-
: '
|
|
3162
|
+
? 'composer pick; automatic routing still applies'
|
|
3163
|
+
: 'deployment default; automatic routing applies';
|
|
2693
3164
|
lines.push([
|
|
2694
3165
|
shortId(row.sessionId),
|
|
2695
3166
|
String(row.seen.role ?? '?').padEnd(9),
|
|
@@ -2700,9 +3171,16 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2700
3171
|
].join(' '));
|
|
2701
3172
|
}
|
|
2702
3173
|
lines.push('');
|
|
2703
|
-
lines.push('
|
|
2704
|
-
lines.push('
|
|
2705
|
-
|
|
3174
|
+
lines.push('Composer selections do not lock the top-level route. Automatic role routing applies');
|
|
3175
|
+
lines.push('unless a direct user message pins the role with @model or @provider/model.');
|
|
3176
|
+
const directiveRows = topRows.flatMap((row) => {
|
|
3177
|
+
const live = probe(() => ctx.get('agents')?.get?.(row.sessionId));
|
|
3178
|
+
return live === undefined ? [] : directiveSummary(live)
|
|
3179
|
+
.map((summary) => `${shortId(row.sessionId)} ${summary}`);
|
|
3180
|
+
});
|
|
3181
|
+
if (directiveRows.length > 0) {
|
|
3182
|
+
lines.push('', 'Message model directives (persist for the session):', ...directiveRows);
|
|
3183
|
+
}
|
|
2706
3184
|
const skillTriggers = topRows.filter((row) => typeof row.seen.trigger === 'string'
|
|
2707
3185
|
&& row.seen.trigger.startsWith('skill:')
|
|
2708
3186
|
&& row.seen.reason !== 'manager disabled (observed only)');
|
|
@@ -2712,7 +3190,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2712
3190
|
.map((row) => `${shortId(row.sessionId)} → ${row.seen.trigger.slice('skill:'.length)}`)
|
|
2713
3191
|
.join(', '));
|
|
2714
3192
|
lines.push('These sessions invoked a planning skill, so they route to the planning tier for');
|
|
2715
|
-
lines.push('the rest of the session, like plan mode
|
|
3193
|
+
lines.push('the rest of the session, like plan mode, unless that role has a message pin.');
|
|
2716
3194
|
}
|
|
2717
3195
|
const commandTriggers = topRows.filter((row) => typeof row.seen.trigger === 'string'
|
|
2718
3196
|
&& row.seen.trigger.startsWith('command:')
|
|
@@ -2779,6 +3257,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2779
3257
|
}
|
|
2780
3258
|
|
|
2781
3259
|
async function routes() {
|
|
3260
|
+
await refreshModelCatalog();
|
|
2782
3261
|
const vision = await visionReport();
|
|
2783
3262
|
const visionBlock = vision.reason === 'no-service'
|
|
2784
3263
|
? 'Vision role: not checked (no llm service in this composition).'
|
|
@@ -2794,6 +3273,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2794
3273
|
return ` ${tag} ${row.label} — ${row.detail}`;
|
|
2795
3274
|
}),
|
|
2796
3275
|
].join('\n');
|
|
3276
|
+
const liveAgents = probe(() => ctx.get('agents')?.list?.());
|
|
3277
|
+
const activeDirectives = (Array.isArray(liveAgents) ? liveAgents : []).flatMap((agent) =>
|
|
3278
|
+
directiveSummary(agent).map((summary) => ` ${shortId(agent?.id)} ${summary}`));
|
|
3279
|
+
const directiveBlock = activeDirectives.length === 0
|
|
3280
|
+
? 'Message directives: no active pins observed. Pin a role in Chinese or English, for example\n'
|
|
3281
|
+
+ ' 主模型请使用@kimi-k3.1-pro,理解模型用@glm-5.3-prime\n'
|
|
3282
|
+
+ ' Use @kimi-k3.1-pro as the main model and @glm-5.3-prime as the understanding model.'
|
|
3283
|
+
: ['Message directives (session-persistent; unspecified roles remain automatic):',
|
|
3284
|
+
...activeDirectives,
|
|
3285
|
+
' Later “keep the previous model assignments” messages preserve these pins; a new',
|
|
3286
|
+
' assignment overrides one role, and an explicit automatic-routing request clears it.'].join('\n');
|
|
2797
3287
|
return [
|
|
2798
3288
|
'Model manager roles',
|
|
2799
3289
|
'',
|
|
@@ -2810,6 +3300,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2810
3300
|
+ (config.strategy.mode === 'managed' ? ' (always apply the role route)' : '')
|
|
2811
3301
|
+ (config.strategy.mode === 'advisory' ? ' (never rewrite — report only)' : ''),
|
|
2812
3302
|
'',
|
|
3303
|
+
directiveBlock,
|
|
3304
|
+
'',
|
|
2813
3305
|
`Auto-delegation: ${config.strategy.autoDelegate === 'off'
|
|
2814
3306
|
? 'off — no delegation policy is added to the system prompt'
|
|
2815
3307
|
: `${config.strategy.autoDelegate} — the top-level agent is prompted to ${config.strategy.autoDelegate === 'eager'
|
|
@@ -2858,7 +3350,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2858
3350
|
].join('\n');
|
|
2859
3351
|
}
|
|
2860
3352
|
|
|
2861
|
-
function cheatSheet() {
|
|
3353
|
+
function cheatSheet(context) {
|
|
2862
3354
|
const summary = ROLE_NAMES
|
|
2863
3355
|
.map((key) => {
|
|
2864
3356
|
const models = effectiveModels(key);
|
|
@@ -2866,13 +3358,16 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2866
3358
|
return ` ${key}: ${models.map((route) => `${route.provider}/${route.model}`).join(', ')}`;
|
|
2867
3359
|
})
|
|
2868
3360
|
.filter(Boolean);
|
|
2869
|
-
|
|
3361
|
+
const pins = directiveSummary(context?.agent);
|
|
3362
|
+
if (summary.length === 0 && pins.length === 0) return '';
|
|
2870
3363
|
const routing = config.strategy.mode === 'advisory'
|
|
2871
3364
|
? 'The manager is observing only (advisory), so labels classify but never rewrite a route.'
|
|
2872
3365
|
: [
|
|
2873
3366
|
'Label a delegation `description` with "plan:" for thinking work, "vision:" for image',
|
|
2874
3367
|
'work, or leave it plain for execution; a leading prefix wins over keyword matches.',
|
|
2875
3368
|
'Leave `provider` and `model` unset on those units so the role route applies.',
|
|
3369
|
+
'A direct user @model directive pins only the named role for the session, outranks a',
|
|
3370
|
+
'composer pick, and disables manager rotation/failover. Unspecified roles stay automatic.',
|
|
2876
3371
|
].join('\n');
|
|
2877
3372
|
const planningGap = effectiveModels('planning').length === 0
|
|
2878
3373
|
? '\nThe planning tier has no models, so "plan:" labels keep the inherited route.'
|
|
@@ -2898,6 +3393,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
2898
3393
|
'Delegated work is routed by the label you give each delegation:',
|
|
2899
3394
|
...summary,
|
|
2900
3395
|
routing,
|
|
3396
|
+
...(pins.length === 0 ? [] : ['Active message directives:', ...pins.map((line) => ` ${line}`)]),
|
|
2901
3397
|
`Call \`model_manager\` with action "report" to see which model each subagent actually used.${planningGap}${skillNote}${readImageNote}${quickTaskNote}`,
|
|
2902
3398
|
].join('\n');
|
|
2903
3399
|
}
|
|
@@ -3035,6 +3531,30 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3035
3531
|
wire: { viewSchema: usageProjectionSchema, view: (state) => state },
|
|
3036
3532
|
};
|
|
3037
3533
|
|
|
3534
|
+
/**
|
|
3535
|
+
* Raw message-authored model pins, folded from the durable session log.
|
|
3536
|
+
* Resolution stays outside the fold because provider discovery is async and
|
|
3537
|
+
* may change after restart. The live claim-time map covers the not-yet-
|
|
3538
|
+
* committed message; this projection covers restart, resume and fork replay.
|
|
3539
|
+
*/
|
|
3540
|
+
const directiveProjectionSchema = { parse: normalizeDirectiveState };
|
|
3541
|
+
const directiveProjectionDefinition = {
|
|
3542
|
+
key: DIRECTIVE_PROJECTION_KEY,
|
|
3543
|
+
stateVersion: 1,
|
|
3544
|
+
stateSchema: directiveProjectionSchema,
|
|
3545
|
+
init: (header, inheritedEventCount) => ({
|
|
3546
|
+
pins: {},
|
|
3547
|
+
topLevel: header?.origin !== 'subagent',
|
|
3548
|
+
inherited: Number.isSafeInteger(inheritedEventCount) && inheritedEventCount > 0 ? inheritedEventCount : 0,
|
|
3549
|
+
}),
|
|
3550
|
+
apply: (state, event) => {
|
|
3551
|
+
const inherited = state.inherited > 0;
|
|
3552
|
+
const base = inherited ? { ...state, inherited: state.inherited - 1 } : state;
|
|
3553
|
+
if (event.type !== 'user/message' || (!state.topLevel && !inherited)) return base;
|
|
3554
|
+
return applyDirectivePatches(base, modelDirectivesInMessages([event.data]));
|
|
3555
|
+
},
|
|
3556
|
+
};
|
|
3557
|
+
|
|
3038
3558
|
/**
|
|
3039
3559
|
* Whether this Session ever recorded an *explicit* model selection.
|
|
3040
3560
|
*
|
|
@@ -3265,6 +3785,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3265
3785
|
}
|
|
3266
3786
|
|
|
3267
3787
|
function attach() {
|
|
3788
|
+
// Prewarm bare-model ownership before the first composer message. The claim
|
|
3789
|
+
// hook itself stays synchronous because DSH fixes the route immediately
|
|
3790
|
+
// after it returns.
|
|
3791
|
+
void refreshModelCatalog();
|
|
3792
|
+
ctx.on('llm/adapters-updated', () => { void refreshModelCatalog(true); });
|
|
3793
|
+
ctx.on('llm/models-updated', () => { void refreshModelCatalog(true); });
|
|
3268
3794
|
ctx.on('agent/request', onAgentRequest);
|
|
3269
3795
|
ctx.on('agent/request-error', onRequestError);
|
|
3270
3796
|
// Prepend so `next()` returns the decision WITH the harness's own skill
|
|
@@ -3288,6 +3814,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3288
3814
|
liveSkills.delete(id);
|
|
3289
3815
|
topTriggers.delete(id);
|
|
3290
3816
|
managerSelected.delete(id);
|
|
3817
|
+
liveDirectivePatches.delete(id);
|
|
3818
|
+
inheritedDirectiveFallbacks.delete(id);
|
|
3819
|
+
const directivePrefix = `${id}::`;
|
|
3820
|
+
for (const key of [...directiveWarnings.keys()]) {
|
|
3821
|
+
if (key.startsWith(directivePrefix)) directiveWarnings.delete(key);
|
|
3822
|
+
}
|
|
3291
3823
|
commandTurns.delete(id);
|
|
3292
3824
|
});
|
|
3293
3825
|
|
|
@@ -3302,6 +3834,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3302
3834
|
ctx.on('subagent/start', (info) => {
|
|
3303
3835
|
const childId = info?.id;
|
|
3304
3836
|
if (childId === undefined) return;
|
|
3837
|
+
const parent = findParent(ctx, childId);
|
|
3838
|
+
if (parent !== undefined) {
|
|
3839
|
+
// Capture before the asynchronous label lookup and before the parent's
|
|
3840
|
+
// disposal can erase its live patches. Later reads refresh this fallback.
|
|
3841
|
+
inheritedDirectiveFallbacks.set(childId, directiveStateFor(parent));
|
|
3842
|
+
}
|
|
3305
3843
|
void lookupChild(childId).then(() => {
|
|
3306
3844
|
// DSH 0.2.x: the child's route has to be selected before its first
|
|
3307
3845
|
// step is prepared, and the label only exists behind that async
|
|
@@ -3333,6 +3871,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3333
3871
|
};
|
|
3334
3872
|
visionMatch = keywordMatcher(config.strategy.visionKeywords);
|
|
3335
3873
|
planningMatch = keywordMatcher(config.strategy.planningKeywords);
|
|
3874
|
+
void refreshModelCatalog(true);
|
|
3336
3875
|
// A renamed (or disabled) one-turn command takes effect on the save:
|
|
3337
3876
|
// the gesture scan already reads the live config, and this re-arms the
|
|
3338
3877
|
// harness command registrations under the new names.
|
|
@@ -3365,13 +3904,14 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3365
3904
|
name: 'model_manager',
|
|
3366
3905
|
description: 'Inspect and explain the role-based model routing configured for this harness. '
|
|
3367
3906
|
+ 'action "report": a Top-level agents section naming which model served each '
|
|
3368
|
-
+ 'conversation,
|
|
3369
|
-
+ '
|
|
3370
|
-
+ '
|
|
3371
|
-
+ '
|
|
3907
|
+
+ 'conversation, its session-persistent @model role pins, which planning skill '
|
|
3908
|
+
+ '(if any) put a session on the planning tier, and whether the last turn carried '
|
|
3909
|
+
+ 'a one-turn command (/readimage, /quicktask), then one row per subagent with its '
|
|
3910
|
+
+ 'label, role, reason, live status and '
|
|
3372
3911
|
+ 'totals. action "routes": the four role assignments '
|
|
3373
3912
|
+ '(including the vision->execution fallback), the shared selection strategy (first or round-robin), '
|
|
3374
|
-
+ 'the active distribution mode,
|
|
3913
|
+
+ 'the active distribution mode, session @model directives, the auto-delegation level, '
|
|
3914
|
+
+ 'the planning-skill trigger, '
|
|
3375
3915
|
+ 'the one-turn commands (/readimage on the vision role, /quicktask on the execution role), '
|
|
3376
3916
|
+ 'the update-check status, '
|
|
3377
3917
|
+ 'and whether each '
|
|
@@ -3445,9 +3985,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3445
3985
|
registry.register(usageProjectionDefinition);
|
|
3446
3986
|
registry.register(selectionProjectionDefinition);
|
|
3447
3987
|
registry.register(planningSkillProjectionDefinition);
|
|
3988
|
+
registry.register(directiveProjectionDefinition);
|
|
3448
3989
|
projections = registry;
|
|
3449
|
-
log('info', `registered the ${USAGE_PROJECTION_KEY}, ${SELECTION_PROJECTION_KEY}
|
|
3450
|
-
+ `${PLANNING_SKILL_PROJECTION_KEY} session projections`);
|
|
3990
|
+
log('info', `registered the ${USAGE_PROJECTION_KEY}, ${SELECTION_PROJECTION_KEY}, `
|
|
3991
|
+
+ `${PLANNING_SKILL_PROJECTION_KEY} and ${DIRECTIVE_PROJECTION_KEY} session projections`);
|
|
3451
3992
|
} catch (error) {
|
|
3452
3993
|
log('warn', `could not register the usage projection: ${error?.message ?? error}`);
|
|
3453
3994
|
}
|
|
@@ -3461,7 +4002,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
|
|
|
3461
4002
|
disposers.push(scoped.systemPrompt.section({
|
|
3462
4003
|
name: 'model-manager',
|
|
3463
4004
|
order: 60,
|
|
3464
|
-
text: () => cheatSheet(),
|
|
4005
|
+
text: (context) => cheatSheet(context),
|
|
3465
4006
|
}));
|
|
3466
4007
|
// The delegation policy: rendered per assembly, only for the
|
|
3467
4008
|
// top-level orchestrator, and only while it actually has the
|
|
@@ -3663,6 +4204,11 @@ export {
|
|
|
3663
4204
|
selectionModelOf,
|
|
3664
4205
|
sameSelection,
|
|
3665
4206
|
planningSkillInMessages,
|
|
4207
|
+
modelDirectivesInMessages,
|
|
4208
|
+
normalizeDirectiveState,
|
|
4209
|
+
applyDirectivePatches,
|
|
4210
|
+
resolveModelDirective,
|
|
4211
|
+
directiveReferenceParts,
|
|
3666
4212
|
commandGestureInMessages,
|
|
3667
4213
|
readImageGestureInMessages,
|
|
3668
4214
|
normalizeReadImageCommand,
|