dsh-subagent-default-model 2.2.2 → 2.2.4
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/CHANGELOG.md +137 -0
- package/README.en.md +25 -6
- package/README.md +30 -6
- package/lib/client.js +19 -151
- package/lib/index.js +653 -48
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -131,7 +131,7 @@ const SUBAGENT_DEFAULT_MODEL_SETTINGS_SCHEMA = z.object({
|
|
|
131
131
|
//
|
|
132
132
|
// Declared volatile like every other configurable field: the settings write
|
|
133
133
|
// gate rejects any path that is not a declared volatile field.
|
|
134
|
-
injectRouteContext: volatileField(z.boolean().default(true).description("
|
|
134
|
+
injectRouteContext: volatileField(z.boolean().default(true).description("Tell a subagent the route it is actually running on, and the main agent which model its delegations will use")),
|
|
135
135
|
// Must be DECLARED and volatile: the settings write gate rejects every path
|
|
136
136
|
// that is not a declared volatile field (`@deepseek-ai/dsh-settings`
|
|
137
137
|
// `write()` throws `Config field "…" is not volatile`). The client card
|
|
@@ -158,7 +158,29 @@ const SUBAGENT_DEFAULT_MODEL_SETTINGS_SCHEMA = z.object({
|
|
|
158
158
|
//
|
|
159
159
|
// Opting IN is a deliberate trade: you want fork children on the pool route
|
|
160
160
|
// and accept paying to re-run the inherited prefix once.
|
|
161
|
-
applyToForkChildren: volatileField(z.boolean().default(false).description("Let same-context channels (subagent_fork) follow the configured route instead of inheriting the parent's; off keeps the host's KV-cache reuse"))
|
|
161
|
+
applyToForkChildren: volatileField(z.boolean().default(false).description("Let same-context channels (subagent_fork) follow the configured route instead of inheriting the parent's; off keeps the host's KV-cache reuse")),
|
|
162
|
+
// Whether a subagent whose turn died on a FAILOVER-ELIGIBLE failure is woken
|
|
163
|
+
// for one more turn, so the route `agent.model.select()` just chose is
|
|
164
|
+
// actually used instead of waiting for somebody to send more input.
|
|
165
|
+
//
|
|
166
|
+
// WHY THIS IS NEEDED AT ALL. On DSH 0.2.2+ the failing step keeps its fixed
|
|
167
|
+
// route, so the switch only takes effect on a LATER turn. Without a wake, a
|
|
168
|
+
// one-shot `subagent` simply ends: the pool is switched to a healthy route
|
|
169
|
+
// that never gets used, and the parent is told the child failed. Measured
|
|
170
|
+
// before this existed: a pool route returned 429, failover selected the
|
|
171
|
+
// healthy entry, and the child still ended `error` with zero further
|
|
172
|
+
// requests.
|
|
173
|
+
//
|
|
174
|
+
// Default ON, because "switch, then keep working" is the whole point of the
|
|
175
|
+
// failover feature; `false` restores the pre-2.2.3 behaviour (switch recorded,
|
|
176
|
+
// current turn ends).
|
|
177
|
+
continueAfterFailover: volatileField(z.boolean().default(true).description("Wake a subagent for one more turn after a failover switch, so the healthy route is actually used instead of ending the task")),
|
|
178
|
+
// How many consecutive automatic continuations one subagent run may have.
|
|
179
|
+
// A pool of N entries can only switch N-1 times, so a cap above that would
|
|
180
|
+
// never be reached; the failover pool-exhaustion rule is the real bound.
|
|
181
|
+
// Kept separate because it is what stops a pathological loop when the pool
|
|
182
|
+
// keeps being edited while the run is alive.
|
|
183
|
+
maxAutoContinues: volatileField(z.number().default(2).description("Maximum consecutive automatic continuations per subagent run (0 disables)"))
|
|
162
184
|
}).default({});
|
|
163
185
|
|
|
164
186
|
/** The plugin's Cordis Config — on DSH 0.1.7+ this IS the settings section. */
|
|
@@ -351,10 +373,27 @@ function failoverView(state) {
|
|
|
351
373
|
const section = state.getSection?.();
|
|
352
374
|
if (section === void 0 || section === null) return void 0;
|
|
353
375
|
if (section.failoverEnabled === false) return void 0;
|
|
354
|
-
|
|
376
|
+
// Deduplicate by provider+model.
|
|
377
|
+
//
|
|
378
|
+
// A pool such as `["a", "a"]` — or two entries that happen to resolve to the
|
|
379
|
+
// same route — is not a two-route pool: `AgentModel.select()` compares the
|
|
380
|
+
// new selection with the recorded one and returns WITHOUT appending
|
|
381
|
+
// `model/selection` when they match. The "switch" would then be a silent
|
|
382
|
+
// no-op while this plugin still recorded a switch and woke the child, so the
|
|
383
|
+
// continuation re-requested the same dead route. Distinct
|
|
384
|
+
// `reasoningEffort` values still count as distinct selections (the host
|
|
385
|
+
// compares effort too), so the key includes it.
|
|
386
|
+
const resolved = Array.isArray(section.models)
|
|
355
387
|
? section.models.map((entry) => resolveEntry(section, entry)).filter((entry) => entry !== void 0)
|
|
356
388
|
: [];
|
|
357
|
-
|
|
389
|
+
const seen = new Set();
|
|
390
|
+
const entries = resolved.filter((entry) => {
|
|
391
|
+
const key = `${entry.provider}\u0000${entry.model}\u0000${entry.reasoningEffort ?? ""}`;
|
|
392
|
+
if (seen.has(key)) return false;
|
|
393
|
+
seen.add(key);
|
|
394
|
+
return true;
|
|
395
|
+
});
|
|
396
|
+
// A pool of <2 DISTINCT models has nothing to switch to; keep the parent route.
|
|
358
397
|
if (entries.length < 2) return void 0;
|
|
359
398
|
return { entries, strategy: section.strategy === "random" ? "random" : "round-robin" };
|
|
360
399
|
}
|
|
@@ -370,15 +409,52 @@ function isSubagentAgent(agent) {
|
|
|
370
409
|
* - round-robin: the next entry after the currently-served model, wrapping
|
|
371
410
|
* around the list (the "queue"), skipping entries this run already tried so a
|
|
372
411
|
* single bad candidate is not re-selected while an untried one remains.
|
|
373
|
-
* - random:
|
|
374
|
-
*
|
|
412
|
+
* - random: uniformly among the entries this run has NOT already tried.
|
|
413
|
+
* Deliberately NOT "any entry": `model.select()` is a silent no-op when the
|
|
414
|
+
* selection equals the current one, so picking a dead route again records
|
|
415
|
+
* nothing and the continuation re-requests it. `tried` therefore carries both
|
|
416
|
+
* the routes switched to and the route that failed (seeded by the caller).
|
|
417
|
+
*
|
|
418
|
+
* @param view - pool entries and strategy.
|
|
419
|
+
* @param agent - the failing subagent (its live route is the fallback anchor).
|
|
420
|
+
* @param current - this run's switch bookkeeping, if any.
|
|
421
|
+
* @param seededTried - `current.tried` already extended with the failed route.
|
|
422
|
+
* @returns the chosen pool index.
|
|
375
423
|
*/
|
|
376
|
-
function nextFailoverIndex(view, agent, current) {
|
|
424
|
+
function nextFailoverIndex(view, agent, current, seededTried = undefined) {
|
|
377
425
|
const { entries, strategy } = view;
|
|
426
|
+
const tried = seededTried ?? current?.tried;
|
|
378
427
|
if (strategy === "random") {
|
|
379
|
-
|
|
428
|
+
// A random pick must still be a USEFUL pick. The naive
|
|
429
|
+
// `Math.random() * entries.length` ignored both `tried` and the route
|
|
430
|
+
// that just failed, so it re-selected the dead entry with probability
|
|
431
|
+
// 1/entries.length — and worse, it could return the very entry the
|
|
432
|
+
// failure came from.
|
|
433
|
+
//
|
|
434
|
+
// Measured consequence: `model.select()` compared the "new" selection
|
|
435
|
+
// with the current one, found them equal, and returned WITHOUT appending
|
|
436
|
+
// `model/selection`. The switch silently did nothing, the continuation
|
|
437
|
+
// turn re-requested the same dead route, and the child failed again.
|
|
438
|
+
// The diagnostic read exactly that: `selecting minmax/… (before=minmax/…)`
|
|
439
|
+
// followed by an unchanged `current()` and an unchanged session seq.
|
|
440
|
+
//
|
|
441
|
+
// Only entries this run has not already tried are candidates. `tried` is
|
|
442
|
+
// seeded by `switchForNextStep` with BOTH the route that just failed and
|
|
443
|
+
// every route it has switched to, so "already failed here" is fully
|
|
444
|
+
// represented — that is what keeps a random pick useful instead of
|
|
445
|
+
// re-selecting a dead entry (which makes `model.select()` a silent no-op).
|
|
446
|
+
const blocked = new Set(tried ?? []);
|
|
447
|
+
const candidates = entries
|
|
448
|
+
.map((entry, index) => index)
|
|
449
|
+
.filter((index) => !blocked.has(index));
|
|
450
|
+
// DEFENSIVE, currently unreachable: the caller returns on
|
|
451
|
+
// `count >= entries.length - 1` before calling, and every switch adds a
|
|
452
|
+
// distinct index, so at least one candidate always remains. Kept anyway —
|
|
453
|
+
// if that guard ever changes, returning `undefined` here would silently
|
|
454
|
+
// select nothing, whereas an index still lets the caller decide.
|
|
455
|
+
if (candidates.length === 0) return Math.floor(Math.random() * entries.length);
|
|
456
|
+
return candidates[Math.floor(Math.random() * candidates.length)];
|
|
380
457
|
}
|
|
381
|
-
const tried = current?.tried;
|
|
382
458
|
if (current !== void 0) {
|
|
383
459
|
// Advance from the last pick, taking the first entry this run has not used.
|
|
384
460
|
for (let step = 1; step <= entries.length; step += 1) {
|
|
@@ -421,12 +497,13 @@ function nextFailoverIndex(view, agent, current) {
|
|
|
421
497
|
* (quota, auth), unlike the host's "after step preparation fixed" guard.
|
|
422
498
|
*
|
|
423
499
|
* The visible consequence, stated plainly: on 0.2.2 a permanently failing
|
|
424
|
-
* route ends the
|
|
425
|
-
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
500
|
+
* route still ends the CURRENT turn — the host fixes its route, so that turn
|
|
501
|
+
* cannot continue elsewhere. What the selection buys is everything after it,
|
|
502
|
+
* and `onSwitched` (see `installAutoContinue`) is what makes "after it" happen
|
|
503
|
+
* without waiting for the parent: it wakes the child for one more turn once the
|
|
504
|
+
* agent goes idle, so the new route is actually used.
|
|
428
505
|
*/
|
|
429
|
-
async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
506
|
+
async function switchForNextStep(ctx, state, pending, payload, next, onSwitched) {
|
|
430
507
|
const { agent, step, failure, signal } = payload;
|
|
431
508
|
const downstream = await next();
|
|
432
509
|
if (signal?.aborted) return downstream;
|
|
@@ -437,12 +514,59 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
437
514
|
const view = failoverView(state);
|
|
438
515
|
if (view === void 0) return downstream;
|
|
439
516
|
const current = pending.get(agent.id);
|
|
440
|
-
|
|
517
|
+
// Guard on turn AND step. A continuation turn restarts at step 1, so a
|
|
518
|
+
// step-only guard treats a fresh turn's first failure as "already switched
|
|
519
|
+
// for this step" and silently refuses to switch again — capping a one-shot
|
|
520
|
+
// child at ONE failover no matter how large the pool is (measured: a 3-entry
|
|
521
|
+
// pool only ever reached the second entry).
|
|
522
|
+
if (current !== void 0 && current.turn === payload.turn && current.step === step) return downstream;
|
|
441
523
|
if (current !== void 0 && current.count >= view.entries.length - 1) return downstream; // pool exhausted
|
|
442
|
-
|
|
524
|
+
// Seed `tried` with the route that FAILED, not just the ones already switched
|
|
525
|
+
// to.
|
|
526
|
+
//
|
|
527
|
+
// `tried` used to record only switch targets, so the route that failed FIRST
|
|
528
|
+
// never entered it. From the second switch onward that dead route was a legal
|
|
529
|
+
// candidate again — no longer `served`, and filtered by nothing — so `random`
|
|
530
|
+
// could send the child straight back to it. Measured with a fixture whose
|
|
531
|
+
// route follows `select` (as the host's own fold does) and a three-entry
|
|
532
|
+
// pool: 136 of 300 second switches returned to the original dead route, and
|
|
533
|
+
// the `entries.length - 1` cap then left the third entry never tried.
|
|
534
|
+
//
|
|
535
|
+
// This must run BEFORE `nextFailoverIndex`, which is the only consumer.
|
|
536
|
+
const tried = new Set(current?.tried ?? []);
|
|
537
|
+
if (current === undefined) {
|
|
538
|
+
// Identify the served entry by provider + model + effort.
|
|
539
|
+
//
|
|
540
|
+
// Locate the served entry by provider + model + effort.
|
|
541
|
+
//
|
|
542
|
+
// `session.requestContext()` carries no `reasoningEffort`, but the host's
|
|
543
|
+
// `AgentModel.select()` compares effort as part of the selection. A pool
|
|
544
|
+
// differing only by effort (`[a/high, a/low]`) would then resolve the
|
|
545
|
+
// served route to the WRONG entry and pick the very selection the child is
|
|
546
|
+
// already on — a silent no-op that still costs a wake.
|
|
547
|
+
//
|
|
548
|
+
// `requestHeader().config` is the route the LAST REQUEST actually used,
|
|
549
|
+
// including effort, and is exactly what `selectionOfHeader()` feeds the
|
|
550
|
+
// host's comparison. `model.current()` would also carry effort but reads
|
|
551
|
+
// `pending ?? lastUsed`, so another plugin's not-yet-used selection could
|
|
552
|
+
// name an entry this run never actually served.
|
|
553
|
+
const live = agent?.session?.requestHeader?.()?.config
|
|
554
|
+
?? agent?.model?.current?.()
|
|
555
|
+
?? agent?.session?.requestContext?.();
|
|
556
|
+
if (live !== void 0 && live !== null) {
|
|
557
|
+
const servedIndex = view.entries.findIndex((entry) =>
|
|
558
|
+
entry.provider === live.provider
|
|
559
|
+
&& entry.model === live.model
|
|
560
|
+
&& (entry.reasoningEffort ?? void 0) === (live.reasoningEffort ?? void 0)
|
|
561
|
+
);
|
|
562
|
+
if (servedIndex >= 0) tried.add(servedIndex);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const index = nextFailoverIndex(view, agent, current, tried);
|
|
443
566
|
const target = view.entries[index];
|
|
444
567
|
if (target === void 0) return downstream;
|
|
445
|
-
|
|
568
|
+
// Record the route that FAILED too, not just the one being selected.
|
|
569
|
+
//
|
|
446
570
|
tried.add(index);
|
|
447
571
|
try {
|
|
448
572
|
agent.model.select({
|
|
@@ -470,7 +594,8 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
470
594
|
index,
|
|
471
595
|
tried,
|
|
472
596
|
count: (current?.count ?? 0) + 1,
|
|
473
|
-
step
|
|
597
|
+
step,
|
|
598
|
+
turn: payload.turn
|
|
474
599
|
});
|
|
475
600
|
ctx.logger.warn(
|
|
476
601
|
`[dsh-subagent-default-model] subagent %s failed with %s on turn %d step %d; %s/%s is selected for its NEXT step (this host fixes the route of the failed step, so the current turn cannot continue on it)`,
|
|
@@ -490,6 +615,23 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
490
615
|
target.model
|
|
491
616
|
);
|
|
492
617
|
}
|
|
618
|
+
// The selection only lands on the NEXT step. A one-shot subagent never
|
|
619
|
+
// starts one, so without this the switch would be recorded and wasted.
|
|
620
|
+
// Told from HERE rather than from a second listener on the same waterfall:
|
|
621
|
+
// that would depend on listener order and on re-reading `pending`, which is
|
|
622
|
+
// exactly the coupling this call avoids. It runs after the selection landed.
|
|
623
|
+
// A throw here must not abort the host's failure waterfall and replace a real
|
|
624
|
+
// provider error with a plugin crash; the switch has already landed.
|
|
625
|
+
try {
|
|
626
|
+
onSwitched?.(agent, failure);
|
|
627
|
+
} catch (error) {
|
|
628
|
+
ctx.logger?.warn?.(
|
|
629
|
+
`[dsh-subagent-default-model] could not schedule a continuation for subagent %s after %s: %s`,
|
|
630
|
+
agent?.id,
|
|
631
|
+
failure?.code,
|
|
632
|
+
error instanceof Error ? error.message : String(error)
|
|
633
|
+
);
|
|
634
|
+
}
|
|
493
635
|
return downstream;
|
|
494
636
|
}
|
|
495
637
|
|
|
@@ -501,7 +643,7 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
501
643
|
* subagent run (`agent.id`) and cleaned on `agent/disposed`, so a persistently
|
|
502
644
|
* broken primary is not re-tried on every step of the same run.
|
|
503
645
|
*/
|
|
504
|
-
function installFailover(ctx, state) {
|
|
646
|
+
function installFailover(ctx, state, onSwitched) {
|
|
505
647
|
const pending = new Map();
|
|
506
648
|
|
|
507
649
|
// After a model failure on a subagent loop: advance the pool index and ask
|
|
@@ -517,16 +659,27 @@ function installFailover(ctx, state) {
|
|
|
517
659
|
// 0.2.2+ fixed the route for the whole step, so the route cannot be
|
|
518
660
|
// swapped on the retry this hook used to request. See
|
|
519
661
|
// `switchForNextStep` for what replaces it.
|
|
520
|
-
if (fixesStepRoute(agent)) return switchForNextStep(ctx, state, pending, payload, next);
|
|
662
|
+
if (fixesStepRoute(agent)) return switchForNextStep(ctx, state, pending, payload, next, onSwitched);
|
|
521
663
|
const current = pending.get(agent.id);
|
|
522
664
|
// The primary already failed (that triggered the first switch), so the
|
|
523
665
|
// remaining candidates are the other pool entries: at most
|
|
524
666
|
// `entries.length - 1` switches, then let the real error surface.
|
|
525
667
|
if (current !== void 0 && current.count >= view.entries.length - 1) return next(); // pool exhausted
|
|
526
|
-
|
|
668
|
+
// Same seeding as the 0.2.2+ path: the route that failed FIRST is in
|
|
669
|
+
// `tried` too, so it cannot be picked again on a later failure.
|
|
670
|
+
const tried = new Set(current?.tried ?? []);
|
|
671
|
+
if (current === undefined) {
|
|
672
|
+
const served = agent.session?.requestContext?.();
|
|
673
|
+
if (served !== void 0) {
|
|
674
|
+
const servedIndex = view.entries.findIndex((entry) =>
|
|
675
|
+
entry.provider === served.provider && entry.model === served.model
|
|
676
|
+
);
|
|
677
|
+
if (servedIndex >= 0) tried.add(servedIndex);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const index = nextFailoverIndex(view, agent, current, tried);
|
|
527
681
|
// Remember every pool entry this run has already been switched to, so a
|
|
528
682
|
// candidate that fails again is not selected a second time.
|
|
529
|
-
const tried = new Set(current?.tried ?? []);
|
|
530
683
|
tried.add(index);
|
|
531
684
|
pending.set(agent.id, {
|
|
532
685
|
index,
|
|
@@ -611,6 +764,274 @@ function installFailover(ctx, state) {
|
|
|
611
764
|
}, "dsh-subagent-default-model: failover listeners");
|
|
612
765
|
}
|
|
613
766
|
|
|
767
|
+
// ── automatic continuation after a failover switch ───────────────────────────
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* The producer-owned source kind for this plugin's automatic continuation turn.
|
|
771
|
+
*
|
|
772
|
+
* NOT `"user"`: that would claim the human typed it, and the transcript would
|
|
773
|
+
* render it as their own message — they never said it, and they could not tell
|
|
774
|
+
* it apart from their own input. `MessageSourceMap` is merge-extensible and each
|
|
775
|
+
* producer declares its own kind; `dsh-purge` / `dsh-connect-workbuddy` do the
|
|
776
|
+
* same. It also keeps the plugin's own messages distinguishable from the user's
|
|
777
|
+
* in the transcript, which is what the continuation cap has to key on.
|
|
778
|
+
*/
|
|
779
|
+
const CONTINUE_SOURCE = "plugin:dsh-subagent-default-model";
|
|
780
|
+
/**
|
|
781
|
+
* The instruction a continued subagent receives.
|
|
782
|
+
*
|
|
783
|
+
* Deliberately free of route details AND of any claim that the new provider is
|
|
784
|
+
* healthy: the selection can be a no-op (a duplicate pool entry) or the target
|
|
785
|
+
* can fail immediately, and a prompt that asserts "you are now on a healthy
|
|
786
|
+
* provider" would then be simply false to the model reading it.
|
|
787
|
+
*/
|
|
788
|
+
const CONTINUE_TEXT = "Continue the task from where it stopped. The previous model request failed before your work was finished, so this is a fresh attempt. Do not restart from scratch and do not repeat work you already completed.";
|
|
789
|
+
|
|
790
|
+
/** Message handed to a failed subagent so it takes one more turn on the healthy route. */
|
|
791
|
+
function continuationMessage() {
|
|
792
|
+
return createUserMessage({
|
|
793
|
+
content: [{ type: "text", text: CONTINUE_TEXT }],
|
|
794
|
+
source: { kind: CONTINUE_SOURCE, form: "notice", summary: "failover-continue" }
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* Whether this agent may be woken automatically after a switch.
|
|
800
|
+
*
|
|
801
|
+
* ONLY `subagent` origin. The main agent's loop is never touched by this plugin,
|
|
802
|
+
* and its failures are the user's business, not a place to inject turns.
|
|
803
|
+
*
|
|
804
|
+
* `fork` children are EXCLUDED on purpose. The only durable proof that a child
|
|
805
|
+
* carries a fork-inherited prefix is `header.isSeeded` (the header has no
|
|
806
|
+
* `backend` field), and an extra turn on top of that inherited prefix is billed
|
|
807
|
+
* again in full on the new provider — the same cost this plugin already refuses
|
|
808
|
+
* to pay for `applyToForkChildren`. The pool route still governs its next
|
|
809
|
+
* genuine turn, which is the host's own intended behaviour.
|
|
810
|
+
*/
|
|
811
|
+
function continuationEligible(agent) {
|
|
812
|
+
// Kept even though the only caller already applies the same origin gate: this
|
|
813
|
+
// is the function's own precondition, and a future caller (or a refactor that
|
|
814
|
+
// moves the gate) must not be able to wake the main agent by accident.
|
|
815
|
+
if (!isSubagentAgent(agent)) return false;
|
|
816
|
+
if (agent?.session?.header?.isSeeded === true) return false;
|
|
817
|
+
return typeof agent?.followup === "function";
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Whether somebody already queued this child's next turn.
|
|
822
|
+
*
|
|
823
|
+
* Both the duplicate guard and the deferred re-check ask exactly this, so it
|
|
824
|
+
* lives in one place. `nextTurn` is the host's own pending-turn list — reading
|
|
825
|
+
* it cannot disagree with what the manager will do next.
|
|
826
|
+
*/
|
|
827
|
+
function hasQueuedTurn(agent) {
|
|
828
|
+
const inbox = agent?.inbox;
|
|
829
|
+
return Array.isArray(inbox?.nextTurn) && inbox.nextTurn.length > 0;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* Wake a switched subagent for exactly one more turn.
|
|
834
|
+
*
|
|
835
|
+
* THE POINT. `switchForNextStep` writes the healthy route through
|
|
836
|
+
* `agent.model.select()`, which the NEXT step reads. On a one-shot subagent
|
|
837
|
+
* nothing ever starts that next step, so the switch is recorded and wasted: the
|
|
838
|
+
* measured symptom was a child that ended `error` while a healthy pool entry sat
|
|
839
|
+
* selected and unused. This is the missing half of "switch to another provider
|
|
840
|
+
* and keep working".
|
|
841
|
+
*
|
|
842
|
+
* WHY A `followup` AND NOT A RETRY. The host's contract is explicit — every
|
|
843
|
+
* `followup` message "becomes the sole ordinary message of its own turn". That
|
|
844
|
+
* is the only sanctioned way to start a turn whose route is re-read, and it is
|
|
845
|
+
* also what the host's own settlement gives a continuable child ("will do no
|
|
846
|
+
* further work unless you send it more"). This plugin supplies the "more".
|
|
847
|
+
*
|
|
848
|
+
* BOUNDED BY CONSTRUCTION. It only fires when `switchForNextStep` recorded a
|
|
849
|
+
* real selection for this agent (so the pool had an untried entry and the host
|
|
850
|
+
* accepted the selection), and the switch bookkeeping caps that at
|
|
851
|
+
* `entries.length - 1` per run. `maxAutoContinues` is a second, independent
|
|
852
|
+
* ceiling for the case where settings are edited mid-run.
|
|
853
|
+
*/
|
|
854
|
+
function installAutoContinue(ctx, state) {
|
|
855
|
+
/** Continuations already spent by each agent run. */
|
|
856
|
+
const runs = new Map();
|
|
857
|
+
/** Teardown of the pending wake listener per agent. */
|
|
858
|
+
const pendingWake = new Map();
|
|
859
|
+
|
|
860
|
+
const section = () => state.getSection?.() ?? {};
|
|
861
|
+
const enabled = () => section().continueAfterFailover !== false;
|
|
862
|
+
const ceiling = () => {
|
|
863
|
+
const raw = section().maxAutoContinues;
|
|
864
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return 2;
|
|
865
|
+
return Math.max(0, Math.min(10, Math.trunc(raw)));
|
|
866
|
+
};
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* Called by the failover path AFTER `agent.model.select()` landed.
|
|
870
|
+
*
|
|
871
|
+
* That ordering is the whole point: a selection is only useful to a LATER
|
|
872
|
+
* step, and a one-shot subagent never starts one. Arriving through a direct
|
|
873
|
+
* call — not a second listener on the same waterfall — also means this never
|
|
874
|
+
* depends on listener registration order, and it cannot fire for a failure
|
|
875
|
+
* that was not actually switched (exhausted pool, refused selection).
|
|
876
|
+
*/
|
|
877
|
+
function onSwitched(agent, failure) {
|
|
878
|
+
if (!enabled() || !continuationEligible(agent)) return;
|
|
879
|
+
const run = runs.get(agent.id);
|
|
880
|
+
const done = run?.count ?? 0;
|
|
881
|
+
if (done >= ceiling()) {
|
|
882
|
+
ctx.logger?.warn?.(
|
|
883
|
+
`[dsh-subagent-default-model] subagent %s failed with %s and was switched, but it already used %d automatic continuation(s); ending the task instead`,
|
|
884
|
+
agent.id,
|
|
885
|
+
failure.code,
|
|
886
|
+
done
|
|
887
|
+
);
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
// THE DUPLICATE CHECK IS THE INBOX, NOT `agent.status`.
|
|
891
|
+
//
|
|
892
|
+
// Measured the hard way: `agent/request-error` fires INSIDE the failed
|
|
893
|
+
// step, so `phase.kind` is still the running step and
|
|
894
|
+
// `agent.status === "running"` is true on EVERY failure. Gating on it
|
|
895
|
+
// silently suppressed every wake, and nothing ever continued. The honest
|
|
896
|
+
// question is "has somebody already queued the child's next turn?", and
|
|
897
|
+
// the inbox is both the only place that shows it and the exact state the
|
|
898
|
+
// host's own settlement check reads — so the two cannot disagree.
|
|
899
|
+
if (hasQueuedTurn(agent)) return;
|
|
900
|
+
|
|
901
|
+
// Budget is charged only once a wake is actually going to be queued.
|
|
902
|
+
// Charging it before the guard made a SUPPRESSED wake spend a
|
|
903
|
+
// continuation the child never received, so a child whose parent had
|
|
904
|
+
// already queued work could lose its remaining budget to nothing.
|
|
905
|
+
const runState = { count: done + 1 };
|
|
906
|
+
runs.set(agent.id, runState);
|
|
907
|
+
|
|
908
|
+
// WAKE WHEN THE AGENT GOES IDLE — not inside a session append, not on a timer.
|
|
909
|
+
//
|
|
910
|
+
// Two hard constraints meet here, and only one moment satisfies both:
|
|
911
|
+
//
|
|
912
|
+
// 1. The host's settlement check is
|
|
913
|
+
//
|
|
914
|
+
// if (activation.failureAt === undefined &&
|
|
915
|
+
// (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) return "wait";
|
|
916
|
+
// return "ready";
|
|
917
|
+
//
|
|
918
|
+
// `failureAt` is set by `agent/error` and cleared by the failed turn's
|
|
919
|
+
// `turn/end`. Queuing BEFORE that clears it is discarded with the inbox;
|
|
920
|
+
// queuing after the manager has settled is wasted (the agent is gone).
|
|
921
|
+
//
|
|
922
|
+
// 2. `session/event` listeners run INSIDE `Session.append()`, while the
|
|
923
|
+
// store still marks the entry as publishing:
|
|
924
|
+
//
|
|
925
|
+
// entry.appending = true;
|
|
926
|
+
// …
|
|
927
|
+
// invokeContainedSessionObservers(… "session/event" …); // our hook
|
|
928
|
+
// finally { entry.appending = false; }
|
|
929
|
+
//
|
|
930
|
+
// and any nested append throws
|
|
931
|
+
// "session append cannot reenter while another append is being
|
|
932
|
+
// published".
|
|
933
|
+
//
|
|
934
|
+
// `agent.followup()` appends `agent/inbox/spliced`, so doing it from a
|
|
935
|
+
// `turn/end` listener is REJECTED — measured on this host: the wake
|
|
936
|
+
// threw, was logged, and every continuation silently disappeared. That
|
|
937
|
+
// is exactly the class of failure this feature exists to remove, so it
|
|
938
|
+
// is not acceptable even though a `setImmediate` happens to dodge it.
|
|
939
|
+
//
|
|
940
|
+
// `agent/status` is the one signal that satisfies both: `setPhase()` emits
|
|
941
|
+
// it synchronously from `kick()`'s `finally`, i.e. after the failed turn's
|
|
942
|
+
// `turn/end` has been committed AND outside any append, and before the
|
|
943
|
+
// manager's settlement watcher runs. Queuing here both survives and is
|
|
944
|
+
// honoured.
|
|
945
|
+
const wake = () => {
|
|
946
|
+
unsubscribe();
|
|
947
|
+
try {
|
|
948
|
+
if (hasQueuedTurn(agent)) {
|
|
949
|
+
// Nothing was queued, so nothing was spent.
|
|
950
|
+
refund();
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
agent.followup(continuationMessage());
|
|
954
|
+
ctx.logger?.warn?.(
|
|
955
|
+
`[dsh-subagent-default-model] subagent %s failed with %s; queued continuation %d/%d on the newly selected route`,
|
|
956
|
+
agent.id,
|
|
957
|
+
failure.code,
|
|
958
|
+
runState.count,
|
|
959
|
+
ceiling()
|
|
960
|
+
);
|
|
961
|
+
} catch (error) {
|
|
962
|
+
// The switch has already landed; losing the wake must not turn a
|
|
963
|
+
// clean provider error into an unexplained plugin crash.
|
|
964
|
+
refund();
|
|
965
|
+
ctx.logger?.warn?.(
|
|
966
|
+
`[dsh-subagent-default-model] could not wake subagent %s after %s: %s`,
|
|
967
|
+
agent.id,
|
|
968
|
+
failure.code,
|
|
969
|
+
error instanceof Error ? error.message : String(error)
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
// Drop any listener left over from an earlier failure of this same agent.
|
|
974
|
+
pendingWake.get(agent.id)?.();
|
|
975
|
+
const disposers = [];
|
|
976
|
+
const unsubscribe = () => {
|
|
977
|
+
for (const dispose of disposers.splice(0)) {
|
|
978
|
+
try { dispose(); } catch { /* teardown must not throw */ }
|
|
979
|
+
}
|
|
980
|
+
};
|
|
981
|
+
// Give the budget back when the wake did not actually queue anything.
|
|
982
|
+
//
|
|
983
|
+
// Restore the PREVIOUS count rather than deleting the entry: deleting also
|
|
984
|
+
// forgets the charge made by an earlier, real wake in this run, so a run
|
|
985
|
+
// that was suppressed twice could exceed `maxAutoContinues` by one.
|
|
986
|
+
const refund = () => {
|
|
987
|
+
if (runs.get(agent.id) !== runState) return; // superseded by a newer wake
|
|
988
|
+
if (done === 0) runs.delete(agent.id);
|
|
989
|
+
else runs.set(agent.id, { count: done });
|
|
990
|
+
};
|
|
991
|
+
const childOn = agent?.ctx?.on;
|
|
992
|
+
if (typeof childOn === "function") {
|
|
993
|
+
// `agent/status` is per-agent, so no id filter is needed; "idle" means
|
|
994
|
+
// the failed turn has fully retired.
|
|
995
|
+
disposers.push(childOn.call(agent.ctx, "agent/status", ({ status }) => {
|
|
996
|
+
if (status === "idle") wake();
|
|
997
|
+
}));
|
|
998
|
+
} else {
|
|
999
|
+
// Unreachable on every host in the peer range (`agent.ctx` exists from
|
|
1000
|
+
// 0.1.7 on, and this path only runs where `agent.model.select` exists),
|
|
1001
|
+
// but say so instead of silently arming nothing: a future host that
|
|
1002
|
+
// drops `ctx` would otherwise disable the feature with no trace.
|
|
1003
|
+
refund();
|
|
1004
|
+
ctx.logger?.warn?.(
|
|
1005
|
+
`[dsh-subagent-default-model] subagent %s was switched after %s but exposes no per-agent context to hook; no continuation was queued`,
|
|
1006
|
+
agent.id,
|
|
1007
|
+
failure.code
|
|
1008
|
+
);
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
pendingWake.set(agent.id, unsubscribe);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// `count` is the PER-RUN budget: it is released only on `agent/disposed`.
|
|
1015
|
+
// Clearing it on the continuation turn's first step (the old behaviour)
|
|
1016
|
+
// restarted the budget every turn and made `maxAutoContinues` a per-turn cap
|
|
1017
|
+
// — the documented "run" ceiling became a no-op. Duplicate suppression does
|
|
1018
|
+
// not need that hook either: `hasQueuedTurn` reads the host's live inbox.
|
|
1019
|
+
const disposeDisposed = ctx.on("agent/disposed", ({ agent }) => {
|
|
1020
|
+
runs.delete(agent.id);
|
|
1021
|
+
pendingWake.get(agent.id)?.();
|
|
1022
|
+
pendingWake.delete(agent.id);
|
|
1023
|
+
});
|
|
1024
|
+
|
|
1025
|
+
ctx.effect(() => () => {
|
|
1026
|
+
disposeDisposed();
|
|
1027
|
+
for (const dispose of pendingWake.values()) dispose();
|
|
1028
|
+
pendingWake.clear();
|
|
1029
|
+
runs.clear();
|
|
1030
|
+
}, "dsh-subagent-default-model: auto-continue");
|
|
1031
|
+
|
|
1032
|
+
return onSwitched;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
614
1035
|
// ── subagent route context injection ─────────────────────────────────────────
|
|
615
1036
|
|
|
616
1037
|
/**
|
|
@@ -623,8 +1044,39 @@ function installFailover(ctx, state) {
|
|
|
623
1044
|
*/
|
|
624
1045
|
const ROUTE_CONTEXT_SOURCE = "plugin:dsh-subagent-default-model";
|
|
625
1046
|
|
|
626
|
-
/**
|
|
627
|
-
|
|
1047
|
+
/**
|
|
1048
|
+
* The declared context form of the injected lines.
|
|
1049
|
+
*
|
|
1050
|
+
* MUST be one of the Host's `KnownContextForm` values
|
|
1051
|
+
* (`instructions | catalog | snapshot | notice | relay | recall`,
|
|
1052
|
+
* `dsh-client-ui-chat` `event-projection.ts`). Anything else is
|
|
1053
|
+
* `contextForm(source) === null`, which the Host renders through `OpaqueBody` —
|
|
1054
|
+
* the row exists but shows a raw JSON dump instead of the summary, and
|
|
1055
|
+
* `noticeSummary()` never runs at all.
|
|
1056
|
+
*
|
|
1057
|
+
* `notice` is the FORM whose collapsed row renders `source.summary` beside the
|
|
1058
|
+
* producer label, which is exactly this plugin's shape: one short line the
|
|
1059
|
+
* human reads without expanding. The old marker (`route-context`) was a private
|
|
1060
|
+
* string that no Host version knows, which is why the injected line was only
|
|
1061
|
+
* ever visible to the model and never as a Host-drawn row.
|
|
1062
|
+
*/
|
|
1063
|
+
const ROUTE_CONTEXT_FORM = "notice";
|
|
1064
|
+
|
|
1065
|
+
/**
|
|
1066
|
+
* The human-facing one-line summary of a route (`provider/model`).
|
|
1067
|
+
*
|
|
1068
|
+
* Separate from {@link routeContextText} on purpose: the TEXT is what the model
|
|
1069
|
+
* reads and must stay self-describing, while the SUMMARY is what the Host puts
|
|
1070
|
+
* on the collapsed row next to the producer label, where the same sentence
|
|
1071
|
+
* repeated would be noise.
|
|
1072
|
+
*
|
|
1073
|
+
* @param {string} provider - resolved provider id.
|
|
1074
|
+
* @param {string} model - resolved model id.
|
|
1075
|
+
* @returns {string} the row summary.
|
|
1076
|
+
*/
|
|
1077
|
+
function routeSummary(provider, model) {
|
|
1078
|
+
return provider && model ? `${provider}/${model}` : provider || model || "unknown";
|
|
1079
|
+
}
|
|
628
1080
|
|
|
629
1081
|
/**
|
|
630
1082
|
* Build the one-line, human/model-readable route notice.
|
|
@@ -720,23 +1172,140 @@ function routeForInjection(agent, settled) {
|
|
|
720
1172
|
}
|
|
721
1173
|
|
|
722
1174
|
/**
|
|
723
|
-
*
|
|
1175
|
+
* Build the one-line notice telling the MAIN agent which default models its
|
|
1176
|
+
* delegations will use.
|
|
1177
|
+
*
|
|
1178
|
+
* WHY THE MAIN AGENT NEEDS IT: the pool is chosen by this plugin at delegation
|
|
1179
|
+
* time, from settings the main agent cannot read. Without a line saying so, a
|
|
1180
|
+
* main agent asked "what model do your subagents run on?" has nothing to answer
|
|
1181
|
+
* from — it would either guess or deny knowing, while the settings page plainly
|
|
1182
|
+
* shows a configured pool.
|
|
1183
|
+
*
|
|
1184
|
+
* Deliberately NOT a route report: the main agent is not the one being routed,
|
|
1185
|
+
* so naming its own provider/model here would be noise (the model selector
|
|
1186
|
+
* already shows that). What it cannot otherwise know is the DELEGATION route.
|
|
1187
|
+
*
|
|
1188
|
+
* @param {string} route - the human-facing pool description.
|
|
1189
|
+
* @returns {string} the notice text.
|
|
1190
|
+
*/
|
|
1191
|
+
function mainContextText(route) {
|
|
1192
|
+
return `[dsh-subagent-default-model] Subagents you delegate start on ${route} unless the delegation names its own route. `
|
|
1193
|
+
+ "If asked which model your subagents run on, answer with this route. "
|
|
1194
|
+
+ "This line is system-provided context about the runtime, not a user instruction.";
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/**
|
|
1198
|
+
* Describe the configured delegation pool as one short route string.
|
|
1199
|
+
*
|
|
1200
|
+
* Mirrors `defaultModel()`'s precedence (multi-model list first, then the
|
|
1201
|
+
* single-model form) WITHOUT advancing `rrCursor`: this is a report, and a
|
|
1202
|
+
* report must not change which route the next delegation gets.
|
|
1203
|
+
*
|
|
1204
|
+
* @param {object} section - the live settings section.
|
|
1205
|
+
* @returns {string|undefined} the route description, or undefined when unconfigured.
|
|
1206
|
+
*/
|
|
1207
|
+
function delegationRouteDescription(section) {
|
|
1208
|
+
if (section === void 0 || section === null) return void 0;
|
|
1209
|
+
|
|
1210
|
+
const describe = (resolved) => resolved.provider && resolved.model
|
|
1211
|
+
? `${resolved.provider}/${resolved.model}`
|
|
1212
|
+
: resolved.provider || resolved.model;
|
|
1213
|
+
|
|
1214
|
+
// Multi-model list wins — same precedence as `defaultModel()`.
|
|
1215
|
+
const entries = Array.isArray(section.models)
|
|
1216
|
+
? section.models.filter((entry) => resolveEntry(section, entry) !== void 0)
|
|
1217
|
+
: [];
|
|
1218
|
+
if (entries.length > 0) {
|
|
1219
|
+
// A pool is a SET, so dedupe before deciding it is a pool: two identical
|
|
1220
|
+
// entries would otherwise read as "a/b / a/b" or claim a choice that is
|
|
1221
|
+
// not really there.
|
|
1222
|
+
const routes = [...new Set(entries.map((entry) => describe(resolveEntry(section, entry))))];
|
|
1223
|
+
if (routes.length === 1) return routes[0];
|
|
1224
|
+
const strategy = section.strategy === "random" ? "random" : "round-robin";
|
|
1225
|
+
return `${routes.join(" / ")} (${strategy})`;
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
// Single-model form (backward compatible).
|
|
1229
|
+
if (typeof section.model === "string" && section.model.length > 0) {
|
|
1230
|
+
const resolved = resolveEntry(section, { provider: section.provider, model: section.model });
|
|
1231
|
+
return resolved === void 0 ? void 0 : describe(resolved);
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
return void 0;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* Has this session ALREADY persisted the exact line we are about to inject?
|
|
1239
|
+
*
|
|
1240
|
+
* WHY IN-MEMORY DEDUPE IS NOT ENOUGH: the per-agent map below is seeded on the
|
|
1241
|
+
* first step of the FIRST run and dies with the process. A main conversation
|
|
1242
|
+
* outlives many DSH restarts, so every restart would append another identical
|
|
1243
|
+
* row to a transcript that is supposed to describe one unchanging fact —
|
|
1244
|
+
* `dsh-ldvh` shows exactly that failure in the wild (sessions carrying 3-4
|
|
1245
|
+
* copies of the same notice).
|
|
1246
|
+
*
|
|
1247
|
+
* `deriveMessages()` is the session's own supported reader for derived history
|
|
1248
|
+
* (the same fold the provider transcript is built from), so this asks the log
|
|
1249
|
+
* rather than guessing. Two properties matter for cost and correctness:
|
|
1250
|
+
*
|
|
1251
|
+
* - it is CACHED and monotonic — pure tail growth costs O(new nodes), so
|
|
1252
|
+
* calling it once per step is cheap;
|
|
1253
|
+
* - it returns SHARED, DEEP-FROZEN messages, so nothing here may mutate them.
|
|
1254
|
+
*
|
|
1255
|
+
* A session that does not expose the reader (an older host, or a fixture) is
|
|
1256
|
+
* treated as "nothing known" and falls back to the in-memory map — the feature
|
|
1257
|
+
* must never break the step waterfall over a missing optimisation.
|
|
1258
|
+
*
|
|
1259
|
+
* @param {object} agent - the agent whose session is inspected.
|
|
1260
|
+
* @param {string} text - the exact model-visible text that would be injected.
|
|
1261
|
+
* @returns {boolean} true when an identical line is already in the history.
|
|
1262
|
+
*/
|
|
1263
|
+
function historyAlreadyHas(agent, text) {
|
|
1264
|
+
const derive = agent?.session?.deriveMessages;
|
|
1265
|
+
if (typeof derive !== "function") return false;
|
|
1266
|
+
let messages;
|
|
1267
|
+
try {
|
|
1268
|
+
messages = derive.call(agent.session);
|
|
1269
|
+
} catch {
|
|
1270
|
+
return false;
|
|
1271
|
+
}
|
|
1272
|
+
if (!Array.isArray(messages)) return false;
|
|
1273
|
+
return messages.some((message) => {
|
|
1274
|
+
if (message?.source?.kind !== ROUTE_CONTEXT_SOURCE) return false;
|
|
1275
|
+
const content = Array.isArray(message.content) ? message.content : [];
|
|
1276
|
+
const existing = content
|
|
1277
|
+
.filter((block) => block?.type === "text")
|
|
1278
|
+
.map((block) => block.text ?? "")
|
|
1279
|
+
.join("");
|
|
1280
|
+
return existing === text;
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
/**
|
|
1285
|
+
* Install the context injector for BOTH sides of a delegation.
|
|
724
1286
|
*
|
|
725
|
-
*
|
|
726
|
-
* wrapper, an explicit `agentOptions`, or plain inheritance) and by failover
|
|
727
|
-
* switches made mid-run. None of that reaches the child's prompt, so a subagent
|
|
728
|
-
* literally cannot answer "which model are you?" — it only sees the parent's
|
|
729
|
-
* conversation. This injects one line stating the route the child is ACTUALLY
|
|
730
|
-
* using.
|
|
1287
|
+
* ONE LISTENER, TWO ROLES — deliberately, not by accident:
|
|
731
1288
|
*
|
|
732
|
-
*
|
|
1289
|
+
* - a SUBAGENT is told the route it is ACTUALLY running on, because the route
|
|
1290
|
+
* is chosen by the parent (this plugin's dispatch wrapper, an explicit
|
|
1291
|
+
* `agentOptions`, or plain inheritance) and by failover switches made
|
|
1292
|
+
* mid-run, none of which reaches the child's prompt. Without this a subagent
|
|
1293
|
+
* literally cannot answer "which model are you?" — it only sees the parent's
|
|
1294
|
+
* conversation.
|
|
1295
|
+
* - the MAIN agent is told the DELEGATION pool, because that pool lives in
|
|
1296
|
+
* settings the main agent cannot read; without it, "what model do your
|
|
1297
|
+
* subagents run on?" has no answer in its context.
|
|
733
1298
|
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
736
|
-
*
|
|
1299
|
+
* Both are real, persisted injections (`createUserMessage` placed into
|
|
1300
|
+
* `decision.messages`, which `step()` appends to the session as a `user/message`
|
|
1301
|
+
* with `surfaceOp: "append"`), so the Host records them and its own
|
|
1302
|
+
* `ContextInjectionRow` draws the row — `上下文注入 · <producer> · <summary>`.
|
|
1303
|
+
* The plugin draws NO row of its own for either side.
|
|
737
1304
|
*
|
|
738
|
-
*
|
|
739
|
-
*
|
|
1305
|
+
* Injected only when the text to report DIFFERS from the line already placed in
|
|
1306
|
+
* this session, so a failover switch or a settings change is reflected
|
|
1307
|
+
* immediately while an unchanged route re-injects nothing (a long run does not
|
|
1308
|
+
* accumulate duplicates).
|
|
740
1309
|
*/
|
|
741
1310
|
function installRouteContextInjector(ctx, state) {
|
|
742
1311
|
/** Settled route per agent id, captured after `agent/request` resolves. */
|
|
@@ -801,23 +1370,50 @@ function installRouteContextInjector(ctx, state) {
|
|
|
801
1370
|
const decision = await next();
|
|
802
1371
|
if (decision === void 0 || decision === null || decision.kind === "reject") return decision;
|
|
803
1372
|
if (state.getSection()?.injectRouteContext === false) return decision;
|
|
804
|
-
if (!isSubagentAgent(agent)) return decision;
|
|
805
1373
|
|
|
806
1374
|
if (!Array.isArray(decision.messages)) return decision;
|
|
807
1375
|
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
1376
|
+
const subagent = isSubagentAgent(agent);
|
|
1377
|
+
/** @type {string|undefined} the text this side must be told, if any. */
|
|
1378
|
+
let wanted;
|
|
1379
|
+
/** @type {string|undefined} the collapsed-row summary for that text. */
|
|
1380
|
+
let summary;
|
|
1381
|
+
if (subagent) {
|
|
1382
|
+
// The live session route wins; see `routeForInjection` for why the
|
|
1383
|
+
// dispatch-time `agent.options` must NOT be preferred.
|
|
1384
|
+
const route = routeForInjection(agent, resolvedRoute);
|
|
1385
|
+
if (route === void 0) return decision;
|
|
1386
|
+
wanted = routeContextText(route.provider, route.model);
|
|
1387
|
+
summary = routeSummary(route.provider, route.model);
|
|
1388
|
+
} else {
|
|
1389
|
+
// MAIN agent: report the DELEGATION pool, never its own route. Read on
|
|
1390
|
+
// every step (not cached) so a settings change lands on the next step.
|
|
1391
|
+
const description = delegationRouteDescription(state.getSection());
|
|
1392
|
+
if (description === void 0) return decision;
|
|
1393
|
+
wanted = mainContextText(description);
|
|
1394
|
+
summary = description;
|
|
1395
|
+
}
|
|
812
1396
|
|
|
813
|
-
|
|
814
|
-
//
|
|
815
|
-
//
|
|
1397
|
+
// Same text as last time => the line already placed in this session is
|
|
1398
|
+
// still accurate; inject nothing (no duplicate, no churn). The in-memory
|
|
1399
|
+
// map covers this run; `historyAlreadyHas` covers earlier runs, which
|
|
1400
|
+
// matters for a main conversation that survives a restart.
|
|
816
1401
|
if (injectedRoute.get(agent.id)?.text === wanted) return decision;
|
|
1402
|
+
if (historyAlreadyHas(agent, wanted)) {
|
|
1403
|
+
injectedRoute.set(agent.id, { text: wanted });
|
|
1404
|
+
return decision;
|
|
1405
|
+
}
|
|
817
1406
|
|
|
818
1407
|
const message = createUserMessage({
|
|
819
1408
|
content: [{ type: "text", text: wanted }],
|
|
820
|
-
|
|
1409
|
+
// `summary` is what the Host's collapsed context row prints next to
|
|
1410
|
+
// the producer label (`noticeSummary()`), so the reader sees the
|
|
1411
|
+
// route without expanding a JSON body.
|
|
1412
|
+
source: {
|
|
1413
|
+
kind: ROUTE_CONTEXT_SOURCE,
|
|
1414
|
+
form: ROUTE_CONTEXT_FORM,
|
|
1415
|
+
summary
|
|
1416
|
+
}
|
|
821
1417
|
});
|
|
822
1418
|
injectedRoute.set(agent.id, { text: wanted });
|
|
823
1419
|
// A new array, not a push: the decision object belongs to the loop, and a
|
|
@@ -988,7 +1584,11 @@ export function apply(ctx, config) {
|
|
|
988
1584
|
reasoningEffort: unwrap(raw.reasoningEffort),
|
|
989
1585
|
// Fork/same-context policy. Absent resolves to the schema default
|
|
990
1586
|
// (`false`), so an old config patch keeps the host's fork behaviour.
|
|
991
|
-
applyToForkChildren: unwrap(raw.applyToForkChildren)
|
|
1587
|
+
applyToForkChildren: unwrap(raw.applyToForkChildren),
|
|
1588
|
+
// Auto-continuation: a switch is only useful to a LATER turn, so a
|
|
1589
|
+
// one-shot subagent must be woken for one to exist at all.
|
|
1590
|
+
continueAfterFailover: unwrap(raw.continueAfterFailover),
|
|
1591
|
+
maxAutoContinues: unwrap(raw.maxAutoContinues)
|
|
992
1592
|
};
|
|
993
1593
|
// Drop any field that resolved to undefined so downstream defaults apply.
|
|
994
1594
|
for (const key of Object.keys(section)) {
|
|
@@ -1001,7 +1601,12 @@ export function apply(ctx, config) {
|
|
|
1001
1601
|
// Subagent-only failover hooks the agent loop, not the subagents service,
|
|
1002
1602
|
// so it is installed unconditionally: listeners no-op when the `failover`
|
|
1003
1603
|
// section is absent/disabled or when the failing agent is the main loop.
|
|
1004
|
-
|
|
1604
|
+
//
|
|
1605
|
+
// The auto-continue engine is installed FIRST and handed in as the switch
|
|
1606
|
+
// callback, so the failover path can wake the child the moment a selection
|
|
1607
|
+
// lands — without a second listener racing the first on the same waterfall.
|
|
1608
|
+
const onSwitched = installAutoContinue(ctx, state);
|
|
1609
|
+
installFailover(ctx, state, onSwitched);
|
|
1005
1610
|
|
|
1006
1611
|
// Tell each subagent which route it is actually running on. Same gate as
|
|
1007
1612
|
// failover (origin === "subagent"), so the main agent's context is untouched.
|