opencode-model-router 2.2.0 → 2.3.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 +65 -0
- package/README.md +35 -3
- package/package.json +4 -1
- package/src/commands/output.ts +4 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +118 -31
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +484 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/index.ts +486 -38
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1365 -19
- package/src/router/protocol.ts +47 -0
- package/src/router/sessions.ts +441 -9
- package/src/routing/advisor/findings.ts +706 -0
- package/src/routing/advisor/index.ts +606 -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 +576 -0
- package/src/routing/classify/route-line.ts +298 -0
- package/src/routing/classify/rules.ts +607 -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 +1280 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +131 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +597 -0
- package/src/routing/engine/ladders.ts +561 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +133 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +270 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +141 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +172 -0
- package/src/routing/outcomes/ingest.ts +812 -0
- package/src/routing/outcomes/persist.ts +1058 -0
- package/src/routing/outcomes/stats.ts +602 -0
- package/src/routing/outcomes/store.ts +653 -0
- package/src/routing/outcomes/types.ts +954 -0
- package/src/routing/wire/dispatch.ts +799 -0
- package/src/routing/wire/hint.ts +208 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +259 -0
- package/src/v2.ts +15 -1
package/src/router/protocol.ts
CHANGED
|
@@ -132,6 +132,53 @@ export function buildDelegationProtocol(cfg: RouterConfig): string {
|
|
|
132
132
|
].join("\n");
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
// Routing engine seams (Phase 2.2; v2 `advise`/`enforce` only, never called for `static`/`shadow`)
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
/** First line of {@link buildDelegationProtocol}: how the adapter recognises the protocol text among the system parts. */
|
|
140
|
+
export const DELEGATION_PROTOCOL_HEADING = "## Model Delegation Protocol (MANDATORY)";
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Swap the taxonomy (`R:`) line of an assembled protocol text for `line` (the generated line of the routing engine,
|
|
144
|
+
* `generateTaxonomy`). The base line is `buildTaskTaxonomy(cfg)`; when it is empty the protocol carries no `R:` line and
|
|
145
|
+
* `line` is inserted where the taxonomy would go (before the decomposition hint, else before `Rules:`).
|
|
146
|
+
*
|
|
147
|
+
* Handoff 1.4 (QA-1.4-11): the text is spliced, never passed to `String.replace` with a string replacement, because the
|
|
148
|
+
* line carries agent ids and `$&`, `$1` or `$$` inside one would be expanded. A text that does not contain the base line
|
|
149
|
+
* (a child's stripped protocol, a user-edited prompt) is returned unchanged.
|
|
150
|
+
*/
|
|
151
|
+
export function swapTaxonomyLine(protocol: string, cfg: RouterConfig, line: string): string {
|
|
152
|
+
const base = buildTaskTaxonomy(cfg);
|
|
153
|
+
if (line === base || line === "") return protocol;
|
|
154
|
+
if (base !== "") {
|
|
155
|
+
const at = protocol.indexOf(base);
|
|
156
|
+
return at < 0 ? protocol : protocol.slice(0, at) + line + protocol.slice(at + base.length);
|
|
157
|
+
}
|
|
158
|
+
for (const anchor of [buildDecomposeHint(cfg), "Rules: "]) {
|
|
159
|
+
if (anchor === "") continue;
|
|
160
|
+
const at = protocol.indexOf(`\n${anchor}`);
|
|
161
|
+
if (at >= 0) return `${protocol.slice(0, at + 1)}${line}\n\n${protocol.slice(at + 1)}`;
|
|
162
|
+
}
|
|
163
|
+
return protocol;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The paragraph `advise` and `enforce` append to the delegation protocol (D13, A22): the optional first-line route
|
|
168
|
+
* directive, the `pin` flag, and how to read the per-turn hint. It never asks the orchestrator to pick a model
|
|
169
|
+
* (§0.10.11): the engine writes models itself. `static` and `shadow` never receive it (the text stays byte-identical).
|
|
170
|
+
*/
|
|
171
|
+
export function buildRouteLineProtocol(mode: "advise" | "enforce"): string {
|
|
172
|
+
return [
|
|
173
|
+
"Routing line (optional): when the FIRST line of a dispatch prompt is `[route class=<c> risk=<r> scope=<s> needs=<n,..> pin]`, the router reads it as the description of the work and removes it before the subagent sees it. Values: class = search|recon|mechanical|implement|debug|design|review|other; risk = low|medium|high; scope = single|multi|repo; needs = shell|web|edit|network|external_dir. Every field is optional and an unknown value is ignored. A route line anywhere but the first line is plain text.",
|
|
174
|
+
"Add the bare flag `pin` when a plan tag or policy mandates the tier (a `[tier:X]` step, a QA review): a pinned dispatch is never switched.",
|
|
175
|
+
mode === "enforce"
|
|
176
|
+
? "The router may start a dispatch on another agent than the one you name when recorded outcomes show it is cheaper or safer for that kind of work."
|
|
177
|
+
: "The router does not change your dispatches; a `Route hint` line, when present, shows where recorded outcomes suggest sending the next one.",
|
|
178
|
+
"Treat a `Route hint` as advice: follow it when it fits the task.",
|
|
179
|
+
].join("\n");
|
|
180
|
+
}
|
|
181
|
+
|
|
135
182
|
// ---------------------------------------------------------------------------
|
|
136
183
|
// Claude-model adversarial prefixes
|
|
137
184
|
//
|
package/src/router/sessions.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
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";
|
|
4
6
|
|
|
5
7
|
// ---------------------------------------------------------------------------
|
|
6
8
|
// Types
|
|
@@ -160,7 +162,7 @@ export const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
|
|
|
160
162
|
// ---------------------------------------------------------------------------
|
|
161
163
|
|
|
162
164
|
/** Normalise a taskPattern keyword to a lowercase stem for substring matching. */
|
|
163
|
-
function normTaskKw(kw: string): string {
|
|
165
|
+
export function normTaskKw(kw: string): string {
|
|
164
166
|
return kw.toLowerCase().split("(")[0]!.split("/")[0]!.trim();
|
|
165
167
|
}
|
|
166
168
|
|
|
@@ -176,7 +178,7 @@ function normTaskKw(kw: string): string {
|
|
|
176
178
|
* common phrasing; `step N` is also matched inline, since it frequently appears
|
|
177
179
|
* mid-line rather than at the start of one.
|
|
178
180
|
*/
|
|
179
|
-
const MULTI_STEP_RE =
|
|
181
|
+
export const MULTI_STEP_RE =
|
|
180
182
|
/(?:^\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
183
|
|
|
182
184
|
/**
|
|
@@ -185,7 +187,7 @@ const MULTI_STEP_RE =
|
|
|
185
187
|
* Two items are deliberately NOT enough: "read a.json, b.json" is already caught
|
|
186
188
|
* by the path count, and a two-item phrase is common in single-shot requests.
|
|
187
189
|
*/
|
|
188
|
-
const ENUMERATION_RE =
|
|
190
|
+
export const ENUMERATION_RE =
|
|
189
191
|
/[\w./-]+\s*,\s*[\w./-]+\s*(?:,\s*[\w./-]+|\b(?:and|or)\s+[\w./-]+)/i;
|
|
190
192
|
|
|
191
193
|
/**
|
|
@@ -207,7 +209,7 @@ const ENUMERATION_RE =
|
|
|
207
209
|
* words ending in `s` — "what does all this mean in tiers.json" must stay a
|
|
208
210
|
* single-file lookup.
|
|
209
211
|
*/
|
|
210
|
-
const DISTRIBUTIVE_RE =
|
|
212
|
+
export const DISTRIBUTIVE_RE =
|
|
211
213
|
/\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
214
|
|
|
213
215
|
/**
|
|
@@ -215,7 +217,7 @@ const DISTRIBUTIVE_RE =
|
|
|
215
217
|
* written as prose. Matched per line so the `Working directory:` / `Platform:` /
|
|
216
218
|
* `Shell:` footer described below cannot inflate the count.
|
|
217
219
|
*/
|
|
218
|
-
const IMPERATIVE_LINE_RE =
|
|
220
|
+
export const IMPERATIVE_LINE_RE =
|
|
219
221
|
/^\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
222
|
|
|
221
223
|
/**
|
|
@@ -228,7 +230,7 @@ const IMPERATIVE_LINE_RE =
|
|
|
228
230
|
* extension is what keeps a POSIX cwd (`/home/u/proj`) from being miscounted as
|
|
229
231
|
* a target file.
|
|
230
232
|
*/
|
|
231
|
-
const PATH_TOKEN_RE =
|
|
233
|
+
export const PATH_TOKEN_RE =
|
|
232
234
|
/[\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
235
|
|
|
234
236
|
/**
|
|
@@ -238,7 +240,7 @@ const PATH_TOKEN_RE =
|
|
|
238
240
|
* field in package.json" names one. The lookahead prevents double-counting
|
|
239
241
|
* `README.md`, which `PATH_TOKEN_RE` already matches.
|
|
240
242
|
*/
|
|
241
|
-
const BARE_FILENAME_RE =
|
|
243
|
+
export const BARE_FILENAME_RE =
|
|
242
244
|
/\b(?:Makefile|Dockerfile|LICENSE|README|CHANGELOG|Gemfile|Rakefile|Procfile|NOTICE|CODEOWNERS)\b(?!\.\w)/g;
|
|
243
245
|
|
|
244
246
|
/**
|
|
@@ -249,7 +251,7 @@ const BARE_FILENAME_RE =
|
|
|
249
251
|
* requiring exactly one path would reclassify them. Breadth that names no file
|
|
250
252
|
* is caught by `ENUMERATION_RE` and `IMPERATIVE_LINE_RE` instead.
|
|
251
253
|
*/
|
|
252
|
-
const MAX_TRIVIAL_PATHS = 1;
|
|
254
|
+
export const MAX_TRIVIAL_PATHS = 1;
|
|
253
255
|
|
|
254
256
|
/**
|
|
255
257
|
* Backstop for multi-step dispatches that use none of the marker words above:
|
|
@@ -258,7 +260,7 @@ const MAX_TRIVIAL_PATHS = 1;
|
|
|
258
260
|
* recon brief, and measured AFTER the cwd/platform footer so that footer can
|
|
259
261
|
* never by itself push a dispatch over the line.
|
|
260
262
|
*/
|
|
261
|
-
const MAX_TRIVIAL_CHARS = 240;
|
|
263
|
+
export const MAX_TRIVIAL_CHARS = 240;
|
|
262
264
|
|
|
263
265
|
/**
|
|
264
266
|
* Classify a dispatch as "trivial" AT DISPATCH TIME (m2): conservative,
|
|
@@ -563,3 +565,433 @@ export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
|
563
565
|
},
|
|
564
566
|
};
|
|
565
567
|
}
|
|
568
|
+
|
|
569
|
+
// ---------------------------------------------------------------------------
|
|
570
|
+
// Dispatch-facts registry (M6, plan 2.1.1, amendment A3)
|
|
571
|
+
//
|
|
572
|
+
// Remembers, per child session, what the router knew when it dispatched it: the typed
|
|
573
|
+
// facts, the agent and model that were actually dispatched, and the attempt id that
|
|
574
|
+
// outcome signals are scored under. Telemetry ingestion (src/routing/outcomes/ingest.ts)
|
|
575
|
+
// reads it to attribute `session.step.ended`, verdicts and false refusals; a child that is
|
|
576
|
+
// not registered here is never recorded.
|
|
577
|
+
//
|
|
578
|
+
// MODULE (process) scope, deliberately unlike the per-instance session store above: the host
|
|
579
|
+
// delivers the same event to the plugin instance of every live location (S3b), so every
|
|
580
|
+
// instance must see the same registry. Entries are TTL-swept with the existing store sweeper
|
|
581
|
+
// (index.ts calls `sweepDispatches` from the same idle sweep) and bounded in size.
|
|
582
|
+
// ---------------------------------------------------------------------------
|
|
583
|
+
|
|
584
|
+
/** `routing.detection` keys: how strongly the dispatch's acceptance checks detect a failure (D8). */
|
|
585
|
+
export type DetectionDepth = "deterministic" | "grader" | "none";
|
|
586
|
+
|
|
587
|
+
export interface DispatchInput {
|
|
588
|
+
/** Typed task facts of the dispatch (1.2 `TaskFacts` is assignable). */
|
|
589
|
+
facts: DecisionFacts;
|
|
590
|
+
/** Agent id the child runs under (router tier or host agent). */
|
|
591
|
+
agent: string;
|
|
592
|
+
/** `provider/model` the child runs on, or null when it could not be resolved (nothing is recorded then). */
|
|
593
|
+
model: string | null;
|
|
594
|
+
/** Variant of that model; null/absent = `default` (A9). */
|
|
595
|
+
variant?: string | null;
|
|
596
|
+
/** Router tier that owns the dispatch, when there is one. */
|
|
597
|
+
tier?: string | null;
|
|
598
|
+
/** The dispatch's verification depth (`routing.detection` key, D8), carried for the engine; ingestion does not read it. */
|
|
599
|
+
acceptance?: DetectionDepth | null;
|
|
600
|
+
/** The orchestrator session that dispatched the child. */
|
|
601
|
+
parentSessionID?: string | null;
|
|
602
|
+
/** Attempt id outcomes are scored under. Default: `${childSessionID}:${attemptIndex}:${nonce}-${seq}`, unique across restarts. */
|
|
603
|
+
attemptId?: string;
|
|
604
|
+
/** Id of the decision row of this dispatch (2.2), so verdict/refusal rows can reference it. */
|
|
605
|
+
decisionID?: string | null;
|
|
606
|
+
/**
|
|
607
|
+
* The agent the orchestrator NAMED for this dispatch before the router changed anything (a floor lift, an evidence switch): what a
|
|
608
|
+
* 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
|
|
609
|
+
* resume names; QA-2.4-R3-1). Absent for a registration that is not an orchestrator dispatch (the runner's, a ladder step).
|
|
610
|
+
*/
|
|
611
|
+
picked?: string | null;
|
|
612
|
+
/** Kind of attempt (default `dispatch`; 2.3 ladder attempts pass `variant | retry | escalate`). */
|
|
613
|
+
step?: LadderStepKind;
|
|
614
|
+
/**
|
|
615
|
+
* `false`: the instance that registered the child had outcome ingestion off (`routing.engine: static`), so no
|
|
616
|
+
* instance may score this attempt (QA-2.3-6). The registry is process-wide and every plugin instance (one per
|
|
617
|
+
* location) sees the child's events, so an instance in `shadow` would otherwise record the outcomes of a dispatch
|
|
618
|
+
* whose own configuration said not to. Default `true`.
|
|
619
|
+
*/
|
|
620
|
+
outcomes?: boolean;
|
|
621
|
+
/**
|
|
622
|
+
* QA-2.3-1a (integration 2.2 + 2.3): this registration corrects or completes the SAME execution of an already registered
|
|
623
|
+
* child (the 2.2 router fixing a heuristic claim, or registering a child under its result), so the step context and the
|
|
624
|
+
* execution-end state the registry has seen are kept, and whoever waits for the end keeps waiting. Default `false`: a
|
|
625
|
+
* resume or a ladder attempt is a new execution and starts from nothing.
|
|
626
|
+
*/
|
|
627
|
+
keepExecution?: boolean;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
export interface DispatchRecord {
|
|
631
|
+
readonly childSessionID: string;
|
|
632
|
+
readonly facts: DecisionFacts;
|
|
633
|
+
readonly agent: string;
|
|
634
|
+
readonly model: string | null;
|
|
635
|
+
readonly variant: string | null;
|
|
636
|
+
readonly tier: string | null;
|
|
637
|
+
readonly acceptance: DetectionDepth | null;
|
|
638
|
+
readonly parentSessionID: string | null;
|
|
639
|
+
readonly attemptId: string;
|
|
640
|
+
/** 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. */
|
|
641
|
+
readonly attemptIndex: number;
|
|
642
|
+
readonly decisionID: string | null;
|
|
643
|
+
/** See `DispatchInput.picked`. */
|
|
644
|
+
readonly picked: string | null;
|
|
645
|
+
readonly step: LadderStepKind;
|
|
646
|
+
/** See `DispatchInput.outcomes`: false = ingestion was off where this child was registered. */
|
|
647
|
+
readonly outcomes: boolean;
|
|
648
|
+
readonly registeredAt: number;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
interface DispatchSlot {
|
|
652
|
+
record: DispatchRecord;
|
|
653
|
+
lastTouch: number;
|
|
654
|
+
/** Context size of the child's largest step of this registration (D11), or null until a step is observed. */
|
|
655
|
+
stepTokens: number | null;
|
|
656
|
+
/** The child's execution ended after this registration (`noteExecutionEnded`): every step event of it was seen. */
|
|
657
|
+
ended: boolean;
|
|
658
|
+
/** Callers of `awaitExecutionEnd` still waiting; settled with `true` at the end, `false` when the slot goes away. */
|
|
659
|
+
waiters: Set<(ended: boolean) => void>;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Hard bound on remembered children; the oldest registration is dropped first. */
|
|
663
|
+
export const MAX_DISPATCH_RECORDS = 2000;
|
|
664
|
+
/** Execution-end event ids already applied (`noteExecutionEnded`), bounded, oldest first. */
|
|
665
|
+
const SEEN_END_CAP = 2048;
|
|
666
|
+
const seenEnds = new Set<string>();
|
|
667
|
+
|
|
668
|
+
const dispatchRegistry = new Map<string, DispatchSlot>();
|
|
669
|
+
/**
|
|
670
|
+
* Process-wide attempt counter (QA-2.1-1). `attemptIndex` restarts at 0 whenever a child is re-registered after
|
|
671
|
+
* an eviction (TTL, bound, session deletion), so `${child}:${index}` alone can name two different attempts, and
|
|
672
|
+
* the store, which remembers scored attempt ids, would then drop the second attempt's outcome. The sequence
|
|
673
|
+
* number makes every default attempt id unique within the process, and a random per-process component makes it unique
|
|
674
|
+
* across restarts too (QA-2.1-R2-2): the outcome log outlives the process, and ids that repeat after a restart would
|
|
675
|
+
* let `routing:stats` join a refusal to the wrong pass.
|
|
676
|
+
*/
|
|
677
|
+
let attemptSeq = 0;
|
|
678
|
+
const attemptNonce = randomBytes(4).toString("hex");
|
|
679
|
+
|
|
680
|
+
/** Remove a registration and release whoever waits for its execution end (the wait ends `false`); true when it existed. */
|
|
681
|
+
function dropDispatch(childSessionID: string): boolean {
|
|
682
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
683
|
+
if (slot === undefined) return false;
|
|
684
|
+
dispatchRegistry.delete(childSessionID);
|
|
685
|
+
for (const settle of [...slot.waiters]) settle(false);
|
|
686
|
+
slot.waiters.clear();
|
|
687
|
+
return true;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Register (or re-register) the dispatch facts of a child session. Re-registering an existing child
|
|
692
|
+
* (a resume, or a ladder attempt) starts a new attempt: the index moves on unless the caller supplies
|
|
693
|
+
* `attemptId`, so one attempt is never scored twice. Returns the stored record.
|
|
694
|
+
*/
|
|
695
|
+
export function rememberDispatch(
|
|
696
|
+
childSessionID: string,
|
|
697
|
+
input: DispatchInput,
|
|
698
|
+
nowMs: number = Date.now(),
|
|
699
|
+
): DispatchRecord {
|
|
700
|
+
const previous = dispatchRegistry.get(childSessionID);
|
|
701
|
+
const attemptIndex = previous === undefined ? 0 : previous.record.attemptIndex + 1;
|
|
702
|
+
const record: DispatchRecord = Object.freeze({
|
|
703
|
+
childSessionID,
|
|
704
|
+
facts: input.facts,
|
|
705
|
+
agent: input.agent,
|
|
706
|
+
model: input.model,
|
|
707
|
+
variant: input.variant ?? null,
|
|
708
|
+
tier: input.tier ?? null,
|
|
709
|
+
acceptance: input.acceptance ?? null,
|
|
710
|
+
parentSessionID: input.parentSessionID ?? null,
|
|
711
|
+
attemptId: input.attemptId ?? `${childSessionID}:${attemptIndex}:${attemptNonce}-${++attemptSeq}`,
|
|
712
|
+
attemptIndex,
|
|
713
|
+
decisionID: input.decisionID ?? null,
|
|
714
|
+
picked: input.picked ?? null,
|
|
715
|
+
step: input.step ?? "dispatch",
|
|
716
|
+
outcomes: input.outcomes ?? true,
|
|
717
|
+
registeredAt: nowMs,
|
|
718
|
+
});
|
|
719
|
+
// Delete first so a re-registration moves to the young end of the insertion order.
|
|
720
|
+
// QA-2.3-1a: a registration of the same execution keeps what was observed of it (see `DispatchInput.keepExecution`).
|
|
721
|
+
const carried = input.keepExecution === true ? previous : undefined;
|
|
722
|
+
if (carried !== undefined) dispatchRegistry.delete(childSessionID);
|
|
723
|
+
else dropDispatch(childSessionID);
|
|
724
|
+
dispatchRegistry.set(childSessionID, {
|
|
725
|
+
record, lastTouch: nowMs,
|
|
726
|
+
stepTokens: carried?.stepTokens ?? null, ended: carried?.ended ?? false, waiters: carried?.waiters ?? new Set(),
|
|
727
|
+
});
|
|
728
|
+
while (dispatchRegistry.size > MAX_DISPATCH_RECORDS) {
|
|
729
|
+
const oldest = dispatchRegistry.keys().next();
|
|
730
|
+
if (oldest.done === true) break;
|
|
731
|
+
dropDispatch(oldest.value);
|
|
732
|
+
}
|
|
733
|
+
return record;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** The registered dispatch of a child session, or undefined (unknown, forgotten or swept). */
|
|
737
|
+
export function lookupDispatch(childSessionID: string): DispatchRecord | undefined {
|
|
738
|
+
return dispatchRegistry.get(childSessionID)?.record;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** Refresh a child's idle stamp (called on every recorded step so a long-running child is not swept). */
|
|
742
|
+
export function touchDispatch(childSessionID: string, nowMs: number = Date.now()): void {
|
|
743
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
744
|
+
if (slot !== undefined) slot.lastTouch = nowMs;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* Note the context size (D11: `input + cache.read + cache.write + output`) of a finished step of a registered
|
|
749
|
+
* child. Phase 2.3: the delegate ladder reads it to decide resume vs fresh, whatever the engine mode, so it is
|
|
750
|
+
* kept in memory here and never touches the disk. The largest value of the current registration wins: the
|
|
751
|
+
* context only grows within a child, a duplicate delivery of an older step cannot lower it, and after a
|
|
752
|
+
* compaction the larger number errs towards a fresh start. A re-registration (a resume, a ladder attempt)
|
|
753
|
+
* starts from null. An unregistered child, or a value that is not a finite number >= 0, is ignored.
|
|
754
|
+
*/
|
|
755
|
+
export function noteStepContext(childSessionID: string, tokens: number, nowMs: number = Date.now()): void {
|
|
756
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
757
|
+
if (slot === undefined || typeof tokens !== "number" || !Number.isFinite(tokens) || tokens < 0) return;
|
|
758
|
+
slot.stepTokens = slot.stepTokens === null ? tokens : Math.max(slot.stepTokens, tokens);
|
|
759
|
+
slot.lastTouch = nowMs;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* The child execution ended (`session.execution.*`): the events are delivered in order, so every step event of the
|
|
764
|
+
* registration has been noted. Marks the current registration and wakes the callers of `awaitExecutionEnd`. A child
|
|
765
|
+
* that is not registered is ignored. Only a registration made after an earlier end can be marked by a later one,
|
|
766
|
+
* because a re-registration starts with `ended: false`.
|
|
767
|
+
*/
|
|
768
|
+
export function noteExecutionEnded(childSessionID: string, nowMs: number = Date.now(), eventId?: string): void {
|
|
769
|
+
// QA-2.3-R2-1: the host delivers the same event to the plugin instance of every live location (A3), and a lagging
|
|
770
|
+
// instance can deliver it after the child was registered again; that stale copy must not mark the new registration
|
|
771
|
+
// as ended. An event id is applied once per process; an event without an id cannot be told apart and is applied.
|
|
772
|
+
if (typeof eventId === "string" && eventId !== "") {
|
|
773
|
+
if (seenEnds.has(eventId)) return;
|
|
774
|
+
seenEnds.add(eventId);
|
|
775
|
+
while (seenEnds.size > SEEN_END_CAP) {
|
|
776
|
+
const oldest = seenEnds.values().next();
|
|
777
|
+
if (oldest.done === true) break;
|
|
778
|
+
seenEnds.delete(oldest.value);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
782
|
+
if (slot === undefined) return;
|
|
783
|
+
slot.ended = true;
|
|
784
|
+
slot.lastTouch = nowMs;
|
|
785
|
+
for (const settle of [...slot.waiters]) settle(true);
|
|
786
|
+
slot.waiters.clear();
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* The context size of the **largest** step of the child's current registration (D11), or null: unknown, not
|
|
791
|
+
* registered, or the execution end has not been seen since the registration (QA-2.3-2). The end event follows
|
|
792
|
+
* every step event on the stream, so a number read before it may miss the final, largest step, which would make a
|
|
793
|
+
* resume look safe when it is not; null leads the ladder to a fresh start (`unknown-tokens`).
|
|
794
|
+
*/
|
|
795
|
+
export function lastStepContext(childSessionID: string): number | null {
|
|
796
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
797
|
+
return slot !== undefined && slot.ended ? slot.stepTokens : null;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Wait, at most `timeoutMs` and until `signal` aborts, for the child's execution end since its current
|
|
802
|
+
* registration. Resolves `true` when it was seen (now or meanwhile), `false` on timeout, abort, or when the
|
|
803
|
+
* registration is replaced or removed. Never rejects. The wait is the runner's only barrier against an end event
|
|
804
|
+
* that is still queued behind the stream's earlier events.
|
|
805
|
+
*/
|
|
806
|
+
export function awaitExecutionEnd(childSessionID: string, timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
807
|
+
const slot = dispatchRegistry.get(childSessionID);
|
|
808
|
+
if (slot === undefined) return Promise.resolve(false);
|
|
809
|
+
if (slot.ended) return Promise.resolve(true);
|
|
810
|
+
if (signal?.aborted === true || !(timeoutMs > 0)) return Promise.resolve(false);
|
|
811
|
+
const waiters = slot.waiters;
|
|
812
|
+
return new Promise<boolean>((resolve) => {
|
|
813
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
814
|
+
// A pending wait must never keep the process alive.
|
|
815
|
+
if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
|
|
816
|
+
const onAbort = (): void => finish(false);
|
|
817
|
+
function finish(ended: boolean): void {
|
|
818
|
+
clearTimeout(timer);
|
|
819
|
+
signal?.removeEventListener("abort", onAbort);
|
|
820
|
+
waiters.delete(finish);
|
|
821
|
+
resolve(ended);
|
|
822
|
+
}
|
|
823
|
+
waiters.add(finish);
|
|
824
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** Remove one child; true when it was registered. */
|
|
829
|
+
export function forgetDispatch(childSessionID: string): boolean {
|
|
830
|
+
return dropDispatch(childSessionID);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** Remove every child dispatched by `parentSessionID` (the orchestrator went away); returns what was removed. */
|
|
834
|
+
export function forgetDispatchesOf(parentSessionID: string): DispatchRecord[] {
|
|
835
|
+
const removed: DispatchRecord[] = [];
|
|
836
|
+
for (const [id, slot] of [...dispatchRegistry]) {
|
|
837
|
+
if (slot.record.parentSessionID === parentSessionID && dropDispatch(id)) removed.push(slot.record);
|
|
838
|
+
}
|
|
839
|
+
return removed;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** Evict every dispatch idle for >= ttlMs (future stamps are never evicted); returns how many. */
|
|
843
|
+
export function sweepDispatches(nowMs: number = Date.now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): number {
|
|
844
|
+
let removed = 0;
|
|
845
|
+
for (const [id, slot] of [...dispatchRegistry]) {
|
|
846
|
+
if (nowMs - slot.lastTouch >= ttlMs && dropDispatch(id)) removed += 1;
|
|
847
|
+
}
|
|
848
|
+
return removed;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/** Number of registered children (tests, diagnostics). */
|
|
852
|
+
export function dispatchCount(): number {
|
|
853
|
+
return dispatchRegistry.size;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/** Test-only: drop every registration. */
|
|
857
|
+
export function resetDispatchRegistry(): void {
|
|
858
|
+
seenEnds.clear();
|
|
859
|
+
for (const id of [...dispatchRegistry.keys()]) dropDispatch(id);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// ===========================================================================================================
|
|
863
|
+
// Phase 2.2 / 2.3 integration — the single-writer runner token (QA-2.2-1, QA-2.3-1). Self-contained block.
|
|
864
|
+
//
|
|
865
|
+
// The delegate runner (2.3) dispatches producer and grader children through the host's native `subagent` tool, and the
|
|
866
|
+
// host does NOT run `tool.execute.before` for those calls on measured versions 2.0.22 and 2.0.24. The mark is defensive
|
|
867
|
+
// for hosts that do: the dispatch router must not touch them, since the runner has already decided the agent and model#variant, writes
|
|
868
|
+
// the attempt's decision row and registers the child itself (one writer). The runner announces each native call here, just
|
|
869
|
+
// before it makes it, keyed by the calling session, the agent and a hash of the prompt; the router consumes the mark when
|
|
870
|
+
// the hook arrives and leaves the call alone. The router only looks at a call that carries the runner's own `description`
|
|
871
|
+
// (`runnerDescription`), so an orchestrator dispatch with the same agent and prompt can never spend the runner's mark
|
|
872
|
+
// (QA-INT-1); if another plugin rewrote the prompt on the way, a runner-titled call still finds its mark by (session, agent).
|
|
873
|
+
// Marks expire and are bounded, each has its own id for withdrawal (QA-INT-3), and the runner withdraws its own mark when
|
|
874
|
+
// the call returns, so a hook that never fires cannot leave a mark that would later swallow an orchestrator dispatch.
|
|
875
|
+
// ===========================================================================================================
|
|
876
|
+
|
|
877
|
+
/** A runner mark is honoured for at most this long. */
|
|
878
|
+
export const RUNNER_TOKEN_TTL_MS = 120_000;
|
|
879
|
+
/** Bound on live mark keys (oldest key dropped first). */
|
|
880
|
+
export const MAX_RUNNER_TOKENS = 256;
|
|
881
|
+
/** The `description` of a runner verification (grader) call. */
|
|
882
|
+
export const RUNNER_VERIFICATION_DESCRIPTION = "Router result verification";
|
|
883
|
+
|
|
884
|
+
/** The `description` the runner sends with a native call: `Router <agent> delegation`, or the verification text (no agent). */
|
|
885
|
+
export function runnerDescription(agent: string | undefined): string {
|
|
886
|
+
return agent ? `Router ${agent} delegation` : RUNNER_VERIFICATION_DESCRIPTION;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
interface RunnerMark {
|
|
890
|
+
/** Unique per announcement: a withdrawal removes exactly its own mark (QA-INT-3). */
|
|
891
|
+
readonly id: number;
|
|
892
|
+
readonly expiresAt: number;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** Marks per `parent \0 agent \0 sha1(prompt)`. */
|
|
896
|
+
const runnerTokens = new Map<string, RunnerMark[]>();
|
|
897
|
+
let runnerMarkSeq = 0;
|
|
898
|
+
|
|
899
|
+
export interface RunnerDispatchKey {
|
|
900
|
+
/** The session whose tool context the runner dispatches under (`ToolContext.sessionID`, `event.sessionID` in the hook). */
|
|
901
|
+
readonly parentSessionID: string;
|
|
902
|
+
/** The agent the call names (the grader agent for a verification). */
|
|
903
|
+
readonly agent: string;
|
|
904
|
+
/** The exact prompt string of the call. */
|
|
905
|
+
readonly prompt: string;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function runnerTokenPrefix(parentSessionID: string, agent: string): string {
|
|
909
|
+
return `${parentSessionID}\u0000${agent}\u0000`;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function runnerTokenKey(key: RunnerDispatchKey): string {
|
|
913
|
+
return `${runnerTokenPrefix(key.parentSessionID, key.agent)}${createHash("sha1").update(key.prompt).digest("hex")}`;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function liveMarks(marks: readonly RunnerMark[], nowMs: number): RunnerMark[] {
|
|
917
|
+
return marks.filter((mark) => mark.expiresAt > nowMs);
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* The runner is about to make a native `subagent` call: announce it. Returns a function that withdraws this announcement
|
|
922
|
+
* (call it when the native call has returned); withdrawing a mark that was consumed or expired is a no-op, and it never
|
|
923
|
+
* removes another announcement's mark.
|
|
924
|
+
*/
|
|
925
|
+
export function markRunnerDispatch(key: RunnerDispatchKey, nowMs: number = Date.now()): () => void {
|
|
926
|
+
const id = runnerTokenKey(key);
|
|
927
|
+
const mark: RunnerMark = { id: ++runnerMarkSeq, expiresAt: nowMs + RUNNER_TOKEN_TTL_MS };
|
|
928
|
+
const marks = liveMarks(runnerTokens.get(id) ?? [], nowMs);
|
|
929
|
+
marks.push(mark);
|
|
930
|
+
runnerTokens.delete(id);
|
|
931
|
+
runnerTokens.set(id, marks);
|
|
932
|
+
while (runnerTokens.size > MAX_RUNNER_TOKENS) {
|
|
933
|
+
const oldest = runnerTokens.keys().next();
|
|
934
|
+
if (oldest.done === true) break;
|
|
935
|
+
runnerTokens.delete(oldest.value);
|
|
936
|
+
}
|
|
937
|
+
return () => {
|
|
938
|
+
const current = runnerTokens.get(id);
|
|
939
|
+
if (current === undefined) return;
|
|
940
|
+
const at = current.findIndex((candidate) => candidate.id === mark.id);
|
|
941
|
+
if (at >= 0) current.splice(at, 1);
|
|
942
|
+
if (current.length === 0) runnerTokens.delete(id);
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** The hook for a native call arrived: true (and the mark is spent) when the runner announced exactly this call, else false. */
|
|
947
|
+
export function consumeRunnerDispatch(key: RunnerDispatchKey, nowMs: number = Date.now()): boolean {
|
|
948
|
+
const id = runnerTokenKey(key);
|
|
949
|
+
const marks = runnerTokens.get(id);
|
|
950
|
+
if (marks === undefined) return false;
|
|
951
|
+
const live = liveMarks(marks, nowMs);
|
|
952
|
+
if (live.length === 0) {
|
|
953
|
+
runnerTokens.delete(id);
|
|
954
|
+
return false;
|
|
955
|
+
}
|
|
956
|
+
live.shift();
|
|
957
|
+
if (live.length === 0) runnerTokens.delete(id);
|
|
958
|
+
else runnerTokens.set(id, live);
|
|
959
|
+
return true;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* QA-INT-1: the call carries the runner's title but its prompt is not the announced one (another plugin rewrote it). Spend the
|
|
964
|
+
* oldest live mark of this session and agent, whatever its prompt; false when there is none.
|
|
965
|
+
*/
|
|
966
|
+
export function consumeRunnerDispatchLoose(key: { readonly parentSessionID: string; readonly agent: string }, nowMs: number = Date.now()): boolean {
|
|
967
|
+
const prefix = runnerTokenPrefix(key.parentSessionID, key.agent);
|
|
968
|
+
let bestKey: string | null = null;
|
|
969
|
+
let best: RunnerMark | null = null;
|
|
970
|
+
for (const [id, marks] of runnerTokens) {
|
|
971
|
+
if (!id.startsWith(prefix)) continue;
|
|
972
|
+
for (const mark of liveMarks(marks, nowMs)) {
|
|
973
|
+
if (best === null || mark.expiresAt < best.expiresAt) {
|
|
974
|
+
best = mark;
|
|
975
|
+
bestKey = id;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
if (best === null || bestKey === null) return false;
|
|
980
|
+
const remaining = (runnerTokens.get(bestKey) ?? []).filter((mark) => mark.id !== best!.id);
|
|
981
|
+
if (remaining.length === 0) runnerTokens.delete(bestKey);
|
|
982
|
+
else runnerTokens.set(bestKey, remaining);
|
|
983
|
+
return true;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/** Number of live runner marks (diagnostics, tests). */
|
|
987
|
+
export function runnerTokenCount(nowMs: number = Date.now()): number {
|
|
988
|
+
let count = 0;
|
|
989
|
+
for (const marks of runnerTokens.values()) count += liveMarks(marks, nowMs).length;
|
|
990
|
+
return count;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/** Test-only: forget every mark. */
|
|
994
|
+
export function resetRunnerTokens(): void {
|
|
995
|
+
runnerTokens.clear();
|
|
996
|
+
}
|
|
997
|
+
// ===== end of the 2.2 / 2.3 runner token block ===============================================================
|