opencode-model-router 2.2.0 → 2.4.0
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 +214 -0
- package/README.md +90 -12
- package/package.json +4 -1
- package/src/commands/output.ts +24 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +1435 -44
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +496 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +1193 -56
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1611 -19
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +180 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +533 -9
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +898 -0
- package/src/routing/advisor/index.ts +614 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +594 -0
- package/src/routing/classify/route-line.ts +362 -0
- package/src/routing/classify/rules.ts +667 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1310 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +134 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +760 -0
- package/src/routing/engine/ladders.ts +802 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +150 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +368 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +147 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +215 -0
- package/src/routing/outcomes/ingest.ts +960 -0
- package/src/routing/outcomes/persist.ts +1080 -0
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +873 -0
- package/src/routing/outcomes/store.ts +673 -0
- package/src/routing/outcomes/types.ts +1093 -0
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +2088 -0
- package/src/routing/wire/hint.ts +222 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +348 -0
- package/src/v2.ts +40 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
package/src/router/sessions.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
1
2
|
import type { RouterConfig } from "./config";
|
|
2
3
|
import { fingerprintToolCall } from "../guard/fingerprint";
|
|
3
4
|
import { DEFAULT_IDLE_TTL_MS } from "./idle-sweep";
|
|
5
|
+
import type { DecisionFacts, LadderStepKind } from "../routing/outcomes/types";
|
|
6
|
+
import type { ChangedFile } from "../verify/dispatch";
|
|
7
|
+
import type { ReferenceState } from "../verify/types";
|
|
4
8
|
|
|
5
9
|
// ---------------------------------------------------------------------------
|
|
6
10
|
// Types
|
|
@@ -160,7 +164,7 @@ export const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
|
|
|
160
164
|
// ---------------------------------------------------------------------------
|
|
161
165
|
|
|
162
166
|
/** Normalise a taskPattern keyword to a lowercase stem for substring matching. */
|
|
163
|
-
function normTaskKw(kw: string): string {
|
|
167
|
+
export function normTaskKw(kw: string): string {
|
|
164
168
|
return kw.toLowerCase().split("(")[0]!.split("/")[0]!.trim();
|
|
165
169
|
}
|
|
166
170
|
|
|
@@ -176,7 +180,7 @@ function normTaskKw(kw: string): string {
|
|
|
176
180
|
* common phrasing; `step N` is also matched inline, since it frequently appears
|
|
177
181
|
* mid-line rather than at the start of one.
|
|
178
182
|
*/
|
|
179
|
-
const MULTI_STEP_RE =
|
|
183
|
+
export const MULTI_STEP_RE =
|
|
180
184
|
/(?:^\s*(?:[-*+]|\d+[.):])\s)|\bstep\s*\d+\s*[.):]|\bthen\b|\bone at a time\b|\bone-at-a-time\b|\bsequentially\b|\bin order\b|\bin this exact order\b|\beach\b|\bafter that\b|\bfor every\b|;|&&/im;
|
|
181
185
|
|
|
182
186
|
/**
|
|
@@ -185,7 +189,7 @@ const MULTI_STEP_RE =
|
|
|
185
189
|
* Two items are deliberately NOT enough: "read a.json, b.json" is already caught
|
|
186
190
|
* by the path count, and a two-item phrase is common in single-shot requests.
|
|
187
191
|
*/
|
|
188
|
-
const ENUMERATION_RE =
|
|
192
|
+
export const ENUMERATION_RE =
|
|
189
193
|
/[\w./-]+\s*,\s*[\w./-]+\s*(?:,\s*[\w./-]+|\b(?:and|or)\s+[\w./-]+)/i;
|
|
190
194
|
|
|
191
195
|
/**
|
|
@@ -207,7 +211,7 @@ const ENUMERATION_RE =
|
|
|
207
211
|
* words ending in `s` — "what does all this mean in tiers.json" must stay a
|
|
208
212
|
* single-file lookup.
|
|
209
213
|
*/
|
|
210
|
-
const DISTRIBUTIVE_RE =
|
|
214
|
+
export const DISTRIBUTIVE_RE =
|
|
211
215
|
/\b(?:every|all)\s+(?:(?:the|these|those|other|remaining)\s+)?(?:(?!of\b)[a-z][a-z-]*\s+){0,2}(?:files?|modules?|tests?|configs?|dirs?|directory|directories|components?|routes?|stores?|handlers?|guards?|helpers?|scripts?|packages?|classes?|functions?|endpoints?|entries?|(?!(?:this|its|his|hers|thus|was|has|does|less|plus|yes|gas|bus|css|js|status|focus|process|access|address|business|class|success)\b)[a-z][a-z-]{2,}s)\b(?!\.[a-z])/i;
|
|
212
216
|
|
|
213
217
|
/**
|
|
@@ -215,7 +219,7 @@ const DISTRIBUTIVE_RE =
|
|
|
215
219
|
* written as prose. Matched per line so the `Working directory:` / `Platform:` /
|
|
216
220
|
* `Shell:` footer described below cannot inflate the count.
|
|
217
221
|
*/
|
|
218
|
-
const IMPERATIVE_LINE_RE =
|
|
222
|
+
export const IMPERATIVE_LINE_RE =
|
|
219
223
|
/^\s*(?:read|search|grep|list|find|check|report|summari[sz]e|open|inspect|show|tell|explain|analy[sz]e|compare|verify|count|locate|trace)\b/i;
|
|
220
224
|
|
|
221
225
|
/**
|
|
@@ -228,7 +232,7 @@ const IMPERATIVE_LINE_RE =
|
|
|
228
232
|
* extension is what keeps a POSIX cwd (`/home/u/proj`) from being miscounted as
|
|
229
233
|
* a target file.
|
|
230
234
|
*/
|
|
231
|
-
const PATH_TOKEN_RE =
|
|
235
|
+
export const PATH_TOKEN_RE =
|
|
232
236
|
/[\w./\\-]*[\w-]\.(?:ts|tsx|js|jsx|mjs|cjs|json|jsonc|md|ya?ml|toml|txt|css|scss|html|py|rs|go|rb|java|sh|ps1|sql|lock)\b/gi;
|
|
233
237
|
|
|
234
238
|
/**
|
|
@@ -238,7 +242,7 @@ const PATH_TOKEN_RE =
|
|
|
238
242
|
* field in package.json" names one. The lookahead prevents double-counting
|
|
239
243
|
* `README.md`, which `PATH_TOKEN_RE` already matches.
|
|
240
244
|
*/
|
|
241
|
-
const BARE_FILENAME_RE =
|
|
245
|
+
export const BARE_FILENAME_RE =
|
|
242
246
|
/\b(?:Makefile|Dockerfile|LICENSE|README|CHANGELOG|Gemfile|Rakefile|Procfile|NOTICE|CODEOWNERS)\b(?!\.\w)/g;
|
|
243
247
|
|
|
244
248
|
/**
|
|
@@ -249,7 +253,7 @@ const BARE_FILENAME_RE =
|
|
|
249
253
|
* requiring exactly one path would reclassify them. Breadth that names no file
|
|
250
254
|
* is caught by `ENUMERATION_RE` and `IMPERATIVE_LINE_RE` instead.
|
|
251
255
|
*/
|
|
252
|
-
const MAX_TRIVIAL_PATHS = 1;
|
|
256
|
+
export const MAX_TRIVIAL_PATHS = 1;
|
|
253
257
|
|
|
254
258
|
/**
|
|
255
259
|
* Backstop for multi-step dispatches that use none of the marker words above:
|
|
@@ -258,7 +262,7 @@ const MAX_TRIVIAL_PATHS = 1;
|
|
|
258
262
|
* recon brief, and measured AFTER the cwd/platform footer so that footer can
|
|
259
263
|
* never by itself push a dispatch over the line.
|
|
260
264
|
*/
|
|
261
|
-
const MAX_TRIVIAL_CHARS = 240;
|
|
265
|
+
export const MAX_TRIVIAL_CHARS = 240;
|
|
262
266
|
|
|
263
267
|
/**
|
|
264
268
|
* Classify a dispatch as "trivial" AT DISPATCH TIME (m2): conservative,
|
|
@@ -374,6 +378,25 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
374
378
|
return subagentCapState.get(sessionID)?.tierName ?? null;
|
|
375
379
|
},
|
|
376
380
|
|
|
381
|
+
/**
|
|
382
|
+
* The current dispatch round's honoured cap: "none" only for CAP:none with a
|
|
383
|
+
* reason: line, else a number; null for an untracked session. A resume
|
|
384
|
+
* re-registers and replaces it (QA-P15-1-3: the guard's reader signal).
|
|
385
|
+
*/
|
|
386
|
+
getCap(sessionID: string): Cap | null {
|
|
387
|
+
return subagentCapState.get(sessionID)?.cap ?? null;
|
|
388
|
+
},
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The current round's read-only counter reached its cap (calls >= a numeric
|
|
392
|
+
* cap). Captured when a task returns, it validates a `NEED MORE: budget`
|
|
393
|
+
* claim (QA-P15-2-2); false for CAP:none and untracked sessions.
|
|
394
|
+
*/
|
|
395
|
+
readCapReached(sessionID: string): boolean {
|
|
396
|
+
const state = subagentCapState.get(sessionID);
|
|
397
|
+
return state !== undefined && state.cap !== "none" && state.calls >= state.cap;
|
|
398
|
+
},
|
|
399
|
+
|
|
377
400
|
/** Returns true when the session was classified as trivial at dispatch time. */
|
|
378
401
|
isTrivial(sessionID: string): boolean {
|
|
379
402
|
return subagentCapState.get(sessionID)?.trivial === true;
|
|
@@ -419,6 +442,21 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
419
442
|
touch(sessionID);
|
|
420
443
|
},
|
|
421
444
|
|
|
445
|
+
/**
|
|
446
|
+
* #84 QA-P21-3-1: a routed resume of a role child (the host gives no chat.message for it): start a new dispatch round of its
|
|
447
|
+
* read-only counter, as a same-tier re-registration does — calls back to 0, `seen` and totalCalls kept, the previous cap kept
|
|
448
|
+
* unless the resume names one. False (nothing done) when the child has no read-only cap state.
|
|
449
|
+
*/
|
|
450
|
+
resumeRoleSession(sessionID: string, cap: Cap | null): boolean {
|
|
451
|
+
const existing = subagentCapState.get(sessionID);
|
|
452
|
+
if (existing === undefined) return false;
|
|
453
|
+
if (cap !== null) existing.cap = cap;
|
|
454
|
+
existing.calls = 0;
|
|
455
|
+
existing.dispatches += 1;
|
|
456
|
+
touch(sessionID);
|
|
457
|
+
return true;
|
|
458
|
+
},
|
|
459
|
+
|
|
422
460
|
/** Remove a session from tracking (used to clean up delegate producer sessions). */
|
|
423
461
|
unregister(sessionID: string): void {
|
|
424
462
|
evict(sessionID);
|
|
@@ -563,3 +601,489 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
563
601
|
},
|
|
564
602
|
};
|
|
565
603
|
}
|
|
604
|
+
|
|
605
|
+
// ---------------------------------------------------------------------------
|
|
606
|
+
// Dispatch-facts registry (M6, plan 2.1.1, amendment A3)
|
|
607
|
+
//
|
|
608
|
+
// Remembers, per child session, what the router knew when it dispatched it: the typed
|
|
609
|
+
// facts, the agent and model that were actually dispatched, and the attempt id that
|
|
610
|
+
// outcome signals are scored under. Telemetry ingestion (src/routing/outcomes/ingest.ts)
|
|
611
|
+
// reads it to attribute `session.step.ended`, verdicts and false refusals; a child that is
|
|
612
|
+
// not registered here is never recorded.
|
|
613
|
+
//
|
|
614
|
+
// MODULE (process) scope, deliberately unlike the per-instance session store above: the host
|
|
615
|
+
// delivers the same event to the plugin instance of every live location (S3b), so every
|
|
616
|
+
// instance must see the same registry. Entries are TTL-swept with the existing store sweeper
|
|
617
|
+
// (index.ts calls `sweepDispatches` from the same idle sweep) and bounded in size.
|
|
618
|
+
// ---------------------------------------------------------------------------
|
|
619
|
+
|
|
620
|
+
/** `routing.detection` keys: how strongly the dispatch's acceptance checks detect a failure (D8). */
|
|
621
|
+
export type DetectionDepth = "deterministic" | "grader" | "none";
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* #84 QA-G-B-1: what a role dispatch's verification was built from — the first `[acceptance]` block of its prompt (verbatim lines)
|
|
625
|
+
* and its whole-line `VERIFY:` / `VERIFY_WAIT:` directives — so a resume that names none of its own ("continue and finish") is
|
|
626
|
+
* verified, and its tier floor computed, on the same acceptance as the dispatch it resumes.
|
|
627
|
+
*/
|
|
628
|
+
export interface CarriedVerification {
|
|
629
|
+
readonly block: string;
|
|
630
|
+
readonly directives: readonly string[];
|
|
631
|
+
/** QA-G-B N-a: the route line's `d=` claim of the dispatch that introduced the block; absent: none. */
|
|
632
|
+
readonly claim?: DetectionDepth;
|
|
633
|
+
/**
|
|
634
|
+
* QA-G-B-2-1: the change baseline of the child's attempts under this block — set by the gate of the attempt that introduced it
|
|
635
|
+
* (its dispatch reference and change set), widened by every later attempt that carried it. Absent until that gate ran.
|
|
636
|
+
*/
|
|
637
|
+
readonly baseline?: VerificationBaseline;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** QA-G-B-2-1: what a carried acceptance is judged against (see {@link CarriedVerification}.baseline). */
|
|
641
|
+
export interface VerificationBaseline {
|
|
642
|
+
/** The dispatch reference of the attempt that introduced the block (its pre-existing failures are excused; later ones not). */
|
|
643
|
+
readonly reference: ReferenceState;
|
|
644
|
+
/** Every file the child changed in that attempt and every later one under the block; "unavailable" once any set was unknown. */
|
|
645
|
+
readonly changed: readonly ChangedFile[] | "unavailable";
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export interface DispatchInput {
|
|
649
|
+
/** Typed task facts of the dispatch (1.2 `TaskFacts` is assignable). */
|
|
650
|
+
facts: DecisionFacts;
|
|
651
|
+
/** Agent id the child runs under (router tier or host agent). */
|
|
652
|
+
agent: string;
|
|
653
|
+
/** `provider/model` the child runs on, or null when it could not be resolved (nothing is recorded then). */
|
|
654
|
+
model: string | null;
|
|
655
|
+
/** Variant of that model; null/absent = `default` (A9). */
|
|
656
|
+
variant?: string | null;
|
|
657
|
+
/** Router tier that owns the dispatch, when there is one. */
|
|
658
|
+
tier?: string | null;
|
|
659
|
+
/** The dispatch's verification depth (`routing.detection` key, D8), carried for the engine; ingestion does not read it. */
|
|
660
|
+
acceptance?: DetectionDepth | null;
|
|
661
|
+
/** The orchestrator session that dispatched the child. */
|
|
662
|
+
parentSessionID?: string | null;
|
|
663
|
+
/** Attempt id outcomes are scored under. Default: `${childSessionID}:${attemptIndex}:${nonce}-${seq}`, unique across restarts. */
|
|
664
|
+
attemptId?: string;
|
|
665
|
+
/** Id of the decision row of this dispatch (2.2), so verdict/refusal rows can reference it. */
|
|
666
|
+
decisionID?: string | null;
|
|
667
|
+
/**
|
|
668
|
+
* The agent the orchestrator NAMED for this dispatch before the router changed anything (a floor lift, an evidence switch): what a
|
|
669
|
+
* later resume of the child that repeats it must not be allowed to move back (the host switches a resumed child to the agent the
|
|
670
|
+
* resume names; QA-2.4-R3-1). Absent for a registration that is not an orchestrator dispatch (the runner's, a ladder step).
|
|
671
|
+
*/
|
|
672
|
+
picked?: string | null;
|
|
673
|
+
/** Kind of attempt (default `dispatch`; 2.3 ladder attempts pass `variant | retry | escalate`). */
|
|
674
|
+
step?: LadderStepKind;
|
|
675
|
+
/**
|
|
676
|
+
* `false`: the instance that registered the child had outcome ingestion off (`routing.engine: static`), so no
|
|
677
|
+
* instance may score this attempt (QA-2.3-6). The registry is process-wide and every plugin instance (one per
|
|
678
|
+
* location) sees the child's events, so an instance in `shadow` would otherwise record the outcomes of a dispatch
|
|
679
|
+
* whose own configuration said not to. Default `true`.
|
|
680
|
+
*/
|
|
681
|
+
outcomes?: boolean;
|
|
682
|
+
/**
|
|
683
|
+
* QA-2.3-1a (integration 2.2 + 2.3): this registration corrects or completes the SAME execution of an already registered
|
|
684
|
+
* child (the 2.2 router fixing a heuristic claim, or registering a child under its result), so the step context and the
|
|
685
|
+
* execution-end state the registry has seen are kept, and whoever waits for the end keeps waiting. Default `false`: a
|
|
686
|
+
* resume or a ladder attempt is a new execution and starts from nothing.
|
|
687
|
+
*/
|
|
688
|
+
keepExecution?: boolean;
|
|
689
|
+
/** #84 QA-G-B-1, role dispatches only: the verification its resumes carry ({@link CarriedVerification}). Absent: none. */
|
|
690
|
+
verification?: CarriedVerification | null;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
export interface DispatchRecord {
|
|
694
|
+
readonly childSessionID: string;
|
|
695
|
+
readonly facts: DecisionFacts;
|
|
696
|
+
readonly agent: string;
|
|
697
|
+
readonly model: string | null;
|
|
698
|
+
readonly variant: string | null;
|
|
699
|
+
readonly tier: string | null;
|
|
700
|
+
readonly acceptance: DetectionDepth | null;
|
|
701
|
+
readonly parentSessionID: string | null;
|
|
702
|
+
readonly attemptId: string;
|
|
703
|
+
/** 0 for the first registration of the child; +1 for each re-registration. Display only: it restarts at 0 after an eviction, `attemptId` never repeats. */
|
|
704
|
+
readonly attemptIndex: number;
|
|
705
|
+
readonly decisionID: string | null;
|
|
706
|
+
/** See `DispatchInput.picked`. */
|
|
707
|
+
readonly picked: string | null;
|
|
708
|
+
readonly step: LadderStepKind;
|
|
709
|
+
/** See `DispatchInput.outcomes`: false = ingestion was off where this child was registered. */
|
|
710
|
+
readonly outcomes: boolean;
|
|
711
|
+
readonly registeredAt: number;
|
|
712
|
+
/** See `DispatchInput.verification`; present only on a role dispatch that carries one. */
|
|
713
|
+
readonly verification?: CarriedVerification;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
interface DispatchSlot {
|
|
717
|
+
record: DispatchRecord;
|
|
718
|
+
lastTouch: number;
|
|
719
|
+
/** Context size of the child's largest step of this registration (D11), or null until a step is observed. */
|
|
720
|
+
stepTokens: number | null;
|
|
721
|
+
/** The child's execution ended after this registration (`noteExecutionEnded`): every step event of it was seen. */
|
|
722
|
+
ended: boolean;
|
|
723
|
+
/** Callers of `awaitExecutionEnd` still waiting; settled with `true` at the end, `false` when the slot goes away. */
|
|
724
|
+
waiters: Set<(ended: boolean) => void>;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Hard bound on remembered children; the oldest registration is dropped first. */
|
|
728
|
+
export const MAX_DISPATCH_RECORDS = 2000;
|
|
729
|
+
/** Execution-end event ids already applied (`noteExecutionEnded`), bounded, oldest first. */
|
|
730
|
+
const SEEN_END_CAP = 2048;
|
|
731
|
+
const seenEnds = new Set<string>();
|
|
732
|
+
|
|
733
|
+
const dispatchRegistry = new Map<string, DispatchSlot>();
|
|
734
|
+
/**
|
|
735
|
+
* Process-wide attempt counter (QA-2.1-1). `attemptIndex` restarts at 0 whenever a child is re-registered after
|
|
736
|
+
* an eviction (TTL, bound, session deletion), so `${child}:${index}` alone can name two different attempts, and
|
|
737
|
+
* the store, which remembers scored attempt ids, would then drop the second attempt's outcome. The sequence
|
|
738
|
+
* number makes every default attempt id unique within the process, and a random per-process component makes it unique
|
|
739
|
+
* across restarts too (QA-2.1-R2-2): the outcome log outlives the process, and ids that repeat after a restart would
|
|
740
|
+
* let `routing:stats` join a refusal to the wrong pass.
|
|
741
|
+
*/
|
|
742
|
+
let attemptSeq = 0;
|
|
743
|
+
const attemptNonce = randomBytes(4).toString("hex");
|
|
744
|
+
|
|
745
|
+
/** Remove a registration and release whoever waits for its execution end (the wait ends `false`); true when it existed. */
|
|
746
|
+
function dropDispatch(childSessionID: string): boolean {
|
|
747
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
748
|
+
if (slot === undefined) return false;
|
|
749
|
+
dispatchRegistry.delete(childSessionID);
|
|
750
|
+
for (const settle of [...slot.waiters]) settle(false);
|
|
751
|
+
slot.waiters.clear();
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Register (or re-register) the dispatch facts of a child session. Re-registering an existing child
|
|
757
|
+
* (a resume, or a ladder attempt) starts a new attempt: the index moves on unless the caller supplies
|
|
758
|
+
* `attemptId`, so one attempt is never scored twice. Returns the stored record.
|
|
759
|
+
*/
|
|
760
|
+
export function rememberDispatch(
|
|
761
|
+
childSessionID: string,
|
|
762
|
+
input: DispatchInput,
|
|
763
|
+
nowMs: number = Date.now(),
|
|
764
|
+
): DispatchRecord {
|
|
765
|
+
const previous = dispatchRegistry.get(childSessionID);
|
|
766
|
+
const attemptIndex = previous === undefined ? 0 : previous.record.attemptIndex + 1;
|
|
767
|
+
const record: DispatchRecord = Object.freeze({
|
|
768
|
+
childSessionID,
|
|
769
|
+
facts: input.facts,
|
|
770
|
+
agent: input.agent,
|
|
771
|
+
model: input.model,
|
|
772
|
+
variant: input.variant ?? null,
|
|
773
|
+
tier: input.tier ?? null,
|
|
774
|
+
acceptance: input.acceptance ?? null,
|
|
775
|
+
parentSessionID: input.parentSessionID ?? null,
|
|
776
|
+
attemptId: input.attemptId ?? `${childSessionID}:${attemptIndex}:${attemptNonce}-${++attemptSeq}`,
|
|
777
|
+
attemptIndex,
|
|
778
|
+
decisionID: input.decisionID ?? null,
|
|
779
|
+
picked: input.picked ?? null,
|
|
780
|
+
step: input.step ?? "dispatch",
|
|
781
|
+
outcomes: input.outcomes ?? true,
|
|
782
|
+
registeredAt: nowMs,
|
|
783
|
+
// Only when there is one: every other record keeps its exact shape.
|
|
784
|
+
...(input.verification === undefined || input.verification === null ? {} : { verification: frozenVerification(input.verification) }),
|
|
785
|
+
});
|
|
786
|
+
// Delete first so a re-registration moves to the young end of the insertion order.
|
|
787
|
+
// QA-2.3-1a: a registration of the same execution keeps what was observed of it (see `DispatchInput.keepExecution`).
|
|
788
|
+
const carried = input.keepExecution === true ? previous : undefined;
|
|
789
|
+
if (carried !== undefined) dispatchRegistry.delete(childSessionID);
|
|
790
|
+
else dropDispatch(childSessionID);
|
|
791
|
+
dispatchRegistry.set(childSessionID, {
|
|
792
|
+
record, lastTouch: nowMs,
|
|
793
|
+
stepTokens: carried?.stepTokens ?? null, ended: carried?.ended ?? false, waiters: carried?.waiters ?? new Set(),
|
|
794
|
+
});
|
|
795
|
+
while (dispatchRegistry.size > MAX_DISPATCH_RECORDS) {
|
|
796
|
+
const oldest = dispatchRegistry.keys().next();
|
|
797
|
+
if (oldest.done === true) break;
|
|
798
|
+
dropDispatch(oldest.value);
|
|
799
|
+
}
|
|
800
|
+
return record;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** A frozen copy of a carried verification; `claim` and `baseline` only when present (a record keeps its exact shape). */
|
|
804
|
+
function frozenVerification(v: CarriedVerification): CarriedVerification {
|
|
805
|
+
return Object.freeze({
|
|
806
|
+
block: v.block,
|
|
807
|
+
directives: Object.freeze([...v.directives]),
|
|
808
|
+
...(v.claim === undefined ? {} : { claim: v.claim }),
|
|
809
|
+
...(v.baseline === undefined ? {} : {
|
|
810
|
+
baseline: Object.freeze({
|
|
811
|
+
reference: v.baseline.reference,
|
|
812
|
+
changed: v.baseline.changed === "unavailable" ? "unavailable" as const : Object.freeze(v.baseline.changed.map((f) => Object.freeze({ ...f }))),
|
|
813
|
+
}),
|
|
814
|
+
}),
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* #84 QA-G-B-2-1: replace the carried verification of a child's CURRENT registration — the same attempt (no new attempt id, nothing
|
|
820
|
+
* observed of the execution is reset), only its verification baseline moves on. Nothing when the child is not registered.
|
|
821
|
+
*/
|
|
822
|
+
export function updateDispatchVerification(childSessionID: string, verification: CarriedVerification): void {
|
|
823
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
824
|
+
if (slot === undefined) return;
|
|
825
|
+
slot.record = Object.freeze({ ...slot.record, verification: frozenVerification(verification) });
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** The registered dispatch of a child session, or undefined (unknown, forgotten or swept). */
|
|
829
|
+
export function lookupDispatch(childSessionID: string): DispatchRecord | undefined {
|
|
830
|
+
return dispatchRegistry.get(childSessionID)?.record;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** Refresh a child's idle stamp (called on every recorded step so a long-running child is not swept). */
|
|
834
|
+
export function touchDispatch(childSessionID: string, nowMs: number = Date.now()): void {
|
|
835
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
836
|
+
if (slot !== undefined) slot.lastTouch = nowMs;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Note the context size (D11: `input + cache.read + cache.write + output`) of a finished step of a registered
|
|
841
|
+
* child. Phase 2.3: the delegate ladder reads it to decide resume vs fresh, whatever the engine mode, so it is
|
|
842
|
+
* kept in memory here and never touches the disk. The largest value of the current registration wins: the
|
|
843
|
+
* context only grows within a child, a duplicate delivery of an older step cannot lower it, and after a
|
|
844
|
+
* compaction the larger number errs towards a fresh start. A re-registration (a resume, a ladder attempt)
|
|
845
|
+
* starts from null. An unregistered child, or a value that is not a finite number >= 0, is ignored.
|
|
846
|
+
*/
|
|
847
|
+
export function noteStepContext(childSessionID: string, tokens: number, nowMs: number = Date.now()): void {
|
|
848
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
849
|
+
if (slot === undefined || typeof tokens !== "number" || !Number.isFinite(tokens) || tokens < 0) return;
|
|
850
|
+
slot.stepTokens = slot.stepTokens === null ? tokens : Math.max(slot.stepTokens, tokens);
|
|
851
|
+
slot.lastTouch = nowMs;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* The child execution ended (`session.execution.*`): the events are delivered in order, so every step event of the
|
|
856
|
+
* registration has been noted. Marks the current registration and wakes the callers of `awaitExecutionEnd`. A child
|
|
857
|
+
* that is not registered is ignored. Only a registration made after an earlier end can be marked by a later one,
|
|
858
|
+
* because a re-registration starts with `ended: false`.
|
|
859
|
+
*/
|
|
860
|
+
export function noteExecutionEnded(childSessionID: string, nowMs: number = Date.now(), eventId?: string): void {
|
|
861
|
+
// QA-2.3-R2-1: the host delivers the same event to the plugin instance of every live location (A3), and a lagging
|
|
862
|
+
// instance can deliver it after the child was registered again; that stale copy must not mark the new registration
|
|
863
|
+
// as ended. An event id is applied once per process; an event without an id cannot be told apart and is applied.
|
|
864
|
+
if (typeof eventId === "string" && eventId !== "") {
|
|
865
|
+
if (seenEnds.has(eventId)) return;
|
|
866
|
+
seenEnds.add(eventId);
|
|
867
|
+
while (seenEnds.size > SEEN_END_CAP) {
|
|
868
|
+
const oldest = seenEnds.values().next();
|
|
869
|
+
if (oldest.done === true) break;
|
|
870
|
+
seenEnds.delete(oldest.value);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
874
|
+
if (slot === undefined) return;
|
|
875
|
+
slot.ended = true;
|
|
876
|
+
slot.lastTouch = nowMs;
|
|
877
|
+
for (const settle of [...slot.waiters]) settle(true);
|
|
878
|
+
slot.waiters.clear();
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* The context size of the **largest** step of the child's current registration (D11), or null: unknown, not
|
|
883
|
+
* registered, or the execution end has not been seen since the registration (QA-2.3-2). The end event follows
|
|
884
|
+
* every step event on the stream, so a number read before it may miss the final, largest step, which would make a
|
|
885
|
+
* resume look safe when it is not; null leads the ladder to a fresh start (`unknown-tokens`).
|
|
886
|
+
*/
|
|
887
|
+
export function lastStepContext(childSessionID: string): number | null {
|
|
888
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
889
|
+
return slot !== undefined && slot.ended ? slot.stepTokens : null;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/**
|
|
893
|
+
* Wait, at most `timeoutMs` and until `signal` aborts, for the child's execution end since its current
|
|
894
|
+
* registration. Resolves `true` when it was seen (now or meanwhile), `false` on timeout, abort, or when the
|
|
895
|
+
* registration is replaced or removed. Never rejects. The wait is the runner's only barrier against an end event
|
|
896
|
+
* that is still queued behind the stream's earlier events.
|
|
897
|
+
*/
|
|
898
|
+
export function awaitExecutionEnd(childSessionID: string, timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
899
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
900
|
+
if (slot === undefined) return Promise.resolve(false);
|
|
901
|
+
if (slot.ended) return Promise.resolve(true);
|
|
902
|
+
if (signal?.aborted === true || !(timeoutMs > 0)) return Promise.resolve(false);
|
|
903
|
+
const waiters = slot.waiters;
|
|
904
|
+
return new Promise<boolean>((resolve) => {
|
|
905
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
906
|
+
// A pending wait must never keep the process alive.
|
|
907
|
+
if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
|
|
908
|
+
const onAbort = (): void => finish(false);
|
|
909
|
+
function finish(ended: boolean): void {
|
|
910
|
+
clearTimeout(timer);
|
|
911
|
+
signal?.removeEventListener("abort", onAbort);
|
|
912
|
+
waiters.delete(finish);
|
|
913
|
+
resolve(ended);
|
|
914
|
+
}
|
|
915
|
+
waiters.add(finish);
|
|
916
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/** Remove one child; true when it was registered. */
|
|
921
|
+
export function forgetDispatch(childSessionID: string): boolean {
|
|
922
|
+
return dropDispatch(childSessionID);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/** Remove every child dispatched by `parentSessionID` (the orchestrator went away); returns what was removed. */
|
|
926
|
+
export function forgetDispatchesOf(parentSessionID: string): DispatchRecord[] {
|
|
927
|
+
const removed: DispatchRecord[] = [];
|
|
928
|
+
for (const [id, slot] of [...dispatchRegistry]) {
|
|
929
|
+
if (slot.record.parentSessionID === parentSessionID && dropDispatch(id)) removed.push(slot.record);
|
|
930
|
+
}
|
|
931
|
+
return removed;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** Evict every dispatch idle for >= ttlMs (future stamps are never evicted); returns how many. */
|
|
935
|
+
export function sweepDispatches(nowMs: number = Date.now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): number {
|
|
936
|
+
let removed = 0;
|
|
937
|
+
for (const [id, slot] of [...dispatchRegistry]) {
|
|
938
|
+
if (nowMs - slot.lastTouch >= ttlMs && dropDispatch(id)) removed += 1;
|
|
939
|
+
}
|
|
940
|
+
return removed;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/** Number of registered children (tests, diagnostics). */
|
|
944
|
+
export function dispatchCount(): number {
|
|
945
|
+
return dispatchRegistry.size;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/** Test-only: drop every registration. */
|
|
949
|
+
export function resetDispatchRegistry(): void {
|
|
950
|
+
seenEnds.clear();
|
|
951
|
+
for (const id of [...dispatchRegistry.keys()]) dropDispatch(id);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// ===========================================================================================================
|
|
955
|
+
// Phase 2.2 / 2.3 integration — the single-writer runner token (QA-2.2-1, QA-2.3-1). Self-contained block.
|
|
956
|
+
//
|
|
957
|
+
// The delegate runner (2.3) dispatches producer and grader children through the host's native `subagent` tool, and the
|
|
958
|
+
// host does NOT run `tool.execute.before` for those calls on measured versions 2.0.22 and 2.0.24. The mark is defensive
|
|
959
|
+
// for hosts that do: the dispatch router must not touch them, since the runner has already decided the agent and model#variant, writes
|
|
960
|
+
// the attempt's decision row and registers the child itself (one writer). The runner announces each native call here, just
|
|
961
|
+
// before it makes it, keyed by the calling session, the agent and a hash of the prompt; the router consumes the mark when
|
|
962
|
+
// the hook arrives and leaves the call alone. The router only looks at a call that carries the runner's own `description`
|
|
963
|
+
// (`runnerDescription`), so an orchestrator dispatch with the same agent and prompt can never spend the runner's mark
|
|
964
|
+
// (QA-INT-1); if another plugin rewrote the prompt on the way, a runner-titled call still finds its mark by (session, agent).
|
|
965
|
+
// Marks expire and are bounded, each has its own id for withdrawal (QA-INT-3), and the runner withdraws its own mark when
|
|
966
|
+
// the call returns, so a hook that never fires cannot leave a mark that would later swallow an orchestrator dispatch.
|
|
967
|
+
// ===========================================================================================================
|
|
968
|
+
|
|
969
|
+
/** A runner mark is honoured for at most this long. */
|
|
970
|
+
export const RUNNER_TOKEN_TTL_MS = 120_000;
|
|
971
|
+
/** Bound on live mark keys (oldest key dropped first). */
|
|
972
|
+
export const MAX_RUNNER_TOKENS = 256;
|
|
973
|
+
/** The `description` of a runner verification (grader) call. */
|
|
974
|
+
export const RUNNER_VERIFICATION_DESCRIPTION = "Router result verification";
|
|
975
|
+
|
|
976
|
+
/** The `description` the runner sends with a native call: `Router <agent> delegation`, or the verification text (no agent). */
|
|
977
|
+
export function runnerDescription(agent: string | undefined): string {
|
|
978
|
+
return agent ? `Router ${agent} delegation` : RUNNER_VERIFICATION_DESCRIPTION;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
interface RunnerMark {
|
|
982
|
+
/** Unique per announcement: a withdrawal removes exactly its own mark (QA-INT-3). */
|
|
983
|
+
readonly id: number;
|
|
984
|
+
readonly expiresAt: number;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/** Marks per `parent \0 agent \0 sha1(prompt)`. */
|
|
988
|
+
const runnerTokens = new Map<string, RunnerMark[]>();
|
|
989
|
+
let runnerMarkSeq = 0;
|
|
990
|
+
|
|
991
|
+
export interface RunnerDispatchKey {
|
|
992
|
+
/** The session whose tool context the runner dispatches under (`ToolContext.sessionID`, `event.sessionID` in the hook). */
|
|
993
|
+
readonly parentSessionID: string;
|
|
994
|
+
/** The agent the call names (the grader agent for a verification). */
|
|
995
|
+
readonly agent: string;
|
|
996
|
+
/** The exact prompt string of the call. */
|
|
997
|
+
readonly prompt: string;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function runnerTokenPrefix(parentSessionID: string, agent: string): string {
|
|
1001
|
+
return `${parentSessionID}\u0000${agent}\u0000`;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
function runnerTokenKey(key: RunnerDispatchKey): string {
|
|
1005
|
+
return `${runnerTokenPrefix(key.parentSessionID, key.agent)}${createHash("sha1").update(key.prompt).digest("hex")}`;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function liveMarks(marks: readonly RunnerMark[], nowMs: number): RunnerMark[] {
|
|
1009
|
+
return marks.filter((mark) => mark.expiresAt > nowMs);
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* The runner is about to make a native `subagent` call: announce it. Returns a function that withdraws this announcement
|
|
1014
|
+
* (call it when the native call has returned); withdrawing a mark that was consumed or expired is a no-op, and it never
|
|
1015
|
+
* removes another announcement's mark.
|
|
1016
|
+
*/
|
|
1017
|
+
export function markRunnerDispatch(key: RunnerDispatchKey, nowMs: number = Date.now()): () => void {
|
|
1018
|
+
const id = runnerTokenKey(key);
|
|
1019
|
+
const mark: RunnerMark = { id: ++runnerMarkSeq, expiresAt: nowMs + RUNNER_TOKEN_TTL_MS };
|
|
1020
|
+
const marks = liveMarks(runnerTokens.get(id) ?? [], nowMs);
|
|
1021
|
+
marks.push(mark);
|
|
1022
|
+
runnerTokens.delete(id);
|
|
1023
|
+
runnerTokens.set(id, marks);
|
|
1024
|
+
while (runnerTokens.size > MAX_RUNNER_TOKENS) {
|
|
1025
|
+
const oldest = runnerTokens.keys().next();
|
|
1026
|
+
if (oldest.done === true) break;
|
|
1027
|
+
runnerTokens.delete(oldest.value);
|
|
1028
|
+
}
|
|
1029
|
+
return () => {
|
|
1030
|
+
const current = runnerTokens.get(id);
|
|
1031
|
+
if (current === undefined) return;
|
|
1032
|
+
const at = current.findIndex((candidate) => candidate.id === mark.id);
|
|
1033
|
+
if (at >= 0) current.splice(at, 1);
|
|
1034
|
+
if (current.length === 0) runnerTokens.delete(id);
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/** The hook for a native call arrived: true (and the mark is spent) when the runner announced exactly this call, else false. */
|
|
1039
|
+
export function consumeRunnerDispatch(key: RunnerDispatchKey, nowMs: number = Date.now()): boolean {
|
|
1040
|
+
const id = runnerTokenKey(key);
|
|
1041
|
+
const marks = runnerTokens.get(id);
|
|
1042
|
+
if (marks === undefined) return false;
|
|
1043
|
+
const live = liveMarks(marks, nowMs);
|
|
1044
|
+
if (live.length === 0) {
|
|
1045
|
+
runnerTokens.delete(id);
|
|
1046
|
+
return false;
|
|
1047
|
+
}
|
|
1048
|
+
live.shift();
|
|
1049
|
+
if (live.length === 0) runnerTokens.delete(id);
|
|
1050
|
+
else runnerTokens.set(id, live);
|
|
1051
|
+
return true;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* QA-INT-1: the call carries the runner's title but its prompt is not the announced one (another plugin rewrote it). Spend the
|
|
1056
|
+
* oldest live mark of this session and agent, whatever its prompt; false when there is none.
|
|
1057
|
+
*/
|
|
1058
|
+
export function consumeRunnerDispatchLoose(key: { readonly parentSessionID: string; readonly agent: string }, nowMs: number = Date.now()): boolean {
|
|
1059
|
+
const prefix = runnerTokenPrefix(key.parentSessionID, key.agent);
|
|
1060
|
+
let bestKey: string | null = null;
|
|
1061
|
+
let best: RunnerMark | null = null;
|
|
1062
|
+
for (const [id, marks] of runnerTokens) {
|
|
1063
|
+
if (!id.startsWith(prefix)) continue;
|
|
1064
|
+
for (const mark of liveMarks(marks, nowMs)) {
|
|
1065
|
+
if (best === null || mark.expiresAt < best.expiresAt) {
|
|
1066
|
+
best = mark;
|
|
1067
|
+
bestKey = id;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (best === null || bestKey === null) return false;
|
|
1072
|
+
const remaining = (runnerTokens.get(bestKey) ?? []).filter((mark) => mark.id !== best!.id);
|
|
1073
|
+
if (remaining.length === 0) runnerTokens.delete(bestKey);
|
|
1074
|
+
else runnerTokens.set(bestKey, remaining);
|
|
1075
|
+
return true;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/** Number of live runner marks (diagnostics, tests). */
|
|
1079
|
+
export function runnerTokenCount(nowMs: number = Date.now()): number {
|
|
1080
|
+
let count = 0;
|
|
1081
|
+
for (const marks of runnerTokens.values()) count += liveMarks(marks, nowMs).length;
|
|
1082
|
+
return count;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** Test-only: forget every mark. */
|
|
1086
|
+
export function resetRunnerTokens(): void {
|
|
1087
|
+
runnerTokens.clear();
|
|
1088
|
+
}
|
|
1089
|
+
// ===== end of the 2.2 / 2.3 runner token block ===============================================================
|
package/src/router/subagents.ts
CHANGED
|
@@ -11,6 +11,15 @@ export interface SubagentOverride {
|
|
|
11
11
|
variant: string | undefined;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Set (non-enumerable, `true`) on the config object the v2 adapter hands to the
|
|
16
|
+
* `config` hook while host agents may still be missing: the "no such agent"
|
|
17
|
+
* notice then waits for its first prompt-time check.
|
|
18
|
+
*/
|
|
19
|
+
/** v2 only: non-enumerable `Set<string>` of agent names that came from the host setup seed (host built-ins). */
|
|
20
|
+
export const HOST_SEED_AGENTS = Symbol.for("opencode-model-router.host-seed-agents");
|
|
21
|
+
export const DEFER_MISSING_SUBAGENT_NOTICE = Symbol.for("opencode-model-router.defer-missing-subagent-notice");
|
|
22
|
+
|
|
14
23
|
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
15
24
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
16
25
|
}
|
|
@@ -39,8 +48,15 @@ export function resolveSubagentOverrides(input: {
|
|
|
39
48
|
tiers: Preset;
|
|
40
49
|
/** The opencode config's `agent` record, when already populated. */
|
|
41
50
|
existingAgents?: Record<string, unknown>;
|
|
51
|
+
/**
|
|
52
|
+
* Names defined by the router `agents` block (#81). Their `tier` wins, so a
|
|
53
|
+
* `subagentTiers` entry for one of them is skipped.
|
|
54
|
+
*/
|
|
55
|
+
pluginAgents?: Record<string, unknown>;
|
|
56
|
+
/** Called for each skipped name whose agent does not exist (phantom) or is plugin-defined. */
|
|
57
|
+
onSkip?: (agentName: string, reason: "missing" | "plugin-agent") => void;
|
|
42
58
|
}): Record<string, SubagentOverride> {
|
|
43
|
-
const { subagentTiers, tiers, existingAgents } = input;
|
|
59
|
+
const { subagentTiers, tiers, existingAgents, pluginAgents, onSkip } = input;
|
|
44
60
|
if (!isPlainObject(subagentTiers)) return {};
|
|
45
61
|
|
|
46
62
|
const out: Record<string, SubagentOverride> = {};
|
|
@@ -55,6 +71,17 @@ export function resolveSubagentOverrides(input: {
|
|
|
55
71
|
const tier = tiers[tierName];
|
|
56
72
|
if (!tier || typeof tier.model !== "string" || tier.model === "") continue;
|
|
57
73
|
|
|
74
|
+
if (isPlainObject(pluginAgents) && Object.hasOwn(pluginAgents, agentName)) {
|
|
75
|
+
onSkip?.(agentName, "plugin-agent");
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
// A name that no agent record carries would be created from nothing: a
|
|
79
|
+
// phantom agent with only a model. Only checked when the record is known.
|
|
80
|
+
if (isPlainObject(existingAgents) && !Object.hasOwn(existingAgents, agentName)) {
|
|
81
|
+
onSkip?.(agentName, "missing");
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
|
|
58
85
|
const existing = existingAgents?.[agentName];
|
|
59
86
|
if (isPlainObject(existing) && typeof existing.mode === "string") {
|
|
60
87
|
if (existing.mode !== "subagent") continue;
|