dsh-subagent-default-model 2.2.2 → 2.2.6
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 +306 -0
- package/README.en.md +27 -8
- package/README.md +32 -8
- package/lib/client.js +19 -151
- package/lib/index.js +709 -51
- 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. */
|
|
@@ -173,8 +195,50 @@ const WRAPPED = Symbol.for("dsh-subagent-default-model.wrapped");
|
|
|
173
195
|
* Failure codes that count as "connection failed" (rate limit, quota, server /
|
|
174
196
|
* transport errors, empty responses). Switching on these is safe because a
|
|
175
197
|
* different model/provider may well succeed where the primary just failed.
|
|
198
|
+
*
|
|
199
|
+
* The list was written in 2026-08 against the failure codes the host raised
|
|
200
|
+
* THEN, and the host has added codes since. Two of them were missing until
|
|
201
|
+
* 2.2.6, and both are exactly the kind this feature exists for:
|
|
202
|
+
*
|
|
203
|
+
* - `STREAM_CLOSED` — the provider's stream ended before its terminal event
|
|
204
|
+
* (`dsh-llm-deepseek`: "DeepSeek Messages stream ended before message_stop";
|
|
205
|
+
* `dsh-llm-pi-ai`: "pi-ai event stream ended without done/error"). A dropped
|
|
206
|
+
* connection mid-stream is the textbook case for trying another provider,
|
|
207
|
+
* yet the plugin used to pass the error straight through and end the
|
|
208
|
+
* subagent.
|
|
209
|
+
* - `ACCOUNT_QUOTA` — `dsh-llm-deepseek-account` REWRITES a plain `QUOTA` into
|
|
210
|
+
* this code when the *account's* balance is exhausted. It is the same
|
|
211
|
+
* situation as `QUOTA` (which this list always had), just told apart from a
|
|
212
|
+
* per-key quota; skipping it meant the one code that says "this account is
|
|
213
|
+
* out of credit" was the one code that never triggered a switch.
|
|
214
|
+
*
|
|
215
|
+
* Deliberately still absent:
|
|
216
|
+
*
|
|
217
|
+
* - `CONTENT_REFUSED` — the provider's safety review rejected the content.
|
|
218
|
+
* Another provider would refuse the same request, so switching only burns
|
|
219
|
+
* the pool.
|
|
220
|
+
* - `CONTEXT_WINDOW_EXCEEDED`, `IMAGE_OFFLOAD_REQUIRED`, `INVALID_REQUEST` —
|
|
221
|
+
* the request itself is wrong; retrying it elsewhere fails identically.
|
|
222
|
+
* - `MALFORMED_RESPONSE` — kept out on purpose even though the host marks it
|
|
223
|
+
* `retryChoice`. A malformed stream is a real candidate for "this provider is
|
|
224
|
+
* broken", but it is also what a permanent adapter bug looks like, and the
|
|
225
|
+
* plugin has no way to tell them apart. Adding a code here is cheap; adding
|
|
226
|
+
* one that turns a deterministic parse failure into a pool-wide burn is not.
|
|
227
|
+
*
|
|
228
|
+
* `test/failover-codes.test.mjs` pins this list against the host's own failure
|
|
229
|
+
* code vocabulary, so a future host release that adds a code fails a test
|
|
230
|
+
* instead of silently going unswitched.
|
|
176
231
|
*/
|
|
177
|
-
const FAILOVER_TRIGGER_CODES = [
|
|
232
|
+
const FAILOVER_TRIGGER_CODES = [
|
|
233
|
+
"RATE_LIMIT",
|
|
234
|
+
"QUOTA",
|
|
235
|
+
"ACCOUNT_QUOTA",
|
|
236
|
+
"SERVER",
|
|
237
|
+
"TIMEOUT",
|
|
238
|
+
"TRANSPORT",
|
|
239
|
+
"EMPTY_RESPONSE",
|
|
240
|
+
"STREAM_CLOSED"
|
|
241
|
+
];
|
|
178
242
|
|
|
179
243
|
/**
|
|
180
244
|
* Auth failures, handled SEPARATELY from the connection codes above.
|
|
@@ -197,8 +261,19 @@ const FAILOVER_TRIGGER_CODES = ["RATE_LIMIT", "QUOTA", "SERVER", "TIMEOUT", "TRA
|
|
|
197
261
|
*/
|
|
198
262
|
const AUTH_FAILURE_CODES = ["AUTH", "INVALID_CREDENTIAL"];
|
|
199
263
|
|
|
200
|
-
/**
|
|
201
|
-
|
|
264
|
+
/**
|
|
265
|
+
* Every failure code that may trigger a switch.
|
|
266
|
+
*
|
|
267
|
+
* Exported as a read-only test seam, the same convention `volatileField` and
|
|
268
|
+
* `Config` follow: `test/failover-codes.test.mjs` compares it against the
|
|
269
|
+
* host's own failure-code vocabulary, and a hand-copied duplicate inside the
|
|
270
|
+
* test would defeat the point (it would keep passing after this list changed).
|
|
271
|
+
* The module loader only reads `apply` / `inject`.
|
|
272
|
+
*/
|
|
273
|
+
export const FAILOVER_ELIGIBLE_CODES = Object.freeze([...FAILOVER_TRIGGER_CODES, ...AUTH_FAILURE_CODES]);
|
|
274
|
+
|
|
275
|
+
/** The connection-class subset, exported alongside for the same reason. */
|
|
276
|
+
export const FAILOVER_TRIGGER_CODE_SET = Object.freeze([...FAILOVER_TRIGGER_CODES]);
|
|
202
277
|
|
|
203
278
|
/**
|
|
204
279
|
* Whether this host fixes the step's route and only sanctions changing it
|
|
@@ -351,10 +426,27 @@ function failoverView(state) {
|
|
|
351
426
|
const section = state.getSection?.();
|
|
352
427
|
if (section === void 0 || section === null) return void 0;
|
|
353
428
|
if (section.failoverEnabled === false) return void 0;
|
|
354
|
-
|
|
429
|
+
// Deduplicate by provider+model.
|
|
430
|
+
//
|
|
431
|
+
// A pool such as `["a", "a"]` — or two entries that happen to resolve to the
|
|
432
|
+
// same route — is not a two-route pool: `AgentModel.select()` compares the
|
|
433
|
+
// new selection with the recorded one and returns WITHOUT appending
|
|
434
|
+
// `model/selection` when they match. The "switch" would then be a silent
|
|
435
|
+
// no-op while this plugin still recorded a switch and woke the child, so the
|
|
436
|
+
// continuation re-requested the same dead route. Distinct
|
|
437
|
+
// `reasoningEffort` values still count as distinct selections (the host
|
|
438
|
+
// compares effort too), so the key includes it.
|
|
439
|
+
const resolved = Array.isArray(section.models)
|
|
355
440
|
? section.models.map((entry) => resolveEntry(section, entry)).filter((entry) => entry !== void 0)
|
|
356
441
|
: [];
|
|
357
|
-
|
|
442
|
+
const seen = new Set();
|
|
443
|
+
const entries = resolved.filter((entry) => {
|
|
444
|
+
const key = `${entry.provider}\u0000${entry.model}\u0000${entry.reasoningEffort ?? ""}`;
|
|
445
|
+
if (seen.has(key)) return false;
|
|
446
|
+
seen.add(key);
|
|
447
|
+
return true;
|
|
448
|
+
});
|
|
449
|
+
// A pool of <2 DISTINCT models has nothing to switch to; keep the parent route.
|
|
358
450
|
if (entries.length < 2) return void 0;
|
|
359
451
|
return { entries, strategy: section.strategy === "random" ? "random" : "round-robin" };
|
|
360
452
|
}
|
|
@@ -370,15 +462,52 @@ function isSubagentAgent(agent) {
|
|
|
370
462
|
* - round-robin: the next entry after the currently-served model, wrapping
|
|
371
463
|
* around the list (the "queue"), skipping entries this run already tried so a
|
|
372
464
|
* single bad candidate is not re-selected while an untried one remains.
|
|
373
|
-
* - random:
|
|
374
|
-
*
|
|
465
|
+
* - random: uniformly among the entries this run has NOT already tried.
|
|
466
|
+
* Deliberately NOT "any entry": `model.select()` is a silent no-op when the
|
|
467
|
+
* selection equals the current one, so picking a dead route again records
|
|
468
|
+
* nothing and the continuation re-requests it. `tried` therefore carries both
|
|
469
|
+
* the routes switched to and the route that failed (seeded by the caller).
|
|
470
|
+
*
|
|
471
|
+
* @param view - pool entries and strategy.
|
|
472
|
+
* @param agent - the failing subagent (its live route is the fallback anchor).
|
|
473
|
+
* @param current - this run's switch bookkeeping, if any.
|
|
474
|
+
* @param seededTried - `current.tried` already extended with the failed route.
|
|
475
|
+
* @returns the chosen pool index.
|
|
375
476
|
*/
|
|
376
|
-
function nextFailoverIndex(view, agent, current) {
|
|
477
|
+
function nextFailoverIndex(view, agent, current, seededTried = undefined) {
|
|
377
478
|
const { entries, strategy } = view;
|
|
479
|
+
const tried = seededTried ?? current?.tried;
|
|
378
480
|
if (strategy === "random") {
|
|
379
|
-
|
|
481
|
+
// A random pick must still be a USEFUL pick. The naive
|
|
482
|
+
// `Math.random() * entries.length` ignored both `tried` and the route
|
|
483
|
+
// that just failed, so it re-selected the dead entry with probability
|
|
484
|
+
// 1/entries.length — and worse, it could return the very entry the
|
|
485
|
+
// failure came from.
|
|
486
|
+
//
|
|
487
|
+
// Measured consequence: `model.select()` compared the "new" selection
|
|
488
|
+
// with the current one, found them equal, and returned WITHOUT appending
|
|
489
|
+
// `model/selection`. The switch silently did nothing, the continuation
|
|
490
|
+
// turn re-requested the same dead route, and the child failed again.
|
|
491
|
+
// The diagnostic read exactly that: `selecting minmax/… (before=minmax/…)`
|
|
492
|
+
// followed by an unchanged `current()` and an unchanged session seq.
|
|
493
|
+
//
|
|
494
|
+
// Only entries this run has not already tried are candidates. `tried` is
|
|
495
|
+
// seeded by `switchForNextStep` with BOTH the route that just failed and
|
|
496
|
+
// every route it has switched to, so "already failed here" is fully
|
|
497
|
+
// represented — that is what keeps a random pick useful instead of
|
|
498
|
+
// re-selecting a dead entry (which makes `model.select()` a silent no-op).
|
|
499
|
+
const blocked = new Set(tried ?? []);
|
|
500
|
+
const candidates = entries
|
|
501
|
+
.map((entry, index) => index)
|
|
502
|
+
.filter((index) => !blocked.has(index));
|
|
503
|
+
// DEFENSIVE, currently unreachable: the caller returns on
|
|
504
|
+
// `count >= entries.length - 1` before calling, and every switch adds a
|
|
505
|
+
// distinct index, so at least one candidate always remains. Kept anyway —
|
|
506
|
+
// if that guard ever changes, returning `undefined` here would silently
|
|
507
|
+
// select nothing, whereas an index still lets the caller decide.
|
|
508
|
+
if (candidates.length === 0) return Math.floor(Math.random() * entries.length);
|
|
509
|
+
return candidates[Math.floor(Math.random() * candidates.length)];
|
|
380
510
|
}
|
|
381
|
-
const tried = current?.tried;
|
|
382
511
|
if (current !== void 0) {
|
|
383
512
|
// Advance from the last pick, taking the first entry this run has not used.
|
|
384
513
|
for (let step = 1; step <= entries.length; step += 1) {
|
|
@@ -421,12 +550,13 @@ function nextFailoverIndex(view, agent, current) {
|
|
|
421
550
|
* (quota, auth), unlike the host's "after step preparation fixed" guard.
|
|
422
551
|
*
|
|
423
552
|
* The visible consequence, stated plainly: on 0.2.2 a permanently failing
|
|
424
|
-
* route ends the
|
|
425
|
-
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
553
|
+
* route still ends the CURRENT turn — the host fixes its route, so that turn
|
|
554
|
+
* cannot continue elsewhere. What the selection buys is everything after it,
|
|
555
|
+
* and `onSwitched` (see `installAutoContinue`) is what makes "after it" happen
|
|
556
|
+
* without waiting for the parent: it wakes the child for one more turn once the
|
|
557
|
+
* agent goes idle, so the new route is actually used.
|
|
428
558
|
*/
|
|
429
|
-
async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
559
|
+
async function switchForNextStep(ctx, state, pending, payload, next, onSwitched) {
|
|
430
560
|
const { agent, step, failure, signal } = payload;
|
|
431
561
|
const downstream = await next();
|
|
432
562
|
if (signal?.aborted) return downstream;
|
|
@@ -437,12 +567,59 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
437
567
|
const view = failoverView(state);
|
|
438
568
|
if (view === void 0) return downstream;
|
|
439
569
|
const current = pending.get(agent.id);
|
|
440
|
-
|
|
570
|
+
// Guard on turn AND step. A continuation turn restarts at step 1, so a
|
|
571
|
+
// step-only guard treats a fresh turn's first failure as "already switched
|
|
572
|
+
// for this step" and silently refuses to switch again — capping a one-shot
|
|
573
|
+
// child at ONE failover no matter how large the pool is (measured: a 3-entry
|
|
574
|
+
// pool only ever reached the second entry).
|
|
575
|
+
if (current !== void 0 && current.turn === payload.turn && current.step === step) return downstream;
|
|
441
576
|
if (current !== void 0 && current.count >= view.entries.length - 1) return downstream; // pool exhausted
|
|
442
|
-
|
|
577
|
+
// Seed `tried` with the route that FAILED, not just the ones already switched
|
|
578
|
+
// to.
|
|
579
|
+
//
|
|
580
|
+
// `tried` used to record only switch targets, so the route that failed FIRST
|
|
581
|
+
// never entered it. From the second switch onward that dead route was a legal
|
|
582
|
+
// candidate again — no longer `served`, and filtered by nothing — so `random`
|
|
583
|
+
// could send the child straight back to it. Measured with a fixture whose
|
|
584
|
+
// route follows `select` (as the host's own fold does) and a three-entry
|
|
585
|
+
// pool: 136 of 300 second switches returned to the original dead route, and
|
|
586
|
+
// the `entries.length - 1` cap then left the third entry never tried.
|
|
587
|
+
//
|
|
588
|
+
// This must run BEFORE `nextFailoverIndex`, which is the only consumer.
|
|
589
|
+
const tried = new Set(current?.tried ?? []);
|
|
590
|
+
if (current === undefined) {
|
|
591
|
+
// Identify the served entry by provider + model + effort.
|
|
592
|
+
//
|
|
593
|
+
// Locate the served entry by provider + model + effort.
|
|
594
|
+
//
|
|
595
|
+
// `session.requestContext()` carries no `reasoningEffort`, but the host's
|
|
596
|
+
// `AgentModel.select()` compares effort as part of the selection. A pool
|
|
597
|
+
// differing only by effort (`[a/high, a/low]`) would then resolve the
|
|
598
|
+
// served route to the WRONG entry and pick the very selection the child is
|
|
599
|
+
// already on — a silent no-op that still costs a wake.
|
|
600
|
+
//
|
|
601
|
+
// `requestHeader().config` is the route the LAST REQUEST actually used,
|
|
602
|
+
// including effort, and is exactly what `selectionOfHeader()` feeds the
|
|
603
|
+
// host's comparison. `model.current()` would also carry effort but reads
|
|
604
|
+
// `pending ?? lastUsed`, so another plugin's not-yet-used selection could
|
|
605
|
+
// name an entry this run never actually served.
|
|
606
|
+
const live = agent?.session?.requestHeader?.()?.config
|
|
607
|
+
?? agent?.model?.current?.()
|
|
608
|
+
?? agent?.session?.requestContext?.();
|
|
609
|
+
if (live !== void 0 && live !== null) {
|
|
610
|
+
const servedIndex = view.entries.findIndex((entry) =>
|
|
611
|
+
entry.provider === live.provider
|
|
612
|
+
&& entry.model === live.model
|
|
613
|
+
&& (entry.reasoningEffort ?? void 0) === (live.reasoningEffort ?? void 0)
|
|
614
|
+
);
|
|
615
|
+
if (servedIndex >= 0) tried.add(servedIndex);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
const index = nextFailoverIndex(view, agent, current, tried);
|
|
443
619
|
const target = view.entries[index];
|
|
444
620
|
if (target === void 0) return downstream;
|
|
445
|
-
|
|
621
|
+
// Record the route that FAILED too, not just the one being selected.
|
|
622
|
+
//
|
|
446
623
|
tried.add(index);
|
|
447
624
|
try {
|
|
448
625
|
agent.model.select({
|
|
@@ -470,7 +647,8 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
470
647
|
index,
|
|
471
648
|
tried,
|
|
472
649
|
count: (current?.count ?? 0) + 1,
|
|
473
|
-
step
|
|
650
|
+
step,
|
|
651
|
+
turn: payload.turn
|
|
474
652
|
});
|
|
475
653
|
ctx.logger.warn(
|
|
476
654
|
`[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 +668,23 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
490
668
|
target.model
|
|
491
669
|
);
|
|
492
670
|
}
|
|
671
|
+
// The selection only lands on the NEXT step. A one-shot subagent never
|
|
672
|
+
// starts one, so without this the switch would be recorded and wasted.
|
|
673
|
+
// Told from HERE rather than from a second listener on the same waterfall:
|
|
674
|
+
// that would depend on listener order and on re-reading `pending`, which is
|
|
675
|
+
// exactly the coupling this call avoids. It runs after the selection landed.
|
|
676
|
+
// A throw here must not abort the host's failure waterfall and replace a real
|
|
677
|
+
// provider error with a plugin crash; the switch has already landed.
|
|
678
|
+
try {
|
|
679
|
+
onSwitched?.(agent, failure);
|
|
680
|
+
} catch (error) {
|
|
681
|
+
ctx.logger?.warn?.(
|
|
682
|
+
`[dsh-subagent-default-model] could not schedule a continuation for subagent %s after %s: %s`,
|
|
683
|
+
agent?.id,
|
|
684
|
+
failure?.code,
|
|
685
|
+
error instanceof Error ? error.message : String(error)
|
|
686
|
+
);
|
|
687
|
+
}
|
|
493
688
|
return downstream;
|
|
494
689
|
}
|
|
495
690
|
|
|
@@ -501,7 +696,7 @@ async function switchForNextStep(ctx, state, pending, payload, next) {
|
|
|
501
696
|
* subagent run (`agent.id`) and cleaned on `agent/disposed`, so a persistently
|
|
502
697
|
* broken primary is not re-tried on every step of the same run.
|
|
503
698
|
*/
|
|
504
|
-
function installFailover(ctx, state) {
|
|
699
|
+
function installFailover(ctx, state, onSwitched) {
|
|
505
700
|
const pending = new Map();
|
|
506
701
|
|
|
507
702
|
// After a model failure on a subagent loop: advance the pool index and ask
|
|
@@ -517,16 +712,27 @@ function installFailover(ctx, state) {
|
|
|
517
712
|
// 0.2.2+ fixed the route for the whole step, so the route cannot be
|
|
518
713
|
// swapped on the retry this hook used to request. See
|
|
519
714
|
// `switchForNextStep` for what replaces it.
|
|
520
|
-
if (fixesStepRoute(agent)) return switchForNextStep(ctx, state, pending, payload, next);
|
|
715
|
+
if (fixesStepRoute(agent)) return switchForNextStep(ctx, state, pending, payload, next, onSwitched);
|
|
521
716
|
const current = pending.get(agent.id);
|
|
522
717
|
// The primary already failed (that triggered the first switch), so the
|
|
523
718
|
// remaining candidates are the other pool entries: at most
|
|
524
719
|
// `entries.length - 1` switches, then let the real error surface.
|
|
525
720
|
if (current !== void 0 && current.count >= view.entries.length - 1) return next(); // pool exhausted
|
|
526
|
-
|
|
721
|
+
// Same seeding as the 0.2.2+ path: the route that failed FIRST is in
|
|
722
|
+
// `tried` too, so it cannot be picked again on a later failure.
|
|
723
|
+
const tried = new Set(current?.tried ?? []);
|
|
724
|
+
if (current === undefined) {
|
|
725
|
+
const served = agent.session?.requestContext?.();
|
|
726
|
+
if (served !== void 0) {
|
|
727
|
+
const servedIndex = view.entries.findIndex((entry) =>
|
|
728
|
+
entry.provider === served.provider && entry.model === served.model
|
|
729
|
+
);
|
|
730
|
+
if (servedIndex >= 0) tried.add(servedIndex);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const index = nextFailoverIndex(view, agent, current, tried);
|
|
527
734
|
// Remember every pool entry this run has already been switched to, so a
|
|
528
735
|
// candidate that fails again is not selected a second time.
|
|
529
|
-
const tried = new Set(current?.tried ?? []);
|
|
530
736
|
tried.add(index);
|
|
531
737
|
pending.set(agent.id, {
|
|
532
738
|
index,
|
|
@@ -611,6 +817,274 @@ function installFailover(ctx, state) {
|
|
|
611
817
|
}, "dsh-subagent-default-model: failover listeners");
|
|
612
818
|
}
|
|
613
819
|
|
|
820
|
+
// ── automatic continuation after a failover switch ───────────────────────────
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* The producer-owned source kind for this plugin's automatic continuation turn.
|
|
824
|
+
*
|
|
825
|
+
* NOT `"user"`: that would claim the human typed it, and the transcript would
|
|
826
|
+
* render it as their own message — they never said it, and they could not tell
|
|
827
|
+
* it apart from their own input. `MessageSourceMap` is merge-extensible and each
|
|
828
|
+
* producer declares its own kind; `dsh-purge` / `dsh-connect-workbuddy` do the
|
|
829
|
+
* same. It also keeps the plugin's own messages distinguishable from the user's
|
|
830
|
+
* in the transcript, which is what the continuation cap has to key on.
|
|
831
|
+
*/
|
|
832
|
+
const CONTINUE_SOURCE = "plugin:dsh-subagent-default-model";
|
|
833
|
+
/**
|
|
834
|
+
* The instruction a continued subagent receives.
|
|
835
|
+
*
|
|
836
|
+
* Deliberately free of route details AND of any claim that the new provider is
|
|
837
|
+
* healthy: the selection can be a no-op (a duplicate pool entry) or the target
|
|
838
|
+
* can fail immediately, and a prompt that asserts "you are now on a healthy
|
|
839
|
+
* provider" would then be simply false to the model reading it.
|
|
840
|
+
*/
|
|
841
|
+
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.";
|
|
842
|
+
|
|
843
|
+
/** Message handed to a failed subagent so it takes one more turn on the healthy route. */
|
|
844
|
+
function continuationMessage() {
|
|
845
|
+
return createUserMessage({
|
|
846
|
+
content: [{ type: "text", text: CONTINUE_TEXT }],
|
|
847
|
+
source: { kind: CONTINUE_SOURCE, form: "notice", summary: "failover-continue" }
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Whether this agent may be woken automatically after a switch.
|
|
853
|
+
*
|
|
854
|
+
* ONLY `subagent` origin. The main agent's loop is never touched by this plugin,
|
|
855
|
+
* and its failures are the user's business, not a place to inject turns.
|
|
856
|
+
*
|
|
857
|
+
* `fork` children are EXCLUDED on purpose. The only durable proof that a child
|
|
858
|
+
* carries a fork-inherited prefix is `header.isSeeded` (the header has no
|
|
859
|
+
* `backend` field), and an extra turn on top of that inherited prefix is billed
|
|
860
|
+
* again in full on the new provider — the same cost this plugin already refuses
|
|
861
|
+
* to pay for `applyToForkChildren`. The pool route still governs its next
|
|
862
|
+
* genuine turn, which is the host's own intended behaviour.
|
|
863
|
+
*/
|
|
864
|
+
function continuationEligible(agent) {
|
|
865
|
+
// Kept even though the only caller already applies the same origin gate: this
|
|
866
|
+
// is the function's own precondition, and a future caller (or a refactor that
|
|
867
|
+
// moves the gate) must not be able to wake the main agent by accident.
|
|
868
|
+
if (!isSubagentAgent(agent)) return false;
|
|
869
|
+
if (agent?.session?.header?.isSeeded === true) return false;
|
|
870
|
+
return typeof agent?.followup === "function";
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* Whether somebody already queued this child's next turn.
|
|
875
|
+
*
|
|
876
|
+
* Both the duplicate guard and the deferred re-check ask exactly this, so it
|
|
877
|
+
* lives in one place. `nextTurn` is the host's own pending-turn list — reading
|
|
878
|
+
* it cannot disagree with what the manager will do next.
|
|
879
|
+
*/
|
|
880
|
+
function hasQueuedTurn(agent) {
|
|
881
|
+
const inbox = agent?.inbox;
|
|
882
|
+
return Array.isArray(inbox?.nextTurn) && inbox.nextTurn.length > 0;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/**
|
|
886
|
+
* Wake a switched subagent for exactly one more turn.
|
|
887
|
+
*
|
|
888
|
+
* THE POINT. `switchForNextStep` writes the healthy route through
|
|
889
|
+
* `agent.model.select()`, which the NEXT step reads. On a one-shot subagent
|
|
890
|
+
* nothing ever starts that next step, so the switch is recorded and wasted: the
|
|
891
|
+
* measured symptom was a child that ended `error` while a healthy pool entry sat
|
|
892
|
+
* selected and unused. This is the missing half of "switch to another provider
|
|
893
|
+
* and keep working".
|
|
894
|
+
*
|
|
895
|
+
* WHY A `followup` AND NOT A RETRY. The host's contract is explicit — every
|
|
896
|
+
* `followup` message "becomes the sole ordinary message of its own turn". That
|
|
897
|
+
* is the only sanctioned way to start a turn whose route is re-read, and it is
|
|
898
|
+
* also what the host's own settlement gives a continuable child ("will do no
|
|
899
|
+
* further work unless you send it more"). This plugin supplies the "more".
|
|
900
|
+
*
|
|
901
|
+
* BOUNDED BY CONSTRUCTION. It only fires when `switchForNextStep` recorded a
|
|
902
|
+
* real selection for this agent (so the pool had an untried entry and the host
|
|
903
|
+
* accepted the selection), and the switch bookkeeping caps that at
|
|
904
|
+
* `entries.length - 1` per run. `maxAutoContinues` is a second, independent
|
|
905
|
+
* ceiling for the case where settings are edited mid-run.
|
|
906
|
+
*/
|
|
907
|
+
function installAutoContinue(ctx, state) {
|
|
908
|
+
/** Continuations already spent by each agent run. */
|
|
909
|
+
const runs = new Map();
|
|
910
|
+
/** Teardown of the pending wake listener per agent. */
|
|
911
|
+
const pendingWake = new Map();
|
|
912
|
+
|
|
913
|
+
const section = () => state.getSection?.() ?? {};
|
|
914
|
+
const enabled = () => section().continueAfterFailover !== false;
|
|
915
|
+
const ceiling = () => {
|
|
916
|
+
const raw = section().maxAutoContinues;
|
|
917
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return 2;
|
|
918
|
+
return Math.max(0, Math.min(10, Math.trunc(raw)));
|
|
919
|
+
};
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* Called by the failover path AFTER `agent.model.select()` landed.
|
|
923
|
+
*
|
|
924
|
+
* That ordering is the whole point: a selection is only useful to a LATER
|
|
925
|
+
* step, and a one-shot subagent never starts one. Arriving through a direct
|
|
926
|
+
* call — not a second listener on the same waterfall — also means this never
|
|
927
|
+
* depends on listener registration order, and it cannot fire for a failure
|
|
928
|
+
* that was not actually switched (exhausted pool, refused selection).
|
|
929
|
+
*/
|
|
930
|
+
function onSwitched(agent, failure) {
|
|
931
|
+
if (!enabled() || !continuationEligible(agent)) return;
|
|
932
|
+
const run = runs.get(agent.id);
|
|
933
|
+
const done = run?.count ?? 0;
|
|
934
|
+
if (done >= ceiling()) {
|
|
935
|
+
ctx.logger?.warn?.(
|
|
936
|
+
`[dsh-subagent-default-model] subagent %s failed with %s and was switched, but it already used %d automatic continuation(s); ending the task instead`,
|
|
937
|
+
agent.id,
|
|
938
|
+
failure.code,
|
|
939
|
+
done
|
|
940
|
+
);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
// THE DUPLICATE CHECK IS THE INBOX, NOT `agent.status`.
|
|
944
|
+
//
|
|
945
|
+
// Measured the hard way: `agent/request-error` fires INSIDE the failed
|
|
946
|
+
// step, so `phase.kind` is still the running step and
|
|
947
|
+
// `agent.status === "running"` is true on EVERY failure. Gating on it
|
|
948
|
+
// silently suppressed every wake, and nothing ever continued. The honest
|
|
949
|
+
// question is "has somebody already queued the child's next turn?", and
|
|
950
|
+
// the inbox is both the only place that shows it and the exact state the
|
|
951
|
+
// host's own settlement check reads — so the two cannot disagree.
|
|
952
|
+
if (hasQueuedTurn(agent)) return;
|
|
953
|
+
|
|
954
|
+
// Budget is charged only once a wake is actually going to be queued.
|
|
955
|
+
// Charging it before the guard made a SUPPRESSED wake spend a
|
|
956
|
+
// continuation the child never received, so a child whose parent had
|
|
957
|
+
// already queued work could lose its remaining budget to nothing.
|
|
958
|
+
const runState = { count: done + 1 };
|
|
959
|
+
runs.set(agent.id, runState);
|
|
960
|
+
|
|
961
|
+
// WAKE WHEN THE AGENT GOES IDLE — not inside a session append, not on a timer.
|
|
962
|
+
//
|
|
963
|
+
// Two hard constraints meet here, and only one moment satisfies both:
|
|
964
|
+
//
|
|
965
|
+
// 1. The host's settlement check is
|
|
966
|
+
//
|
|
967
|
+
// if (activation.failureAt === undefined &&
|
|
968
|
+
// (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) return "wait";
|
|
969
|
+
// return "ready";
|
|
970
|
+
//
|
|
971
|
+
// `failureAt` is set by `agent/error` and cleared by the failed turn's
|
|
972
|
+
// `turn/end`. Queuing BEFORE that clears it is discarded with the inbox;
|
|
973
|
+
// queuing after the manager has settled is wasted (the agent is gone).
|
|
974
|
+
//
|
|
975
|
+
// 2. `session/event` listeners run INSIDE `Session.append()`, while the
|
|
976
|
+
// store still marks the entry as publishing:
|
|
977
|
+
//
|
|
978
|
+
// entry.appending = true;
|
|
979
|
+
// …
|
|
980
|
+
// invokeContainedSessionObservers(… "session/event" …); // our hook
|
|
981
|
+
// finally { entry.appending = false; }
|
|
982
|
+
//
|
|
983
|
+
// and any nested append throws
|
|
984
|
+
// "session append cannot reenter while another append is being
|
|
985
|
+
// published".
|
|
986
|
+
//
|
|
987
|
+
// `agent.followup()` appends `agent/inbox/spliced`, so doing it from a
|
|
988
|
+
// `turn/end` listener is REJECTED — measured on this host: the wake
|
|
989
|
+
// threw, was logged, and every continuation silently disappeared. That
|
|
990
|
+
// is exactly the class of failure this feature exists to remove, so it
|
|
991
|
+
// is not acceptable even though a `setImmediate` happens to dodge it.
|
|
992
|
+
//
|
|
993
|
+
// `agent/status` is the one signal that satisfies both: `setPhase()` emits
|
|
994
|
+
// it synchronously from `kick()`'s `finally`, i.e. after the failed turn's
|
|
995
|
+
// `turn/end` has been committed AND outside any append, and before the
|
|
996
|
+
// manager's settlement watcher runs. Queuing here both survives and is
|
|
997
|
+
// honoured.
|
|
998
|
+
const wake = () => {
|
|
999
|
+
unsubscribe();
|
|
1000
|
+
try {
|
|
1001
|
+
if (hasQueuedTurn(agent)) {
|
|
1002
|
+
// Nothing was queued, so nothing was spent.
|
|
1003
|
+
refund();
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
agent.followup(continuationMessage());
|
|
1007
|
+
ctx.logger?.warn?.(
|
|
1008
|
+
`[dsh-subagent-default-model] subagent %s failed with %s; queued continuation %d/%d on the newly selected route`,
|
|
1009
|
+
agent.id,
|
|
1010
|
+
failure.code,
|
|
1011
|
+
runState.count,
|
|
1012
|
+
ceiling()
|
|
1013
|
+
);
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
// The switch has already landed; losing the wake must not turn a
|
|
1016
|
+
// clean provider error into an unexplained plugin crash.
|
|
1017
|
+
refund();
|
|
1018
|
+
ctx.logger?.warn?.(
|
|
1019
|
+
`[dsh-subagent-default-model] could not wake subagent %s after %s: %s`,
|
|
1020
|
+
agent.id,
|
|
1021
|
+
failure.code,
|
|
1022
|
+
error instanceof Error ? error.message : String(error)
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
// Drop any listener left over from an earlier failure of this same agent.
|
|
1027
|
+
pendingWake.get(agent.id)?.();
|
|
1028
|
+
const disposers = [];
|
|
1029
|
+
const unsubscribe = () => {
|
|
1030
|
+
for (const dispose of disposers.splice(0)) {
|
|
1031
|
+
try { dispose(); } catch { /* teardown must not throw */ }
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
// Give the budget back when the wake did not actually queue anything.
|
|
1035
|
+
//
|
|
1036
|
+
// Restore the PREVIOUS count rather than deleting the entry: deleting also
|
|
1037
|
+
// forgets the charge made by an earlier, real wake in this run, so a run
|
|
1038
|
+
// that was suppressed twice could exceed `maxAutoContinues` by one.
|
|
1039
|
+
const refund = () => {
|
|
1040
|
+
if (runs.get(agent.id) !== runState) return; // superseded by a newer wake
|
|
1041
|
+
if (done === 0) runs.delete(agent.id);
|
|
1042
|
+
else runs.set(agent.id, { count: done });
|
|
1043
|
+
};
|
|
1044
|
+
const childOn = agent?.ctx?.on;
|
|
1045
|
+
if (typeof childOn === "function") {
|
|
1046
|
+
// `agent/status` is per-agent, so no id filter is needed; "idle" means
|
|
1047
|
+
// the failed turn has fully retired.
|
|
1048
|
+
disposers.push(childOn.call(agent.ctx, "agent/status", ({ status }) => {
|
|
1049
|
+
if (status === "idle") wake();
|
|
1050
|
+
}));
|
|
1051
|
+
} else {
|
|
1052
|
+
// Unreachable on every host in the peer range (`agent.ctx` exists from
|
|
1053
|
+
// 0.1.7 on, and this path only runs where `agent.model.select` exists),
|
|
1054
|
+
// but say so instead of silently arming nothing: a future host that
|
|
1055
|
+
// drops `ctx` would otherwise disable the feature with no trace.
|
|
1056
|
+
refund();
|
|
1057
|
+
ctx.logger?.warn?.(
|
|
1058
|
+
`[dsh-subagent-default-model] subagent %s was switched after %s but exposes no per-agent context to hook; no continuation was queued`,
|
|
1059
|
+
agent.id,
|
|
1060
|
+
failure.code
|
|
1061
|
+
);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
pendingWake.set(agent.id, unsubscribe);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// `count` is the PER-RUN budget: it is released only on `agent/disposed`.
|
|
1068
|
+
// Clearing it on the continuation turn's first step (the old behaviour)
|
|
1069
|
+
// restarted the budget every turn and made `maxAutoContinues` a per-turn cap
|
|
1070
|
+
// — the documented "run" ceiling became a no-op. Duplicate suppression does
|
|
1071
|
+
// not need that hook either: `hasQueuedTurn` reads the host's live inbox.
|
|
1072
|
+
const disposeDisposed = ctx.on("agent/disposed", ({ agent }) => {
|
|
1073
|
+
runs.delete(agent.id);
|
|
1074
|
+
pendingWake.get(agent.id)?.();
|
|
1075
|
+
pendingWake.delete(agent.id);
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
ctx.effect(() => () => {
|
|
1079
|
+
disposeDisposed();
|
|
1080
|
+
for (const dispose of pendingWake.values()) dispose();
|
|
1081
|
+
pendingWake.clear();
|
|
1082
|
+
runs.clear();
|
|
1083
|
+
}, "dsh-subagent-default-model: auto-continue");
|
|
1084
|
+
|
|
1085
|
+
return onSwitched;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
614
1088
|
// ── subagent route context injection ─────────────────────────────────────────
|
|
615
1089
|
|
|
616
1090
|
/**
|
|
@@ -623,8 +1097,39 @@ function installFailover(ctx, state) {
|
|
|
623
1097
|
*/
|
|
624
1098
|
const ROUTE_CONTEXT_SOURCE = "plugin:dsh-subagent-default-model";
|
|
625
1099
|
|
|
626
|
-
/**
|
|
627
|
-
|
|
1100
|
+
/**
|
|
1101
|
+
* The declared context form of the injected lines.
|
|
1102
|
+
*
|
|
1103
|
+
* MUST be one of the Host's `KnownContextForm` values
|
|
1104
|
+
* (`instructions | catalog | snapshot | notice | relay | recall`,
|
|
1105
|
+
* `dsh-client-ui-chat` `event-projection.ts`). Anything else is
|
|
1106
|
+
* `contextForm(source) === null`, which the Host renders through `OpaqueBody` —
|
|
1107
|
+
* the row exists but shows a raw JSON dump instead of the summary, and
|
|
1108
|
+
* `noticeSummary()` never runs at all.
|
|
1109
|
+
*
|
|
1110
|
+
* `notice` is the FORM whose collapsed row renders `source.summary` beside the
|
|
1111
|
+
* producer label, which is exactly this plugin's shape: one short line the
|
|
1112
|
+
* human reads without expanding. The old marker (`route-context`) was a private
|
|
1113
|
+
* string that no Host version knows, which is why the injected line was only
|
|
1114
|
+
* ever visible to the model and never as a Host-drawn row.
|
|
1115
|
+
*/
|
|
1116
|
+
const ROUTE_CONTEXT_FORM = "notice";
|
|
1117
|
+
|
|
1118
|
+
/**
|
|
1119
|
+
* The human-facing one-line summary of a route (`provider/model`).
|
|
1120
|
+
*
|
|
1121
|
+
* Separate from {@link routeContextText} on purpose: the TEXT is what the model
|
|
1122
|
+
* reads and must stay self-describing, while the SUMMARY is what the Host puts
|
|
1123
|
+
* on the collapsed row next to the producer label, where the same sentence
|
|
1124
|
+
* repeated would be noise.
|
|
1125
|
+
*
|
|
1126
|
+
* @param {string} provider - resolved provider id.
|
|
1127
|
+
* @param {string} model - resolved model id.
|
|
1128
|
+
* @returns {string} the row summary.
|
|
1129
|
+
*/
|
|
1130
|
+
function routeSummary(provider, model) {
|
|
1131
|
+
return provider && model ? `${provider}/${model}` : provider || model || "unknown";
|
|
1132
|
+
}
|
|
628
1133
|
|
|
629
1134
|
/**
|
|
630
1135
|
* Build the one-line, human/model-readable route notice.
|
|
@@ -720,23 +1225,140 @@ function routeForInjection(agent, settled) {
|
|
|
720
1225
|
}
|
|
721
1226
|
|
|
722
1227
|
/**
|
|
723
|
-
*
|
|
1228
|
+
* Build the one-line notice telling the MAIN agent which default models its
|
|
1229
|
+
* delegations will use.
|
|
724
1230
|
*
|
|
725
|
-
* WHY
|
|
726
|
-
*
|
|
727
|
-
*
|
|
728
|
-
*
|
|
729
|
-
*
|
|
730
|
-
* using.
|
|
1231
|
+
* WHY THE MAIN AGENT NEEDS IT: the pool is chosen by this plugin at delegation
|
|
1232
|
+
* time, from settings the main agent cannot read. Without a line saying so, a
|
|
1233
|
+
* main agent asked "what model do your subagents run on?" has nothing to answer
|
|
1234
|
+
* from — it would either guess or deny knowing, while the settings page plainly
|
|
1235
|
+
* shows a configured pool.
|
|
731
1236
|
*
|
|
732
|
-
*
|
|
1237
|
+
* Deliberately NOT a route report: the main agent is not the one being routed,
|
|
1238
|
+
* so naming its own provider/model here would be noise (the model selector
|
|
1239
|
+
* already shows that). What it cannot otherwise know is the DELEGATION route.
|
|
733
1240
|
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
736
|
-
|
|
1241
|
+
* @param {string} route - the human-facing pool description.
|
|
1242
|
+
* @returns {string} the notice text.
|
|
1243
|
+
*/
|
|
1244
|
+
function mainContextText(route) {
|
|
1245
|
+
return `[dsh-subagent-default-model] Subagents you delegate start on ${route} unless the delegation names its own route. `
|
|
1246
|
+
+ "If asked which model your subagents run on, answer with this route. "
|
|
1247
|
+
+ "This line is system-provided context about the runtime, not a user instruction.";
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* Describe the configured delegation pool as one short route string.
|
|
737
1252
|
*
|
|
738
|
-
*
|
|
739
|
-
*
|
|
1253
|
+
* Mirrors `defaultModel()`'s precedence (multi-model list first, then the
|
|
1254
|
+
* single-model form) WITHOUT advancing `rrCursor`: this is a report, and a
|
|
1255
|
+
* report must not change which route the next delegation gets.
|
|
1256
|
+
*
|
|
1257
|
+
* @param {object} section - the live settings section.
|
|
1258
|
+
* @returns {string|undefined} the route description, or undefined when unconfigured.
|
|
1259
|
+
*/
|
|
1260
|
+
function delegationRouteDescription(section) {
|
|
1261
|
+
if (section === void 0 || section === null) return void 0;
|
|
1262
|
+
|
|
1263
|
+
const describe = (resolved) => resolved.provider && resolved.model
|
|
1264
|
+
? `${resolved.provider}/${resolved.model}`
|
|
1265
|
+
: resolved.provider || resolved.model;
|
|
1266
|
+
|
|
1267
|
+
// Multi-model list wins — same precedence as `defaultModel()`.
|
|
1268
|
+
const entries = Array.isArray(section.models)
|
|
1269
|
+
? section.models.filter((entry) => resolveEntry(section, entry) !== void 0)
|
|
1270
|
+
: [];
|
|
1271
|
+
if (entries.length > 0) {
|
|
1272
|
+
// A pool is a SET, so dedupe before deciding it is a pool: two identical
|
|
1273
|
+
// entries would otherwise read as "a/b / a/b" or claim a choice that is
|
|
1274
|
+
// not really there.
|
|
1275
|
+
const routes = [...new Set(entries.map((entry) => describe(resolveEntry(section, entry))))];
|
|
1276
|
+
if (routes.length === 1) return routes[0];
|
|
1277
|
+
const strategy = section.strategy === "random" ? "random" : "round-robin";
|
|
1278
|
+
return `${routes.join(" / ")} (${strategy})`;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// Single-model form (backward compatible).
|
|
1282
|
+
if (typeof section.model === "string" && section.model.length > 0) {
|
|
1283
|
+
const resolved = resolveEntry(section, { provider: section.provider, model: section.model });
|
|
1284
|
+
return resolved === void 0 ? void 0 : describe(resolved);
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
return void 0;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
/**
|
|
1291
|
+
* Has this session ALREADY persisted the exact line we are about to inject?
|
|
1292
|
+
*
|
|
1293
|
+
* WHY IN-MEMORY DEDUPE IS NOT ENOUGH: the per-agent map below is seeded on the
|
|
1294
|
+
* first step of the FIRST run and dies with the process. A main conversation
|
|
1295
|
+
* outlives many DSH restarts, so every restart would append another identical
|
|
1296
|
+
* row to a transcript that is supposed to describe one unchanging fact —
|
|
1297
|
+
* `dsh-ldvh` shows exactly that failure in the wild (sessions carrying 3-4
|
|
1298
|
+
* copies of the same notice).
|
|
1299
|
+
*
|
|
1300
|
+
* `deriveMessages()` is the session's own supported reader for derived history
|
|
1301
|
+
* (the same fold the provider transcript is built from), so this asks the log
|
|
1302
|
+
* rather than guessing. Two properties matter for cost and correctness:
|
|
1303
|
+
*
|
|
1304
|
+
* - it is CACHED and monotonic — pure tail growth costs O(new nodes), so
|
|
1305
|
+
* calling it once per step is cheap;
|
|
1306
|
+
* - it returns SHARED, DEEP-FROZEN messages, so nothing here may mutate them.
|
|
1307
|
+
*
|
|
1308
|
+
* A session that does not expose the reader (an older host, or a fixture) is
|
|
1309
|
+
* treated as "nothing known" and falls back to the in-memory map — the feature
|
|
1310
|
+
* must never break the step waterfall over a missing optimisation.
|
|
1311
|
+
*
|
|
1312
|
+
* @param {object} agent - the agent whose session is inspected.
|
|
1313
|
+
* @param {string} text - the exact model-visible text that would be injected.
|
|
1314
|
+
* @returns {boolean} true when an identical line is already in the history.
|
|
1315
|
+
*/
|
|
1316
|
+
function historyAlreadyHas(agent, text) {
|
|
1317
|
+
const derive = agent?.session?.deriveMessages;
|
|
1318
|
+
if (typeof derive !== "function") return false;
|
|
1319
|
+
let messages;
|
|
1320
|
+
try {
|
|
1321
|
+
messages = derive.call(agent.session);
|
|
1322
|
+
} catch {
|
|
1323
|
+
return false;
|
|
1324
|
+
}
|
|
1325
|
+
if (!Array.isArray(messages)) return false;
|
|
1326
|
+
return messages.some((message) => {
|
|
1327
|
+
if (message?.source?.kind !== ROUTE_CONTEXT_SOURCE) return false;
|
|
1328
|
+
const content = Array.isArray(message.content) ? message.content : [];
|
|
1329
|
+
const existing = content
|
|
1330
|
+
.filter((block) => block?.type === "text")
|
|
1331
|
+
.map((block) => block.text ?? "")
|
|
1332
|
+
.join("");
|
|
1333
|
+
return existing === text;
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
/**
|
|
1338
|
+
* Install the context injector for BOTH sides of a delegation.
|
|
1339
|
+
*
|
|
1340
|
+
* ONE LISTENER, TWO ROLES — deliberately, not by accident:
|
|
1341
|
+
*
|
|
1342
|
+
* - a SUBAGENT is told the route it is ACTUALLY running on, because the route
|
|
1343
|
+
* is chosen by the parent (this plugin's dispatch wrapper, an explicit
|
|
1344
|
+
* `agentOptions`, or plain inheritance) and by failover switches made
|
|
1345
|
+
* mid-run, none of which reaches the child's prompt. Without this a subagent
|
|
1346
|
+
* literally cannot answer "which model are you?" — it only sees the parent's
|
|
1347
|
+
* conversation.
|
|
1348
|
+
* - the MAIN agent is told the DELEGATION pool, because that pool lives in
|
|
1349
|
+
* settings the main agent cannot read; without it, "what model do your
|
|
1350
|
+
* subagents run on?" has no answer in its context.
|
|
1351
|
+
*
|
|
1352
|
+
* Both are real, persisted injections (`createUserMessage` placed into
|
|
1353
|
+
* `decision.messages`, which `step()` appends to the session as a `user/message`
|
|
1354
|
+
* with `surfaceOp: "append"`), so the Host records them and its own
|
|
1355
|
+
* `ContextInjectionRow` draws the row — `上下文注入 · <producer> · <summary>`.
|
|
1356
|
+
* The plugin draws NO row of its own for either side.
|
|
1357
|
+
*
|
|
1358
|
+
* Injected only when the text to report DIFFERS from the line already placed in
|
|
1359
|
+
* this session, so a failover switch or a settings change is reflected
|
|
1360
|
+
* immediately while an unchanged route re-injects nothing (a long run does not
|
|
1361
|
+
* accumulate duplicates).
|
|
740
1362
|
*/
|
|
741
1363
|
function installRouteContextInjector(ctx, state) {
|
|
742
1364
|
/** Settled route per agent id, captured after `agent/request` resolves. */
|
|
@@ -801,23 +1423,50 @@ function installRouteContextInjector(ctx, state) {
|
|
|
801
1423
|
const decision = await next();
|
|
802
1424
|
if (decision === void 0 || decision === null || decision.kind === "reject") return decision;
|
|
803
1425
|
if (state.getSection()?.injectRouteContext === false) return decision;
|
|
804
|
-
if (!isSubagentAgent(agent)) return decision;
|
|
805
1426
|
|
|
806
1427
|
if (!Array.isArray(decision.messages)) return decision;
|
|
807
1428
|
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
1429
|
+
const subagent = isSubagentAgent(agent);
|
|
1430
|
+
/** @type {string|undefined} the text this side must be told, if any. */
|
|
1431
|
+
let wanted;
|
|
1432
|
+
/** @type {string|undefined} the collapsed-row summary for that text. */
|
|
1433
|
+
let summary;
|
|
1434
|
+
if (subagent) {
|
|
1435
|
+
// The live session route wins; see `routeForInjection` for why the
|
|
1436
|
+
// dispatch-time `agent.options` must NOT be preferred.
|
|
1437
|
+
const route = routeForInjection(agent, resolvedRoute);
|
|
1438
|
+
if (route === void 0) return decision;
|
|
1439
|
+
wanted = routeContextText(route.provider, route.model);
|
|
1440
|
+
summary = routeSummary(route.provider, route.model);
|
|
1441
|
+
} else {
|
|
1442
|
+
// MAIN agent: report the DELEGATION pool, never its own route. Read on
|
|
1443
|
+
// every step (not cached) so a settings change lands on the next step.
|
|
1444
|
+
const description = delegationRouteDescription(state.getSection());
|
|
1445
|
+
if (description === void 0) return decision;
|
|
1446
|
+
wanted = mainContextText(description);
|
|
1447
|
+
summary = description;
|
|
1448
|
+
}
|
|
812
1449
|
|
|
813
|
-
|
|
814
|
-
//
|
|
815
|
-
//
|
|
1450
|
+
// Same text as last time => the line already placed in this session is
|
|
1451
|
+
// still accurate; inject nothing (no duplicate, no churn). The in-memory
|
|
1452
|
+
// map covers this run; `historyAlreadyHas` covers earlier runs, which
|
|
1453
|
+
// matters for a main conversation that survives a restart.
|
|
816
1454
|
if (injectedRoute.get(agent.id)?.text === wanted) return decision;
|
|
1455
|
+
if (historyAlreadyHas(agent, wanted)) {
|
|
1456
|
+
injectedRoute.set(agent.id, { text: wanted });
|
|
1457
|
+
return decision;
|
|
1458
|
+
}
|
|
817
1459
|
|
|
818
1460
|
const message = createUserMessage({
|
|
819
1461
|
content: [{ type: "text", text: wanted }],
|
|
820
|
-
|
|
1462
|
+
// `summary` is what the Host's collapsed context row prints next to
|
|
1463
|
+
// the producer label (`noticeSummary()`), so the reader sees the
|
|
1464
|
+
// route without expanding a JSON body.
|
|
1465
|
+
source: {
|
|
1466
|
+
kind: ROUTE_CONTEXT_SOURCE,
|
|
1467
|
+
form: ROUTE_CONTEXT_FORM,
|
|
1468
|
+
summary
|
|
1469
|
+
}
|
|
821
1470
|
});
|
|
822
1471
|
injectedRoute.set(agent.id, { text: wanted });
|
|
823
1472
|
// A new array, not a push: the decision object belongs to the loop, and a
|
|
@@ -988,7 +1637,11 @@ export function apply(ctx, config) {
|
|
|
988
1637
|
reasoningEffort: unwrap(raw.reasoningEffort),
|
|
989
1638
|
// Fork/same-context policy. Absent resolves to the schema default
|
|
990
1639
|
// (`false`), so an old config patch keeps the host's fork behaviour.
|
|
991
|
-
applyToForkChildren: unwrap(raw.applyToForkChildren)
|
|
1640
|
+
applyToForkChildren: unwrap(raw.applyToForkChildren),
|
|
1641
|
+
// Auto-continuation: a switch is only useful to a LATER turn, so a
|
|
1642
|
+
// one-shot subagent must be woken for one to exist at all.
|
|
1643
|
+
continueAfterFailover: unwrap(raw.continueAfterFailover),
|
|
1644
|
+
maxAutoContinues: unwrap(raw.maxAutoContinues)
|
|
992
1645
|
};
|
|
993
1646
|
// Drop any field that resolved to undefined so downstream defaults apply.
|
|
994
1647
|
for (const key of Object.keys(section)) {
|
|
@@ -1001,7 +1654,12 @@ export function apply(ctx, config) {
|
|
|
1001
1654
|
// Subagent-only failover hooks the agent loop, not the subagents service,
|
|
1002
1655
|
// so it is installed unconditionally: listeners no-op when the `failover`
|
|
1003
1656
|
// section is absent/disabled or when the failing agent is the main loop.
|
|
1004
|
-
|
|
1657
|
+
//
|
|
1658
|
+
// The auto-continue engine is installed FIRST and handed in as the switch
|
|
1659
|
+
// callback, so the failover path can wake the child the moment a selection
|
|
1660
|
+
// lands — without a second listener racing the first on the same waterfall.
|
|
1661
|
+
const onSwitched = installAutoContinue(ctx, state);
|
|
1662
|
+
installFailover(ctx, state, onSwitched);
|
|
1005
1663
|
|
|
1006
1664
|
// Tell each subagent which route it is actually running on. Same gate as
|
|
1007
1665
|
// failover (origin === "subagent"), so the main agent's context is untouched.
|