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/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,71 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.3.0] - 2026-10-07
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Cost-aware routing engine (#74), OpenCode v2, opt-in.** A `routing` block
|
|
15
|
+
turns on a decision engine that picks the `(agent, model#variant, retry path)`
|
|
16
|
+
of each dispatch from an expected-cost formula fed by typed task facts decided
|
|
17
|
+
in code and a scoreboard of verified outcomes per `(task class × agent ×
|
|
18
|
+
model#variant)`. With no `routing` block the plugin behaves exactly as 2.2.0.
|
|
19
|
+
Suggested in #73 by @javizuurc (giving custom agents and the context of the work
|
|
20
|
+
to a routing step that decides who does it); implemented from scratch with the
|
|
21
|
+
decision kept in code, and TypeSafe supported as an optional classifier backend.
|
|
22
|
+
- `routing.engine`: `static` (default), `shadow` (decide and record), `advise`
|
|
23
|
+
(generated `R:` line and a stable one-line `Route hint`, advise only) and `enforce` (no hint; reroute under
|
|
24
|
+
a strict margin, an evidence gate of 5 effective (decayed) outcomes on the
|
|
25
|
+
candidate's own key, permission and
|
|
26
|
+
floor rules, and the D9 never-down gate: high-risk work without detection
|
|
27
|
+
cannot run below the pick's capability rank or at lower effort on the same
|
|
28
|
+
model; detection uses the weaker route-line/acceptance claim. A dispatch
|
|
29
|
+
carrying `[route … pin]` is never rerouted).
|
|
30
|
+
- A task classifier (rules, an optional first-line `[route …]` directive, and
|
|
31
|
+
optional `host`, `openai-compatible` and `typesafe` backends; `host` is
|
|
32
|
+
experimental). Backends see a bounded, scrubbed excerpt only, never a task
|
|
33
|
+
that names a credential, and are configurable only from the global override.
|
|
34
|
+
- An outcome store and a decision log under the trajectory directory, with
|
|
35
|
+
cost units that never mix USD and `costRatio` and a zero cost for an unpriced
|
|
36
|
+
model treated as unknown.
|
|
37
|
+
- Same-session variant steps: a failed verification retries on the same
|
|
38
|
+
model's next variant, resuming the child session, before the ladder pays for
|
|
39
|
+
a bigger model (`enforcement.escalate.variantSteps`, `tiers.<t>.candidates`,
|
|
40
|
+
`routing.sessionReuse`).
|
|
41
|
+
- Native agents (`explore`, `general`) as default candidates on v2
|
|
42
|
+
(`routing.roles`; `roles: {}` disables them). The plugin never raises
|
|
43
|
+
`subagent_depth`.
|
|
44
|
+
- A cost doctor: findings in `/router` (title model, unpriced and missing
|
|
45
|
+
models, impossible variants, subscription pricing) and at most one notice,
|
|
46
|
+
delivered as a synthetic transcript entry, throttled per project.
|
|
47
|
+
`variant-effort` reports an empty variant ladder when a tier also sets effort
|
|
48
|
+
options; it fires on bundled `hybrid-2`/`anthropic` once a `routing` block
|
|
49
|
+
exists (unless variant steps are explicitly off). `effort-variant-mismatch`
|
|
50
|
+
reports different `variant` and `effort` values with a live engine and variant
|
|
51
|
+
steps off: the wire effort and learned outcome key would differ.
|
|
52
|
+
Throttle/pending state is stored as `advisor-notice.<hash>.json` with an
|
|
53
|
+
`advisor-notice.<hash>.lock` file in the outcomes directory, per project.
|
|
54
|
+
- `/router stats` and `npm run routing:stats` (the script needs Node 22.18 / 23.6 or
|
|
55
|
+
newer and is not part of the package); `/annotate-plan` emits `[route …]`
|
|
56
|
+
lines and pins `[tier:heavy]` steps when the engine is live; the bare
|
|
57
|
+
`/router` view prints `router: engine=<mode> build=<version>+<sha7>`.
|
|
58
|
+
It also prints `router: config notice:` lines for findings from the last
|
|
59
|
+
config load. A18: `routing.outcomes.path`, like classifier backend settings,
|
|
60
|
+
is accepted only from bundled config or the global override; project-local
|
|
61
|
+
values are dropped with a one-time warning.
|
|
62
|
+
- Documentation: `docs/ROUTING_ENGINE.md`, `docs/adr/0005-cost-aware-routing-engine.md`
|
|
63
|
+
and the `routing` section of `docs/CONFIG_REFERENCE.md`.
|
|
64
|
+
|
|
65
|
+
### Changed
|
|
66
|
+
|
|
67
|
+
- With a `routing` block, `enforcement.escalate.variantSteps` defaults to `auto`
|
|
68
|
+
on OpenCode v2 (without one it stays `none`, so the 2.2.0 ladder is
|
|
69
|
+
unchanged); `enforcement.escalate.effortBumpMax` also caps the variant ladders
|
|
70
|
+
read from the model catalog.
|
|
71
|
+
- OpenCode v1: the `routing` block is validated and `routing.engine` is forced
|
|
72
|
+
to `static` with one log line; setting `routing.roles` explicitly adds a
|
|
73
|
+
prose-only destination suffix to the `R:` line.
|
|
74
|
+
|
|
10
75
|
## [2.2.0] - 2026-10-05
|
|
11
76
|
|
|
12
77
|
### Added
|
package/README.md
CHANGED
|
@@ -1075,11 +1075,40 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
|
|
|
1075
1075
|
- `docs/ENFORCEMENT.md` — architecture, hook wiring, session lifecycle
|
|
1076
1076
|
- `docs/VERIFICATION.md` — DoD schema, deterministic checks, grader dispatch
|
|
1077
1077
|
- `docs/ESCALATION.md` — escalation ladder configuration and cost ceilings
|
|
1078
|
-
- `docs/CONFIG_REFERENCE.md` — full `enforcement` block schema
|
|
1078
|
+
- `docs/CONFIG_REFERENCE.md` — full `enforcement` and `routing` block schema
|
|
1079
1079
|
- `docs/ENFORCEMENT_PRESETS.md` — ready-to-paste enforcement presets
|
|
1080
|
+
- `docs/ROUTING_ENGINE.md` — the cost-aware routing engine: modes, formula, classifier backends, session-aware ladder, cost doctor, privacy
|
|
1081
|
+
- `docs/adr/0005-cost-aware-routing-engine.md` — the decisions behind the routing engine
|
|
1080
1082
|
|
|
1081
1083
|
> These files are not included in the npm tarball. This section is the self-contained summary; the docs are available in the repository for contributors and advanced users.
|
|
1082
1084
|
|
|
1085
|
+
## Cost-aware routing (opt-in, OpenCode v2)
|
|
1086
|
+
|
|
1087
|
+
By default the router picks a tier from the taxonomy in the protocol text and a fixed model per tier. The **routing engine** (issue #74, inspired by #73) can instead pick the `(agent, model#variant, retry path)` of each dispatch from an expected-cost formula fed by two things the plugin already produces: typed facts about the task, decided in code, and a scoreboard of **verified outcomes** (verification verdicts, false refusals, measured cost) per `(task class × agent × model#variant)`. It is off unless you add a `routing` block, and with no `routing` block the plugin behaves exactly as `2.2.0`.
|
|
1088
|
+
|
|
1089
|
+
| `routing.engine` | What happens |
|
|
1090
|
+
|---|---|
|
|
1091
|
+
| `static` (default) | Nothing is decided or recorded; the protocol text and `R:` line are unchanged. |
|
|
1092
|
+
| `shadow` | Every dispatch is decided and logged; nothing about it changes. |
|
|
1093
|
+
| `advise` | As `shadow`, and the orchestrator also receives the generated `R:` line and a one-line `Route hint`; it still decides. |
|
|
1094
|
+
| `enforce` | As `advise`, and the engine reroutes a dispatch when its expected cost is lower by more than `margin`, the class is trusted, the target has at least 5 effective outcomes (or ranks above the orchestrator's pick) and the permission and floor rules allow it. A dispatch carrying `[route … pin]` is never rerouted. |
|
|
1095
|
+
|
|
1096
|
+
Start in `shadow`, read `/router stats`, then raise the mode. A mode is a config-only change (hot reloaded); `static` is the instant kill switch. Put it in the global override file, `~/.config/opencode/opencode-model-router.overrides.jsonc`:
|
|
1097
|
+
|
|
1098
|
+
```jsonc
|
|
1099
|
+
{ "routing": { "engine": "shadow" } }
|
|
1100
|
+
```
|
|
1101
|
+
|
|
1102
|
+
What else ships with it:
|
|
1103
|
+
|
|
1104
|
+
- **Same-session variant steps.** On OpenCode v2 a failed verification retries on the same model's next variant, resuming the child session (history kept), before paying for a bigger model.
|
|
1105
|
+
- **Native agents as candidates.** `explore` and `general` can be chosen for `search`, `implement`, `debug` and `review` work (`routing.roles`; `roles: {}` turns this off).
|
|
1106
|
+
- **A cost doctor.** `/router` reports waste outside the router (an unset title model on an expensive session model, unpriced models, variants the catalog does not offer) and sends at most one short notice.
|
|
1107
|
+
- **Observability.** A decision log and an outcome store under the trajectory directory, `/router stats`, and `npm run routing:stats` in a clone.
|
|
1108
|
+
- **Classifier backends** for uncertain task classes: `rules` (default, local), `openai-compatible` (Ollama, any OpenAI-style server), `typesafe`, and `host` (**experimental**). Backends receive at most a bounded, scrubbed excerpt of the task, are only configurable from the global override, and never block a dispatch.
|
|
1109
|
+
|
|
1110
|
+
OpenCode v1 is unchanged: the `routing` block is validated and `engine` is forced to `static`; the only effect is an opt-in prose line when you set `routing.roles`. Every key and default is in [`docs/CONFIG_REFERENCE.md`](docs/CONFIG_REFERENCE.md#routing--cost-aware-routing-engine-74); the full guide is [`docs/ROUTING_ENGINE.md`](docs/ROUTING_ENGINE.md) and the decision record is [`docs/adr/0005-cost-aware-routing-engine.md`](docs/adr/0005-cost-aware-routing-engine.md).
|
|
1111
|
+
|
|
1083
1112
|
## Commands
|
|
1084
1113
|
|
|
1085
1114
|
| Command | Description |
|
|
@@ -1089,11 +1118,12 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
|
|
|
1089
1118
|
| `/preset <name>` | Switch preset (e.g., `/preset openai`) |
|
|
1090
1119
|
| `/budget` | Show available modes and which is active |
|
|
1091
1120
|
| `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
|
|
1092
|
-
| `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
|
|
1121
|
+
| `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step (and `[route …]` lines when the routing engine is live on v2) |
|
|
1093
1122
|
| `/router overrides` | Show the global + project override file paths and merge precedence |
|
|
1094
1123
|
| `/router models [provider]` | List valid model ids from your configured providers (with defaults and deprecated flags) |
|
|
1095
1124
|
| `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
|
|
1096
|
-
| `/router` |
|
|
1125
|
+
| `/router stats [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]` | Routing engine statistics for a time window (dispatches, agreement, switches, savings estimate, verdict and false-refusal rates per key); same table as `npm run routing:stats` in a clone. The script does not read config: pass `--dir <routing.outcomes.path>` when set. |
|
|
1126
|
+
| `/router` | With no subcommand — or an unrecognized one — prints the `/router` help and the current enforcement mode, plus the line `router: engine=<mode> build=<version>+<sha7>` (the engine in force and the build of the running code; on v1 it also prints, always as `engine=static`) and, on v2 with a `routing` block, the cost doctor's findings |
|
|
1097
1127
|
| `/bypass [on\|off]` | Toggle the router off/on for the session |
|
|
1098
1128
|
|
|
1099
1129
|
## Plan annotation
|
|
@@ -1118,6 +1148,8 @@ After `/annotate-plan`:
|
|
|
1118
1148
|
4. [tier:heavy] Design a token bucket algorithm for advanced rate limiting
|
|
1119
1149
|
```
|
|
1120
1150
|
|
|
1151
|
+
With the [routing engine](#cost-aware-routing-opt-in-opencode-v2) live on OpenCode v2, `/annotate-plan` also emits a `[route class=… risk=… d=…]` line per step, and pins (`pin`) every step whose final tag is `[tier:heavy]`, so the engine never reroutes it. A step that **starts with a code block** is skipped and reported (the command says which line and what to add by hand); the command never edits the file itself. Details: [`docs/ROUTING_ENGINE.md`](docs/ROUTING_ENGINE.md#annotate-plan).
|
|
1152
|
+
|
|
1121
1153
|
## Token overhead
|
|
1122
1154
|
|
|
1123
1155
|
Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,249 characters for a non-Claude orchestrator. A Claude orchestrator receives 4,021 characters after its authority prefix, or 6,357 characters when the 2,336-character DoD/enforcement section is enabled. That is roughly 812–1,766 tokens across the three paths at 3.6–4.0 characters per token. The optional anti-narration clause adds another 650 characters to the Claude path.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-model-router",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -9,9 +9,12 @@
|
|
|
9
9
|
"test:watch": "vitest",
|
|
10
10
|
"test:coverage": "vitest run --coverage",
|
|
11
11
|
"smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
|
|
12
|
+
"smoke:v1": "node scripts/smoke-v1-preflight.mjs && npm run smoke:keyless",
|
|
12
13
|
"smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts test/smoke/deferred-catalog.smoke.test.ts test/smoke/depth-effort.smoke.test.ts test/smoke/helpers/scripted-provider.test.ts",
|
|
13
14
|
"smoke:v2": "cross-env RUN_OC_SMOKE_V2=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-registration.smoke.test.ts",
|
|
15
|
+
"smoke:routing": "cross-env RUN_OC_SMOKE_ROUTING=1 vitest run --config vitest.smoke.config.ts test/smoke/routing-engine.smoke.test.ts",
|
|
14
16
|
"smoke:v2:e2e": "cross-env RUN_OC_SMOKE_V2_E2E=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-provider-e2e.smoke.test.ts",
|
|
17
|
+
"routing:stats": "node scripts/routing-stats.ts",
|
|
15
18
|
"typecheck": "tsc --noEmit"
|
|
16
19
|
},
|
|
17
20
|
"license": "GPL-3.0-only",
|
package/src/commands/output.ts
CHANGED
|
@@ -211,7 +211,7 @@ export function buildOverridesOutput(v: OverridesView): string {
|
|
|
211
211
|
}
|
|
212
212
|
|
|
213
213
|
/** Bare `/router`. */
|
|
214
|
-
export function buildRouterHelp(current: string): string {
|
|
214
|
+
export function buildRouterHelp(current: string, options: { stats?: boolean } = {}): string {
|
|
215
215
|
return [
|
|
216
216
|
`# Model Router`,
|
|
217
217
|
`Enforcement: **${current}**`,
|
|
@@ -220,6 +220,9 @@ export function buildRouterHelp(current: string): string {
|
|
|
220
220
|
"- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
|
|
221
221
|
"- `/router overrides` — show the global + project override file paths and precedence",
|
|
222
222
|
"- `/router models [provider]` — list valid model ids from your configured providers",
|
|
223
|
+
...(options.stats === true
|
|
224
|
+
? ["- `/router stats [--since <ISO>]` — routing statistics from the decision log and outcome store (same table as `npm run routing:stats` (in a clone))"]
|
|
225
|
+
: []),
|
|
223
226
|
"- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
|
|
224
227
|
].join("\n");
|
|
225
228
|
}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { PluginInput } from "@opencode-ai/plugin";
|
|
2
|
+
import type { RunnerCatalogModel } from "../escalate/resume";
|
|
3
|
+
import type { CatalogModel, Ingest } from "../routing/outcomes/ingest";
|
|
4
|
+
import type { HostGenerate } from "../routing/classify/types";
|
|
2
5
|
|
|
3
6
|
/** Marks the legacy tool.execute.before output bag when verification starts for
|
|
4
7
|
* that task call. V1 hosts read only output.args, so this symbol is invisible. */
|
|
@@ -16,8 +19,29 @@ export interface ChildSessionRequest {
|
|
|
16
19
|
system?: string;
|
|
17
20
|
prompt: string;
|
|
18
21
|
signal?: AbortSignal;
|
|
22
|
+
/**
|
|
23
|
+
* Resume this existing child (the host `subagent` call's `sessionID`, D11) instead of creating one: the
|
|
24
|
+
* history is kept, `agent`/`model` switch it when they differ. The runner checks that it is a child of the
|
|
25
|
+
* calling session first and rejects with {@link ResumeRejectedError} otherwise, before anything is sent.
|
|
26
|
+
* `onCreated(resumeSessionID)` runs for a resumed child too (after that check, before the host runs it), so
|
|
27
|
+
* one callback registers every child the request runs on; `cwd` is not applied again.
|
|
28
|
+
*/
|
|
29
|
+
resumeSessionID?: string;
|
|
19
30
|
/** Runs before the child can start its first model request. */
|
|
20
31
|
onCreated(sessionID: string): Promise<void>;
|
|
32
|
+
/** Runs once when progress or the completed result confirms which child the host actually ran. */
|
|
33
|
+
onConfirmed?(sessionID: string): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A resume that was refused before the child ran: the session is gone, or it is not a child of the calling
|
|
38
|
+
* session. Nothing was sent, so the caller may start a fresh child for the same attempt (D11 fallback).
|
|
39
|
+
*/
|
|
40
|
+
export class ResumeRejectedError extends Error {
|
|
41
|
+
constructor(readonly sessionID: string, reason: string) {
|
|
42
|
+
super(`[model-router] cannot resume child session ${sessionID}: ${reason}`);
|
|
43
|
+
this.name = "ResumeRejectedError";
|
|
44
|
+
}
|
|
21
45
|
}
|
|
22
46
|
|
|
23
47
|
export interface ChildSessionRunner {
|
|
@@ -29,4 +53,23 @@ export type RouterPluginInput = PluginInput & {
|
|
|
29
53
|
routerChildRunner?: ChildSessionRunner;
|
|
30
54
|
/** Set only by src/v2.ts; absent = v1 host (A3). */
|
|
31
55
|
routerHost?: "v2";
|
|
56
|
+
/**
|
|
57
|
+
* Set only by src/v2.ts: the host model catalog (`ctx.model.list`): prices child steps (A1) and, with its `variants`
|
|
58
|
+
* and `limit`, lets the delegate ladder validate variants and size resumes (D10/D11, Phase 2.3).
|
|
59
|
+
*/
|
|
60
|
+
routerCatalog?: () => Promise<readonly (CatalogModel & RunnerCatalogModel)[]>;
|
|
61
|
+
/**
|
|
62
|
+
* Set only by src/v2.ts: the host's agents (`ctx.agent.list().data`, Agent.Info records). The cost doctor (Phase 2.4) reads which
|
|
63
|
+
* agents have a model of their own (title, summary, the role agents) and which tier agents the host offers.
|
|
64
|
+
*/
|
|
65
|
+
routerAgents?: () => Promise<readonly unknown[]>;
|
|
66
|
+
/**
|
|
67
|
+
* Set only by src/v2.ts: the host's synthetic transcript entry (`ctx.session.synthetic`, `resume: false`), the call the adapter already uses
|
|
68
|
+
* for its config-reload and narration notices. The cost doctor's notice goes through it, never into the user's message.
|
|
69
|
+
*/
|
|
70
|
+
routerSynthetic?: (input: { sessionID: string; text: string; description: string }) => Promise<void>;
|
|
71
|
+
/** Set only by src/v2.ts: the host `generate` (the `host` classifier backend of `/annotate-plan`, A4); absent when the host has none. */
|
|
72
|
+
routerGenerate?: HostGenerate;
|
|
73
|
+
/** Set only by src/v2.ts: receives this plugin instance's telemetry ingest, whose step events the v2 adapter feeds (QA-2.1-7). */
|
|
74
|
+
routerOnIngest?: (ingest: Ingest) => void;
|
|
32
75
|
};
|
package/src/compat/v2-client.ts
CHANGED
|
@@ -2,10 +2,13 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
2
2
|
import type { Plugin } from "@opencode/plugin";
|
|
3
3
|
import type { ToolContext } from "@opencode/plugin/promise/tool";
|
|
4
4
|
import type { SessionContext } from "@opencode/plugin/promise/session";
|
|
5
|
-
import type
|
|
5
|
+
import { ResumeRejectedError, type ChildSessionRunner } from "./child-session";
|
|
6
|
+
import { markRunnerDispatch, runnerDescription } from "../router/sessions";
|
|
6
7
|
|
|
7
8
|
export const V2_GRADER_AGENT = "model-router-grader";
|
|
8
9
|
const RETAINED_CONTEXT_LIMIT = 500;
|
|
10
|
+
/** How long a delegation waits for the host to remove a child it started by mistake before it reports the error. */
|
|
11
|
+
export const STRAY_CLEANUP_TIMEOUT_MS = 2_000;
|
|
9
12
|
|
|
10
13
|
/** The small v1 client surface still used by the shared hooks. */
|
|
11
14
|
export function createV2Runtime(ctx: Plugin.Context) {
|
|
@@ -45,7 +48,18 @@ export function createV2Runtime(ctx: Plugin.Context) {
|
|
|
45
48
|
name: provider.name,
|
|
46
49
|
models: Object.fromEntries(models.data
|
|
47
50
|
.filter(model => model.providerID === provider.id && model.enabled)
|
|
48
|
-
|
|
51
|
+
// `id` and `status` are what the v1 shape had; the rest lets the cost doctor (Phase 2.4) read the SAME call instead of a second
|
|
52
|
+
// `model.list` (QA-2.4-3). v1 consumers (`normalizeCatalog`) ignore the extra fields.
|
|
53
|
+
.map(model => [model.id, {
|
|
54
|
+
id: model.id,
|
|
55
|
+
status: model.status,
|
|
56
|
+
enabled: model.enabled,
|
|
57
|
+
family: model.family,
|
|
58
|
+
capabilities: model.capabilities,
|
|
59
|
+
cost: model.cost,
|
|
60
|
+
variants: model.variants,
|
|
61
|
+
limit: model.limit,
|
|
62
|
+
}])),
|
|
49
63
|
})),
|
|
50
64
|
default: defaultModel.data
|
|
51
65
|
? { [defaultModel.data.providerID]: defaultModel.data.id }
|
|
@@ -57,6 +71,28 @@ export function createV2Runtime(ctx: Plugin.Context) {
|
|
|
57
71
|
// v2 has no app.log endpoint. createPluginLogger uses its console fallback.
|
|
58
72
|
};
|
|
59
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Stop and remove a child the host started that no caller knows (QA-2.3-5). Bounded (QA-2.3-R2-3): resolves with ""
|
|
76
|
+
* when it is gone, otherwise with a sentence for the error (a failure, or a removal still running after
|
|
77
|
+
* STRAY_CLEANUP_TIMEOUT_MS, which then finishes or fails in the background without anyone waiting for it). Never rejects.
|
|
78
|
+
*/
|
|
79
|
+
const removeStray = async (sessionID: string): Promise<string> => {
|
|
80
|
+
const removal = childRunner.dispose(sessionID).then(
|
|
81
|
+
() => "",
|
|
82
|
+
(error: unknown) => `; removing it failed (${error instanceof Error ? error.message : String(error)})`,
|
|
83
|
+
);
|
|
84
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
85
|
+
const timeout = new Promise<string>((resolve) => {
|
|
86
|
+
timer = setTimeout(() => resolve(`; removing it did not finish within ${STRAY_CLEANUP_TIMEOUT_MS} ms and may still be running`), STRAY_CLEANUP_TIMEOUT_MS);
|
|
87
|
+
if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
|
|
88
|
+
});
|
|
89
|
+
try {
|
|
90
|
+
return await Promise.race([removal, timeout]);
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
60
96
|
const childRunner: ChildSessionRunner = {
|
|
61
97
|
async run(request) {
|
|
62
98
|
lifetime.signal.throwIfAborted();
|
|
@@ -82,14 +118,54 @@ export function createV2Runtime(ctx: Plugin.Context) {
|
|
|
82
118
|
...(request.signal ? [request.signal] : []),
|
|
83
119
|
]);
|
|
84
120
|
signal.throwIfAborted();
|
|
85
|
-
|
|
121
|
+
const resumeID = request.resumeSessionID;
|
|
122
|
+
if (resumeID !== undefined) {
|
|
123
|
+
// The host resumes any session id it is given, so ours checks that the child exists and belongs to the
|
|
124
|
+
// calling session before anything is sent. Whatever the lookup says other than "my child", the caller
|
|
125
|
+
// falls back to a fresh child.
|
|
126
|
+
const parent = scope.context.sessionID;
|
|
127
|
+
let info: { parentID?: unknown } | undefined;
|
|
128
|
+
try {
|
|
129
|
+
info = await ctx.session.get({ sessionID: resumeID }, { signal });
|
|
130
|
+
} catch (error) {
|
|
131
|
+
signal.throwIfAborted();
|
|
132
|
+
throw new ResumeRejectedError(resumeID, `session lookup failed (${error instanceof Error ? error.message : String(error)})`);
|
|
133
|
+
}
|
|
134
|
+
if (info?.parentID !== parent) throw new ResumeRejectedError(resumeID, `it is not a child of session ${parent}`);
|
|
135
|
+
}
|
|
136
|
+
// A resumed child is known up front: the host does not create one, and a progress event for another id is an error.
|
|
137
|
+
let childID: string | undefined = resumeID;
|
|
138
|
+
let confirmed = false;
|
|
139
|
+
const confirmChild = async (sessionID: string): Promise<void> => {
|
|
140
|
+
if (confirmed) return;
|
|
141
|
+
confirmed = true;
|
|
142
|
+
await request.onConfirmed?.(sessionID);
|
|
143
|
+
};
|
|
144
|
+
/** Set when the host answered a resume with another child; thrown from `run` whatever the host made of the progress error. */
|
|
145
|
+
let strayResume: ResumeRejectedError | undefined;
|
|
146
|
+
if (resumeID !== undefined) {
|
|
147
|
+
activeChildren.set(resumeID, controller);
|
|
148
|
+
if (request.system) childSystems.set(resumeID, request.system);
|
|
149
|
+
}
|
|
86
150
|
const model = request.model;
|
|
151
|
+
// 2.2 / 2.3 single writer (QA-2.2-1): announce the native call to the 2.2 dispatch router, which must leave it alone
|
|
152
|
+
// (this runner has chosen the agent and model#variant, writes the attempt's row and registers the child itself). Measured on 2.0.22
|
|
153
|
+
// (Phase 3.2, H4): the host runs no plugin tool hook for a call made through `ctx.tool.list()`, so the router never sees it and the
|
|
154
|
+
// mark is withdrawn below unconsumed; it is defensive, for a host that does hook such calls.
|
|
155
|
+
let withdrawMark: (() => void) | undefined;
|
|
87
156
|
try {
|
|
157
|
+
// A resumed child is registered here, before the host can run it, exactly like a created one is in `progress`.
|
|
158
|
+
if (resumeID !== undefined) {
|
|
159
|
+
await request.onCreated(resumeID);
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
}
|
|
162
|
+
withdrawMark = markRunnerDispatch({ parentSessionID: toolContext.sessionID, agent: request.agent ?? V2_GRADER_AGENT, prompt: request.prompt });
|
|
88
163
|
const result = await native.execute({
|
|
89
164
|
agent: request.agent ?? V2_GRADER_AGENT,
|
|
90
|
-
description: request.agent
|
|
165
|
+
description: runnerDescription(request.agent),
|
|
91
166
|
prompt: request.prompt,
|
|
92
167
|
...(model ? { model: `${model.providerID}/${model.modelID}${model.variant ? `#${model.variant}` : ""}` } : {}),
|
|
168
|
+
...(resumeID !== undefined ? { sessionID: resumeID } : {}),
|
|
93
169
|
background: false,
|
|
94
170
|
}, {
|
|
95
171
|
...toolContext,
|
|
@@ -97,7 +173,22 @@ export function createV2Runtime(ctx: Plugin.Context) {
|
|
|
97
173
|
async progress(metadata) {
|
|
98
174
|
const sessionID = metadata.sessionID;
|
|
99
175
|
if (typeof sessionID === "string" && sessionID !== childID) {
|
|
100
|
-
if (childID)
|
|
176
|
+
if (childID) {
|
|
177
|
+
// The host started another child than the one this call is about (a resume that did not resume, or a
|
|
178
|
+
// second child): no caller knows its id, so it is stopped and removed here before the error, or it
|
|
179
|
+
// would live until the host is restarted (QA-2.3-5). The original child is interrupted below.
|
|
180
|
+
// The removal is bounded (QA-2.3-R2-3): a host that hangs on it must not hang the delegation, and the error
|
|
181
|
+
// says so instead of hiding it.
|
|
182
|
+
const cleanup = await removeStray(sessionID);
|
|
183
|
+
if (resumeID !== undefined && childID === resumeID) {
|
|
184
|
+
// A resume that did not resume: the caller starts a fresh child for the same attempt (D11 fallback)
|
|
185
|
+
// instead of counting a failed attempt. Kept aside so the host's own wrapping of a progress error
|
|
186
|
+
// cannot hide the type.
|
|
187
|
+
strayResume = new ResumeRejectedError(resumeID, `the host started another child (${sessionID}) instead${cleanup}`);
|
|
188
|
+
throw strayResume;
|
|
189
|
+
}
|
|
190
|
+
throw new Error(`[model-router] native subagent changed its child session ID (${childID} -> ${sessionID}${cleanup})`);
|
|
191
|
+
}
|
|
101
192
|
childID = sessionID;
|
|
102
193
|
activeChildren.set(sessionID, controller);
|
|
103
194
|
if (request.system) childSystems.set(sessionID, request.system);
|
|
@@ -107,6 +198,7 @@ export function createV2Runtime(ctx: Plugin.Context) {
|
|
|
107
198
|
if (request.cwd) await ctx.session.move({ sessionID, directory: request.cwd }, { signal });
|
|
108
199
|
signal.throwIfAborted();
|
|
109
200
|
}
|
|
201
|
+
if (typeof sessionID === "string" && sessionID === childID) await confirmChild(sessionID);
|
|
110
202
|
// V2 rejects progress outside a running call. Deferred/queued graders
|
|
111
203
|
// retain settled parent contexts; also tolerate settlement during progress.
|
|
112
204
|
if (scope.active) {
|
|
@@ -115,19 +207,27 @@ export function createV2Runtime(ctx: Plugin.Context) {
|
|
|
115
207
|
}
|
|
116
208
|
},
|
|
117
209
|
});
|
|
118
|
-
signal.throwIfAborted();
|
|
119
210
|
const output = result.output as { sessionID?: unknown; status?: unknown; output?: unknown } | undefined;
|
|
211
|
+
// A named child confirms an attempted resume even when its result failed or was aborted.
|
|
212
|
+
if (childID && output?.sessionID === childID) await confirmChild(childID);
|
|
213
|
+
signal.throwIfAborted();
|
|
214
|
+
if (resumeID !== undefined && typeof output?.sessionID === "string" && output.sessionID !== resumeID) {
|
|
215
|
+
const cleanup = await removeStray(output.sessionID);
|
|
216
|
+
throw new ResumeRejectedError(resumeID, `the host started another child (${output.sessionID}) instead${cleanup}`);
|
|
217
|
+
}
|
|
120
218
|
if (!childID || output?.sessionID !== childID || output.status !== "completed" || typeof output.output !== "string") {
|
|
121
219
|
throw new Error("[model-router] native subagent did not return a completed child result; verification cannot use a pending result");
|
|
122
220
|
}
|
|
221
|
+
await confirmChild(childID);
|
|
123
222
|
return { sessionID: childID, text: output.output };
|
|
124
223
|
} catch (error) {
|
|
125
224
|
controller.abort();
|
|
126
225
|
if (childID) {
|
|
127
226
|
try { await ctx.session.interrupt({ sessionID: childID }); } catch { /* keep the original dispatch failure */ }
|
|
128
227
|
}
|
|
129
|
-
throw error;
|
|
228
|
+
throw strayResume ?? error;
|
|
130
229
|
} finally {
|
|
230
|
+
withdrawMark?.(); // a hook that never fired must not leave a mark behind
|
|
131
231
|
if (childID) {
|
|
132
232
|
childSystems.delete(childID);
|
|
133
233
|
activeChildren.delete(childID);
|
package/src/compat/v2-hooks.ts
CHANGED
|
@@ -11,7 +11,13 @@ import { loadConfig } from "../router/config";
|
|
|
11
11
|
import { getActiveTiers } from "../router/protocol";
|
|
12
12
|
import { resolveSubagentOverrides } from "../router/subagents";
|
|
13
13
|
import { stripDelegateInstructions } from "../router/instructions";
|
|
14
|
+
import { createPluginLogger } from "../router/logger";
|
|
14
15
|
import { GRADER_SYSTEM } from "../verify/checker";
|
|
16
|
+
import { EXECUTION_END_TYPES, FLUSH_EVENT_TYPES, NOOP_INGEST } from "../routing/outcomes/ingest";
|
|
17
|
+
import type { Ingest } from "../routing/outcomes/ingest";
|
|
18
|
+
import { createEngineRuntime } from "../routing/wire/runtime";
|
|
19
|
+
import { childSessionOf, createDispatchRouter } from "../routing/wire/dispatch";
|
|
20
|
+
import { createSystemAugmenter } from "../routing/wire/hint";
|
|
15
21
|
|
|
16
22
|
/** Translate the router's own v1 tool vocabulary at the v2 boundary. */
|
|
17
23
|
export function v2Instructions(text: string): string {
|
|
@@ -80,6 +86,8 @@ export async function registerV2Hooks(
|
|
|
80
86
|
ctx: Context,
|
|
81
87
|
hooks: Hooks,
|
|
82
88
|
runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession">>,
|
|
89
|
+
/** `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing. */
|
|
90
|
+
options: { ingest?: Ingest } = {},
|
|
83
91
|
): Promise<() => Promise<void>> {
|
|
84
92
|
// The old plugin surface uses separate mutable input/output bags. Keep those
|
|
85
93
|
// casts confined to this adapter, rather than weakening the v2 event types.
|
|
@@ -88,6 +96,33 @@ export async function registerV2Hooks(
|
|
|
88
96
|
const abort = new AbortController();
|
|
89
97
|
const verifyingCalls = new Set<string>();
|
|
90
98
|
const depthBanners = new Map<string, string>();
|
|
99
|
+
// M6 (2.1.3): child-session outcomes and costs reach the outcome store through the plugin instance's ingest, which
|
|
100
|
+
// does nothing unless routing.engine != static (its settings are null otherwise: no bundle, no files).
|
|
101
|
+
const ingestLogger = createPluginLogger();
|
|
102
|
+
const ingest: Ingest = options.ingest ?? NOOP_INGEST;
|
|
103
|
+
// An ingestion error is logged and the loop carries on: it must never cost the router an event.
|
|
104
|
+
const ingesting = async (what: string, run: () => void | Promise<void>): Promise<void> => {
|
|
105
|
+
try {
|
|
106
|
+
await run();
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (!abort.signal.aborted) ingestLogger.warn(`[router] telemetry ingestion: ${what} failed`, { error: error instanceof Error ? error.message : String(error) });
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
// M7 (2.2): dispatch routing and the protocol/hint adaptation share one runtime; it touches nothing (no host call, no
|
|
112
|
+
// store, no disk) while routing.engine is static, which is the default and what every config without a `routing` block is.
|
|
113
|
+
const sessionOf = (sessionID: string): Promise<unknown> => ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
|
|
114
|
+
const engine = createEngineRuntime({
|
|
115
|
+
loadConfig: () => loadConfig(ctx.location.directory),
|
|
116
|
+
listAgents: async () => (await ctx.agent.list()).data,
|
|
117
|
+
listModels: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
|
|
118
|
+
...(ctx.generate === undefined ? {} : { generate: ctx.generate }),
|
|
119
|
+
logger: ingestLogger,
|
|
120
|
+
});
|
|
121
|
+
const dispatchRouter = createDispatchRouter({
|
|
122
|
+
runtime: engine, getSession: sessionOf, graderAgent: V2_GRADER_AGENT, directory: ctx.location.directory,
|
|
123
|
+
logger: { warn: (message, extra) => ingestLogger.warn(message, extra), debug: (message, extra) => console.debug(message, extra ?? "") },
|
|
124
|
+
});
|
|
125
|
+
const systemAugmenter = createSystemAugmenter({ runtime: engine, getSession: sessionOf, logger: ingestLogger });
|
|
91
126
|
let eventTask: Promise<void> | undefined;
|
|
92
127
|
let disposed = false;
|
|
93
128
|
const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
|
|
@@ -108,6 +143,10 @@ export async function registerV2Hooks(
|
|
|
108
143
|
disposed = true;
|
|
109
144
|
abort.abort();
|
|
110
145
|
await runtime?.dispose?.();
|
|
146
|
+
// Before the event task: disposing releases a step handler that waits for the model catalog (QA-2.1-5).
|
|
147
|
+
await ingest.dispose();
|
|
148
|
+
dispatchRouter.dispose(); // this location no longer owns its sessions
|
|
149
|
+
await engine.dispose();
|
|
111
150
|
await eventTask;
|
|
112
151
|
await Promise.allSettled(registrations.map((registration) => registration.dispose()));
|
|
113
152
|
await hooks.dispose?.();
|
|
@@ -255,7 +294,8 @@ export async function registerV2Hooks(
|
|
|
255
294
|
if (!(key in event.options)) event.options[key] = value;
|
|
256
295
|
}
|
|
257
296
|
await legacy["chat.params"]?.(input, event.options);
|
|
258
|
-
const
|
|
297
|
+
const routerConfig = loadConfig(ctx.location.directory);
|
|
298
|
+
const verify = routerConfig.enforcement?.verify;
|
|
259
299
|
if (event.agent === V2_GRADER_AGENT
|
|
260
300
|
&& (verify?.graderTemperature === null
|
|
261
301
|
|| !(verify?.graderTemperatureModels ?? []).includes(`${event.model.providerID}/${event.model.id}`))) {
|
|
@@ -276,6 +316,11 @@ export async function registerV2Hooks(
|
|
|
276
316
|
return Array.prototype.push.apply(output.system, texts);
|
|
277
317
|
} });
|
|
278
318
|
await legacy["experimental.chat.system.transform"]?.(input, output);
|
|
319
|
+
// M7 (2.2): advise/enforce swap the R: line, append the route-line paragraph and add the per-turn hint.
|
|
320
|
+
// static/shadow (and every config without a routing block) leave `output.system` exactly as the legacy hook built it.
|
|
321
|
+
await systemAugmenter.augment({
|
|
322
|
+
sessionID: event.sessionID, agent: event.agent, parentModel: `${event.model.providerID}/${event.model.id}`, messages: event.messages, cfg: routerConfig,
|
|
323
|
+
}, output.system, added);
|
|
279
324
|
event.system = output.system.map((text): SystemPart =>
|
|
280
325
|
original.get(text)?.shift() ?? { type: "text", text: added.has(text) ? v2Instructions(text) : text });
|
|
281
326
|
runtime?.applyChildSystem(event.sessionID, event.system);
|
|
@@ -311,41 +356,65 @@ export async function registerV2Hooks(
|
|
|
311
356
|
|
|
312
357
|
registrations.push(await ctx.tool.hook("execute.before", async (event) => {
|
|
313
358
|
const args = await scopedArgs(event);
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
if (event.tool === "subagent" && args && typeof args.agent === "string" && args.model === undefined) {
|
|
359
|
+
if (event.tool === "subagent" && args && typeof args.agent === "string") {
|
|
360
|
+
// The model `subagentTiers` would fill in when the call names none (unchanged behaviour: only then, only for a mapped agent).
|
|
317
361
|
const cfg = loadConfig(ctx.location.directory);
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
362
|
+
let tierModel: string | undefined;
|
|
363
|
+
if (args.model === undefined) {
|
|
364
|
+
if (cfg.subagentTiers?.[args.agent]) {
|
|
365
|
+
const actual = await ctx.agent.list();
|
|
366
|
+
const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
|
|
367
|
+
subagentTiers: cfg.subagentTiers, tiers: getActiveTiers(cfg),
|
|
368
|
+
existingAgents: Object.fromEntries(actual.data.map((agent) => [agent.id, { mode: agent.mode }])),
|
|
369
|
+
}) : {};
|
|
370
|
+
const override = overrides[args.agent];
|
|
371
|
+
if (override) tierModel = `${override.model}${override.variant ? `#${override.variant}` : ""}`;
|
|
372
|
+
}
|
|
326
373
|
}
|
|
374
|
+
// M7 (2.2): the engine goes first. Static (the default) returns untouched without any host call; shadow/advise only
|
|
375
|
+
// log and strip `[route …]`; enforce may also replace agent and model. `subagentTiers` then only fills a missing model.
|
|
376
|
+
const routed = await dispatchRouter.route({
|
|
377
|
+
callID: event.id, sessionID: event.sessionID, agent: event.agent, args, tierModel, cfg,
|
|
378
|
+
});
|
|
379
|
+
if (routed.prompt !== undefined) args.prompt = routed.prompt;
|
|
380
|
+
if (routed.agent !== undefined) { args.agent = routed.agent; args.subagent_type = routed.agent; }
|
|
381
|
+
if (routed.model !== undefined) args.model = routed.model;
|
|
382
|
+
if (args.model === undefined && tierModel !== undefined) args.model = tierModel;
|
|
327
383
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
384
|
+
// After routing: the prompt the legacy hook starts from is the one the engine left (a stripped route line is not "added" text).
|
|
385
|
+
try {
|
|
386
|
+
const original = args && typeof args === "object" ? { ...args } : args;
|
|
387
|
+
const output = { args };
|
|
388
|
+
await within(hookContext(event), async () => {
|
|
389
|
+
await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
|
|
390
|
+
});
|
|
391
|
+
const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
|
|
392
|
+
const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
|
|
393
|
+
if (typeof banner === "string") {
|
|
394
|
+
depthBanners.delete(event.id);
|
|
395
|
+
depthBanners.set(event.id, banner);
|
|
396
|
+
while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
|
|
397
|
+
}
|
|
398
|
+
if (verifying) {
|
|
399
|
+
verifyingCalls.add(event.id);
|
|
400
|
+
while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
|
|
401
|
+
}
|
|
402
|
+
if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
|
|
403
|
+
const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
|
|
404
|
+
output.args.prompt = translateAdded(prompt, output.args.prompt);
|
|
405
|
+
}
|
|
406
|
+
event.input = nativeArgs(event.tool, output.args, original, verifying);
|
|
407
|
+
} catch (error) {
|
|
408
|
+
dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
|
|
409
|
+
throw error;
|
|
345
410
|
}
|
|
346
|
-
|
|
411
|
+
// The input the host will execute (after the legacy hook): the dispatch is registered for ingestion from it, not from what the engine decided (2.2).
|
|
412
|
+
dispatchRouter.commit(event.id, event.input);
|
|
347
413
|
}));
|
|
348
414
|
registrations.push(await ctx.tool.hook("execute.after", async (event) => {
|
|
415
|
+
// 2.2: the result names the child. A dispatch still waiting for it is registered under it, and a heuristic claim that picked
|
|
416
|
+
// the wrong child is corrected here, before the legacy hook below records the verdict. A call without a result is just dropped.
|
|
417
|
+
dispatchRouter.onCallResult(event.id, event.status === "completed" ? childSessionOf(event.result) : null);
|
|
349
418
|
const banner = depthBanners.get(event.id);
|
|
350
419
|
depthBanners.delete(event.id);
|
|
351
420
|
const verifying = verifyingCalls.delete(event.id);
|
|
@@ -418,7 +487,25 @@ export async function registerV2Hooks(
|
|
|
418
487
|
if (abort.signal.aborted) break;
|
|
419
488
|
try {
|
|
420
489
|
const data = event.data as Record<string, any>;
|
|
421
|
-
if (event.type === "session.
|
|
490
|
+
if (event.type === "session.step.ended" || event.type === "session.step.failed") {
|
|
491
|
+
// Cost and tokens of a registered child dispatch (ingest ignores every other session).
|
|
492
|
+
await ingesting(event.type, () => ingest.onStepEnded(event));
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
// A new child session: the dispatch the engine routed for it is registered with the 2.1 registry (2.2).
|
|
496
|
+
if (event.type === "session.created") dispatchRouter.onSessionCreated({ sessionID: data.sessionID, parentID: data.parentID, agent: data.agent, title: data.title });
|
|
497
|
+
if (event.type === "session.deleted") {
|
|
498
|
+
runtime?.forgetSession?.(data.sessionID);
|
|
499
|
+
await ingesting("session.deleted", () => ingest.onSessionGone(data.sessionID));
|
|
500
|
+
} else if (FLUSH_EVENT_TYPES.has(event.type)) {
|
|
501
|
+
// The v2 equivalents of session.idle: coalesced, throttled flush (D15); never awaited.
|
|
502
|
+
await ingesting(event.type, () => {
|
|
503
|
+
// The child's attempt is over: fold it before the flush that persists it.
|
|
504
|
+
if (EXECUTION_END_TYPES.has(event.type)) ingest.onExecutionEnded(data.sessionID, event.id);
|
|
505
|
+
ingest.sweep();
|
|
506
|
+
ingest.requestFlush();
|
|
507
|
+
});
|
|
508
|
+
}
|
|
422
509
|
if (event.type === "session.text.ended") {
|
|
423
510
|
const output = { text: data.text };
|
|
424
511
|
await legacy["experimental.text.complete"]?.({ sessionID: data.sessionID, messageID: data.assistantMessageID }, output);
|