opencode-model-router 2.1.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 +86 -0
- package/README.md +44 -5
- 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 +174 -47
- 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 +557 -61
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1691 -67
- 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/tiers.json +43 -0
|
@@ -0,0 +1,799 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dispatch-time routing on v2 (M7, Phase 2.2.1): `route()` composes M2 (classify) → ladders → M4 (decide) for one
|
|
3
|
+
* `subagent` call and applies the engine mode; `commit()` writes the decision row (QA-G-A2) and registers the dispatch with the 2.1
|
|
4
|
+
* dispatch-facts registry once the FINAL input is known, so ingestion sees what really ran.
|
|
5
|
+
*
|
|
6
|
+
* Design (the order the adapter calls it in, `src/compat/v2-hooks.ts` `execute.before` / `execute.after`):
|
|
7
|
+
*
|
|
8
|
+
* 1. Engine first. `route()` runs before the `subagentTiers` override and before the legacy `tool.execute.before`.
|
|
9
|
+
* `subagentTiers` only fills a MISSING `model`: the engine sees the model it would fill (`callModel`) when it
|
|
10
|
+
* resolves the orchestrator's pick, and when it switches it always writes a model of its own, so the override
|
|
11
|
+
* never fires after a switch. The legacy hook runs last, so headers and the depth banner see the final agent.
|
|
12
|
+
* 2. Modes (§1.2): `static` returns before any host call, allocation or disk access. `shadow` classifies, decides and
|
|
13
|
+
* logs (a `switched` row is a would-switch); the input is untouched except that the first-line `[route …]` is
|
|
14
|
+
* stripped. `advise` is `shadow` plus the protocol/hint of the context hook. `enforce` additionally writes `agent`
|
|
15
|
+
* and `model#variant` when the kernel switches (D9, A16, A24, A27) and the dispatch is not pinned.
|
|
16
|
+
* 3. Only the orchestrator's own prompt is parsed: the session must be a root session, and the route line only counts
|
|
17
|
+
* on the first non-empty line of the prompt (A22); every other byte of the prompt passes through unchanged. A
|
|
18
|
+
* subagent's dispatch is left exactly as it is.
|
|
19
|
+
* 4. Errors never reach the session: any failure is logged and the dispatch proceeds as the orchestrator wrote it.
|
|
20
|
+
* 5. Registration (2.1 handoff, QA-2.1-R2-10; QA-2.2-2/3): once per execution of a child, from the FINAL input.
|
|
21
|
+
* `route()` only decides; its decision row is held until `commit()` (QA-G-A2: a call the hook chain rejects writes no row; a
|
|
22
|
+
* call the HOST then fails keeps its row, a known limit — no retraction row). After the legacy hook has had its say, the adapter calls `commit(callID, input)`
|
|
23
|
+
* with the input the host will execute: a resume (`sessionID` given) is registered at once; a fresh child does not
|
|
24
|
+
* exist yet, so the dispatch waits and is claimed by the `session.created` event of the child (parent, agent and
|
|
25
|
+
* title decide which one). `execute.after` then names the child (`onCallResult`): a dispatch still waiting is
|
|
26
|
+
* registered under it, and a heuristic claim that picked the wrong child is corrected before the verdict is
|
|
27
|
+
* recorded. A call that ends without a result, or whose hook chain throws, is dropped (`onCallFinished`).
|
|
28
|
+
* 6. Single writer with the delegate runner (QA-2.2-1, QA-2.3-1): the runner (2.3) dispatches its producer and grader children
|
|
29
|
+
* through the same native tool. It announces each call (`markRunnerDispatch`, keyed by the calling session, the agent and a hash of
|
|
30
|
+
* the prompt) and `route()` consumes the mark first: the call is left exactly as the runner wrote it (no rewrite, no route-line
|
|
31
|
+
* strip, no floor lift, no decision row, no registration). The runner's own recorder is the only writer for ladder attempts. A
|
|
32
|
+
* `session.created` that is the runner's child is never claimed for an orchestrator dispatch (already registered, or titled like a
|
|
33
|
+
* runner call). MEASURED on the real OpenCode 2.0.22 host (Phase 3.2, H4): the host does NOT run the plugin's `execute.before` /
|
|
34
|
+
* `execute.after` hooks for calls made through `ctx.tool.list()` natives, so on 2.0.22 `route()` never sees a runner call and the mark
|
|
35
|
+
* is withdrawn unconsumed (`v2-client.ts`). The mark and the "runner description" rule are defensive: they only matter on a host
|
|
36
|
+
* that does hook such calls.
|
|
37
|
+
* 7. Multi-instance (A3): MEASURED on 2.0.22 (Phase 3.2, H2): the host hands a SESSION EVENT to the plugin instance of every live
|
|
38
|
+
* location, but the TOOL HOOKS of a call only to the instance of the session's location. The receiving instance acts; the
|
|
39
|
+
* process-wide set of handled calls is defensive for hooks. What protects
|
|
40
|
+
* the store from a duplicated EVENT is the event-id LRU of the ingest (`firstDelivery`) and of the registry. Only the first instance
|
|
41
|
+
* whose engine is live acts on a call.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
import {
|
|
45
|
+
buildLadder, candidateKey, capabilityRank, coversNeeds, decide, detectionOf, escalateLadder, floorRankOf, lowerEffortOnSameModel, resolveChosen,
|
|
46
|
+
tierRankOf, weakerDetection,
|
|
47
|
+
} from "../engine";
|
|
48
|
+
import { routerTierIds } from "../engine/ladders";
|
|
49
|
+
import type { ChosenDispatch, Decision, HostAgentInfo, Ladder } from "../engine/types";
|
|
50
|
+
import { classify } from "../classify";
|
|
51
|
+
import type { ClassifyResult, Detection, TaskFacts } from "../classify/types";
|
|
52
|
+
import type { RouterConfig } from "../../router/config";
|
|
53
|
+
import {
|
|
54
|
+
consumeRunnerDispatch, consumeRunnerDispatchLoose, forgetDispatch, lookupDispatch, rememberDispatch, runnerDescription,
|
|
55
|
+
type DetectionDepth, type DispatchInput, type DispatchRecord,
|
|
56
|
+
} from "../../router/sessions";
|
|
57
|
+
import { randomBytes } from "node:crypto";
|
|
58
|
+
import {
|
|
59
|
+
FLOOR_LIFT_REASON,
|
|
60
|
+
RESUME_REASON,
|
|
61
|
+
RESUME_RUNNING_REASON,
|
|
62
|
+
RESUME_PINNED_REASON,
|
|
63
|
+
RESUME_NAMED_NEEDS_REASON,
|
|
64
|
+
RESUME_NAMED_NEVER_DOWN_REASON,
|
|
65
|
+
LOG_ROW_VERSION,
|
|
66
|
+
classifyAgentOrigin,
|
|
67
|
+
makeKey,
|
|
68
|
+
normalizeVariant,
|
|
69
|
+
safeNow,
|
|
70
|
+
splitModelRef,
|
|
71
|
+
type DecisionRow,
|
|
72
|
+
type DecisionTrace,
|
|
73
|
+
type RouteChoice,
|
|
74
|
+
} from "../outcomes/types";
|
|
75
|
+
import { agentModelRef, type AgentView } from "./host-info";
|
|
76
|
+
import { sessionRulesOf, type EngineRuntime, type Prepared, type WireLogger } from "./runtime";
|
|
77
|
+
|
|
78
|
+
/** A fresh dispatch can be claimed by a `session.created` event for at most this long. */
|
|
79
|
+
export const PENDING_TTL_MS = 120_000;
|
|
80
|
+
/** Bound on dispatches kept for claiming and for the result (oldest dropped first). */
|
|
81
|
+
export const MAX_PENDING = 200;
|
|
82
|
+
/** A dispatch whose result never arrives is forgotten after this long (the registry's own idle TTL). */
|
|
83
|
+
export const ENTRY_TTL_MS = 3_600_000;
|
|
84
|
+
/** Bound on the process-wide set of handled calls (LRU). */
|
|
85
|
+
export const MAX_HANDLED_CALLS = 4096;
|
|
86
|
+
|
|
87
|
+
export interface RouteCall {
|
|
88
|
+
/** The tool call id (`event.id`): the dispatch ends with the call. */
|
|
89
|
+
readonly callID: string;
|
|
90
|
+
/** The dispatching (orchestrator) session. */
|
|
91
|
+
readonly sessionID: string;
|
|
92
|
+
/** Its agent. */
|
|
93
|
+
readonly agent: string | undefined;
|
|
94
|
+
/** The call's input in the adapter's legacy vocabulary: `agent` (and `subagent_type`), `prompt`, `description`, `model`, `sessionID` (`task_id`). */
|
|
95
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
96
|
+
/** The model `subagentTiers` would fill in when the call sets none (the engine resolves the pick with it). */
|
|
97
|
+
readonly tierModel?: string | undefined;
|
|
98
|
+
/** The router config the caller already loaded for this call. */
|
|
99
|
+
readonly cfg?: RouterConfig | undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface RouteOutcome {
|
|
103
|
+
readonly mode: "static" | "shadow" | "advise" | "enforce";
|
|
104
|
+
/** The prompt without its first-line `[route …]`; only when something was stripped. */
|
|
105
|
+
readonly prompt?: string;
|
|
106
|
+
/** `enforce`: the agent to dispatch instead (never for a pinned dispatch). */
|
|
107
|
+
readonly agent?: string;
|
|
108
|
+
/** `enforce`: `provider/model[#variant]` to dispatch with. */
|
|
109
|
+
readonly model?: string;
|
|
110
|
+
readonly decisionID?: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Titles of the runner's own children (`description` of `v2-client.ts`: `Router <agent> delegation`, `Router result
|
|
117
|
+
* verification`): a `session.created` carrying one is the runner's, never an orchestrator dispatch's.
|
|
118
|
+
*/
|
|
119
|
+
const RUNNER_CHILD_TITLE = /^Router (?:.+ delegation|result verification)$/;
|
|
120
|
+
|
|
121
|
+
export interface DispatchRouter {
|
|
122
|
+
/** Decide one `subagent` call. Writes and registers nothing: `commit` writes its decision row and registers it. Never throws. */
|
|
123
|
+
route(call: RouteCall): Promise<RouteOutcome>;
|
|
124
|
+
/**
|
|
125
|
+
* The input the host is about to execute (`event.input` after the legacy hook ran): write the call's decision row, then register the
|
|
126
|
+
* dispatch from it. A call `route()` did not act on is ignored. Never throws.
|
|
127
|
+
*/
|
|
128
|
+
commit(callID: string, input: unknown): void;
|
|
129
|
+
/** A `session.created` event: claim the waiting dispatch of this child, if there is one. Never throws. */
|
|
130
|
+
onSessionCreated(created: { readonly sessionID: unknown; readonly parentID: unknown; readonly agent: unknown; readonly title: unknown }): void;
|
|
131
|
+
/** `execute.after`: the call's result names the child (or `null`). Registers/corrects, then forgets the call. Never throws. */
|
|
132
|
+
onCallResult(callID: string, childSessionID: string | null): void;
|
|
133
|
+
/** The call ended without a result, or its hook chain failed: forget it. */
|
|
134
|
+
onCallFinished(callID: string): void;
|
|
135
|
+
/** Dispatches still waiting to be claimed (diagnostics, tests). */
|
|
136
|
+
pendingCount(): number;
|
|
137
|
+
/** Children registered by a wrong heuristic claim and not yet taken over by their own dispatch (diagnostics, tests). */
|
|
138
|
+
misclaimedCount(): number;
|
|
139
|
+
/** This instance is gone: it no longer owns any session directory. Idempotent. */
|
|
140
|
+
dispose(): void;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface DispatchRouterDeps {
|
|
144
|
+
readonly runtime: EngineRuntime;
|
|
145
|
+
/** `ctx.session.get({ sessionID })`. */
|
|
146
|
+
readonly getSession: (sessionID: string) => Promise<unknown>;
|
|
147
|
+
/** The adapter's own grader agent id: never routed. */
|
|
148
|
+
readonly graderAgent: string;
|
|
149
|
+
/** The default directory of the plugin instance (fallback `cwd` of the classifier). */
|
|
150
|
+
readonly directory: string;
|
|
151
|
+
readonly logger: WireLogger;
|
|
152
|
+
readonly now?: () => number;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** What `route()` decided, until `commit()` has the final input. */
|
|
156
|
+
interface Decided {
|
|
157
|
+
readonly parentSessionID: string;
|
|
158
|
+
readonly decisionID: string;
|
|
159
|
+
readonly facts: DecisionRow["facts"];
|
|
160
|
+
readonly acceptance: DetectionDepth;
|
|
161
|
+
readonly description: string | null;
|
|
162
|
+
/**
|
|
163
|
+
* QA-G-A2: the decision row, written by `commit()` — i.e. only for a dispatch whose hook chain let it through to the host. A call the
|
|
164
|
+
* legacy hook rejects (`onCallFinished`) never writes it. Known limit: a call the HOST then fails (`onCallResult` with no child for a
|
|
165
|
+
* fresh dispatch) keeps its row; no retraction row is written.
|
|
166
|
+
*/
|
|
167
|
+
readonly row: DecisionRow;
|
|
168
|
+
/** Appends a row to the decision log (`Prepared.enqueue` of the call). */
|
|
169
|
+
readonly enqueue: (row: DecisionRow) => void;
|
|
170
|
+
/** A34 (QA-G-B8): the capability rank of what the host is handed (`row.capability.dispatched`); `null` = unknown. */
|
|
171
|
+
readonly capabilityOf: (ran: RanDispatch) => number | null;
|
|
172
|
+
/** What the engine dispatches: the fallback for what the final input leaves out. `null`: the pick resolved to no model (row only). */
|
|
173
|
+
readonly final: { readonly agent: string; readonly model: string; readonly variant: string | null } | null;
|
|
174
|
+
/** The agent the orchestrator NAMED for this dispatch, before the router changed anything: recorded with the child (QA-2.4-R3-1). */
|
|
175
|
+
readonly picked: string;
|
|
176
|
+
readonly routerIds: readonly string[];
|
|
177
|
+
/** Resolve an agent the legacy hook switched to (the same resolution the engine used for the pick). */
|
|
178
|
+
readonly resolve: (agent: string) => ChosenDispatch | null;
|
|
179
|
+
readonly at: number;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A committed dispatch, kept until its call ends. */
|
|
183
|
+
interface Entry {
|
|
184
|
+
readonly callID: string;
|
|
185
|
+
readonly parentSessionID: string;
|
|
186
|
+
readonly agent: string;
|
|
187
|
+
readonly description: string | null;
|
|
188
|
+
readonly input: DispatchInput;
|
|
189
|
+
readonly at: number;
|
|
190
|
+
/** A resume: the child it was registered under, and what the registry held for it before (QA-2.2-R2-1). */
|
|
191
|
+
readonly resumeID?: string;
|
|
192
|
+
readonly previous?: DispatchRecord;
|
|
193
|
+
/** `waiting`: no child yet; `claimed`: a `session.created` was matched to it; `resumed`: registered at commit. */
|
|
194
|
+
state: "waiting" | "claimed" | "resumed";
|
|
195
|
+
claimedChild?: string;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* A3: every plugin instance of the process may be handed the same hook event. The first instance whose engine is live
|
|
200
|
+
* claims the call; the others leave it alone (the first one already routed, logged and will register it).
|
|
201
|
+
*/
|
|
202
|
+
const handledCalls = new Set<string>();
|
|
203
|
+
|
|
204
|
+
function claimCall(key: string): boolean {
|
|
205
|
+
if (handledCalls.has(key)) return false;
|
|
206
|
+
handledCalls.add(key);
|
|
207
|
+
while (handledCalls.size > MAX_HANDLED_CALLS) handledCalls.delete(handledCalls.values().next().value as string);
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Test-only: forget which calls were handled. */
|
|
212
|
+
export function resetDispatchRouting(): void {
|
|
213
|
+
handledCalls.clear();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
217
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function describeError(error: unknown): string {
|
|
221
|
+
return error instanceof Error ? error.message : String(error);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function str(value: unknown): string | null {
|
|
225
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The child session a finished `subagent` call names (`result.output.sessionID`, else `result.metadata.sessionID`; spike S1). */
|
|
229
|
+
export function childSessionOf(result: unknown): string | null {
|
|
230
|
+
if (!isRecord(result)) return null;
|
|
231
|
+
const output = result.output;
|
|
232
|
+
const fromOutput = isRecord(output) ? str(output.sessionID) : null;
|
|
233
|
+
if (fromOutput !== null) return fromOutput;
|
|
234
|
+
return isRecord(result.metadata) ? str(result.metadata.sessionID) : null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
interface SessionView {
|
|
238
|
+
readonly parentID: string | null;
|
|
239
|
+
readonly agent: string | null;
|
|
240
|
+
readonly model: string | null;
|
|
241
|
+
readonly directory: string | null;
|
|
242
|
+
readonly rules: ReturnType<typeof sessionRulesOf>;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function readSession(raw: unknown): SessionView {
|
|
246
|
+
const session = isRecord(raw) ? raw : {};
|
|
247
|
+
const location = isRecord(session.location) ? session.location : {};
|
|
248
|
+
return {
|
|
249
|
+
parentID: str(session.parentID),
|
|
250
|
+
agent: str(session.agent),
|
|
251
|
+
model: agentModelRef(session.model),
|
|
252
|
+
directory: str(location.directory),
|
|
253
|
+
rules: sessionRulesOf(session),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The row's `facts` (1.3's structural view of `TaskFacts`). */
|
|
258
|
+
function factsOf(facts: TaskFacts): DecisionRow["facts"] {
|
|
259
|
+
return { class: facts.class, risk: facts.risk, scope: facts.scope, needs: [...facts.needs], confidence: facts.confidence, source: facts.source };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function traceOf(result: ClassifyResult, argmin: RouteChoice | null): DecisionTrace {
|
|
263
|
+
const { routeLines, backend, backendSkipped } = result.trace;
|
|
264
|
+
return {
|
|
265
|
+
routeLines: { count: routeLines.count, conflict: routeLines.conflict, edgeOnly: routeLines.edgeOnly },
|
|
266
|
+
backend: backend === null
|
|
267
|
+
? null
|
|
268
|
+
: {
|
|
269
|
+
id: backend.id,
|
|
270
|
+
status: backend.status,
|
|
271
|
+
latencyMs: backend.latencyMs,
|
|
272
|
+
...(backend.label === undefined ? {} : { label: backend.label }),
|
|
273
|
+
...(backend.rejected === true ? { rejected: true as const } : {}),
|
|
274
|
+
...(backend.disagrees === true ? { disagrees: true as const } : {}),
|
|
275
|
+
},
|
|
276
|
+
...(backendSkipped === undefined ? {} : { backendSkipped }),
|
|
277
|
+
...(argmin === null ? {} : { argmin }),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function choiceOf(cls: string, dispatch: ChosenDispatch): RouteChoice {
|
|
282
|
+
const key = candidateKey(cls, dispatch);
|
|
283
|
+
return { key, agent: dispatch.agent.id, origin: dispatch.agent.origin, model: dispatch.model, variant: normalizeVariant(dispatch.variant) };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** `provider/model[#variant]`. */
|
|
287
|
+
function refOf(model: string, variant: string | null): string {
|
|
288
|
+
return variant === null || variant === "" || variant === "default" ? model : `${model}#${variant}`;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function depthOf(detection: string): DetectionDepth {
|
|
292
|
+
return detection === "deterministic" || detection === "grader" ? detection : "none";
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The row's reason for the kernel's decision: its reason CODE, then the kernel's text without the leading word the text carries itself
|
|
297
|
+
* (`kept: …`, `switched: …`), so a row reads `switched: C(best)=…` and `kept:best-is-chosen: the chosen dispatch …`, not `switched: switched: …` /
|
|
298
|
+
* `kept:best-is-chosen: kept: …` (QA-3.2-12). The code stays the first token: `routing:stats` reads `kept:evidence` and `lift:floor` by prefix.
|
|
299
|
+
*/
|
|
300
|
+
function reasonText(decision: Pick<Decision, "reasonCode" | "reason">): string {
|
|
301
|
+
return `${decision.reasonCode}: ${decision.reason.replace(/^(?:kept|switched): /, "")}`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** A pick the engine cannot resolve to a model: logged as kept, never priced (1.4 handoff). */
|
|
305
|
+
function unresolvedChoice(cls: string, agent: string, routerIds: readonly string[]): RouteChoice {
|
|
306
|
+
const origin = classifyAgentOrigin(agent, routerIds);
|
|
307
|
+
return { key: makeKey(cls, { origin, id: agent }, "", "", null), agent, origin, model: "unknown/unknown", variant: "default" };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** What the host runs for a committed call: agent, `provider/model` and variant. */
|
|
311
|
+
interface RanDispatch {
|
|
312
|
+
readonly agent: string;
|
|
313
|
+
readonly model: string;
|
|
314
|
+
readonly variant: string | null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Same `provider/model` (a `#variant` suffix split off) and the same normalized variant. */
|
|
318
|
+
function sameModelVariant(a: { readonly model: string; readonly variant: string | null }, b: { readonly model: string; readonly variant: string | null }): boolean {
|
|
319
|
+
const left = splitModelRef(a.model);
|
|
320
|
+
const right = splitModelRef(b.model);
|
|
321
|
+
const modelOf = (ref: ReturnType<typeof splitModelRef>, raw: string): string => (ref === null ? raw : `${ref.provider}/${ref.model}`);
|
|
322
|
+
return modelOf(left, a.model) === modelOf(right, b.model)
|
|
323
|
+
&& normalizeVariant(a.variant ?? left?.variant ?? null) === normalizeVariant(b.variant ?? right?.variant ?? null);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* What the host will run for a committed call: the final input's agent and `model` win over what the engine decided (the legacy hook
|
|
328
|
+
* runs after the engine); a model the final input leaves out is the engine's (same agent) or the resolved one (another agent). `null`
|
|
329
|
+
* when it cannot be told (an unparseable `model`, an agent that resolves to no model).
|
|
330
|
+
*/
|
|
331
|
+
function ranOf(
|
|
332
|
+
d: Pick<Decided, "resolve">,
|
|
333
|
+
decidedFinal: NonNullable<Decided["final"]>,
|
|
334
|
+
final: Readonly<Record<string, unknown>>,
|
|
335
|
+
): RanDispatch | null {
|
|
336
|
+
const agent = str(final.agent) ?? decidedFinal.agent;
|
|
337
|
+
const ref = str(final.model);
|
|
338
|
+
if (ref !== null) {
|
|
339
|
+
const parts = splitModelRef(ref);
|
|
340
|
+
return parts === null ? null : { agent, model: `${parts.provider}/${parts.model}`, variant: parts.variant };
|
|
341
|
+
}
|
|
342
|
+
if (agent === decidedFinal.agent) return { agent, model: decidedFinal.model, variant: decidedFinal.variant };
|
|
343
|
+
const resolved = d.resolve(agent);
|
|
344
|
+
return resolved === null ? null : { agent, model: resolved.model, variant: resolved.variant };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
348
|
+
const now = deps.now ?? (() => Date.now());
|
|
349
|
+
const instanceNonce = randomBytes(8).toString("hex");
|
|
350
|
+
/** Between `route()` and `commit()`. */
|
|
351
|
+
const decided = new Map<string, Decided>();
|
|
352
|
+
/** Committed dispatches, in insertion order, until their call ends. */
|
|
353
|
+
const entries = new Map<string, Entry>();
|
|
354
|
+
/**
|
|
355
|
+
* QA-2.2-R2-7: children registered under a dispatch by a heuristic claim that the dispatch's own result then disowned (child →
|
|
356
|
+
* the wrong dispatch's decision). They stay registered (their steps keep being counted, under the wrong facts) until the
|
|
357
|
+
* result of the dispatch that really started them takes them over.
|
|
358
|
+
*/
|
|
359
|
+
const misclaimed = new Map<string, string>();
|
|
360
|
+
let sequence = 0;
|
|
361
|
+
|
|
362
|
+
const trim = <T>(map: Map<string, T>, limit: number): void => {
|
|
363
|
+
while (map.size > limit) map.delete(map.keys().next().value as string);
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
const sweep = (t: number): void => {
|
|
367
|
+
for (const [callID, entry] of entries) {
|
|
368
|
+
if (t - entry.at >= ENTRY_TTL_MS) entries.delete(callID);
|
|
369
|
+
}
|
|
370
|
+
trim(entries, MAX_PENDING);
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* QA-2.2-R2-1: the call of a resume ended without a result (the host rejected it after the hooks ran). Its registration was
|
|
375
|
+
* made for an execution that never started: drop it, and put back what the registry held for the child before, so a live
|
|
376
|
+
* child keeps its facts and its attempt id (what the registry had observed of the execution cannot be restored).
|
|
377
|
+
*/
|
|
378
|
+
const undoResume = (entry: Entry): void => {
|
|
379
|
+
if (entry.state !== "resumed" || entry.resumeID === undefined) return;
|
|
380
|
+
if (lookupDispatch(entry.resumeID)?.decisionID !== entry.input.decisionID) return; // someone registered it since: theirs
|
|
381
|
+
const before = entry.previous;
|
|
382
|
+
if (before === undefined) {
|
|
383
|
+
forgetDispatch(entry.resumeID);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
register(entry.resumeID, {
|
|
387
|
+
facts: before.facts, agent: before.agent, model: before.model, variant: before.variant, tier: before.tier, acceptance: before.acceptance,
|
|
388
|
+
parentSessionID: before.parentSessionID, attemptId: before.attemptId, decisionID: before.decisionID, step: before.step,
|
|
389
|
+
outcomes: before.outcomes, picked: before.picked, keepExecution: true,
|
|
390
|
+
});
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
const claimable = (entry: Entry, t: number): boolean => entry.state === "waiting" && t - entry.at < PENDING_TTL_MS;
|
|
394
|
+
|
|
395
|
+
const register = (childSessionID: string, input: DispatchInput): void => {
|
|
396
|
+
try {
|
|
397
|
+
rememberDispatch(childSessionID, input, now());
|
|
398
|
+
} catch (error) {
|
|
399
|
+
deps.logger.warn("[router] routing: the dispatch could not be registered for ingestion", { error: describeError(error) });
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* The orchestrator's pick lifted to `floorTier` (handoff 1.4, QA-1.4-17): `enforce` starts the dispatch on
|
|
405
|
+
* `max(pick, floor)`, so the row prices what runs. Only router tiers have a rank; a host agent is never lifted. The floor
|
|
406
|
+
* tier must be startable by the parent AND cover the task's needs (QA-2.2-7): a lift must not send a shell task to an
|
|
407
|
+
* agent without a shell.
|
|
408
|
+
*/
|
|
409
|
+
const floorLift = (prepared: Prepared, chosen: ChosenDispatch, infos: readonly HostAgentInfo[] | null, facts: TaskFacts): ChosenDispatch | null => {
|
|
410
|
+
const floorRank = floorRankOf(prepared.cfg);
|
|
411
|
+
if (floorRank === null || chosen.agent.origin !== "router") return null;
|
|
412
|
+
const rank = tierRankOf(prepared.cfg, chosen.agent.id);
|
|
413
|
+
if (rank === null || rank >= floorRank) return null;
|
|
414
|
+
const floorTier = escalateLadder(prepared.cfg)[floorRank];
|
|
415
|
+
if (floorTier === undefined) return null;
|
|
416
|
+
const lifted = resolveChosen({ cfg: prepared.cfg, agents: infos, agent: floorTier });
|
|
417
|
+
const info = infos?.find((agent) => agent.id === floorTier);
|
|
418
|
+
if (lifted === null || info === undefined) return null;
|
|
419
|
+
if (!info.permitted || info.mode === "primary" || info.hidden) return null;
|
|
420
|
+
return coversNeeds(info.grants, facts.needs) ? lifted : null;
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* A30 as amended (QA-2.4-R3-1): the host switches a resumed child to the agent the resume NAMES when it differs from the one the child
|
|
425
|
+
* runs (`switchAgent` in the host's subagent tool: the child's model becomes that agent's). An orchestrator that resumes a child
|
|
426
|
+
* with its own original pick of a child the router moved (floor lift, evidence switch) would move it back below where the router put
|
|
427
|
+
* it. What the child runs, when that is the case: the resume names the pick the child was dispatched under, the child runs another
|
|
428
|
+
* agent, and it is this orchestrator's child.
|
|
429
|
+
*/
|
|
430
|
+
const runningAfterRouter = (resumeID: string, parentSessionID: string, named: string): { agent: string; model: string; variant: string | null } | null => {
|
|
431
|
+
const record = lookupDispatch(resumeID);
|
|
432
|
+
if (record === undefined || record.parentSessionID !== parentSessionID) return null;
|
|
433
|
+
if (record.picked === null || record.picked !== named || record.agent === named || record.model === null) return null;
|
|
434
|
+
return { agent: record.agent, model: record.model, variant: record.variant };
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* A34 (QA-G-B3): may the A30 rewrite send this resume to the agent the child runs? Only when that agent is still startable by the
|
|
439
|
+
* parent and its EVALUATED permissions cover the resume's own `needs` (A11: the resume may ask for more than the first dispatch did),
|
|
440
|
+
* and, on high-risk work without detection (D9 never-down), when it is not below the named pick's capability rank — nor the pick's own
|
|
441
|
+
* model on a lower variant at that rank. Unknown agent info or an unknown capability is a refusal: the resume is then sent as named,
|
|
442
|
+
* which is the orchestrator's own pick and so never a move down. `null` = the rewrite is allowed.
|
|
443
|
+
*/
|
|
444
|
+
const runningRefusal = (
|
|
445
|
+
running: { readonly agent: string; readonly model: string; readonly variant: string | null },
|
|
446
|
+
named: ChosenDispatch,
|
|
447
|
+
namedRank: number | null,
|
|
448
|
+
ladder: Ladder,
|
|
449
|
+
infos: readonly HostAgentInfo[] | null,
|
|
450
|
+
facts: TaskFacts,
|
|
451
|
+
detection: Detection,
|
|
452
|
+
): "needs" | "never-down" | null => {
|
|
453
|
+
const info = infos?.find((candidate) => candidate.id === running.agent);
|
|
454
|
+
if (info === undefined || !info.permitted || info.mode === "primary" || info.hidden || !coversNeeds(info.grants, facts.needs)) return "needs";
|
|
455
|
+
if (facts.risk !== "high" || detection !== "none") return null;
|
|
456
|
+
const pickRank = capabilityRank(ladder, named, namedRank);
|
|
457
|
+
const runRank = capabilityRank(ladder, running, null);
|
|
458
|
+
if (pickRank === null || runRank === null || runRank < pickRank) return "never-down";
|
|
459
|
+
return runRank === pickRank && lowerEffortOnSameModel(running, named) ? "never-down" : null;
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
const decideAndRecord = async (call: RouteCall, prepared: Prepared, session: SessionView, view: AgentView | null): Promise<RouteOutcome> => {
|
|
463
|
+
const { args } = call;
|
|
464
|
+
const agent = str(args.agent);
|
|
465
|
+
const prompt = typeof args.prompt === "string" ? args.prompt : null;
|
|
466
|
+
if (agent === null || prompt === null) return UNTOUCHED;
|
|
467
|
+
const mode = prepared.settings.engine;
|
|
468
|
+
const infos = view === null ? null : view.infos;
|
|
469
|
+
const routerIds = routerTierIds(prepared.cfg);
|
|
470
|
+
|
|
471
|
+
const result = await classify(
|
|
472
|
+
{ description: typeof args.description === "string" ? args.description : "", prompt, cwd: session.directory ?? deps.directory },
|
|
473
|
+
deps.runtime.classifyDeps(prepared),
|
|
474
|
+
);
|
|
475
|
+
const facts = result.facts;
|
|
476
|
+
// A34 (QA-G-B2): the weaker of the route line's `d=` claim and the prompt's own `[acceptance]` block. Detection is the only
|
|
477
|
+
// field a route line could use to WEAKEN a safety rule (D9 never-down holds for `d == none`), so a claim never raises it.
|
|
478
|
+
const detection = weakerDetection(result.detection, detectionOf(prompt));
|
|
479
|
+
const pin = result.pin;
|
|
480
|
+
// `classify` removes only the first-line route line and returns every other byte unchanged (probe, QA-2.2-5).
|
|
481
|
+
const stripped = result.stripped !== prompt ? result.stripped : undefined;
|
|
482
|
+
const callModel = str(args.model) ?? call.tierModel ?? null;
|
|
483
|
+
const resumeID = str(args.sessionID);
|
|
484
|
+
const decisionID = `${call.sessionID}:${safeNow(now)}:${instanceNonce}:${++sequence}`;
|
|
485
|
+
|
|
486
|
+
const chosen = resolveChosen({ cfg: prepared.cfg, agents: infos, agent, model: callModel, parentModel: session.model });
|
|
487
|
+
let decision: Decision | null = null;
|
|
488
|
+
let argmin: RouteChoice | null = null; // A27: the cheapest option the evidence filter removed, when it did
|
|
489
|
+
let row: Pick<DecisionRow, "chosen" | "best" | "switched" | "pinned" | "unit" | "costs" | "confidence" | "reason">;
|
|
490
|
+
let final: { agent: string; model: string; variant: string | null } | null = null;
|
|
491
|
+
let outcome: RouteOutcome = { mode, ...(stripped === undefined ? {} : { prompt: stripped }), decisionID };
|
|
492
|
+
// A34 (QA-G-B8): the pick's capability rank for the row, and how to rank what the host is finally handed (at `commit`).
|
|
493
|
+
let pickCapability: number | null = null;
|
|
494
|
+
let capabilityOf: (ran: RanDispatch) => number | null = () => null;
|
|
495
|
+
|
|
496
|
+
if (chosen === null) {
|
|
497
|
+
row = {
|
|
498
|
+
chosen: unresolvedChoice(facts.class, agent, routerIds),
|
|
499
|
+
best: null, switched: false, pinned: pin, unit: "ratio", costs: {}, confidence: 0,
|
|
500
|
+
reason: "kept:unresolved: the dispatched agent resolves to no model, so nothing could be priced",
|
|
501
|
+
};
|
|
502
|
+
} else {
|
|
503
|
+
const ladder = buildLadder({
|
|
504
|
+
cfg: prepared.cfg,
|
|
505
|
+
routing: prepared.routing,
|
|
506
|
+
facts,
|
|
507
|
+
agents: infos,
|
|
508
|
+
pricing: (model) => prepared.catalog.pricing(model),
|
|
509
|
+
parentModel: session.model,
|
|
510
|
+
logger: deps.logger,
|
|
511
|
+
session: prepared.session,
|
|
512
|
+
});
|
|
513
|
+
decision = decide({
|
|
514
|
+
facts, chosen, ladder, detection, pin, routing: prepared.routing, store: prepared.store, floorRank: floorRankOf(prepared.cfg),
|
|
515
|
+
});
|
|
516
|
+
argmin = decision.argmin !== null && decision.argmin.key !== decision.best?.key ? decision.argmin : null;
|
|
517
|
+
const pickRank = decision.pickRank ?? capabilityRank(ladder, chosen, null);
|
|
518
|
+
pickCapability = pickRank;
|
|
519
|
+
capabilityOf = (ran) => {
|
|
520
|
+
// The pick itself ranks as the pick (its candidate rank included); anything else by its model, never below its candidate rank.
|
|
521
|
+
if (ran.agent === agent && sameModelVariant(ran, chosen)) return pickRank;
|
|
522
|
+
const candidate = ladder.candidates.find((c) => c.agent.id === ran.agent && sameModelVariant(c, ran));
|
|
523
|
+
return capabilityRank(ladder, ran, candidate?.rank ?? null);
|
|
524
|
+
};
|
|
525
|
+
// A30 (QA-2.4-R2-3): a dispatch that resumes an existing child (`task_id`/`sessionID`) is never switched by the engine, in any mode:
|
|
526
|
+
// the kernel's decision is still logged (best, costs, its own reason), but `switched` is false and the reason code is `kept:resume`.
|
|
527
|
+
const resuming = resumeID !== null;
|
|
528
|
+
// QA-2.4-R3-1 (A30 amended): the router never moves a child from where it runs. A resume that repeats the orchestrator's original
|
|
529
|
+
// pick of a child the router moved is sent to the agent/model the child runs (`enforce`; the other modes only say so in the row).
|
|
530
|
+
const moved = resumeID === null ? null : runningAfterRouter(resumeID, call.sessionID, agent);
|
|
531
|
+
// A34 (QA-G-B3): the rewrite must neither send the resume to an agent that cannot do the resumed work (needs, permission) nor move
|
|
532
|
+
// it below the named pick on high-risk work without detection (D9 never-down). Refused: the resume is sent as named (and floor-lifted).
|
|
533
|
+
const refusal = moved === null || decision.pinned
|
|
534
|
+
? null
|
|
535
|
+
: runningRefusal(moved, chosen, decision.pickRank, ladder, infos, facts, detection);
|
|
536
|
+
const running = refusal === null ? moved : null;
|
|
537
|
+
row = {
|
|
538
|
+
chosen: decision.chosen, best: decision.best, switched: resuming ? false : decision.switched, pinned: decision.pinned,
|
|
539
|
+
unit: decision.unit, costs: { ...decision.costs }, confidence: decision.confidence,
|
|
540
|
+
reason: moved !== null
|
|
541
|
+
? decision.pinned
|
|
542
|
+
// A pinned resume is sent as named (`kept:resume:pinned`): it was NOT rewritten, so the row must not claim it was.
|
|
543
|
+
? `${RESUME_PINNED_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; pinned, so it is sent as named and NOT rewritten (the host moves the child to @${agent}); engine decision: ${reasonText(decision)}`
|
|
544
|
+
: refusal === "needs"
|
|
545
|
+
? `${RESUME_NAMED_NEEDS_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; @${moved.agent} is not startable or its permissions do not cover needs [${facts.needs.join(",")}], so it is sent as named and NOT rewritten (the host moves the child to @${agent}) (A34); engine decision: ${reasonText(decision)}`
|
|
546
|
+
: refusal === "never-down"
|
|
547
|
+
? `${RESUME_NAMED_NEVER_DOWN_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; @${moved.agent} is below the pick's capability on high-risk work without detection (D9 never down), so it is sent as named and NOT rewritten (the host moves the child to @${agent}) (A34); engine decision: ${reasonText(decision)}`
|
|
548
|
+
: `${RESUME_RUNNING_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; ${mode === "enforce" ? "sent to @" + moved.agent + " so the host does not switch it back (A30)" : "would be sent to @" + moved.agent + " (not applied in " + mode + ") so the host does not switch it back (A30)"}; engine decision: ${reasonText(decision)}`
|
|
549
|
+
: resuming
|
|
550
|
+
? `${RESUME_REASON}: a dispatch that resumes an existing child is never switched by the engine (A30); engine decision: ${reasonText(decision)}`
|
|
551
|
+
: reasonText(decision),
|
|
552
|
+
};
|
|
553
|
+
final = { agent, model: chosen.model, variant: chosen.variant };
|
|
554
|
+
|
|
555
|
+
if (mode === "enforce" && !decision.pinned && running !== null) {
|
|
556
|
+
outcome = { ...outcome, agent: running.agent, model: refOf(running.model, running.variant) };
|
|
557
|
+
final = { agent: running.agent, model: running.model, variant: running.variant };
|
|
558
|
+
} else if (mode === "enforce" && !decision.pinned && resuming) {
|
|
559
|
+
// A resume naming an agent other than the one the child runs, and other than the pick it was dispatched under, is the
|
|
560
|
+
// orchestrator's choice: honoured, never below the floor. Without a record of the child nothing is known to move.
|
|
561
|
+
const record = lookupDispatch(resumeID);
|
|
562
|
+
const lifted = record !== undefined && record.parentSessionID === call.sessionID && record.agent !== agent ? floorLift(prepared, chosen, infos, facts) : null;
|
|
563
|
+
if (lifted !== null) {
|
|
564
|
+
outcome = { ...outcome, agent: lifted.agent.id, model: refOf(lifted.model, lifted.variant) };
|
|
565
|
+
final = { agent: lifted.agent.id, model: lifted.model, variant: lifted.variant };
|
|
566
|
+
row = {
|
|
567
|
+
...row,
|
|
568
|
+
best: choiceOf(facts.class, lifted),
|
|
569
|
+
switched: true,
|
|
570
|
+
reason: `${FLOOR_LIFT_REASON}: resume lifted from @${agent} to @${lifted.agent.id} by enforcement.escalate.floorTier (the child runs @${record?.agent ?? "?"}); engine decision: ${row.reason}`,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
} else if (mode === "enforce" && !decision.pinned) {
|
|
574
|
+
if (decision.switched && decision.target !== null) {
|
|
575
|
+
const target = decision.target;
|
|
576
|
+
outcome = { ...outcome, agent: target.agent.id, model: refOf(target.model, target.variant) };
|
|
577
|
+
final = { agent: target.agent.id, model: target.model, variant: target.variant };
|
|
578
|
+
} else {
|
|
579
|
+
const lifted = floorLift(prepared, chosen, infos, facts);
|
|
580
|
+
if (lifted !== null) {
|
|
581
|
+
outcome = { ...outcome, agent: lifted.agent.id, model: refOf(lifted.model, lifted.variant) };
|
|
582
|
+
final = { agent: lifted.agent.id, model: lifted.model, variant: lifted.variant };
|
|
583
|
+
row = {
|
|
584
|
+
...row,
|
|
585
|
+
best: choiceOf(facts.class, lifted),
|
|
586
|
+
switched: true,
|
|
587
|
+
// Its own reason code (QA-2.2-7): a floor lift is policy, not an evidence-based switch; D17 does not count it.
|
|
588
|
+
reason: `${FLOOR_LIFT_REASON}: dispatch lifted from @${agent} to @${lifted.agent.id} by enforcement.escalate.floorTier; engine decision: ${row.reason}`,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const decisionRow: DecisionRow = {
|
|
596
|
+
v: LOG_ROW_VERSION,
|
|
597
|
+
ts: new Date(safeNow(now)).toISOString(),
|
|
598
|
+
sessionID: call.sessionID,
|
|
599
|
+
kind: "decision",
|
|
600
|
+
decisionID,
|
|
601
|
+
mode,
|
|
602
|
+
childSessionID: resumeID,
|
|
603
|
+
facts: factsOf(facts),
|
|
604
|
+
...row,
|
|
605
|
+
step: "dispatch",
|
|
606
|
+
resume: resumeID !== null,
|
|
607
|
+
trace: traceOf(result, argmin),
|
|
608
|
+
// A34 (QA-G-B8): the detection decided with, and the route line's claim when the prompt did not back it.
|
|
609
|
+
detection: {
|
|
610
|
+
effective: detection,
|
|
611
|
+
...(result.detection !== undefined && result.detection !== null && result.detection !== detection ? { claimed: result.detection } : {}),
|
|
612
|
+
},
|
|
613
|
+
capability: { pick: pickCapability, dispatched: null }, // `dispatched` is filled in by `commit()` from the final input
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
// QA-G-A2: the row waits for `commit()`, so a call whose hook chain rejects it (`onCallFinished`) never writes one.
|
|
617
|
+
decided.set(call.callID, {
|
|
618
|
+
parentSessionID: call.sessionID,
|
|
619
|
+
decisionID,
|
|
620
|
+
facts: factsOf(facts),
|
|
621
|
+
acceptance: depthOf(detection),
|
|
622
|
+
description: typeof args.description === "string" && args.description !== "" ? args.description : null,
|
|
623
|
+
row: decisionRow,
|
|
624
|
+
enqueue: (logged) => prepared.enqueue(logged),
|
|
625
|
+
capabilityOf,
|
|
626
|
+
final,
|
|
627
|
+
routerIds,
|
|
628
|
+
resolve: (target) => resolveChosen({ cfg: prepared.cfg, agents: infos, agent: target, parentModel: session.model }),
|
|
629
|
+
picked: agent,
|
|
630
|
+
at: now(),
|
|
631
|
+
});
|
|
632
|
+
trim(decided, MAX_PENDING);
|
|
633
|
+
return outcome;
|
|
634
|
+
};
|
|
635
|
+
|
|
636
|
+
return {
|
|
637
|
+
async route(call): Promise<RouteOutcome> {
|
|
638
|
+
try {
|
|
639
|
+
const agent = str(call.args.agent);
|
|
640
|
+
const callKey = `${call.sessionID}\u0000${call.callID}`;
|
|
641
|
+
// QA-2.2-1 / QA-INT-1: a call the delegate runner announced is the runner's alone. Only a call that carries the runner's own
|
|
642
|
+
// description can be one (an orchestrator dispatch with the same agent and prompt never spends the runner's mark); if the
|
|
643
|
+
// prompt is not the announced one (rewritten by another plugin) a runner-titled call still finds its mark by session and
|
|
644
|
+
// agent. The call is then marked handled, so no other instance of this process (A3) routes it either.
|
|
645
|
+
if (agent !== null && typeof call.args.prompt === "string"
|
|
646
|
+
&& call.args.description === runnerDescription(agent === deps.graderAgent ? undefined : agent)) {
|
|
647
|
+
const exact = consumeRunnerDispatch({ parentSessionID: call.sessionID, agent, prompt: call.args.prompt });
|
|
648
|
+
if (exact || consumeRunnerDispatchLoose({ parentSessionID: call.sessionID, agent })) {
|
|
649
|
+
if (!exact) deps.logger.warn("[router] routing: a runner call arrived with another prompt than the one it announced (rewritten by another plugin?); it was left alone", { agent });
|
|
650
|
+
claimCall(callKey);
|
|
651
|
+
return UNTOUCHED;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
if (agent === null || agent === deps.graderAgent) return UNTOUCHED;
|
|
655
|
+
const prepared = await deps.runtime.prepare(call.cfg);
|
|
656
|
+
if (prepared === null) return UNTOUCHED; // static: nothing touched
|
|
657
|
+
if (handledCalls.has(callKey)) return UNTOUCHED; // A3 (QA-2.2-12): another instance already acted on this call
|
|
658
|
+
let session: SessionView;
|
|
659
|
+
try {
|
|
660
|
+
session = readSession(await deps.getSession(call.sessionID));
|
|
661
|
+
} catch (error) {
|
|
662
|
+
deps.logger.warn("[router] routing: the dispatching session is unavailable; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
|
|
663
|
+
return UNTOUCHED;
|
|
664
|
+
}
|
|
665
|
+
// QA-G-A6: only the session location receives tool hooks on measured hosts. Never defer to an instance that
|
|
666
|
+
// may receive no hook; the process-wide call claim below remains the single-writer guard.
|
|
667
|
+
if (!claimCall(callKey)) return UNTOUCHED;
|
|
668
|
+
// Only an orchestrator's own prompt is parsed (QA focus: a delegate must not be able to pin or steer).
|
|
669
|
+
if (session.parentID !== null) return UNTOUCHED;
|
|
670
|
+
const view = await deps.runtime.agents(session.agent ?? call.agent, session.rules);
|
|
671
|
+
return await decideAndRecord(call, prepared, session, view);
|
|
672
|
+
} catch (error) {
|
|
673
|
+
deps.logger.warn("[router] routing: the engine failed; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
|
|
674
|
+
return UNTOUCHED;
|
|
675
|
+
}
|
|
676
|
+
},
|
|
677
|
+
|
|
678
|
+
commit(callID, input): void {
|
|
679
|
+
try {
|
|
680
|
+
const d = decided.get(callID);
|
|
681
|
+
if (d === undefined) return;
|
|
682
|
+
decided.delete(callID);
|
|
683
|
+
const final = isRecord(input) ? input : {};
|
|
684
|
+
// The agent and model the host will run, after the legacy hook: they win over what the engine decided.
|
|
685
|
+
const ran = d.final === null ? null : ranOf(d, d.final, final);
|
|
686
|
+
// QA-G-A2: the hook chain let the call through, so the dispatch runs: its decision row is written now (never for a rejected call).
|
|
687
|
+
try {
|
|
688
|
+
// A34 (QA-G-B8): the capability of what really runs, after the legacy hook.
|
|
689
|
+
const dispatched = ran === null ? null : d.capabilityOf(ran);
|
|
690
|
+
d.enqueue({ ...d.row, capability: { pick: d.row.capability?.pick ?? null, dispatched } });
|
|
691
|
+
} catch (error) {
|
|
692
|
+
deps.logger.warn("[router] routing: the decision row could not be queued", { error: describeError(error) });
|
|
693
|
+
}
|
|
694
|
+
if (ran === null) return; // nothing to record a step against
|
|
695
|
+
const { agent, model, variant } = ran;
|
|
696
|
+
const dispatched: DispatchInput = {
|
|
697
|
+
facts: d.facts,
|
|
698
|
+
agent,
|
|
699
|
+
model,
|
|
700
|
+
variant,
|
|
701
|
+
tier: classifyAgentOrigin(agent, d.routerIds) === "router" ? agent : null,
|
|
702
|
+
acceptance: d.acceptance,
|
|
703
|
+
parentSessionID: d.parentSessionID,
|
|
704
|
+
decisionID: d.decisionID,
|
|
705
|
+
step: "dispatch",
|
|
706
|
+
picked: d.picked,
|
|
707
|
+
};
|
|
708
|
+
const t = now();
|
|
709
|
+
sweep(t);
|
|
710
|
+
const resumeID = str(final.sessionID);
|
|
711
|
+
// QA-2.2-R2-1: remember what the registry held for a resumed child, in case the host then rejects the resume.
|
|
712
|
+
const previous = resumeID === null ? undefined : lookupDispatch(resumeID);
|
|
713
|
+
const entry: Entry = {
|
|
714
|
+
callID, parentSessionID: d.parentSessionID, agent, description: d.description, input: dispatched, at: t,
|
|
715
|
+
state: resumeID === null ? "waiting" : "resumed",
|
|
716
|
+
...(resumeID === null ? {} : { resumeID }),
|
|
717
|
+
...(previous === undefined ? {} : { previous }),
|
|
718
|
+
};
|
|
719
|
+
if (resumeID !== null) register(resumeID, dispatched);
|
|
720
|
+
entries.delete(callID);
|
|
721
|
+
entries.set(callID, entry);
|
|
722
|
+
trim(entries, MAX_PENDING);
|
|
723
|
+
} catch (error) {
|
|
724
|
+
deps.logger.warn("[router] routing: the dispatch could not be committed for ingestion", { error: describeError(error) });
|
|
725
|
+
}
|
|
726
|
+
},
|
|
727
|
+
|
|
728
|
+
onSessionCreated(created): void {
|
|
729
|
+
try {
|
|
730
|
+
const sessionID = str(created.sessionID);
|
|
731
|
+
const parentID = str(created.parentID);
|
|
732
|
+
if (sessionID === null || parentID === null || entries.size === 0) return;
|
|
733
|
+
// The runner registers its own children (and titles them `Router …`): never take one for an orchestrator dispatch.
|
|
734
|
+
if (lookupDispatch(sessionID) !== undefined) return;
|
|
735
|
+
const title = str(created.title);
|
|
736
|
+
if (title !== null && RUNNER_CHILD_TITLE.test(title)) return;
|
|
737
|
+
const t = now();
|
|
738
|
+
sweep(t);
|
|
739
|
+
const agent = str(created.agent);
|
|
740
|
+
const mine = [...entries.values()].filter((entry) => entry.parentSessionID === parentID && claimable(entry, t));
|
|
741
|
+
const sameAgent = agent === null ? mine : mine.filter((entry) => entry.agent === agent);
|
|
742
|
+
if (sameAgent.length === 0) return;
|
|
743
|
+
const claimed = (title === null ? undefined : sameAgent.find((entry) => entry.description === title)) ?? sameAgent[0];
|
|
744
|
+
if (claimed === undefined) return;
|
|
745
|
+
claimed.state = "claimed";
|
|
746
|
+
claimed.claimedChild = sessionID;
|
|
747
|
+
register(sessionID, claimed.input);
|
|
748
|
+
} catch (error) {
|
|
749
|
+
deps.logger.warn("[router] routing: a new child session could not be matched to its dispatch", { error: describeError(error) });
|
|
750
|
+
}
|
|
751
|
+
},
|
|
752
|
+
|
|
753
|
+
onCallResult(callID, childSessionID): void {
|
|
754
|
+
try {
|
|
755
|
+
decided.delete(callID);
|
|
756
|
+
const entry = entries.get(callID);
|
|
757
|
+
entries.delete(callID);
|
|
758
|
+
if (entry === undefined) return;
|
|
759
|
+
if (childSessionID === null) {
|
|
760
|
+
undoResume(entry); // the call ended without a result: a resume the host rejected leaves the child as it was
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (entry.state === "resumed") return;
|
|
764
|
+
// Still waiting (the event was missed, or the claim expired), or claimed for a different child: the result is the truth.
|
|
765
|
+
// The same execution, corrected or completed: keep what the registry has seen of it (QA-2.3-1a).
|
|
766
|
+
misclaimed.delete(childSessionID); // a child this dispatch really started is no longer anyone's wrong claim
|
|
767
|
+
if (lookupDispatch(childSessionID)?.decisionID !== entry.input.decisionID) register(childSessionID, { ...entry.input, keepExecution: true });
|
|
768
|
+
if (entry.state === "claimed" && entry.claimedChild !== undefined && entry.claimedChild !== childSessionID
|
|
769
|
+
&& lookupDispatch(entry.claimedChild)?.decisionID === entry.input.decisionID) {
|
|
770
|
+
// A wrong claim: that child belongs to another dispatch. It stays registered (its steps keep being counted) and is marked;
|
|
771
|
+
// the result of the dispatch that really started it takes it over (R2-7).
|
|
772
|
+
misclaimed.set(entry.claimedChild, entry.input.decisionID ?? "");
|
|
773
|
+
trim(misclaimed, MAX_PENDING);
|
|
774
|
+
}
|
|
775
|
+
} catch (error) {
|
|
776
|
+
deps.logger.warn("[router] routing: the child of a finished dispatch could not be registered", { error: describeError(error) });
|
|
777
|
+
}
|
|
778
|
+
},
|
|
779
|
+
|
|
780
|
+
onCallFinished(callID): void {
|
|
781
|
+
decided.delete(callID);
|
|
782
|
+
const entry = entries.get(callID);
|
|
783
|
+
entries.delete(callID);
|
|
784
|
+
if (entry !== undefined) undoResume(entry);
|
|
785
|
+
},
|
|
786
|
+
|
|
787
|
+
misclaimedCount: () => misclaimed.size,
|
|
788
|
+
|
|
789
|
+
dispose(): void {
|
|
790
|
+
},
|
|
791
|
+
|
|
792
|
+
pendingCount(): number {
|
|
793
|
+
const t = now();
|
|
794
|
+
let count = 0;
|
|
795
|
+
for (const entry of entries.values()) if (claimable(entry, t)) count += 1;
|
|
796
|
+
return count;
|
|
797
|
+
},
|
|
798
|
+
};
|
|
799
|
+
}
|