opencode-model-router 2.4.0 → 2.5.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 +22 -0
- package/README.md +31 -2
- package/package.json +6 -1
- package/src/compat/v2-hooks.ts +53 -7
- package/src/tui/effort-channel.ts +220 -0
- package/src/tui/effort-rpc.ts +60 -0
- package/src/tui/host-types.ts +154 -0
- package/src/tui/opentui-solid.d.ts +16 -0
- package/src/tui/plugin.ts +1007 -0
- package/src/tui/status-model.ts +561 -0
- package/tui.ts +4 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.5.0] - 2026-10-09
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **OpenCode v2 TUI status (#90).** The package ships a TUI entry, `tui.ts` (plugin id `opencode-model-router.status`),
|
|
15
|
+
that OpenCode v2 (2.0.24 or later) auto-loads for every package listed in `opencode.json` `plugins` when the server
|
|
16
|
+
entry loads. The main session's prompt footer shows `effort <value>` when no variant is selected; a delegated
|
|
17
|
+
session's view shows `<agent> · <model> · <effort>` above the composer. Opt-in (off by default, so the main session
|
|
18
|
+
shows only the footer's effort): with `"options": { "runningRow": true }` the main session lists running delegates
|
|
19
|
+
above the composer, one `<agent> · <model> · <effort>` row each, at most `maxRows`, then `+<k> more`. Options
|
|
20
|
+
`enabled`, `footer`, `childView`, `runningRow` and `maxRows` go in OpenCode v2's TUI config file `cli.json`; turn it
|
|
21
|
+
off with `enabled: false` or `"-opencode-model-router.status"`. The v2 server plugin answers the plugin rpc
|
|
22
|
+
`opencode-model-router.effort` (`effortOf`) with the effort each session's latest turn carried; while it has no
|
|
23
|
+
answer, the footer shows `effort default` and the delegate rows show the message's variant. Inert on OpenCode v1,
|
|
24
|
+
which never loads `tui.ts`. See [TUI status](docs/TUI_STATUS.md).
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- OpenCode v1 support is in feature freeze: v1 keeps working and gets fixes for regressions and security issues only;
|
|
29
|
+
every new feature targets OpenCode v2 and stays inert on v1 (at most one notice, no behaviour). See
|
|
30
|
+
[AGENTS.md](AGENTS.md#host-support-policy).
|
|
31
|
+
|
|
10
32
|
## [2.4.0] - 2026-10-09
|
|
11
33
|
|
|
12
34
|
Role × tier × assurance delegation (#84), opt-in on OpenCode v2: role agents, tier floors from authority × detection,
|
package/README.md
CHANGED
|
@@ -275,6 +275,11 @@ For a local checkout, replace the package name with its absolute directory path.
|
|
|
275
275
|
V2 loads the package's `server.ts` definition; v1 continues to load the original
|
|
276
276
|
function from `src/index.ts`. Existing v1 configuration does not need to change.
|
|
277
277
|
|
|
278
|
+
> **OpenCode v1: feature freeze.** Since 2026-10-09, v1 support gets fixes for
|
|
279
|
+
> regressions and security issues only. Every new feature targets OpenCode v2 and
|
|
280
|
+
> stays inert on v1 (at most one notice, no behaviour), as roles mode already does.
|
|
281
|
+
> See the [changelog entry](CHANGELOG.md#250---2026-10-09).
|
|
282
|
+
|
|
278
283
|
Routing, tool guards and verification use the same engine on both versions. V2
|
|
279
284
|
uses its native `subagent` tool to create real child sessions, preserving the
|
|
280
285
|
host's permissions and cancellation. There are a few host differences:
|
|
@@ -1104,6 +1109,7 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
|
|
|
1104
1109
|
- `docs/adr/0005-cost-aware-routing-engine.md` — the decisions behind the routing engine
|
|
1105
1110
|
- `docs/ROLES.md` — roles mode: role agents, authority and separation, tier floor, budgets, `router_run`, migration
|
|
1106
1111
|
- `docs/adr/0006-role-tier-assurance-delegation.md` — the decisions behind roles mode
|
|
1112
|
+
- `docs/TUI_STATUS.md` — the OpenCode v2 TUI status: what it shows, `cli.json` options, the effort channel, limitations
|
|
1107
1113
|
|
|
1108
1114
|
> 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.
|
|
1109
1115
|
|
|
@@ -1132,7 +1138,7 @@ What else ships with it:
|
|
|
1132
1138
|
- **Observability.** A decision log and an outcome store under the trajectory directory, `/router stats`, and `npm run routing:stats` in a clone.
|
|
1133
1139
|
- **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.
|
|
1134
1140
|
|
|
1135
|
-
On OpenCode v1 the routing engine does not run: the `routing` block is validated and `engine` is forced to `static`; setting `routing.roles` adds an opt-in prose line. Roles mode is inert on v1 too: when `routing.delegation: "roles"`, `roleAgents`, `routing.exploration`, `routing.run` or `routing.workRoots` is set, the plugin logs one notice per process, `roles delegation requires OpenCode v2; using tiers`, and with `routing.delegation: "roles"` `/router` also reports the advisor info `roles-on-legacy-host`. v1 is not entirely unchanged by this release: the #84 guard and verification fixes apply on every host (see the [behaviour change entry](CHANGELOG.md#
|
|
1141
|
+
On OpenCode v1 the routing engine does not run: the `routing` block is validated and `engine` is forced to `static`; setting `routing.roles` adds an opt-in prose line. Roles mode is inert on v1 too: when `routing.delegation: "roles"`, `roleAgents`, `routing.exploration`, `routing.run` or `routing.workRoots` is set, the plugin logs one notice per process, `roles delegation requires OpenCode v2; using tiers`, and with `routing.delegation: "roles"` `/router` also reports the advisor info `roles-on-legacy-host`. v1 is not entirely unchanged by this release: the #84 guard and verification fixes apply on every host (see the [behaviour change entry](CHANGELOG.md#240---2026-10-09) of the changelog). 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).
|
|
1136
1142
|
|
|
1137
1143
|
## Roles mode (opt-in, OpenCode v2)
|
|
1138
1144
|
|
|
@@ -1155,6 +1161,29 @@ With `routing.delegation: "roles"` the orchestrator stops picking tiers: it disp
|
|
|
1155
1161
|
|
|
1156
1162
|
Put `{ "routing": { "delegation": "roles" } }` in the global override file and **restart OpenCode** (roles mode is decided at plugin start); restore the previous file and restart to go back. OpenCode v1 keeps the tier model. Guide: [`docs/ROLES.md`](docs/ROLES.md); decision record: [`docs/adr/0006-role-tier-assurance-delegation.md`](docs/adr/0006-role-tier-assurance-delegation.md).
|
|
1157
1163
|
|
|
1164
|
+
## TUI status (OpenCode v2)
|
|
1165
|
+
|
|
1166
|
+
On OpenCode v2 (2.0.24 or later) the package also ships a TUI entry, `tui.ts`, that shows which model and effort the router's sessions run with:
|
|
1167
|
+
|
|
1168
|
+
- **Main session footer:** `effort <value>` in the prompt footer, only when no variant is selected (the host's footer row already shows a selected variant). Root sessions normally show `effort default`, because the router applies no effort to primary agents.
|
|
1169
|
+
- **Delegated session view:** `<agent> · <model> · <effort>` above the composer.
|
|
1170
|
+
- **Main session while delegates run (opt-in, `runningRow`):** one `<agent> · <model> · <effort>` row per running delegate directly above the prompt box, from before the delegate's first token until the delegate finishes (its session is no longer running); at most `maxRows` rows, then `+<k> more`; nothing when no delegate runs. Off by default, so the main session shows only the footer's effort; turn it on with `"options": { "runningRow": true }` in `cli.json`.
|
|
1171
|
+
|
|
1172
|
+
The effort is what the router applied to the session's latest turn, reported by the server plugin over the rpc `opencode-model-router.effort`. While that channel has no answer, the footer shows `effort default` and the delegate rows show the message's variant.
|
|
1173
|
+
|
|
1174
|
+
It is enabled automatically: OpenCode v2 auto-loads the TUI entry of every package listed in `opencode.json` `plugins`, when the server entry loads. Options (`enabled`, `footer`, `childView`, `runningRow`, `maxRows`) go in OpenCode v2's TUI config file `cli.json` (for example `~/.config/opencode/cli.json`), in an entry whose `package` is the package name, or the package directory for a local checkout:
|
|
1175
|
+
|
|
1176
|
+
<!-- cli.json example -->
|
|
1177
|
+
```json
|
|
1178
|
+
{
|
|
1179
|
+
"plugins": [
|
|
1180
|
+
{ "package": "opencode-model-router", "options": { "runningRow": true, "maxRows": 6 } }
|
|
1181
|
+
]
|
|
1182
|
+
}
|
|
1183
|
+
```
|
|
1184
|
+
|
|
1185
|
+
Turn it off with `"options": { "enabled": false }`, or with the selector `"-opencode-model-router.status"` placed after any explicit entry for the plugin. On OpenCode v1 it does nothing: v1 never loads `tui.ts`. Guide: [`docs/TUI_STATUS.md`](docs/TUI_STATUS.md); options: [`docs/CONFIG_REFERENCE.md`](docs/CONFIG_REFERENCE.md#tui-status-options-opencode-v2).
|
|
1186
|
+
|
|
1158
1187
|
## Commands
|
|
1159
1188
|
|
|
1160
1189
|
| Command | Description |
|
|
@@ -1210,7 +1239,7 @@ These are character counts of the prompts the shipped config actually produces,
|
|
|
1210
1239
|
|
|
1211
1240
|
## Requirements
|
|
1212
1241
|
|
|
1213
|
-
- [OpenCode](https://opencode.ai) v1 (`>=1.0.0 <2.0.0`) or v2 **2.0.20+**
|
|
1242
|
+
- [OpenCode](https://opencode.ai) v1 (`>=1.0.0 <2.0.0`) or v2 **2.0.20+** (TUI status: 2.0.24+)
|
|
1214
1243
|
- Node.js 20+
|
|
1215
1244
|
- Provider API keys configured in OpenCode
|
|
1216
1245
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-model-router",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.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",
|
|
@@ -14,6 +14,7 @@
|
|
|
14
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
15
|
"smoke:routing": "cross-env RUN_OC_SMOKE_ROUTING=1 vitest run --config vitest.smoke.config.ts test/smoke/routing-engine.smoke.test.ts",
|
|
16
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
|
+
"smoke:tui": "cross-env RUN_OC_SMOKE_TUI=1 vitest run --config vitest.smoke.config.ts test/smoke/tui-status.smoke.test.ts",
|
|
17
18
|
"routing:stats": "node scripts/routing-stats.ts",
|
|
18
19
|
"typecheck": "tsc --noEmit"
|
|
19
20
|
},
|
|
@@ -45,6 +46,7 @@
|
|
|
45
46
|
],
|
|
46
47
|
"files": [
|
|
47
48
|
"server.ts",
|
|
49
|
+
"tui.ts",
|
|
48
50
|
"src/",
|
|
49
51
|
"tiers.json",
|
|
50
52
|
"LICENSE",
|
|
@@ -55,11 +57,14 @@
|
|
|
55
57
|
"@opencode-ai/plugin": ">=1.0.0 <2.0.0"
|
|
56
58
|
},
|
|
57
59
|
"devDependencies": {
|
|
60
|
+
"@lydell/node-pty": "1.2.0-beta.15",
|
|
58
61
|
"@opencode/plugin": "2.0.22",
|
|
59
62
|
"@types/node": "^26.2.0",
|
|
60
63
|
"@vitest/coverage-v8": "^5.0.3",
|
|
64
|
+
"@xterm/headless": "6.0.0",
|
|
61
65
|
"cross-env": "^10.1.0",
|
|
62
66
|
"istanbul-lib-coverage": "^3.2.2",
|
|
67
|
+
"solid-js": "1.9.15",
|
|
63
68
|
"typescript": "^7.0.2",
|
|
64
69
|
"vitest": "^5.0.3"
|
|
65
70
|
}
|
package/src/compat/v2-hooks.ts
CHANGED
|
@@ -43,6 +43,7 @@ import { createSystemAugmenter } from "../routing/wire/hint";
|
|
|
43
43
|
import { CONTEXT7_DOC_TOOLS, evaluatePermission, permissionMatches, permissionRules, publishReadOnlyPermissions } from "../router/read-only";
|
|
44
44
|
import { filterSensitiveGrep, isSensitivePath } from "../router/sensitive-paths";
|
|
45
45
|
import { canonicalAuthorityPath, insideWorkRoot } from "../routing/roles/work-root";
|
|
46
|
+
import { appliedEffort, appliedThinkingBudget, createEffortStore, registerEffortChannel } from "../tui/effort-channel";
|
|
46
47
|
|
|
47
48
|
/** Translate the router's own v1 tool vocabulary at the v2 boundary. */
|
|
48
49
|
export function v2Instructions(text: string): string {
|
|
@@ -657,6 +658,19 @@ export function roleCatalogFailureNotice(agent: string, childSessionID: string):
|
|
|
657
658
|
+ `again (the router could not build its tool catalog for this dispatch: fail closed, session "${childSessionID}").`;
|
|
658
659
|
}
|
|
659
660
|
|
|
661
|
+
/**
|
|
662
|
+
* Legacy agent-option aliases → the v2 per-turn keys (`reasoning_effort` → `reasoningEffort`, `reasoning_summary` →
|
|
663
|
+
* `reasoningSummary`, `budget_tokens` → `thinking`); an explicit v2 key wins. Returns a copy: `options` is never modified.
|
|
664
|
+
*/
|
|
665
|
+
export function normalizeAgentOptions(options: Readonly<Record<string, unknown>>): Record<string, unknown> {
|
|
666
|
+
const { reasoning_effort, reasoning_summary, budget_tokens, ...rest } = options;
|
|
667
|
+
const normalized: Record<string, unknown> = { ...rest };
|
|
668
|
+
if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
|
|
669
|
+
if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
|
|
670
|
+
if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
|
|
671
|
+
return normalized;
|
|
672
|
+
}
|
|
673
|
+
|
|
660
674
|
/** Register the existing router engine on the public OpenCode 2 domain APIs. */
|
|
661
675
|
export async function registerV2Hooks(
|
|
662
676
|
ctx: Context,
|
|
@@ -700,6 +714,27 @@ export async function registerV2Hooks(
|
|
|
700
714
|
// casts confined to this adapter, rather than weakening the v2 event types.
|
|
701
715
|
const legacy = hooks as unknown as Record<string, LegacyHook | undefined>;
|
|
702
716
|
const registrations: Array<{ dispose(): Promise<void> }> = [];
|
|
717
|
+
/** #90 P1.2: per session, what the context hook's `chat.params` bridge applied to the latest turn (the TUI's `effortOf`). */
|
|
718
|
+
// One store per adapter instance, not module state: every instance of a location records the same turns; the last registration answers.
|
|
719
|
+
const effortStore = createEffortStore();
|
|
720
|
+
/**
|
|
721
|
+
* #90 P1.2: records what a turn's request carries (read-only: `event.options` is normalised into a copy, never written), root and
|
|
722
|
+
* child sessions alike. Only a non-empty string session id is recorded; a turn that cannot be read is forgotten, never left stale.
|
|
723
|
+
*/
|
|
724
|
+
const recordEffortTurn = (event: SessionContext): void => {
|
|
725
|
+
const sessionID: unknown = event.sessionID;
|
|
726
|
+
if (typeof sessionID !== "string" || sessionID === "") return;
|
|
727
|
+
try {
|
|
728
|
+
const applied = normalizeAgentOptions(event.options);
|
|
729
|
+
effortStore.record(sessionID, {
|
|
730
|
+
effort: appliedEffort(applied, { providerID: event.model.providerID, modelID: event.model.id }),
|
|
731
|
+
thinkingBudget: appliedThinkingBudget(applied), variant: event.model.variant,
|
|
732
|
+
providerID: event.model.providerID, modelID: event.model.id, agent: event.agent, at: Date.now(),
|
|
733
|
+
});
|
|
734
|
+
} catch {
|
|
735
|
+
effortStore.forget(sessionID);
|
|
736
|
+
}
|
|
737
|
+
};
|
|
703
738
|
const abort = new AbortController();
|
|
704
739
|
const verifyingCalls = new Set<string>();
|
|
705
740
|
const depthBanners = new Map<string, string>();
|
|
@@ -1127,12 +1162,7 @@ export async function registerV2Hooks(
|
|
|
1127
1162
|
const nextOptions = new Map<string, Record<string, unknown>>();
|
|
1128
1163
|
for (const [name, definition] of Object.entries(next.agent)) {
|
|
1129
1164
|
if (nextOriginals.get(name) === JSON.stringify(definition) || !definition.options) continue;
|
|
1130
|
-
|
|
1131
|
-
const normalized = { ...options };
|
|
1132
|
-
if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
|
|
1133
|
-
if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
|
|
1134
|
-
if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
|
|
1135
|
-
nextOptions.set(name, normalized);
|
|
1165
|
+
nextOptions.set(name, normalizeAgentOptions(definition.options));
|
|
1136
1166
|
}
|
|
1137
1167
|
config = next;
|
|
1138
1168
|
originals = nextOriginals;
|
|
@@ -1378,6 +1408,10 @@ export async function registerV2Hooks(
|
|
|
1378
1408
|
if (!(key in event.options)) event.options[key] = value;
|
|
1379
1409
|
}
|
|
1380
1410
|
await legacy["chat.params"]?.(input, event.options);
|
|
1411
|
+
// #90 P1.2 (A3): what this turn's request carries after the router's hook; no effort key records none (clearing a stale one).
|
|
1412
|
+
// The channel never changes the hook's outcome.
|
|
1413
|
+
// Host v2.0.24 core/src/session/model-request.ts:408-411 fires `context` for primary requests only (compaction, generate, title have their own hooks).
|
|
1414
|
+
recordEffortTurn(event);
|
|
1381
1415
|
const routerConfig = loadConfig(ctx.location.directory);
|
|
1382
1416
|
const verify = routerConfig.enforcement?.verify;
|
|
1383
1417
|
if (event.agent === V2_GRADER_AGENT
|
|
@@ -1437,6 +1471,12 @@ export async function registerV2Hooks(
|
|
|
1437
1471
|
}
|
|
1438
1472
|
}
|
|
1439
1473
|
}
|
|
1474
|
+
// #90 P1.2 (A1): the TUI's `effortOf` rpc, answered from `effortStore`; tiers and roles mode alike. Feature-detected (a host
|
|
1475
|
+
// without `ctx.rpc.register` gets nothing), bounded (2 s; a late registration is kept), never throws; disposed with the other
|
|
1476
|
+
// registrations. GA-4: not awaited here, so a slow `register` never delays the hooks below; its dispose waits for the
|
|
1477
|
+
// registration to settle (at most the 2 s bound) and then disposes it.
|
|
1478
|
+
const effortChannel = registerEffortChannel(ctx.rpc, effortStore, ingestLogger).catch(() => async () => {});
|
|
1479
|
+
registrations.push({ dispose: async () => { await (await effortChannel)(); } });
|
|
1440
1480
|
registrations.push(await ctx.session.hook("context", async (event) => {
|
|
1441
1481
|
// #84 P2.3 (P-3, I9): a role session's context hook never fails the child. ANY error below empties its catalog (the
|
|
1442
1482
|
// strictest outcome) and is annotated for the parent's `subagent` result; every other agent keeps today's behaviour.
|
|
@@ -1444,8 +1484,13 @@ export async function registerV2Hooks(
|
|
|
1444
1484
|
try {
|
|
1445
1485
|
await buildContext(event, role);
|
|
1446
1486
|
} catch (error) {
|
|
1447
|
-
if (role === undefined)
|
|
1487
|
+
if (role === undefined) {
|
|
1488
|
+
// #90 P1.2: the request does not go out, so nothing is recorded for it (not even a record made earlier in this turn).
|
|
1489
|
+
if (typeof event.sessionID === "string") effortStore.forget(event.sessionID);
|
|
1490
|
+
throw error;
|
|
1491
|
+
}
|
|
1448
1492
|
for (const name of Object.keys(event.tools ?? {})) delete event.tools[name];
|
|
1493
|
+
recordEffortTurn(event); // #90 P1.2: the role session goes on fail-closed with these options: they are what is recorded
|
|
1449
1494
|
warnPermissionOnce(`role tool catalog failed for ${role}: ${String(error)}`);
|
|
1450
1495
|
const child = String(event.sessionID);
|
|
1451
1496
|
if (!catalogFailures.has(child)) {
|
|
@@ -1799,6 +1844,7 @@ export async function registerV2Hooks(
|
|
|
1799
1844
|
lookupNamedAgent.delete(data.sessionID);
|
|
1800
1845
|
lastCallOfChild.delete(data.sessionID);
|
|
1801
1846
|
hostBudget.forget(data.sessionID);
|
|
1847
|
+
effortStore.forget(data.sessionID); // #90 P1.2: a deleted session is no longer answered
|
|
1802
1848
|
}
|
|
1803
1849
|
await ingesting("session.deleted", () => ingest.onSessionGone(data.sessionID));
|
|
1804
1850
|
} else if (FLUSH_EVENT_TYPES.has(event.type)) {
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #90 P1.2 (amendments A1, A3): the server side of the TUI effort channel. OpenCode v2 only — the v2 adapter
|
|
3
|
+
* (src/compat/v2-hooks.ts) records, per session (root and child), what its `chat.params` bridge applied to the latest turn and
|
|
4
|
+
* answers the TUI's `effortOf` rpc from this store. Nothing here runs on OpenCode v1.
|
|
5
|
+
*/
|
|
6
|
+
import { isClaudeModel } from "../router/protocol";
|
|
7
|
+
import { effortRpc, type EffortOfOutput } from "./effort-rpc";
|
|
8
|
+
|
|
9
|
+
/** The store's default bound: the sessions of one location the TUI can still ask about. */
|
|
10
|
+
export const EFFORT_STORE_MAX_SESSIONS = 1000;
|
|
11
|
+
|
|
12
|
+
/** How long the registration waits for the host's `rpc.register` before it resolves without the channel (a late one is kept). */
|
|
13
|
+
export const EFFORT_REGISTER_TIMEOUT_MS = 2000;
|
|
14
|
+
|
|
15
|
+
/** One turn as the adapter saw it; fields that are not strings (or a finite `at`, a positive integer budget) are dropped. */
|
|
16
|
+
export interface EffortTurn {
|
|
17
|
+
readonly effort?: unknown;
|
|
18
|
+
readonly variant?: unknown;
|
|
19
|
+
readonly providerID?: unknown;
|
|
20
|
+
readonly modelID?: unknown;
|
|
21
|
+
readonly agent?: unknown;
|
|
22
|
+
readonly at?: unknown;
|
|
23
|
+
readonly thinkingBudget?: unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface EffortStore {
|
|
27
|
+
/** The latest turn of `sessionID` replaces the previous one (an absent effort clears a stale one). */
|
|
28
|
+
record(sessionID: string, turn: EffortTurn): void;
|
|
29
|
+
/** A copy of the latest turn of `sessionID`, or `{}` when nothing is known. */
|
|
30
|
+
lookup(sessionID: string): EffortOfOutput;
|
|
31
|
+
/** Drops what is known about `sessionID` (the session was deleted, or its latest request did not go out). */
|
|
32
|
+
forget(sessionID: string): void;
|
|
33
|
+
/** How many sessions are held. */
|
|
34
|
+
size(): number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
|
38
|
+
const TEXT_FIELDS = ["effort", "variant", "providerID", "modelID", "agent"] as const;
|
|
39
|
+
|
|
40
|
+
const nonEmptyString = (value: unknown): value is string => typeof value === "string" && value !== "";
|
|
41
|
+
const positiveInteger = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
42
|
+
|
|
43
|
+
/** Only the fields the rpc output declares, each only when it has a usable value (the output schema has no other keys). */
|
|
44
|
+
function sanitize(turn: EffortTurn): EffortOfOutput {
|
|
45
|
+
const out: Mutable<EffortOfOutput> = {};
|
|
46
|
+
for (const field of TEXT_FIELDS) {
|
|
47
|
+
const value = turn[field];
|
|
48
|
+
if (nonEmptyString(value)) out[field] = value;
|
|
49
|
+
}
|
|
50
|
+
if (typeof turn.at === "number" && Number.isFinite(turn.at)) out.at = turn.at;
|
|
51
|
+
if (positiveInteger(turn.thinkingBudget)) out.thinkingBudget = turn.thinkingBudget;
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A bounded in-memory store; above `maxSessions` the least recently WRITTEN session is evicted. */
|
|
56
|
+
export function createEffortStore(maxSessions: number = EFFORT_STORE_MAX_SESSIONS): EffortStore {
|
|
57
|
+
const max = Number.isSafeInteger(maxSessions) && maxSessions > 0 ? maxSessions : EFFORT_STORE_MAX_SESSIONS;
|
|
58
|
+
const entries = new Map<string, EffortOfOutput>();
|
|
59
|
+
return {
|
|
60
|
+
record(sessionID, turn) {
|
|
61
|
+
if (!nonEmptyString(sessionID)) return;
|
|
62
|
+
entries.delete(sessionID); // re-inserted last: the write order is the eviction order
|
|
63
|
+
entries.set(sessionID, sanitize(turn));
|
|
64
|
+
while (entries.size > max) entries.delete(entries.keys().next().value!);
|
|
65
|
+
},
|
|
66
|
+
lookup(sessionID) {
|
|
67
|
+
const entry = nonEmptyString(sessionID) ? entries.get(sessionID) : undefined;
|
|
68
|
+
return entry === undefined ? {} : { ...entry };
|
|
69
|
+
},
|
|
70
|
+
forget(sessionID) {
|
|
71
|
+
if (nonEmptyString(sessionID)) entries.delete(sessionID);
|
|
72
|
+
},
|
|
73
|
+
size: () => entries.size,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The effort a turn's (already normalised) request options carry. Two keys can hold it: `effort` (what `buildAgentOptions`
|
|
79
|
+
* writes for a Claude model, and what the escalation override replaces there) and `reasoningEffort` (every other family; the
|
|
80
|
+
* `reasoning_effort` alias once normalised). For a Claude model (the router's own `isClaudeModel`, on `provider/model`)
|
|
81
|
+
* `effort` is read first, otherwise `reasoningEffort`; each falls back to the other. Undefined when neither is a non-empty string.
|
|
82
|
+
*/
|
|
83
|
+
export function appliedEffort(
|
|
84
|
+
options: Readonly<Record<string, unknown>>,
|
|
85
|
+
model: { readonly providerID?: unknown; readonly modelID?: unknown } = {},
|
|
86
|
+
): string | undefined {
|
|
87
|
+
// `provider/model` as the router spells a model (a provider alone stays `anthropic/`, which the predicate still matches).
|
|
88
|
+
const id = nonEmptyString(model.modelID) ? model.modelID : "";
|
|
89
|
+
const ref = nonEmptyString(model.providerID) ? `${model.providerID}/${id}` : id;
|
|
90
|
+
const order = isClaudeModel(ref) ? ["effort", "reasoningEffort"] as const : ["reasoningEffort", "effort"] as const;
|
|
91
|
+
for (const key of order) {
|
|
92
|
+
const value = options[key];
|
|
93
|
+
if (nonEmptyString(value)) return value;
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The thinking budget a turn's (already normalised) request options carry, in the shape the router writes it
|
|
100
|
+
* (src/router/agent-options.ts `buildAgentOptions`: `thinking: { type: "enabled", budgetTokens }`; the `budget_tokens` alias once
|
|
101
|
+
* normalised): `budgetTokens` when `type` is `"enabled"` and the budget a positive integer, else undefined.
|
|
102
|
+
*/
|
|
103
|
+
export function appliedThinkingBudget(options: Readonly<Record<string, unknown>>): number | undefined {
|
|
104
|
+
const thinking = options.thinking;
|
|
105
|
+
if (thinking === null || typeof thinking !== "object") return undefined;
|
|
106
|
+
const { type, budgetTokens } = thinking as { type?: unknown; budgetTokens?: unknown };
|
|
107
|
+
return type === "enabled" && positiveInteger(budgetTokens) ? budgetTokens : undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The `effortOf` handler: defensive about its input (anything but a non-empty `sessionID` string answers `{}`). */
|
|
111
|
+
export function effortOfHandler(store: EffortStore): (input: unknown) => Promise<EffortOfOutput> {
|
|
112
|
+
return async (input) => {
|
|
113
|
+
try {
|
|
114
|
+
if (input === null || typeof input !== "object") return {};
|
|
115
|
+
const sessionID = (input as { sessionID?: unknown }).sessionID;
|
|
116
|
+
return nonEmptyString(sessionID) ? store.lookup(sessionID) : {};
|
|
117
|
+
} catch {
|
|
118
|
+
return {};
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
type EffortHandlers = { readonly effortOf: (input: unknown) => Promise<EffortOfOutput> };
|
|
124
|
+
interface RpcLike {
|
|
125
|
+
register(definition: typeof effortRpc, handlers: EffortHandlers): unknown;
|
|
126
|
+
}
|
|
127
|
+
interface Disposable {
|
|
128
|
+
dispose(): unknown;
|
|
129
|
+
}
|
|
130
|
+
export interface EffortChannelLog {
|
|
131
|
+
warn(message: string): void;
|
|
132
|
+
}
|
|
133
|
+
export interface EffortChannelOptions {
|
|
134
|
+
/** How long to wait for `register` (default {@link EFFORT_REGISTER_TIMEOUT_MS}); injectable for tests. */
|
|
135
|
+
readonly timeoutMs?: number;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const isDisposable = (value: unknown): value is Disposable =>
|
|
139
|
+
value !== null && typeof value === "object" && typeof (value as { dispose?: unknown }).dispose === "function";
|
|
140
|
+
|
|
141
|
+
/** Disposes a registration, best effort: the host drops the registry with the location anyway. */
|
|
142
|
+
async function disposeQuietly(registration: unknown): Promise<void> {
|
|
143
|
+
try {
|
|
144
|
+
if (isDisposable(registration)) await registration.dispose();
|
|
145
|
+
} catch {
|
|
146
|
+
// Never thrown out of a dispose path.
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const defaultLog: EffortChannelLog = { warn: (message) => console.warn(`[model-router] ${message}`) };
|
|
151
|
+
const NO_OP = async (): Promise<void> => {};
|
|
152
|
+
const TIMED_OUT: unique symbol = Symbol("effort-channel-timeout");
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Registers `effortOf` on the host's rpc domain (`ctx.rpc.register(definition, handlers)`, OpenCode v2 ≥ 2.0.22 (types), verified
|
|
156
|
+
* 2.0.24–2.0.26). Feature-detected (no `register` function: nothing, silently); a throwing or rejecting `register` is logged once
|
|
157
|
+
* and swallowed — the channel is optional and must never fail the plugin's setup. The returned promise waits for `register` a
|
|
158
|
+
* bounded time (default 2 s): past it, it resolves without the channel (logged once); the v2 adapter does not await it (GA-4). A
|
|
159
|
+
* registration that arrives later is kept (logged once) and disposed with the channel; one that arrives after the channel was
|
|
160
|
+
* disposed is disposed at once; a late rejection is swallowed. Resolves to a dispose function that never throws.
|
|
161
|
+
*/
|
|
162
|
+
export async function registerEffortChannel(
|
|
163
|
+
rpcLike: unknown,
|
|
164
|
+
store: EffortStore,
|
|
165
|
+
log: EffortChannelLog = defaultLog,
|
|
166
|
+
options: EffortChannelOptions = {},
|
|
167
|
+
): Promise<() => Promise<void>> {
|
|
168
|
+
const note = (message: string): void => {
|
|
169
|
+
try {
|
|
170
|
+
log.warn(message);
|
|
171
|
+
} catch {
|
|
172
|
+
// A failing log sink must not turn an optional channel into a setup failure.
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const warn = (message: string): void => note(`TUI effort channel not registered (effortOf unavailable): ${message}`);
|
|
176
|
+
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
|
177
|
+
let pending: Promise<unknown>;
|
|
178
|
+
try {
|
|
179
|
+
// The host's `ctx.rpc` is callable (`Object.assign(client, { register })`, @opencode/plugin promise/adapter.js): a function
|
|
180
|
+
// or an object carrying `register` both qualify.
|
|
181
|
+
const rpc = rpcLike as Partial<RpcLike> | null | undefined;
|
|
182
|
+
if (rpc === null || (typeof rpc !== "object" && typeof rpc !== "function") || typeof rpc.register !== "function") return NO_OP;
|
|
183
|
+
pending = Promise.resolve(rpc.register(effortRpc, { effortOf: effortOfHandler(store) }));
|
|
184
|
+
} catch (error) {
|
|
185
|
+
warn(messageOf(error));
|
|
186
|
+
return NO_OP;
|
|
187
|
+
}
|
|
188
|
+
const requested = options.timeoutMs;
|
|
189
|
+
const timeoutMs = typeof requested === "number" && Number.isFinite(requested) && requested >= 0 ? requested : EFFORT_REGISTER_TIMEOUT_MS;
|
|
190
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
191
|
+
const outcome = await Promise.race([
|
|
192
|
+
pending.then((registration) => ({ registration }), (error: unknown) => ({ error })),
|
|
193
|
+
new Promise<typeof TIMED_OUT>((resolve) => { timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs); }),
|
|
194
|
+
]);
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
if (outcome !== TIMED_OUT && "error" in outcome) {
|
|
197
|
+
warn(messageOf(outcome.error));
|
|
198
|
+
return NO_OP;
|
|
199
|
+
}
|
|
200
|
+
let disposed = false;
|
|
201
|
+
let registration: unknown = outcome === TIMED_OUT ? undefined : outcome.registration;
|
|
202
|
+
if (outcome === TIMED_OUT) {
|
|
203
|
+
note(`TUI effort channel: rpc.register did not settle within ${timeoutMs} ms; continuing without it (a late registration is kept)`);
|
|
204
|
+
pending.then((late) => {
|
|
205
|
+
if (disposed) {
|
|
206
|
+
void disposeQuietly(late); // the channel is gone already: never leave a registration behind
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
registration = late;
|
|
210
|
+
note(`TUI effort channel registered late (after the ${timeoutMs} ms wait); effortOf is available`);
|
|
211
|
+
}, () => {
|
|
212
|
+
// A late rejection: the channel stays unavailable, as the timeout already said.
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return async () => {
|
|
216
|
+
if (disposed) return;
|
|
217
|
+
disposed = true;
|
|
218
|
+
await disposeQuietly(registration);
|
|
219
|
+
};
|
|
220
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #90 P1.2 (amendment A1): the server→TUI effort channel, as a plain rpc definition shared by the v2 server plugin (which
|
|
3
|
+
* registers it, src/compat/v2-hooks.ts) and the TUI entry (which calls it). No imports on purpose: the TUI entry loads this
|
|
4
|
+
* file as is, so it must not pull the server side (or any host package) in.
|
|
5
|
+
*
|
|
6
|
+
* `effortOf({ sessionID })` answers what the router's own `chat.params` bridge applied to that session's latest turn (root and
|
|
7
|
+
* child sessions alike); `{}` when nothing is known.
|
|
8
|
+
*/
|
|
9
|
+
export const effortRpc = {
|
|
10
|
+
id: "opencode-model-router.effort",
|
|
11
|
+
methods: {
|
|
12
|
+
effortOf: {
|
|
13
|
+
input: {
|
|
14
|
+
type: "object",
|
|
15
|
+
properties: { sessionID: { type: "string" } },
|
|
16
|
+
required: ["sessionID"],
|
|
17
|
+
additionalProperties: false,
|
|
18
|
+
},
|
|
19
|
+
output: {
|
|
20
|
+
type: "object",
|
|
21
|
+
properties: {
|
|
22
|
+
effort: { type: "string" },
|
|
23
|
+
variant: { type: "string" },
|
|
24
|
+
providerID: { type: "string" },
|
|
25
|
+
modelID: { type: "string" },
|
|
26
|
+
agent: { type: "string" },
|
|
27
|
+
at: { type: "number" },
|
|
28
|
+
thinkingBudget: { type: "number" },
|
|
29
|
+
},
|
|
30
|
+
additionalProperties: false,
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
events: {},
|
|
35
|
+
} as const;
|
|
36
|
+
|
|
37
|
+
export type EffortRpc = typeof effortRpc;
|
|
38
|
+
|
|
39
|
+
/** The input of `effortOf`. */
|
|
40
|
+
export interface EffortOfInput {
|
|
41
|
+
readonly sessionID: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The output of `effortOf`; every field is absent when unknown (`{}` for a session the router never saw). */
|
|
45
|
+
export interface EffortOfOutput {
|
|
46
|
+
/**
|
|
47
|
+
* The effort the turn's request carried after the router's hook: the Anthropic `effort` key first for a Claude model,
|
|
48
|
+
* `reasoningEffort` first for any other (each falling back to the other).
|
|
49
|
+
*/
|
|
50
|
+
readonly effort?: string;
|
|
51
|
+
/** The turn's model variant (`Model.Ref.variant`). */
|
|
52
|
+
readonly variant?: string;
|
|
53
|
+
readonly providerID?: string;
|
|
54
|
+
readonly modelID?: string;
|
|
55
|
+
readonly agent?: string;
|
|
56
|
+
/** When the turn was recorded (epoch ms). */
|
|
57
|
+
readonly at?: number;
|
|
58
|
+
/** The Anthropic thinking budget the request carried (`thinking: { type: "enabled", budgetTokens }`), a positive integer. */
|
|
59
|
+
readonly thinkingBudget?: number;
|
|
60
|
+
}
|