@darkbear9494/dsh-model-manager 0.7.0 → 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/lib/index.js CHANGED
@@ -53,7 +53,7 @@ const ROLE_NAMES = ['main', 'planning', 'execution', 'vision'];
53
53
  const KNOWN_TOP_KEYS = ['enabled', 'pick', 'roles', 'strategy', 'update'];
54
54
  const KNOWN_ROLE_KEYS = ['models', 'note'];
55
55
  const KNOWN_ROUTE_KEYS = ['provider', 'model', 'reasoningEffort'];
56
- const KNOWN_STRATEGY_KEYS = ['mode', 'visionKeywords', 'planningKeywords', 'planningSkills', 'readImageCommand', 'historyLimit', 'autoDelegate'];
56
+ const KNOWN_STRATEGY_KEYS = ['mode', 'visionKeywords', 'planningKeywords', 'planningSkills', 'readImageCommand', 'quickTaskCommand', 'historyLimit', 'autoDelegate'];
57
57
  const KNOWN_UPDATE_KEYS = ['enabled', 'registry', 'intervalHours'];
58
58
 
59
59
  /**
@@ -189,6 +189,80 @@ const DEFAULT_PLANNING_SKILLS = ['grill-me', 'grilling'];
189
189
  */
190
190
  const DEFAULT_READ_IMAGE_COMMAND = 'readimage';
191
191
 
192
+ /**
193
+ * The command that puts ONE turn on the execution role (0.7.1).
194
+ *
195
+ * `/quicktask` is the cheap end of the same one-turn contract `/readimage`
196
+ * holds for vision: the turn carrying it runs on the execution tier (the
197
+ * 执行 role) — the tier that serves delegated implementation work — and the
198
+ * next message without it routes normally again. It exists for the quick
199
+ * request that does not deserve the main model: a rename, a one-line lookup,
200
+ * a "what does this error mean". It outranks plan mode, planning skills and a
201
+ * composer-picked model for its turn only, and the pick is restored
202
+ * afterwards, exactly like `/readimage`. Text only, on purpose: unlike
203
+ * `/readimage` the command does not declare attachment support, so the
204
+ * harness's executor refuses an invocation carrying attachments before
205
+ * dispatch — an image belongs to `/readimage`, and a quick turn must never
206
+ * land on an execution model that cannot read it. An empty string disables
207
+ * it.
208
+ */
209
+ const DEFAULT_QUICK_TASK_COMMAND = 'quicktask';
210
+
211
+ /**
212
+ * The manager's one-turn commands: per-message intent that owns its whole
213
+ * turn, then expires (0.7.1 generalises the 0.7.0 `/readimage` machinery).
214
+ *
215
+ * Each entry names the `strategy` key holding its command name, the role its
216
+ * turn runs on, and the surface texts (registration, refusal, routes,
217
+ * report); the engine machinery — turn binding, composer-pick restore,
218
+ * precedence over plan mode and planning skills, registration and re-arm —
219
+ * is shared and generic. `feature` is the label used in reasons and logs,
220
+ * `reportLabel` the heading the report block prints.
221
+ *
222
+ * The list order is also the precedence order for the gesture scan: a
223
+ * message carrying two command tokens binds the FIRST match, so `/readimage`
224
+ * wins over `/quicktask` — the image is physically in the message and only a
225
+ * vision-capable model can serve it, while `/quicktask` is a cost preference
226
+ * the user can re-issue on the next message.
227
+ */
228
+ const TURN_COMMANDS = [
229
+ {
230
+ key: 'readImage',
231
+ field: 'readImageCommand',
232
+ defaultName: DEFAULT_READ_IMAGE_COMMAND,
233
+ role: 'vision',
234
+ feature: 'read-image',
235
+ reportLabel: 'Read-image command:',
236
+ configureHint: 'set roles.vision.models to an image-capable model',
237
+ registeredNote: 'Registered with attachment support, so images pass admission even on a text-only current model.',
238
+ unregisteredNote: 'NOT registered (no commands service, or registration failed — see the startup log) — '
239
+ + 'only plain-text gestures route; images still need a current model that accepts them.',
240
+ description: 'Read attached images with the vision model: this message (and its turn) runs on the '
241
+ + "manager's vision role, then the next message returns to the normal route. Accepts image attachments.",
242
+ hint: 'question about the attached image(s)',
243
+ usageHint: 'question',
244
+ attachments: true,
245
+ },
246
+ {
247
+ key: 'quickTask',
248
+ field: 'quickTaskCommand',
249
+ defaultName: DEFAULT_QUICK_TASK_COMMAND,
250
+ role: 'execution',
251
+ feature: 'quick-task',
252
+ reportLabel: 'Quick-task command:',
253
+ configureHint: 'set roles.execution.models to the model simple tasks should run on',
254
+ registeredNote: 'Registered as a real command; a plain-text /name gesture routes the same turn.',
255
+ unregisteredNote: 'NOT registered (no commands service, or registration failed — see the startup log); '
256
+ + 'plain-text gestures still route the same turn, only the palette entry is missing.',
257
+ description: 'Run one simple task on the execution model: this message (and its turn) runs on the '
258
+ + "manager's execution role, then the next message returns to the normal route. Text only — images "
259
+ + 'belong to the read-image command.',
260
+ hint: 'simple task or question',
261
+ usageHint: 'simple task or question',
262
+ attachments: false,
263
+ },
264
+ ];
265
+
192
266
  /**
193
267
  * The public DSH skill-name grammar and the `/name` gesture the harness scans
194
268
  * for in direct user text.
@@ -200,6 +274,28 @@ const DEFAULT_READ_IMAGE_COMMAND = 'readimage';
200
274
  const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
201
275
  const SKILL_GESTURE = /(^|\s)\/([a-z0-9]+(?:-[a-z0-9]+)*)(?=\s|$)/g;
202
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
+
203
299
  /**
204
300
  * Names of the skills one user message records, in order. Pure.
205
301
  *
@@ -353,6 +449,7 @@ function buildConfigSchema(z) {
353
449
  planningKeywords: z.array(z.string()).default(DEFAULT_PLANNING_KEYWORDS),
354
450
  planningSkills: z.array(z.string()).default(DEFAULT_PLANNING_SKILLS),
355
451
  readImageCommand: z.string().default(DEFAULT_READ_IMAGE_COMMAND),
452
+ quickTaskCommand: z.string().default(DEFAULT_QUICK_TASK_COMMAND),
356
453
  historyLimit: z.number().default(300),
357
454
  autoDelegate: z.union([z.const('off'), z.const('balanced'), z.const('eager')]).default('balanced'),
358
455
  });
@@ -468,31 +565,42 @@ function normalizeSkillNames(value) {
468
565
  }
469
566
 
470
567
  /**
471
- * Normalize `strategy.readImageCommand`.
568
+ * Normalize a one-turn command name (`strategy.readImageCommand` /
569
+ * `strategy.quickTaskCommand`).
472
570
  *
473
- * An absent or non-string value takes the built-in default (the same fail-on
474
- * philosophy as the keyword lists: a malformed value must not silently switch
475
- * a feature off). An explicit empty string is honoured and disables both the
476
- * command registration and the gesture scan. A name outside the grammar logs
477
- * a warning and disables the feature: it must be kebab-case for the gesture
478
- * scanner AND start with a letter for the command registry's own
479
- * `COMMAND_NAME`, so a name failing either could never be invoked as a
480
- * command — better to refuse it at config time than fail registration at boot.
571
+ * An absent or non-string value takes the command's built-in default (the
572
+ * same fail-on philosophy as the keyword lists: a malformed value must not
573
+ * silently switch a feature off). An explicit empty string is honoured and
574
+ * disables both the command registration and the gesture scan. A name
575
+ * outside the grammar logs a warning and disables the feature: it must be
576
+ * kebab-case for the gesture scanner AND start with a letter for the command
577
+ * registry's own `COMMAND_NAME`, so a name failing either could never be
578
+ * invoked as a command — better to refuse it at config time than fail
579
+ * registration at boot.
481
580
  */
482
- const READ_IMAGE_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
581
+ const COMMAND_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
483
582
 
484
- function normalizeReadImageCommand(value, warnings) {
583
+ function normalizeCommandName(value, warnings, field, fallback) {
485
584
  const raw = readVal(value);
486
- if (raw === undefined || raw === null || typeof raw !== 'string') return DEFAULT_READ_IMAGE_COMMAND;
585
+ if (raw === undefined || raw === null || typeof raw !== 'string') return fallback;
487
586
  const name = raw.trim().toLowerCase();
488
587
  if (name === '') return '';
489
- if (!READ_IMAGE_NAME.test(name)) {
490
- warnings?.push(`strategy.readImageCommand "${raw}" is not a lowercase kebab-case name starting with a letter; the read-image command is disabled`);
588
+ if (!COMMAND_NAME.test(name)) {
589
+ warnings?.push(`strategy.${field} "${raw}" is not a lowercase kebab-case name starting with a letter; the ${field === 'readImageCommand' ? 'read-image' : 'quick-task'} command is disabled`);
491
590
  return '';
492
591
  }
493
592
  return name;
494
593
  }
495
594
 
595
+ function normalizeReadImageCommand(value, warnings) {
596
+ return normalizeCommandName(value, warnings, 'readImageCommand', DEFAULT_READ_IMAGE_COMMAND);
597
+ }
598
+
599
+ /** Normalize `strategy.quickTaskCommand` (0.7.1); see {@link normalizeCommandName}. */
600
+ function normalizeQuickTaskCommand(value, warnings) {
601
+ return normalizeCommandName(value, warnings, 'quickTaskCommand', DEFAULT_QUICK_TASK_COMMAND);
602
+ }
603
+
496
604
  function normalizeRoute(raw) {
497
605
  const value = readVal(raw);
498
606
  if (value === null || typeof value !== 'object') return undefined;
@@ -722,6 +830,9 @@ function readConfig(raw) {
722
830
  // Absent/malformed -> 'readimage'; explicit '' switches the one-turn
723
831
  // vision command off; an invalid name warns and disables it.
724
832
  readImageCommand: normalizeReadImageCommand(strategyRaw.readImageCommand, warnings),
833
+ // Absent/malformed -> 'quicktask'; explicit '' switches the one-turn
834
+ // execution command off; an invalid name warns and disables it.
835
+ quickTaskCommand: normalizeQuickTaskCommand(strategyRaw.quickTaskCommand, warnings),
725
836
  // Guard against a positive fraction flooring to 0, which would evict every
726
837
  // record immediately and silently disable usage tracking.
727
838
  historyLimit: Number.isFinite(limit) && limit > 0 ? Math.max(1, Math.floor(limit)) : 300,
@@ -846,17 +957,209 @@ function planningSkillInMessages(messages, wanted) {
846
957
  return undefined;
847
958
  }
848
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
+
849
980
  /**
850
- * Whether a batch of user messages carries the read-image gesture. Pure.
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
+
1152
+ /**
1153
+ * Whether a batch of user messages carries a given command's gesture. Pure.
851
1154
  *
852
1155
  * Recognition uses the harness's own `/name` grammar (the same word-boundary
853
- * shape tool-skill scans), so `/readimage` reads as a gesture wherever it sits
854
- * in the sentence while file paths and fractions never match. Only direct user
855
- * text counts — no other source can forge the gesture. The command handler
856
- * forwards the original line, token included, so the claimed message it queues
857
- * carries the gesture into the routing seams below.
1156
+ * shape tool-skill scans), so `/readimage` or `/quicktask` reads as a gesture
1157
+ * wherever it sits in the sentence while file paths and fractions never match.
1158
+ * Only direct user text counts — no other source can forge the gesture. The
1159
+ * command handlers forward the original line, token included, so the claimed
1160
+ * message they queue carries the gesture into the routing seams below.
858
1161
  */
859
- function readImageGestureInMessages(messages, command) {
1162
+ function commandGestureInMessages(messages, command) {
860
1163
  if (typeof command !== 'string' || command === '') return false;
861
1164
  for (const message of Array.isArray(messages) ? messages : []) {
862
1165
  if (message?.source?.kind !== 'user') continue;
@@ -870,6 +1173,12 @@ function readImageGestureInMessages(messages, command) {
870
1173
  return false;
871
1174
  }
872
1175
 
1176
+ /**
1177
+ * The 0.7.0 export name for {@link commandGestureInMessages}, kept stable for
1178
+ * the read-image test surface; the function itself is command-agnostic.
1179
+ */
1180
+ const readImageGestureInMessages = commandGestureInMessages;
1181
+
873
1182
  /** Find the delegating parent of a child session. */
874
1183
  function findParent(ctx, childId) {
875
1184
  return probe(() => {
@@ -1030,7 +1339,13 @@ function delegationPolicyText(level, toolNames, opts) {
1030
1339
  const vision = opts?.vision !== false;
1031
1340
  const routed = opts?.routed !== false;
1032
1341
  const fork = has('subagent_fork')
1033
- ? ' Prefer `subagent_fork` when a unit needs this conversation\'s own context.'
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.')
1034
1349
  : '';
1035
1350
  const subagentTool = has('subagent') ? '`subagent`' : '`subagent_fork`';
1036
1351
  const planTag = planning ? ' as a `plan:` unit' : ' to a delegation';
@@ -1055,13 +1370,14 @@ function delegationPolicyText(level, toolNames, opts) {
1055
1370
  '',
1056
1371
  'Default to solving substantive work through subagents instead of doing it all yourself.',
1057
1372
  '',
1058
- '- Plan first: when a task needs more than a few steps, delegate the decomposition',
1059
- ` itself${planTag}, then dispatch the units it returned — research, analysis,`,
1060
- ' implementation of separate areas, review, verification — together.',
1061
- `- Dispatch each unit as a ${subagentTool} delegation — independent units go together in`,
1062
- ` a single message — and continue useful work while they run.${fork}`,
1063
- '- Keep for yourself what does not pay to delegate: coordination, single-step reads or',
1064
- ' tiny edits, decisions that need the user, and the final synthesis of every result.',
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.',
1065
1381
  '- Verify what delegations return before presenting it as done; re-delegate or fix',
1066
1382
  ' yourself when a result misses.',
1067
1383
  ];
@@ -1134,9 +1450,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1134
1450
  * `agent.model.select()` (the DSH 0.2.x selection path).
1135
1451
  *
1136
1452
  * A selected route is recorded in the session log exactly like a composer
1137
- * pick, so ownership has to be remembered here: without it the manager would
1138
- * read back its own selection as a hand-picked model and stop routing the
1139
- * 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.
1140
1455
  */
1141
1456
  const managerSelected = new Map();
1142
1457
  const roundRobin = new Map();
@@ -1154,6 +1469,24 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1154
1469
  /** session id -> `{ key: '<turn>:<step>', switches }`, the per-step budget. */
1155
1470
  const stepSwitches = new Map();
1156
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
+
1157
1490
  /**
1158
1491
  * The `tools` service, captured when its injection resolves, so the
1159
1492
  * delegation-policy section can ask which delegation tools an assembly's
@@ -1171,14 +1504,19 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1171
1504
 
1172
1505
  /**
1173
1506
  * The `commands` service, captured when its injection resolves, plus the
1174
- * live registration of the read-image command. `readImageName` is the name
1175
- * actually registered ('' when none), so a volatile Settings save that
1176
- * renames the command can dispose the old registration and arm the new one,
1177
- * and `routes` can tell "configured" from "registered in this composition".
1507
+ * live registrations of the one-turn commands. `commandRegistrations` maps
1508
+ * each TURN_COMMANDS key to `{ name, dispose }` — the name actually
1509
+ * registered ('' when none) — so a volatile Settings save that renames a
1510
+ * command can dispose the old registration and arm the new one, and
1511
+ * `routes` can tell "configured" from "registered in this composition".
1178
1512
  */
1179
1513
  let commandsService;
1180
- let readImageDispose;
1181
- let readImageName = '';
1514
+ const commandRegistrations = new Map();
1515
+ /**
1516
+ * TURN_COMMANDS key -> the colliding name already warned about, so an
1517
+ * unchanged volatile save does not repeat the collision warning.
1518
+ */
1519
+ const commandCollisionWarned = new Map();
1182
1520
 
1183
1521
  /**
1184
1522
  * Latest update-check outcome. Statuses: `idle` (not yet checked), `checking`,
@@ -1198,6 +1536,201 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1198
1536
  let visionMatch = keywordMatcher(config.strategy.visionKeywords);
1199
1537
  let planningMatch = keywordMatcher(config.strategy.planningKeywords);
1200
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
+
1201
1734
  /**
1202
1735
  * How many sessions' live skill names are remembered, and how many names one
1203
1736
  * session keeps. Both are backstops: `agent/disposed` is the normal cleanup,
@@ -1222,21 +1755,23 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1222
1755
  const topTriggers = new Map();
1223
1756
 
1224
1757
  /**
1225
- * session id -> `{ turn, restore }` for the ONE turn carrying `/readimage`.
1758
+ * session id -> `{ turn, restore, command }` for the ONE turn a one-turn
1759
+ * command owns (`/readimage` since 0.7.0, `/quicktask` since 0.7.1).
1226
1760
  *
1227
1761
  * The override is keyed to the turn number that claimed the gesture, which
1228
1762
  * is what makes it expire by itself: every later step of that turn compares
1229
- * equal and stays on vision, while the first claim of any other turn compares
1230
- * different and ends it. `restore` remembers a hand-picked composer route the
1231
- * command overrode (hybrid normally respects it), so the pick is selected
1232
- * back when the commanded turn ends instead of being silently dropped.
1763
+ * equal and stays on the command's role, while the first claim of any other
1764
+ * turn compares different and ends it. `restore` remembers a hand-picked
1765
+ * composer route the command overrode (hybrid normally respects it), so the
1766
+ * pick is selected back when the commanded turn ends instead of being
1767
+ * silently dropped.
1233
1768
  *
1234
1769
  * Deliberately process-live, with no durable projection: this is per-message
1235
1770
  * intent, not session state. After a restart the next message routes
1236
1771
  * normally, which is exactly the contract — only a fresh gesture commands a
1237
1772
  * fresh turn.
1238
1773
  */
1239
- const readImageTurns = new Map();
1774
+ const commandTurns = new Map();
1240
1775
 
1241
1776
  /** Add one skill name to a session's live list, bounded and de-duplicated. */
1242
1777
  function addLiveSkill(id, name) {
@@ -1297,25 +1832,28 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1297
1832
  try {
1298
1833
  const agent = payload?.agent;
1299
1834
  const id = typeof agent?.id === 'string' ? agent.id : undefined;
1300
- const isSubagent = agent === undefined
1301
- ? false
1302
- : probe(() => agent.session?.header?.origin === 'subagent') === true;
1835
+ const isSubagent = probe(() => agent?.session?.header?.origin === 'subagent') === true;
1303
1836
  if (id !== undefined && decision?.kind !== 'reject') {
1304
1837
  for (const batch of [payload?.messages, decision?.messages]) {
1305
1838
  if (!Array.isArray(batch)) continue;
1306
1839
  for (const message of batch) {
1307
1840
  for (const name of skillNamesOfMessage(message)) addLiveSkill(id, name);
1308
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);
1309
1846
  }
1310
- // The read-image override binds here too, on every transport: the
1311
- // claim boundary covers the first step, and this scan covers a harness
1312
- // whose claim notification predates the listener (or a batch the claim
1313
- // seam never saw). Top-level only — a child's routing stays label-driven.
1847
+ // The one-turn command override binds here too, on every transport:
1848
+ // the claim boundary covers the first step, and this scan covers a
1849
+ // harness whose claim notification predates the listener (or a batch
1850
+ // the claim seam never saw). Top-level only — a child's routing stays
1851
+ // label-driven.
1314
1852
  if (!isSubagent) {
1315
1853
  for (const batch of [payload?.messages, decision?.messages]) {
1316
- if (Array.isArray(batch)) noteReadImageGesture(agent, batch, payload?.turn);
1854
+ if (Array.isArray(batch)) noteCommandGesture(agent, batch, payload?.turn);
1317
1855
  }
1318
- endReadImageTurn(agent, payload?.turn);
1856
+ endCommandTurn(agent, payload?.turn);
1319
1857
  }
1320
1858
  }
1321
1859
  // On a harness that fixes the route at step preparation, keep the
@@ -1331,15 +1869,15 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1331
1869
  applySelection(agent, classifySubagent(facts.label), undefined, facts.label, true);
1332
1870
  }
1333
1871
  } else {
1334
- const readImage = readImageActive(agent, payload?.turn);
1872
+ const command = commandActive(agent, payload?.turn);
1335
1873
  const plan = planActive(ctx, agent);
1336
- const skill = plan || readImage ? undefined : planningSkillFor(agent);
1337
- const trigger = readImage
1338
- ? `command:${config.strategy.readImageCommand}`
1874
+ const skill = plan || command ? undefined : planningSkillFor(agent);
1875
+ const trigger = command
1876
+ ? `command:${config.strategy[command.field]}`
1339
1877
  : skill === undefined ? (plan ? 'plan-mode' : 'main') : `skill:${skill}`;
1340
- noteTopTrigger(agent, trigger);
1341
- applySelection(agent, readImage ? 'vision' : plan || skill !== undefined ? 'planning' : 'main',
1342
- trigger, undefined, false, readImage);
1878
+ noteTopTrigger(agent, trigger, command);
1879
+ applySelection(agent, command ? command.role : plan || skill !== undefined ? 'planning' : 'main',
1880
+ trigger, undefined, false, command !== undefined);
1343
1881
  }
1344
1882
  }
1345
1883
  } catch {
@@ -1348,8 +1886,13 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1348
1886
  return decision;
1349
1887
  }
1350
1888
 
1351
- /** Log a top-level trigger once per switch, never once per request. */
1352
- function noteTopTrigger(agent, trigger) {
1889
+ /**
1890
+ * Log a top-level trigger once per switch, never once per request.
1891
+ *
1892
+ * `command` is the active one-turn command descriptor when `trigger` is a
1893
+ * `command:` trigger, so the log names the role its turn runs on.
1894
+ */
1895
+ function noteTopTrigger(agent, trigger, command) {
1353
1896
  const id = typeof agent?.id === 'string' ? agent.id : undefined;
1354
1897
  if (id === undefined) return;
1355
1898
  if (topTriggers.get(id) === trigger) return;
@@ -1358,17 +1901,46 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1358
1901
  log('info', `planning skill "${trigger.slice('skill:'.length)}" is active in this session; `
1359
1902
  + 'top-level requests route as planning');
1360
1903
  }
1361
- if (trigger.startsWith('command:')) {
1362
- log('info', `/${trigger.slice('command:'.length)} commands this turn on the vision role; `
1904
+ if (trigger.startsWith('command:') && command !== undefined) {
1905
+ log('info', `/${trigger.slice('command:'.length)} commands this turn on the ${command.role} role; `
1363
1906
  + 'the next message without the gesture returns to the normal route');
1364
1907
  }
1365
1908
  }
1366
1909
 
1367
- /** Whether the read-image override owns the turn a step belongs to. */
1368
- function readImageActive(agent, turn) {
1369
- if (!Number.isSafeInteger(turn)) return false;
1910
+ /**
1911
+ * The one-turn command owning the turn a step belongs to, or `undefined`.
1912
+ * A bound turn only answers for its own turn number: a mid-turn steering
1913
+ * message (no gesture, same turn) keeps the command; a later turn does not.
1914
+ */
1915
+ function commandActive(agent, turn) {
1916
+ if (!Number.isSafeInteger(turn)) return undefined;
1370
1917
  const id = typeof agent?.id === 'string' ? agent.id : undefined;
1371
- return id !== undefined && readImageTurns.get(id)?.turn === turn;
1918
+ const active = id === undefined ? undefined : commandTurns.get(id);
1919
+ return active !== undefined && active.turn === turn ? active.command : undefined;
1920
+ }
1921
+
1922
+ /**
1923
+ * The first TURN_COMMANDS descriptor whose configured name appears as a
1924
+ * gesture in a batch of user messages, or `undefined`.
1925
+ *
1926
+ * `TURN_COMMANDS` order decides a message carrying two command tokens:
1927
+ * `/readimage` beats `/quicktask`, because the image in the message can
1928
+ * only be served by a vision-capable model while a quick turn is a cost
1929
+ * preference the user can re-issue.
1930
+ *
1931
+ * A command whose role resolves to no models never binds: there is no
1932
+ * route to command, and binding anyway would let the report claim a turn
1933
+ * "ran on" a role nothing was selected for. The handler and the cheat
1934
+ * sheet gate on the same emptiness, so every surface then agrees: the
1935
+ * gesture is inert, not half-alive.
1936
+ */
1937
+ function turnCommandInMessages(messages) {
1938
+ for (const command of TURN_COMMANDS) {
1939
+ const name = config.strategy[command.field];
1940
+ if (name !== '' && effectiveModels(command.role).length > 0
1941
+ && commandGestureInMessages(messages, name)) return command;
1942
+ }
1943
+ return undefined;
1372
1944
  }
1373
1945
 
1374
1946
  /**
@@ -1379,51 +1951,52 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1379
1951
  * that OWNS the message — a mid-turn steering message without the gesture
1380
1952
  * cannot steal or cancel it. A consecutive commanded turn keeps the original
1381
1953
  * `restore` route: the pick to hand back is the one from before the first
1382
- * override, never the vision route the manager itself selected.
1954
+ * override, never the role route the manager itself selected.
1383
1955
  */
1384
- function noteReadImageGesture(agent, messages, turn) {
1385
- const command = config.strategy.readImageCommand;
1386
- if (command === '' || !Number.isSafeInteger(turn)) return;
1956
+ function noteCommandGesture(agent, messages, turn) {
1957
+ if (!Number.isSafeInteger(turn)) return;
1387
1958
  const id = typeof agent?.id === 'string' ? agent.id : undefined;
1388
- if (id === undefined || !readImageGestureInMessages(messages, command)) return;
1389
- const existing = readImageTurns.get(id);
1959
+ if (id === undefined) return;
1960
+ const command = turnCommandInMessages(messages);
1961
+ if (command === undefined) return;
1962
+ const existing = commandTurns.get(id);
1390
1963
  if (existing?.turn === turn) return;
1391
1964
  const current = probe(() => selectionModelOf(agent)?.current());
1392
1965
  // A pick made after the previous commanded turn is newer than the one
1393
1966
  // remembered then, so it replaces the memory: what must come back is the
1394
1967
  // user's LATEST choice, never a stale one. When current is the manager's
1395
- // own vision route (the ordinary case) it is not foreign and the original
1396
- // memory stands.
1968
+ // own route for the previous commanded turn (the ordinary case) it is not
1969
+ // foreign and the original memory stands.
1397
1970
  const restore = (selectionIsForeign(agent, current) ? current : undefined) ?? existing?.restore;
1398
- readImageTurns.set(id, { turn, restore });
1971
+ commandTurns.set(id, { turn, restore, command });
1399
1972
  }
1400
1973
 
1401
1974
  /**
1402
1975
  * End the override when a DIFFERENT turn claims input, handing a remembered
1403
1976
  * composer pick back.
1404
1977
  *
1405
- * The restore is selected before the normal role decision runs, so the
1406
- * hybrid gate that follows reads the pick as foreign again and respects it —
1407
- * ownership is dropped on purpose: a restored pick is the user's choice, not
1408
- * a route the manager may replace with `main` on the next turn. On the 0.1.x
1409
- * rewrite path nothing was ever durably selected, so there is nothing to
1410
- * restore and the pick survives on its own.
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.
1411
1984
  */
1412
- function endReadImageTurn(agent, turn) {
1985
+ function endCommandTurn(agent, turn) {
1413
1986
  const id = typeof agent?.id === 'string' ? agent.id : undefined;
1414
1987
  if (id === undefined || !Number.isSafeInteger(turn)) return;
1415
- const active = readImageTurns.get(id);
1988
+ const active = commandTurns.get(id);
1416
1989
  if (active === undefined || active.turn === turn) return;
1417
- readImageTurns.delete(id);
1990
+ commandTurns.delete(id);
1418
1991
  if (active.restore === undefined) return;
1419
1992
  if (!config.enabled || config.strategy.mode === 'advisory') return;
1420
1993
  const model = selectionModelOf(agent);
1421
1994
  if (model === undefined) return;
1422
1995
  try {
1423
1996
  // A hand pick made AFTER the commanded turn is newer than the one
1424
- // remembered at command time. Keep it and drop ownership so hybrid
1425
- // respects it — restoring the stale memory would eat the user's latest
1426
- // choice, which is exactly what the restore exists to protect.
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.
1427
2000
  const current = probe(() => model.current());
1428
2001
  if (selectionIsForeign(agent, current)) {
1429
2002
  managerSelected.delete(id);
@@ -1436,12 +2009,37 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1436
2009
  });
1437
2010
  managerSelected.delete(id);
1438
2011
  log('info', `restored the hand-picked ${active.restore.provider}/${active.restore.model} `
1439
- + `for ${shortId(id)} after the read-image turn`);
2012
+ + `for ${shortId(id)} after the ${active.command.feature} turn`);
1440
2013
  } catch (error) {
1441
2014
  log('warn', `could not restore the hand-picked route: ${error?.message ?? error}`);
1442
2015
  }
1443
2016
  }
1444
2017
 
2018
+ /**
2019
+ * First-wins name ownership across the one-turn commands, in `TURN_COMMANDS`
2020
+ * order: the name each command's live config value resolves to, mapped to
2021
+ * the command that owns it. Used by the registration (the registry itself
2022
+ * only shadows a duplicate name) and by the `routes` note, so the two can
2023
+ * never disagree about who owns a token.
2024
+ */
2025
+ function turnCommandOwners() {
2026
+ const owner = new Map();
2027
+ for (const command of TURN_COMMANDS) {
2028
+ const name = config.strategy[command.field];
2029
+ if (name !== '' && !owner.has(name)) owner.set(name, command);
2030
+ }
2031
+ return owner;
2032
+ }
2033
+
2034
+ /**
2035
+ * Whether a one-turn command is registered under its live config name —
2036
+ * the fact `routes` reports next to each command, so an operator can tell
2037
+ * "configured" from "actually invocable in this composition".
2038
+ */
2039
+ function commandRegistered(command) {
2040
+ return commandRegistrations.get(command.key)?.name === config.strategy[command.field];
2041
+ }
2042
+
1445
2043
  /** The model list a role actually resolves to, including the vision fallback. */
1446
2044
  function effectiveModels(key) {
1447
2045
  const role = roleOf(key);
@@ -1482,17 +2080,28 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1482
2080
  return { route: models[at], commit() {} };
1483
2081
  }
1484
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
+
1485
2096
  // -- model selection (DSH 0.2.x) ------------------------------------------
1486
2097
 
1487
2098
  /**
1488
2099
  * Whether the agent's current selection was recorded by somebody else.
1489
2100
  *
1490
2101
  * A route the manager selected is its own; a route equal to the agent's
1491
- * creation options is the deployment default (or the inherited parent route),
1492
- * which the manager is allowed to replace. Anything else is a recorded choice
1493
- * — a composer pick, a resume override, an explicit child route — and
1494
- * `hybrid` leaves it alone, exactly when it is neither manager-owned nor the
1495
- * 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.
1496
2105
  */
1497
2106
  function selectionIsForeign(agent, current) {
1498
2107
  if (current === undefined) return false;
@@ -1526,7 +2135,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1526
2135
  /** Whether `hybrid` permits replacing the agent's current route with `route`. */
1527
2136
  function selectionAllowed(agent, current, isSubagent) {
1528
2137
  if (config.strategy.mode !== 'hybrid') return true;
1529
- if (!isSubagent) return !selectionIsForeign(agent, current);
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;
1530
2141
  return childRouteIsInherited(agent, current);
1531
2142
  }
1532
2143
 
@@ -1541,10 +2152,11 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1541
2152
  * in flight). Returns whether a selection was recorded; every failure is
1542
2153
  * contained.
1543
2154
  *
1544
- * `force` is the read-image command's one-turn authority: an explicit user
1545
- * instruction for THIS message outranks even a hand-picked composer route
1546
- * for the turn it commands (the pick is remembered and restored afterwards
1547
- * by `endReadImageTurn`). It never bypasses the master switch or advisory
2155
+ * `force` is the one-turn commands' authority (`/readimage`, `/quicktask`):
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
1548
2160
  * mode — those mean the manager does not move routes at all.
1549
2161
  */
1550
2162
  function applySelection(agent, role, trigger, label, isSubagent, force = false) {
@@ -1552,15 +2164,14 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1552
2164
  if (model === undefined || !config.enabled) return false;
1553
2165
  try {
1554
2166
  if (config.strategy.mode === 'advisory') return false;
1555
- const candidate = routeCandidate(role, agent.id);
1556
- if (candidate === undefined) return false;
2167
+ const candidate = candidateForAgent(agent, role);
2168
+ if (candidate?.route === undefined) return false;
1557
2169
  const route = candidate.route;
1558
2170
  const current = probe(() => model.current());
1559
- if (!force && !selectionAllowed(agent, current, isSubagent)) {
1560
- if (!isSubagent && current !== undefined) {
1561
- log('info', `session ${shortId(agent.id)} keeps ${current.provider}/${current.model}: `
1562
- + 'a hand-picked model is respected under hybrid');
1563
- }
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)) {
1564
2175
  return false;
1565
2176
  }
1566
2177
  if (sameSelection(current, route)) {
@@ -1640,8 +2251,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1640
2251
  if (!config.enabled) return;
1641
2252
  const agent = payload?.agent;
1642
2253
  const message = payload?.message;
1643
- if (agent === undefined || selectionModelOf(agent) === undefined) return;
2254
+ if (agent === undefined) return;
1644
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;
1645
2260
  if (isSubagent) {
1646
2261
  const facts = catalog.get(agent.id);
1647
2262
  // The label only exists behind an async listing. A child whose facts are
@@ -1654,25 +2269,26 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1654
2269
  return;
1655
2270
  }
1656
2271
  // The claimed message names the intent, and the payload names the turn
1657
- // that owns it: bind the read-image override to THAT turn, end any older
1658
- // one (handing a remembered composer pick back), then decide the role.
1659
- // The command outranks plan mode and planning skills for its own turn —
1660
- // it is the most recent explicit instruction — and only for that turn.
2272
+ // that owns it: bind the one-turn command override to THAT turn, end any
2273
+ // older one (handing a remembered composer pick back), then decide the
2274
+ // role. A command outranks plan mode and planning skills for its own
2275
+ // turn — it is the most recent explicit instruction — and only for that
2276
+ // turn.
1661
2277
  const turn = payload?.turn;
1662
- noteReadImageGesture(agent, [message], turn);
1663
- endReadImageTurn(agent, turn);
1664
- const readImage = readImageActive(agent, turn);
2278
+ noteCommandGesture(agent, [message], turn);
2279
+ endCommandTurn(agent, turn);
2280
+ const command = commandActive(agent, turn);
1665
2281
  const plan = planActive(ctx, agent);
1666
- const skill = plan || readImage
2282
+ const skill = plan || command
1667
2283
  ? undefined
1668
2284
  : (planningSkillFor(agent)
1669
2285
  ?? planningSkillInMessages([message], config.strategy.planningSkills));
1670
- const trigger = readImage
1671
- ? `command:${config.strategy.readImageCommand}`
2286
+ const trigger = command
2287
+ ? `command:${config.strategy[command.field]}`
1672
2288
  : skill === undefined ? (plan ? 'plan-mode' : 'main') : `skill:${skill}`;
1673
- noteTopTrigger(agent, trigger);
1674
- applySelection(agent, readImage ? 'vision' : plan || skill !== undefined ? 'planning' : 'main',
1675
- trigger, undefined, false, readImage);
2289
+ noteTopTrigger(agent, trigger, command);
2290
+ applySelection(agent, command ? command.role : plan || skill !== undefined ? 'planning' : 'main',
2291
+ trigger, undefined, false, command !== undefined);
1676
2292
  } catch {
1677
2293
  /* observe-only at the claim boundary */
1678
2294
  }
@@ -1835,26 +2451,26 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1835
2451
  let role;
1836
2452
  let label;
1837
2453
  let trigger;
1838
- let readImage = false;
2454
+ let command;
1839
2455
  if (isSubagent) {
1840
2456
  const facts = await factsFor(agent.id);
1841
2457
  label = facts?.label;
1842
2458
  role = classifySubagent(label);
1843
2459
  } else {
1844
- // The read-image command owns its turn outright; below it, plan mode
2460
+ // The one-turn commands own their turn outright; below them, plan mode
1845
2461
  // is the harness's own "thinking work" mode and a planning skill
1846
2462
  // (`grilling` / `grill-me`) is the user's own version of the same
1847
2463
  // intent, so both put the top-level session on the planning tier.
1848
- readImage = readImageActive(agent, payload?.turn);
2464
+ command = commandActive(agent, payload?.turn);
1849
2465
  const plan = planActive(ctx, agent);
1850
- const skill = plan || readImage ? undefined : planningSkillFor(agent);
1851
- trigger = readImage
1852
- ? `command:${config.strategy.readImageCommand}`
2466
+ const skill = plan || command ? undefined : planningSkillFor(agent);
2467
+ trigger = command
2468
+ ? `command:${config.strategy[command.field]}`
1853
2469
  : skill === undefined ? (plan ? 'plan-mode' : 'main') : `skill:${skill}`;
1854
2470
  // Only claim routing when routing is on; a disabled manager still records
1855
2471
  // the trigger in its observed rows, but must not log that requests route.
1856
- if (config.enabled) noteTopTrigger(agent, trigger);
1857
- role = readImage ? 'vision' : plan || skill !== undefined ? 'planning' : 'main';
2472
+ if (config.enabled) noteTopTrigger(agent, trigger, command);
2473
+ role = command ? command.role : plan || skill !== undefined ? 'planning' : 'main';
1858
2474
  }
1859
2475
 
1860
2476
  // Master switch off: observe and record, but never rewrite a route. The
@@ -1883,11 +2499,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1883
2499
  // `agent/pre-step`; here the manager only records what the step fixed and
1884
2500
  // returns it untouched.
1885
2501
  if (selectionModelOf(agent) !== undefined) {
1886
- const candidate = routeCandidate(role, agent.id);
1887
- const matches = managerSelected.get(agent.id) === routeKey(resolved)
1888
- || (candidate !== undefined
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
1889
2506
  && candidate.route.provider === resolved.provider
1890
- && candidate.route.model === resolved.model);
2507
+ && candidate.route.model === resolved.model));
1891
2508
  remember(agent.id, {
1892
2509
  role,
1893
2510
  trigger,
@@ -1896,10 +2513,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1896
2513
  provider: resolved.provider,
1897
2514
  model: resolved.model,
1898
2515
  reasoningEffort: resolved.reasoningEffort,
1899
- reason: matches
1900
- ? 'step route selected before preparation'
1901
- : 'step route fixed by the session',
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',
1902
2523
  applied: matches,
2524
+ pinned: candidate?.directive !== undefined,
2525
+ pinRoute: candidate?.directive?.status === 'ok' && matches
2526
+ ? { provider: resolved.provider, model: resolved.model } : undefined,
1903
2527
  parentId: catalog.get(agent.id)?.parentId,
1904
2528
  });
1905
2529
  return resolved;
@@ -1914,15 +2538,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1914
2538
  stepSwitches.set(agent.id, { key: stepKey, switches: 0 });
1915
2539
  }
1916
2540
 
1917
- const candidate = routeCandidate(role, agent.id);
1918
- if (candidate === undefined) {
2541
+ const candidate = candidateForAgent(agent, role);
2542
+ if (candidate?.route === undefined) {
1919
2543
  remember(agent.id, {
1920
2544
  role,
1921
2545
  trigger,
1922
2546
  provider: resolved.provider,
1923
2547
  model: resolved.model,
1924
- reason: 'passthrough (role unconfigured)',
2548
+ reason: candidate?.directive !== undefined
2549
+ ? 'message directive unresolved' : 'passthrough (role unconfigured)',
1925
2550
  applied: false,
2551
+ pinned: candidate?.directive !== undefined,
1926
2552
  isSubagent,
1927
2553
  label,
1928
2554
  });
@@ -1938,22 +2564,20 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1938
2564
  if (mode === 'advisory') {
1939
2565
  reason = 'advisory (not applied)';
1940
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;
1941
2573
  } else {
1942
2574
  let inherited = true;
1943
- if (mode === 'hybrid' && !isSubagent && !readImage && selectionWasExplicit(agent)) {
1944
- // `main` replaces a route the user never chose; it does not overrule
1945
- // one they did choose. The proof is a durable log event, so a real
1946
- // composer pick survives restart, resume and fork, while a session
1947
- // still riding the deployment default is rewritten as before.
1948
- // `managed` is the mode for "the manager owns every route", including a
1949
- // session the user already picked, and is left untouched here.
1950
- // The read-image command is the one exception: it is an explicit user
1951
- // instruction for THIS turn, newer than the pick, so it rewrites for
1952
- // that turn only — the durable selection is untouched on this path,
1953
- // and the next turn respects the pick again by itself.
1954
- inherited = false;
1955
- reason = 'explicit session selection (respected)';
1956
- } 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) {
1957
2581
  // Respect an explicit delegation choice. A child counts as inheriting
1958
2582
  // when its resolved route is either the delegating parent's *effective*
1959
2583
  // route (mirroring DSH's own parentAgentOptionsForDelegation) or the
@@ -1983,7 +2607,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
1983
2607
  }
1984
2608
  output = inherited ? applyRoute(resolved, route) : resolved;
1985
2609
  didApply = inherited;
1986
- if (didApply && readImage) reason = 'applied (read-image command, one turn)';
2610
+ if (didApply && command) reason = `applied (${command.feature} command, one turn)`;
1987
2611
  }
1988
2612
 
1989
2613
  // Commit the rotation only when a route was actually applied, and record
@@ -2009,6 +2633,9 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2009
2633
  reasoningEffort: output.reasoningEffort,
2010
2634
  reason,
2011
2635
  applied: didApply,
2636
+ pinned: candidate.directive !== undefined,
2637
+ pinRoute: candidate.directive?.status === 'ok' && didApply
2638
+ ? { provider: output.provider, model: output.model } : undefined,
2012
2639
  parentId: catalog.get(agent.id)?.parentId,
2013
2640
  });
2014
2641
  return output;
@@ -2048,8 +2675,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2048
2675
 
2049
2676
  // The role is the one this manager routed the failed request as; with no
2050
2677
  // such record there is no chain to fail over within.
2051
- const role = usage.get(agent.id)?.role;
2678
+ const seen = usage.get(agent.id);
2679
+ const role = seen?.role;
2052
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
+ }
2053
2689
  const models = effectiveModels(role);
2054
2690
  if (models.length < 2) return undefined;
2055
2691
 
@@ -2518,13 +3154,13 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2518
3154
  for (const row of topRows) {
2519
3155
  const live = probe(() => ctx.get('agents')?.get?.(row.sessionId));
2520
3156
  const status = live === undefined ? 'inactive' : String(live.status ?? 'live');
2521
- // Read the durable fold rather than this turn's decision, so the answer
2522
- // does not depend on whether the manager happened to be enabled.
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.
2523
3159
  const origin = live === undefined
2524
3160
  ? 'unknown, agent no longer live'
2525
3161
  : selectionWasExplicit(live)
2526
- ? 'picked by hand, so main yields'
2527
- : 'the deployment default, so main applies';
3162
+ ? 'composer pick; automatic routing still applies'
3163
+ : 'deployment default; automatic routing applies';
2528
3164
  lines.push([
2529
3165
  shortId(row.sessionId),
2530
3166
  String(row.seen.role ?? '?').padEnd(9),
@@ -2535,9 +3171,16 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2535
3171
  ].join(' '));
2536
3172
  }
2537
3173
  lines.push('');
2538
- lines.push('A reason ending in (respected) is the verdict itself: a human choice won and the');
2539
- lines.push('manager stepped back. Under managed it never does, and a session that never had');
2540
- lines.push('a manual pick is rewritten by the main role.');
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
+ }
2541
3184
  const skillTriggers = topRows.filter((row) => typeof row.seen.trigger === 'string'
2542
3185
  && row.seen.trigger.startsWith('skill:')
2543
3186
  && row.seen.reason !== 'manager disabled (observed only)');
@@ -2547,18 +3190,24 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2547
3190
  .map((row) => `${shortId(row.sessionId)} → ${row.seen.trigger.slice('skill:'.length)}`)
2548
3191
  .join(', '));
2549
3192
  lines.push('These sessions invoked a planning skill, so they route to the planning tier for');
2550
- lines.push('the rest of the session, like plan mode; a hand-picked composer model still wins.');
3193
+ lines.push('the rest of the session, like plan mode, unless that role has a message pin.');
2551
3194
  }
2552
3195
  const commandTriggers = topRows.filter((row) => typeof row.seen.trigger === 'string'
2553
3196
  && row.seen.trigger.startsWith('command:')
2554
3197
  && row.seen.reason !== 'manager disabled (observed only)');
2555
- if (commandTriggers.length > 0) {
3198
+ // One block per one-turn command, matched by the recorded ROLE rather
3199
+ // than the trigger's name text: a Settings rename after the fact must
3200
+ // not orphan a row, and a top-level turn only ever lands on `vision`
3201
+ // via /readimage or `execution` via /quicktask.
3202
+ for (const command of TURN_COMMANDS) {
3203
+ const rows = commandTriggers.filter((row) => row.seen.role === command.role);
3204
+ if (rows.length === 0) continue;
2556
3205
  lines.push('');
2557
- lines.push('Read-image command: ' + commandTriggers
3206
+ lines.push(command.reportLabel + ' ' + rows
2558
3207
  .map((row) => `${shortId(row.sessionId)} → /${row.seen.trigger.slice('command:'.length)}`)
2559
3208
  .join(', '));
2560
- lines.push('The last turn of these sessions carried the read-image gesture, so it ran on the');
2561
- lines.push('vision role for that one turn; the next message without it routes normally again.');
3209
+ lines.push(`The last turn of these sessions carried the ${command.feature} gesture, so it ran on the`);
3210
+ lines.push(`${command.role} role for that one turn; the next message without it routes normally again.`);
2562
3211
  }
2563
3212
  lines.push('');
2564
3213
  }
@@ -2608,6 +3257,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2608
3257
  }
2609
3258
 
2610
3259
  async function routes() {
3260
+ await refreshModelCatalog();
2611
3261
  const vision = await visionReport();
2612
3262
  const visionBlock = vision.reason === 'no-service'
2613
3263
  ? 'Vision role: not checked (no llm service in this composition).'
@@ -2623,6 +3273,17 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2623
3273
  return ` ${tag} ${row.label} — ${row.detail}`;
2624
3274
  }),
2625
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');
2626
3287
  return [
2627
3288
  'Model manager roles',
2628
3289
  '',
@@ -2639,6 +3300,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2639
3300
  + (config.strategy.mode === 'managed' ? ' (always apply the role route)' : '')
2640
3301
  + (config.strategy.mode === 'advisory' ? ' (never rewrite — report only)' : ''),
2641
3302
  '',
3303
+ directiveBlock,
3304
+ '',
2642
3305
  `Auto-delegation: ${config.strategy.autoDelegate === 'off'
2643
3306
  ? 'off — no delegation policy is added to the system prompt'
2644
3307
  : `${config.strategy.autoDelegate} — the top-level agent is prompted to ${config.strategy.autoDelegate === 'eager'
@@ -2650,15 +3313,20 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2650
3313
  : `${config.strategy.planningSkills.join(', ')} — a top-level session that invoked one routes as `
2651
3314
  + 'planning for the rest of the session, like plan mode'}`,
2652
3315
  '',
2653
- `Read-image command: ${config.strategy.readImageCommand === ''
2654
- ? '(disabled) — strategy.readImageCommand is empty'
2655
- : `/${config.strategy.readImageCommand} — the turn carrying it runs on the vision role (one turn only; `
2656
- + 'the next message without the gesture returns to the normal route, and a hand-picked composer model '
2657
- + 'is restored afterwards). '
2658
- + (readImageName === config.strategy.readImageCommand
2659
- ? 'Registered with attachment support, so images pass admission even on a text-only current model.'
2660
- : 'NOT registered (no commands service, or registration failed — see the startup log) — '
2661
- + 'only plain-text gestures route; images still need a current model that accepts them.')}`,
3316
+ ...TURN_COMMANDS.map((command) => {
3317
+ const name = config.strategy[command.field];
3318
+ const owner = turnCommandOwners().get(name);
3319
+ return `${command.reportLabel} ${name === ''
3320
+ ? `(disabled) — strategy.${command.field} is empty`
3321
+ : `/${name} — the turn carrying it runs on the ${command.role} role (one turn only; `
3322
+ + 'the next message without the gesture returns to the normal route, and a hand-picked composer model '
3323
+ + 'is restored afterwards). '
3324
+ + (commandRegistered(command) ? command.registeredNote
3325
+ : owner !== undefined && owner !== command
3326
+ ? `NOT registered under this name — strategy.${command.field} collides with the `
3327
+ + `${owner.feature} command's name, which keeps /${name}; the token routes ${owner.role}.`
3328
+ : command.unregisteredNote)}`;
3329
+ }),
2662
3330
  '',
2663
3331
  `Autoplan skill: ${autoplanRegistered
2664
3332
  ? 'registered — `/autoplan` plans on the planning tier and implements on `main` '
@@ -2682,7 +3350,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2682
3350
  ].join('\n');
2683
3351
  }
2684
3352
 
2685
- function cheatSheet() {
3353
+ function cheatSheet(context) {
2686
3354
  const summary = ROLE_NAMES
2687
3355
  .map((key) => {
2688
3356
  const models = effectiveModels(key);
@@ -2690,13 +3358,16 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2690
3358
  return ` ${key}: ${models.map((route) => `${route.provider}/${route.model}`).join(', ')}`;
2691
3359
  })
2692
3360
  .filter(Boolean);
2693
- if (summary.length === 0) return '';
3361
+ const pins = directiveSummary(context?.agent);
3362
+ if (summary.length === 0 && pins.length === 0) return '';
2694
3363
  const routing = config.strategy.mode === 'advisory'
2695
3364
  ? 'The manager is observing only (advisory), so labels classify but never rewrite a route.'
2696
3365
  : [
2697
3366
  'Label a delegation `description` with "plan:" for thinking work, "vision:" for image',
2698
3367
  'work, or leave it plain for execution; a leading prefix wins over keyword matches.',
2699
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.',
2700
3371
  ].join('\n');
2701
3372
  const planningGap = effectiveModels('planning').length === 0
2702
3373
  ? '\nThe planning tier has no models, so "plan:" labels keep the inherited route.'
@@ -2711,12 +3382,19 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2711
3382
  + 'tier for its whole turn; the next message without it returns to the normal route. Suggest it when '
2712
3383
  + 'the user wants an image read but the current model cannot see images.'
2713
3384
  : '';
3385
+ const quickTaskNote = config.enabled && config.strategy.mode !== 'advisory'
3386
+ && config.strategy.quickTaskCommand !== '' && effectiveModels('execution').length > 0
3387
+ ? `\nThe user can type /${config.strategy.quickTaskCommand} to run one message on the execution `
3388
+ + 'tier for its whole turn — a simple task or quick question that does not need the main model; '
3389
+ + 'the next message without it returns to the normal route.'
3390
+ : '';
2714
3391
  return [
2715
3392
  '## Model manager',
2716
3393
  'Delegated work is routed by the label you give each delegation:',
2717
3394
  ...summary,
2718
3395
  routing,
2719
- `Call \`model_manager\` with action "report" to see which model each subagent actually used.${planningGap}${skillNote}${readImageNote}`,
3396
+ ...(pins.length === 0 ? [] : ['Active message directives:', ...pins.map((line) => ` ${line}`)]),
3397
+ `Call \`model_manager\` with action "report" to see which model each subagent actually used.${planningGap}${skillNote}${readImageNote}${quickTaskNote}`,
2720
3398
  ].join('\n');
2721
3399
  }
2722
3400
 
@@ -2853,6 +3531,30 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2853
3531
  wire: { viewSchema: usageProjectionSchema, view: (state) => state },
2854
3532
  };
2855
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
+
2856
3558
  /**
2857
3559
  * Whether this Session ever recorded an *explicit* model selection.
2858
3560
  *
@@ -2967,7 +3669,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2967
3669
  }
2968
3670
 
2969
3671
  /**
2970
- * The `/readimage` command handler: forward, don't answer.
3672
+ * The one-turn command handler (`/readimage`, `/quicktask`): forward,
3673
+ * don't answer.
2971
3674
  *
2972
3675
  * The harness's ordinary prompt path refuses images while the selected model
2973
3676
  * declares text-only input (`MODEL_DOES_NOT_SUPPORT_IMAGES` in
@@ -2981,26 +3684,38 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
2981
3684
  * `source.kind: 'user'` — without importing a harness package, which a
2982
3685
  * profile-installed plugin cannot resolve. Routing then happens at the claim
2983
3686
  * boundary exactly as it does for any typed message.
3687
+ *
3688
+ * `/quicktask` declares no attachment support, so the executor refuses an
3689
+ * invocation carrying attachments before this handler can ever see them;
3690
+ * the forwarding below stays generic (and defensive) regardless.
2984
3691
  */
2985
- function readImageHandler(invocation, name) {
3692
+ function turnCommandHandler(invocation, command) {
2986
3693
  try {
3694
+ const name = config.strategy[command.field];
2987
3695
  const agent = invocation?.agent;
2988
3696
  if (agent === undefined || typeof agent.followup !== 'function') {
2989
3697
  return { kind: 'error', text: `/${name}: this composition exposes no agent inbox to forward the message to` };
2990
3698
  }
2991
3699
  if (!config.enabled) {
2992
- return { kind: 'error', text: `/${name}: the model manager is disabled, so the vision route cannot be selected` };
3700
+ return { kind: 'error', text: `/${name}: the model manager is disabled, so the ${command.role} route cannot be selected` };
2993
3701
  }
2994
3702
  if (config.strategy.mode === 'advisory') {
2995
- return { kind: 'error', text: `/${name}: the manager is advisory (observe-only), so it cannot switch this message to the vision model` };
3703
+ return { kind: 'error', text: `/${name}: the manager is advisory (observe-only), so it cannot switch this message to the ${command.role} model` };
2996
3704
  }
2997
- if (effectiveModels('vision').length === 0) {
2998
- return { kind: 'error', text: `/${name}: no vision model is configured — set roles.vision.models to an image-capable model` };
3705
+ if (effectiveModels(command.role).length === 0) {
3706
+ return { kind: 'error', text: `/${name}: no ${command.role} model is configured — ${command.configureHint}` };
2999
3707
  }
3000
3708
  const rawInput = typeof invocation?.rawInput === 'string' ? invocation.rawInput : '';
3001
3709
  const attachments = Array.isArray(invocation?.attachments) ? invocation.attachments : [];
3710
+ // Defensive, mirroring the registration: a non-declaring command never
3711
+ // legitimately receives attachments (the executor refuses the invocation
3712
+ // before dispatch), and a quick turn must not land an image on an
3713
+ // execution model that cannot read it.
3714
+ if (!command.attachments && attachments.length > 0) {
3715
+ return { kind: 'error', text: `/${name}: this command is text only — images belong to the read-image command` };
3716
+ }
3002
3717
  if (rawInput.trim() === '' && attachments.length === 0) {
3003
- return { kind: 'error', text: `usage: /${name} <question> — attach the image(s) to read; the message runs on the vision model for one turn` };
3718
+ return { kind: 'error', text: `usage: /${name} <${command.usageHint}> — ${command.attachments ? 'attach the image(s) to read; ' : ''}the message runs on the ${command.role} model for one turn` };
3004
3719
  }
3005
3720
  if (invocation?.signal?.aborted === true) {
3006
3721
  return { kind: 'error', text: `/${name}: cancelled before the message was forwarded` };
@@ -3014,43 +3729,68 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3014
3729
  }));
3015
3730
  return { kind: 'success' };
3016
3731
  } catch (error) {
3017
- return { kind: 'error', text: `/${name}: ${error?.message ?? error}` };
3732
+ return { kind: 'error', text: `/${config.strategy[command.field]}: ${error?.message ?? error}` };
3018
3733
  }
3019
3734
  }
3020
3735
 
3021
3736
  /**
3022
- * Register (or re-register) the read-image command under the live config
3023
- * name. Idempotent while the name is unchanged; a rename disposes the old
3737
+ * Register (or re-register) every one-turn command under its live config
3738
+ * name. Idempotent while a name is unchanged; a rename disposes the old
3024
3739
  * registration first. Every failure degrades to a warning — a composition
3025
3740
  * without the commands service simply keeps the plain-text gesture routing.
3741
+ *
3742
+ * The registry itself does NOT refuse a duplicate name (a later
3743
+ * registration shadows the earlier one), so a config pointing two commands
3744
+ * at one name is resolved here instead, first-wins in `TURN_COMMANDS`
3745
+ * order: the losing command is skipped with a warning, and the gesture scan
3746
+ * (which walks the same order) stays consistent with what is registered.
3026
3747
  */
3027
- function armReadImageCommand() {
3748
+ function armTurnCommands() {
3028
3749
  if (commandsService === undefined || typeof commandsService.register !== 'function') return;
3029
- const name = config.strategy.readImageCommand;
3030
- if (readImageName === name) return;
3031
- if (readImageDispose !== undefined) {
3032
- try { readImageDispose(); } catch { /* a failed dispose must not block the re-arm */ }
3033
- readImageDispose = undefined;
3034
- }
3035
- readImageName = '';
3036
- if (name === '') return;
3037
- try {
3038
- const dispose = commandsService.register({
3039
- name,
3040
- description: 'Read attached images with the vision model: this message (and its turn) runs on the '
3041
- + "manager's vision role, then the next message returns to the normal route. Accepts image attachments.",
3042
- input: { hint: 'question about the attached image(s)', attachments: true },
3043
- handler: (invocation) => readImageHandler(invocation, name),
3044
- });
3045
- readImageDispose = typeof dispose === 'function' ? dispose : () => {};
3046
- readImageName = name;
3047
- log('info', `registered the /${name} command — one turn on the vision role, with attachment support`);
3048
- } catch (error) {
3049
- log('warn', `/${name} command not registered: ${error?.message ?? error}`);
3750
+ const owner = turnCommandOwners();
3751
+ for (const command of TURN_COMMANDS) {
3752
+ const name = config.strategy[command.field];
3753
+ const registered = commandRegistrations.get(command.key);
3754
+ if (registered?.name === name && owner.get(name) === command) continue;
3755
+ if (registered !== undefined) {
3756
+ try { registered.dispose(); } catch { /* a failed dispose must not block the re-arm */ }
3757
+ commandRegistrations.delete(command.key);
3758
+ }
3759
+ if (name === '') continue;
3760
+ if (owner.get(name) !== command) {
3761
+ // Warn once per colliding name, not once per volatile save: an
3762
+ // unchanged config re-arms identically and must stay quiet.
3763
+ if (commandCollisionWarned.get(command.key) !== name) {
3764
+ commandCollisionWarned.set(command.key, name);
3765
+ log('warn', `/${name} already names the ${owner.get(name).feature} command, so the ${command.feature} `
3766
+ + `command is not registered — give strategy.${command.field} a name of its own`);
3767
+ }
3768
+ continue;
3769
+ }
3770
+ commandCollisionWarned.delete(command.key);
3771
+ try {
3772
+ const dispose = commandsService.register({
3773
+ name,
3774
+ description: command.description,
3775
+ input: { hint: command.hint, ...(command.attachments ? { attachments: true } : {}) },
3776
+ handler: (invocation) => turnCommandHandler(invocation, command),
3777
+ });
3778
+ commandRegistrations.set(command.key, { name, dispose: typeof dispose === 'function' ? dispose : () => {} });
3779
+ log('info', `registered the /${name} command — one turn on the ${command.role} role`
3780
+ + `${command.attachments ? ', with attachment support' : ''}`);
3781
+ } catch (error) {
3782
+ log('warn', `/${name} command not registered: ${error?.message ?? error}`);
3783
+ }
3050
3784
  }
3051
3785
  }
3052
3786
 
3053
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); });
3054
3794
  ctx.on('agent/request', onAgentRequest);
3055
3795
  ctx.on('agent/request-error', onRequestError);
3056
3796
  // Prepend so `next()` returns the decision WITH the harness's own skill
@@ -3074,7 +3814,13 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3074
3814
  liveSkills.delete(id);
3075
3815
  topTriggers.delete(id);
3076
3816
  managerSelected.delete(id);
3077
- readImageTurns.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
+ }
3823
+ commandTurns.delete(id);
3078
3824
  });
3079
3825
 
3080
3826
  // Claim-boundary selection (DSH 0.2.x): the loop claims a step's input and
@@ -3088,6 +3834,12 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3088
3834
  ctx.on('subagent/start', (info) => {
3089
3835
  const childId = info?.id;
3090
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
+ }
3091
3843
  void lookupChild(childId).then(() => {
3092
3844
  // DSH 0.2.x: the child's route has to be selected before its first
3093
3845
  // step is prepared, and the label only exists behind that async
@@ -3119,10 +3871,11 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3119
3871
  };
3120
3872
  visionMatch = keywordMatcher(config.strategy.visionKeywords);
3121
3873
  planningMatch = keywordMatcher(config.strategy.planningKeywords);
3122
- // A renamed (or disabled) read-image command takes effect on the save:
3874
+ void refreshModelCatalog(true);
3875
+ // A renamed (or disabled) one-turn command takes effect on the save:
3123
3876
  // the gesture scan already reads the live config, and this re-arms the
3124
- // harness command registration under the new name.
3125
- armReadImageCommand();
3877
+ // harness command registrations under the new names.
3878
+ armTurnCommands();
3126
3879
  for (const warning of config.warnings) log('warn', warning);
3127
3880
  // The delegation policy and the update schedule both read the live
3128
3881
  // config through this closure, so they follow a save with no restart.
@@ -3131,7 +3884,8 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3131
3884
  if (updateChanged) void checkForUpdate().catch(() => {});
3132
3885
  log('info', `settings reloaded — mode ${config.strategy.mode}, pick ${config.pick}, autoDelegate ${config.strategy.autoDelegate}, `
3133
3886
  + `planningSkills ${config.strategy.planningSkills.join('|') || '-'}, `
3134
- + `readImage ${config.strategy.readImageCommand || '-'}; `
3887
+ + `readImage ${config.strategy.readImageCommand || '-'}, `
3888
+ + `quickTask ${config.strategy.quickTaskCommand || '-'}; `
3135
3889
  + ROLE_NAMES
3136
3890
  .map((key) => `${key}=${config.roles[key].models.length === 0 ? '-' : config.roles[key].models.map((r) => `${r.provider}/${r.model}`).join('|')}`)
3137
3891
  .join(' '));
@@ -3150,14 +3904,15 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3150
3904
  name: 'model_manager',
3151
3905
  description: 'Inspect and explain the role-based model routing configured for this harness. '
3152
3906
  + 'action "report": a Top-level agents section naming which model served each '
3153
- + 'conversation, whether the manager yielded to a model a person picked in the '
3154
- + 'composer, which planning skill (if any) put a session on the planning tier, '
3155
- + 'and whether the last turn carried the read-image command, '
3156
- + 'then one row per subagent with its label, role, reason, live status and '
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 '
3157
3911
  + 'totals. action "routes": the four role assignments '
3158
3912
  + '(including the vision->execution fallback), the shared selection strategy (first or round-robin), '
3159
- + 'the active distribution mode, the auto-delegation level, the planning-skill trigger, '
3160
- + 'the read-image command (one turn on the vision role), '
3913
+ + 'the active distribution mode, session @model directives, the auto-delegation level, '
3914
+ + 'the planning-skill trigger, '
3915
+ + 'the one-turn commands (/readimage on the vision role, /quicktask on the execution role), '
3161
3916
  + 'the update-check status, '
3162
3917
  + 'and whether each '
3163
3918
  + 'route is dispatchable by the delegation tool, with the YAML to add any that are not. '
@@ -3230,9 +3985,10 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3230
3985
  registry.register(usageProjectionDefinition);
3231
3986
  registry.register(selectionProjectionDefinition);
3232
3987
  registry.register(planningSkillProjectionDefinition);
3988
+ registry.register(directiveProjectionDefinition);
3233
3989
  projections = registry;
3234
- log('info', `registered the ${USAGE_PROJECTION_KEY}, ${SELECTION_PROJECTION_KEY} and `
3235
- + `${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`);
3236
3992
  } catch (error) {
3237
3993
  log('warn', `could not register the usage projection: ${error?.message ?? error}`);
3238
3994
  }
@@ -3246,7 +4002,7 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3246
4002
  disposers.push(scoped.systemPrompt.section({
3247
4003
  name: 'model-manager',
3248
4004
  order: 60,
3249
- text: () => cheatSheet(),
4005
+ text: (context) => cheatSheet(context),
3250
4006
  }));
3251
4007
  // The delegation policy: rendered per assembly, only for the
3252
4008
  // top-level orchestrator, and only while it actually has the
@@ -3315,34 +4071,35 @@ function createEngine(initialConfig, ctx, log, rawConfig) {
3315
4071
  }
3316
4072
  });
3317
4073
 
3318
- // The read-image command (0.7.0). Like /autoplan this is a workflow
3319
- // gesture the plugin ships, but unlike a skill it must accept image
3320
- // attachments: the command path is the only admission seam that lets
3321
- // images through while a text-only model is selected. Registration
3322
- // follows the live config name; a volatile save re-arms it below.
4074
+ // The one-turn commands (`/readimage` since 0.7.0, `/quicktask` since
4075
+ // 0.7.1). Like /autoplan these are workflow gestures the plugin ships,
4076
+ // but unlike a skill /readimage must accept image attachments: the
4077
+ // command path is the only admission seam that lets images through while
4078
+ // a text-only model is selected (/quicktask declares none, so the
4079
+ // executor refuses attachments for it before dispatch). Registration
4080
+ // follows the live config names; a volatile save re-arms them below.
3323
4081
  ctx.inject(['commands'], (scoped) => {
3324
4082
  try {
3325
4083
  commandsService = scoped?.commands;
3326
4084
  if (commandsService === undefined || typeof commandsService.register !== 'function') {
3327
- log('warn', 'the commands service is present but exposes no register(); the read-image command is unavailable');
4085
+ log('warn', 'the commands service is present but exposes no register(); the one-turn commands are unavailable');
3328
4086
  return;
3329
4087
  }
3330
4088
  if (typeof scoped.effect === 'function') {
3331
4089
  scoped.effect(() => {
3332
- armReadImageCommand();
4090
+ armTurnCommands();
3333
4091
  return () => {
3334
- if (readImageDispose !== undefined) {
3335
- try { readImageDispose(); } catch { /* disposal is best-effort */ }
3336
- readImageDispose = undefined;
4092
+ for (const [, entry] of commandRegistrations) {
4093
+ try { entry.dispose(); } catch { /* disposal is best-effort */ }
3337
4094
  }
3338
- readImageName = '';
4095
+ commandRegistrations.clear();
3339
4096
  };
3340
4097
  });
3341
4098
  } else {
3342
- armReadImageCommand();
4099
+ armTurnCommands();
3343
4100
  }
3344
4101
  } catch (error) {
3345
- log('warn', `read-image command not registered: ${error?.message ?? error}`);
4102
+ log('warn', `one-turn command not registered: ${error?.message ?? error}`);
3346
4103
  }
3347
4104
  });
3348
4105
  }
@@ -3447,10 +4204,18 @@ export {
3447
4204
  selectionModelOf,
3448
4205
  sameSelection,
3449
4206
  planningSkillInMessages,
4207
+ modelDirectivesInMessages,
4208
+ normalizeDirectiveState,
4209
+ applyDirectivePatches,
4210
+ resolveModelDirective,
4211
+ directiveReferenceParts,
4212
+ commandGestureInMessages,
3450
4213
  readImageGestureInMessages,
3451
4214
  normalizeReadImageCommand,
4215
+ normalizeQuickTaskCommand,
3452
4216
  DEFAULT_PLANNING_KEYWORDS,
3453
4217
  DEFAULT_PLANNING_SKILLS,
3454
4218
  DEFAULT_READ_IMAGE_COMMAND,
4219
+ DEFAULT_QUICK_TASK_COMMAND,
3455
4220
  DEFAULT_VISION_KEYWORDS,
3456
4221
  };