opencode-tier-router 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +383 -2
- package/dist/gui-experimental.cjs +1 -0
- package/index.ts +382 -0
- package/package.json +52 -4
- package/src/alias.ts +2 -0
- package/src/cascade.ts +423 -0
- package/src/catalog.ts +37 -0
- package/src/config.ts +198 -0
- package/src/configstore.ts +274 -0
- package/src/confirmation.ts +162 -0
- package/src/control.ts +80 -0
- package/src/feedback.ts +39 -0
- package/src/gui/advanced.tsx +195 -0
- package/src/gui/api.ts +168 -0
- package/src/gui/budget.tsx +78 -0
- package/src/gui/status.tsx +91 -0
- package/src/gui/tiers.tsx +126 -0
- package/src/gui.tsx +321 -0
- package/src/heuristic.ts +43 -0
- package/src/jev.ts +195 -0
- package/src/log.ts +38 -0
- package/src/policy.ts +184 -0
- package/src/router.ts +498 -0
- package/src/rpc-handlers.ts +149 -0
- package/src/rpc.ts +121 -0
- package/src/session-state.ts +81 -0
- package/src/spend.ts +122 -0
- package/src/tui.ts +48 -0
- package/src/types.ts +150 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Brice Sauvajon
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,384 @@
|
|
|
1
|
-
#
|
|
1
|
+
# opencode-tier-router
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
An OpenCode V2 plugin that picks the **model + variant** pair of a cost tier for
|
|
6
|
+
every request in an `auto` session, on Jev's advice.
|
|
7
|
+
|
|
8
|
+
- Jev ships with the OpenCode Go plan: `opencode-go/jev-1.14`, answered with
|
|
9
|
+
`billing_source: "go-plus"` and cost 0. No external key.
|
|
10
|
+
Decision models appear neither in `opencode models` nor in the chat picker
|
|
11
|
+
(their type is `decision`), but `https://opencode.ai/inference/go/v1/models`
|
|
12
|
+
does list them. Do not target `opencode/jev-1.14` (the Zen provider): that
|
|
13
|
+
route is billed to OpenCode Models credits and answers `402` without them.
|
|
14
|
+
- Routing stays **inside the same provider** (`opencode-go` by default) through
|
|
15
|
+
the native `experimental.model.resolve` hook: no HTTP rewriting, and
|
|
16
|
+
authentication and the connection remain OpenCode's.
|
|
17
|
+
- When Jev is slow, unavailable or out of credit, a local heuristic takes over.
|
|
18
|
+
A classifier failure never blocks the request.
|
|
19
|
+
|
|
20
|
+
## What it does not do
|
|
21
|
+
|
|
22
|
+
- No cross-provider routing: OpenCode rejects a model outside the request's
|
|
23
|
+
provider.
|
|
24
|
+
- No per-tool or per-subagent routing.
|
|
25
|
+
- No override of OpenCode's own title/compaction model: the router only rewrites
|
|
26
|
+
requests already on `auto`. Pick the hidden title agent's model with
|
|
27
|
+
`agents.title.model` in `opencode.json`.
|
|
28
|
+
- No real-time quota handling: the budget is an estimate derived from the token
|
|
29
|
+
usage OpenCode reports (`session.step.started` / `session.step.ended`), not an
|
|
30
|
+
API lookup.
|
|
31
|
+
- No replacement for `/model`: only sessions on `opencode-go/auto` are routed.
|
|
32
|
+
|
|
33
|
+
## Quality cascade (experimental)
|
|
34
|
+
|
|
35
|
+
For `auto` sessions, an optional second pass judges the **actual draft** with
|
|
36
|
+
Jev and replays the request against a stronger tier only when the draft fails.
|
|
37
|
+
The gate is a `sufficient` predicate thresholded on `probability` (0.5 by
|
|
38
|
+
default), costs nothing on the Go plan, and applies only to final-text steps
|
|
39
|
+
(no tool calls). Every failure path is fail-open: the draft is served unchanged.
|
|
40
|
+
Start with `shadow` to measure without escalating:
|
|
41
|
+
|
|
42
|
+
```jsonc
|
|
43
|
+
"cascade": {
|
|
44
|
+
"mode": "off", // off | shadow | auto
|
|
45
|
+
"targetTier": "pro", // must exist in tiers
|
|
46
|
+
"gateThreshold": 0.5,
|
|
47
|
+
"gateTimeoutMs": 1500,
|
|
48
|
+
"fetchTimeoutMs": 30000
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
See `docs/faisabilite-cascade.md` and the design spec under
|
|
53
|
+
`docs/superpowers/specs/` for the measured accuracy and limits.
|
|
54
|
+
|
|
55
|
+
## Installation
|
|
56
|
+
|
|
57
|
+
### From npm (recommended)
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
opencode plugin add opencode-tier-router
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
or by hand in `~/.config/opencode/opencode.json`:
|
|
64
|
+
|
|
65
|
+
```jsonc
|
|
66
|
+
{ "plugins": ["opencode-tier-router"] }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
OpenCode installs the package and its dependencies itself: no clone, no `bun install`.
|
|
70
|
+
A bare name stays on the version it installed; run `opencode plugin update` to move to
|
|
71
|
+
the latest release, or pin it (`"opencode-tier-router@0.1.0"`, or
|
|
72
|
+
`"opencode-tier-router@^0.1.0"` to follow patches).
|
|
73
|
+
|
|
74
|
+
If you previously used the development symlink, remove it first with
|
|
75
|
+
`rm ~/.config/opencode/plugins/tier-router` (this deletes only the link, not the
|
|
76
|
+
checkout it points to) and drop the `./plugins/tier-router` entry from `plugins`.
|
|
77
|
+
|
|
78
|
+
### From a release archive
|
|
79
|
+
|
|
80
|
+
Download `opencode-tier-router-vX.Y.Z.tar.gz` from the repository releases, then:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
(
|
|
84
|
+
target=~/.config/opencode/plugins/tier-router
|
|
85
|
+
if [ -L "$target" ]; then
|
|
86
|
+
echo "$target is a development symlink; remove only the symlink, then re-run" >&2
|
|
87
|
+
exit 1
|
|
88
|
+
fi
|
|
89
|
+
mkdir -p "$target" &&
|
|
90
|
+
tar -xzf opencode-tier-router-vX.Y.Z.tar.gz -C "$target" --strip-components=1 &&
|
|
91
|
+
cd "$target" && bun install --frozen-lockfile
|
|
92
|
+
)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
If you previously used the development symlink, remove it first (see above).
|
|
96
|
+
|
|
97
|
+
then in `~/.config/opencode/opencode.json`:
|
|
98
|
+
|
|
99
|
+
```jsonc
|
|
100
|
+
{ "plugins": [{ "package": "./plugins/tier-router" }] }
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Development (symlink)
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
bun install
|
|
107
|
+
ln -s "$PWD" ~/.config/opencode/plugins/tier-router
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Use the same `plugins` entry as the archive install.
|
|
111
|
+
|
|
112
|
+
Select `opencode-go/auto` as the model afterwards. Check that the plugin loaded
|
|
113
|
+
with `opencode models | grep opencode-go/auto`.
|
|
114
|
+
|
|
115
|
+
### `Model auto isn't included in OpenCode Go`
|
|
116
|
+
|
|
117
|
+
`auto` is a plugin-local alias, not a model in the Go plan: OpenCode Go cannot
|
|
118
|
+
serve it. This 400 means a request reached the gateway before the
|
|
119
|
+
`experimental.model.resolve` hook rewrote it. `opencode models` listing the alias
|
|
120
|
+
only proves the model transform ran, not that routing is active. Check that:
|
|
121
|
+
|
|
122
|
+
- the plugin loaded and its configuration is valid (`mode` is `auto` or `shadow`,
|
|
123
|
+
not `off`);
|
|
124
|
+
- the session's saved tier identity still exists in `tiers` (a removed model is
|
|
125
|
+
refused rather than silently substituted);
|
|
126
|
+
- the session is not blocked by an ambiguous `applying` transition.
|
|
127
|
+
|
|
128
|
+
The decision log and `/tier-router` report the last state; reload or restart
|
|
129
|
+
OpenCode after fixing the configuration.
|
|
130
|
+
|
|
131
|
+
## Configuration
|
|
132
|
+
|
|
133
|
+
There is exactly one source of settings:
|
|
134
|
+
`~/.local/share/opencode/tier-router/config.json`. It is created with the
|
|
135
|
+
defaults on first start. Nothing is read from `opencode.json`; if options were
|
|
136
|
+
present on that first start, they are copied once into the file and a banner in
|
|
137
|
+
the screen then asks you to remove them.
|
|
138
|
+
|
|
139
|
+
Edit it from **Settings → Tier Router** in OpenCode Desktop. The page is not
|
|
140
|
+
available in the standalone web app (`opencode serve` in a browser): the web
|
|
141
|
+
client never fetches plugin GUI bundles today, so no plugin settings page can
|
|
142
|
+
appear there (upstream request: anomalyco/opencode#60976). The RPC itself works
|
|
143
|
+
in the browser, so from the web app use the config file or ask the agent through
|
|
144
|
+
the `tier_router` tool.
|
|
145
|
+
|
|
146
|
+
In Desktop, the screen covers the routing mode, feedback setting, budget, the
|
|
147
|
+
whole tier table (model, variant, optional `usd` override), the classifier, the
|
|
148
|
+
cache/downgrade knobs and the per-task-kind floors. Saves are validated against
|
|
149
|
+
the live catalogue, written atomically, and applied to every running instance
|
|
150
|
+
without a restart.
|
|
151
|
+
|
|
152
|
+
An invalid configuration at startup blocks routing and reports the error. After a
|
|
153
|
+
valid configuration has loaded, an invalid reload keeps the last valid one and
|
|
154
|
+
reports the error. The settings page reports tiers that fail catalogue validation.
|
|
155
|
+
|
|
156
|
+
After changing anything under `src/gui/`, rebuild the bundle and reload:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
bun run build && opencode reload
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`dist/gui-experimental.cjs` is committed because a symlinked local plugin has no
|
|
163
|
+
build step of its own; `bun test` compares its content with a fresh in-memory build.
|
|
164
|
+
|
|
165
|
+
## Default tiers
|
|
166
|
+
|
|
167
|
+
| tier | model | variant | $/M in → out | cache read | ctx / out |
|
|
168
|
+
| --- | --- | --- | --- | --- | --- |
|
|
169
|
+
| `quick` | beam-contributor | `low` | 0 → 0 | 0 | 1M / 131k |
|
|
170
|
+
| `light` | hy4-flash | `none` | 0.07 → 0.281 | 0.003 | 1M / 65k |
|
|
171
|
+
| `standard` | deepseek-v4.1-flash | `high` | 0.15 → 0.60 | 0.003 | 1M / 384k |
|
|
172
|
+
| `pro` | minimax-m4 | `high` | 0.80 → 3.10 | 0.05 | 1M / 262k |
|
|
173
|
+
| `strong` | qwen4-max | `high` | 1.50 → 4.50 | 0.075 | 1M / 262k |
|
|
174
|
+
| `max` | kimi-k3.1-pro | `max` | 2 → 10 | 0.20 | 1M / 1M |
|
|
175
|
+
|
|
176
|
+
`quick` (beam-contributor) bills 0 and keeps a 131k output. `light` (hy4-flash) is
|
|
177
|
+
the cheapest paid text tier but caps output at 65k. `standard` raises that cap to
|
|
178
|
+
384k for the same cache price. `pro` (minimax-m4) doubles the output cap to 262k
|
|
179
|
+
before `strong` flips to the qwen price. `max` (kimi) is not a superset in price
|
|
180
|
+
but removes the output cap: 1M tokens.
|
|
181
|
+
|
|
182
|
+
The settings screen checks tier edits against the live catalogue before saving.
|
|
183
|
+
With fewer than 2 usable tiers, multi-tier routing is inactive. If the source
|
|
184
|
+
model is available, a fresh session can use it as a fallback; a missing previous
|
|
185
|
+
tier is not silently replaced.
|
|
186
|
+
|
|
187
|
+
## Options
|
|
188
|
+
|
|
189
|
+
| key | default | purpose |
|
|
190
|
+
| --- | --- | --- |
|
|
191
|
+
| `providers` | `["opencode-go"]` | Providers where the `auto` alias is added and the hooks are installed. Read-only in the screen: changing it needs a restart. |
|
|
192
|
+
| `mode` | `"auto"` | `auto`, `shadow` (log without applying), `off`. |
|
|
193
|
+
| `feedback` | `"information"` | `information` or `confirmation`, independently of `mode`. |
|
|
194
|
+
| `tiers` | the table above | `[{ name, model, variant, usd? }]`; `variant: null` only when the model exposes no effort control; `usd` (`input`, `output`, `cacheRead`, `cacheWrite`) replaces a price missing from the catalogue. |
|
|
195
|
+
| `classifier.model` | `"opencode-go/jev-1.14"` | Decision model (falls back to `opencode-go/jev-1.13`). |
|
|
196
|
+
| `classifier.timeoutMs` | `900` | Total classifier budget. |
|
|
197
|
+
| `classifier.minPromptChars` | `12` | Below this, no routing. |
|
|
198
|
+
| `classifier.confidenceThreshold` | `0.34` | Below this, the current tier is kept. |
|
|
199
|
+
| `kindMinimumTier` | `plan/review/refactor → pro`, `debug/implement/explain → standard`, `chat → quick` | Floor per task kind. |
|
|
200
|
+
| `budget.dailyUsd` / `monthlyUsd` | — | Machine-wide caps (every project, every session). |
|
|
201
|
+
| `budget.softRatio` / `hardRatio` | `0.7` / `0.9` | Budget thresholds influence the proposed tier; confirmation can keep the current tier. |
|
|
202
|
+
| `cache.minTokens` | `20000` | Below this, the cache guard is ignored. |
|
|
203
|
+
| `cache.minTierDelta` | `1` | Minimum tier gap before a change is accepted with a warm cache. |
|
|
204
|
+
| `cache.maxPenaltyUsd` | `0.05` | Minimum saving required to change with a warm cache. |
|
|
205
|
+
| `downgradeDelta` | `1` | Minimum accepted drop, and only on the next user turn. |
|
|
206
|
+
| `fallbackTier` | `"standard"` | Tier served until a decision has been taken. |
|
|
207
|
+
| — | `~/.local/share/opencode/tier-router/decisions.jsonl` | Decision log (metadata only), fixed. |
|
|
208
|
+
| — | `~/.local/share/opencode/tier-router/spend.jsonl` | Spend ledger, fixed. |
|
|
209
|
+
|
|
210
|
+
## Decision
|
|
211
|
+
|
|
212
|
+
1. Shortcuts without a Jev call: prompt shorter than `minPromptChars`, slash
|
|
213
|
+
command, acknowledgement.
|
|
214
|
+
2. Jev grades the request on four axes (task kind, complexity, deep-reasoning
|
|
215
|
+
need, deserved tier) and returns a confidence.
|
|
216
|
+
3. Composition: `kindMinimumTier` floor, then the capacity guard (context and
|
|
217
|
+
max output of the model), then budget, then stickiness, then cache.
|
|
218
|
+
4. Upgrades are proposed immediately; downgrades only on the next user turn, and
|
|
219
|
+
only by at least `downgradeDelta` tiers. Confirmation, when enabled, precedes
|
|
220
|
+
a change.
|
|
221
|
+
5. In information mode, `compaction`, `title` and `generate` use the cheapest
|
|
222
|
+
tier. In confirmation mode they use the current tier without another question
|
|
223
|
+
or change, which can cost more.
|
|
224
|
+
|
|
225
|
+
## Routing feedback and confirmation
|
|
226
|
+
|
|
227
|
+
The global `feedback` setting defaults to `"information"`, including for older
|
|
228
|
+
configurations without this key. Set it to `"confirmation"` in the config file
|
|
229
|
+
or Desktop settings to ask before changes. It is independent of `mode`:
|
|
230
|
+
`auto` applies routing choices, subject to confirmation when enabled; `shadow`
|
|
231
|
+
reports simulations without applying or confirming them; and `off` does not
|
|
232
|
+
route or ask for confirmation.
|
|
233
|
+
|
|
234
|
+
Desktop and terminal show session-specific toasts for the first selection and
|
|
235
|
+
changes, including tier, model, variant and the available reason. Toasts stay on
|
|
236
|
+
screen for 15 seconds so the transition can be read: the headline carries the
|
|
237
|
+
tier names, and models, variants and the reason appear under it. They state what
|
|
238
|
+
**Tier Router selected** in its resolution hook: this does not prove execution
|
|
239
|
+
or the final model after later hooks or plugins. `session.step.started` instead
|
|
240
|
+
reports the model observed for step accounting; it does not confirm the router's
|
|
241
|
+
selection. An unchanged shadow simulation is not announced repeatedly. The
|
|
242
|
+
standalone web app receives no informational toast or automatic
|
|
243
|
+
conversational summary. In confirmation mode, the native form remains available
|
|
244
|
+
in OpenCode clients that support forms, including web.
|
|
245
|
+
|
|
246
|
+
In confirmation mode, a proposed tier, model or variant change requires approval,
|
|
247
|
+
including the first choice when it differs from the fallback tier and changes
|
|
248
|
+
requested with `tier_router`. The tool records a force request; it does not
|
|
249
|
+
immediately apply a model. The native form is independent of permission
|
|
250
|
+
auto-approval. Accept applies the proposal; reject or close keeps the current
|
|
251
|
+
tier. If no answer is processed within 60 seconds after the server confirms form
|
|
252
|
+
creation, the proposal is accepted automatically. The first decision **processed**
|
|
253
|
+
wins: a refusal clicked before the deadline can arrive too late. Targeted form
|
|
254
|
+
cleanup after interruption, timeout or error is best effort, so a form can remain
|
|
255
|
+
visible if cleanup fails.
|
|
256
|
+
|
|
257
|
+
A creation, host-verification or communication error keeps the current tier and
|
|
258
|
+
reports an error; it is not a timeout. Stop before application invalidates the
|
|
259
|
+
proposal, preventing a late response or deadline from applying it. Refusing a
|
|
260
|
+
budget-driven downgrade can exceed the estimated budget, including its hard
|
|
261
|
+
limit. Refusing a capacity-driven upgrade keeps the current model, so the request
|
|
262
|
+
can fail if that model cannot handle the context.
|
|
263
|
+
|
|
264
|
+
Confirmation uses the shared OpenCode service after verifying that it is the
|
|
265
|
+
plugin's host. In standard `--standalone`, the private server's address and
|
|
266
|
+
authentication are not provided to the plugin, so confirmation is unavailable
|
|
267
|
+
and the current tier is kept. An embedded SDK host without HTTP also needs an
|
|
268
|
+
explicit application integration, which this plugin does not provide.
|
|
269
|
+
|
|
270
|
+
## Log
|
|
271
|
+
|
|
272
|
+
Metadata-only JSON lines distinguish proposals, decisions and selections. A
|
|
273
|
+
`proposalID` correlates a proposal with its decision, whose `outcome` records
|
|
274
|
+
acceptance, refusal or error; an acceptance records `reply`, `timeout` or
|
|
275
|
+
`automatic` as its provenance. A selection is logged only after its durable
|
|
276
|
+
checkpoint succeeds. Entries contain no prompt, tool output or secret:
|
|
277
|
+
|
|
278
|
+
```json
|
|
279
|
+
{"at":"2026-11-29T13:24:31.703Z","sessionID":"ses_…","kind":"primary","source":"jev","phase":"selected","proposalID":"…","tier":"pro","model":"qwen4-max","variant":"high","spendTodayUsd":0.0123,"confidence":0.41,"classifier":"jev"}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
`source` is one of `jev`, `jev-held`, `heuristic`, `sticky`, `tiny`, `cheap`,
|
|
283
|
+
`capacity`, `budget`, `cache`, `forced`, `fallback`.
|
|
284
|
+
|
|
285
|
+
## Cache measurement
|
|
286
|
+
|
|
287
|
+
Three requests in a warm session on `glm-5.3-flash`, through `opencode run`:
|
|
288
|
+
|
|
289
|
+
| request | model#variant | input | cache read |
|
|
290
|
+
| --- | --- | --- | --- |
|
|
291
|
+
| 1 | glm-5.3-flash#low | 2011 | 12912 |
|
|
292
|
+
| 2 | glm-5.3-flash#low | 326 | 14912 |
|
|
293
|
+
| 3 | glm-5.3-flash#max | 14663 | 768 |
|
|
294
|
+
|
|
295
|
+
Conclusion: **changing the variant invalidates the cache** on opencode-go. The
|
|
296
|
+
cache guard therefore applies to every tier change, variants included.
|
|
297
|
+
|
|
298
|
+
## Cost
|
|
299
|
+
|
|
300
|
+
OpenCode Go reports `cost: 0` for its models (subscription, no per-request
|
|
301
|
+
billing). The plugin therefore estimates the cost of each step:
|
|
302
|
+
|
|
303
|
+
- the model observed at `session.step.started` is used for accounting, so
|
|
304
|
+
**every** session counts, including those that do not use `auto`; this is not
|
|
305
|
+
proof of the router's earlier selection;
|
|
306
|
+
- `input`, `output`, `reasoning`, `cache.read` and `cache.write` tokens are
|
|
307
|
+
multiplied by the models.dev price of the served model, with reasoning billed
|
|
308
|
+
at the output price;
|
|
309
|
+
- the cost reported by OpenCode is only used when it is non-zero.
|
|
310
|
+
|
|
311
|
+
For the next-call estimate behind the budget guard, the already-cached share is
|
|
312
|
+
billed at the `cacheRead` rate instead of the input rate: a warm 660k-token
|
|
313
|
+
session does not cost $2.64 but a few cents, so the router does not drop a tier
|
|
314
|
+
for no reason.
|
|
315
|
+
|
|
316
|
+
As a result the budget remains an **estimate**, not an invoice.
|
|
317
|
+
|
|
318
|
+
## Known limitations
|
|
319
|
+
|
|
320
|
+
- Refused targets are not proposed again in the same turn for the same
|
|
321
|
+
configuration and origin, even after another target is refused or after a
|
|
322
|
+
restart. A new turn or changed configuration clears these refusals.
|
|
323
|
+
Interruption or a crash between the durable
|
|
324
|
+
`applying` checkpoint and the final selection checkpoint can leave an ambiguous
|
|
325
|
+
`applying` state that blocks subsequent transitions. No automatic repair is
|
|
326
|
+
provided. On recovery, a valid durable `selected` state remains authoritative;
|
|
327
|
+
it still does not prove execution. If an ambiguous `applying` state contains a
|
|
328
|
+
form ID, recovery attempts targeted cancellation on a best-effort basis without
|
|
329
|
+
clearing the state or unblocking the transition. While blocked, prompt turns do
|
|
330
|
+
not change that saved state and force requests are rejected.
|
|
331
|
+
- An error after the router mutates a model is reported as an ambiguous selection,
|
|
332
|
+
not as proof that the previous tier was retained. A valid durable `selected`
|
|
333
|
+
checkpoint remains authoritative on recovery even if its write reported an
|
|
334
|
+
error and restoring `applying` also failed.
|
|
335
|
+
- If a session's selected identity is missing from the current configuration,
|
|
336
|
+
the router does not substitute another tier or erase the saved identity. It
|
|
337
|
+
logs an `identity_missing` metadata diagnostic once while the condition
|
|
338
|
+
persists; after the session is loaded, `/tier-router` reports the unavailable
|
|
339
|
+
identity instead of claiming there was no routed request. Before the session is
|
|
340
|
+
loaded, the command only reports that routing status is unavailable.
|
|
341
|
+
- The settings screen uses the experimental GUI plugin API (`./gui-experimental`); a rename there can break the page until the plugin is updated.
|
|
342
|
+
- `experimental.model.resolve` and `experimental.generate.decisions` are marked
|
|
343
|
+
experimental: an OpenCode change can break the integration.
|
|
344
|
+
- The `auto` alias is re-added on every transform reload; a refresh of the
|
|
345
|
+
managed catalogue can make it disappear for a few seconds.
|
|
346
|
+
- One Jev call per step (up to 4 per turn). No per-turn cache yet.
|
|
347
|
+
- The spend ledger is append-only and never pruned.
|
|
348
|
+
- Interactive acceptance on OpenCode 2.4.2 has not been performed for Desktop,
|
|
349
|
+
terminal, web or standalone. The locally available OpenCode 2.4.5 is not a
|
|
350
|
+
substitute for that validation.
|
|
351
|
+
|
|
352
|
+
## Development
|
|
353
|
+
|
|
354
|
+
```bash
|
|
355
|
+
bun install
|
|
356
|
+
bun test
|
|
357
|
+
bunx tsc --noEmit
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
`bun test` also packs the npm tarball (`npm pack --dry-run`) and checks that every
|
|
361
|
+
plugin part is inside and that tests, docs and tooling stay out, so a broken `files`
|
|
362
|
+
list fails before a tag is pushed. npm must be on the `PATH` for that check; CI pins
|
|
363
|
+
Node 24.
|
|
364
|
+
|
|
365
|
+
### Releasing
|
|
366
|
+
|
|
367
|
+
1. Bump `version` in `package.json` and merge to `main`.
|
|
368
|
+
2. `git tag v<version> && git push origin v<version>`.
|
|
369
|
+
|
|
370
|
+
The `Release` workflow then checks the tag against `package.json`, re-runs typecheck,
|
|
371
|
+
tests and the bundle freshness check in a job without publish rights, then publishes to
|
|
372
|
+
npm through trusted publishing (OIDC: no token in the repository) and creates the GitHub
|
|
373
|
+
release with the source archive. A version already on npm and an existing GitHub release
|
|
374
|
+
are skipped, so the workflow can be re-run.
|
|
375
|
+
|
|
376
|
+
The very first publish of a new package cannot use trusted publishing: npm requires the
|
|
377
|
+
package to exist before a trusted publisher can be attached. Publish `0.1.0` once by
|
|
378
|
+
hand (`npm publish --access public`, npm login with 2FA), then add the trusted
|
|
379
|
+
publisher on npmjs.com — GitHub Actions, user `bsauvajon`, repository
|
|
380
|
+
`opencode-tier-router`, workflow filename `release.yml`, with `npm publish` allowed.
|
|
381
|
+
A new trusted publisher must complete its first successful publish within 2 days: the
|
|
382
|
+
`v0.1.0` tag does not count (that version is already on npm, so the workflow skips it),
|
|
383
|
+
so publish the next version through the workflow within 2 days or the configuration
|
|
384
|
+
expires and has to be created again.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});let e=require("solid-js/web"),t=require("solid-js"),n=require("@opencode/plugin/gui"),r=require("@opencode/plugin/rpc");var i=15e3,a=e=>`${e.name} (${e.model}, variante ${e.variant??`aucune`})`;function o(e){let t=e.from,n=`${t?`${t.name} → `:``}${e.to.name}`,r=`${t?`${a(t)} → `:``}${a(e.to)} : ${e.reason}`;return e.status===`error`&&e.reason===`selection_ambiguous`?{headline:`Tier Router : état de sélection ambigu après une erreur`,detail:`le modèle final est inconnu.`,failed:!0}:e.status===`selected`?{headline:`Tier Router a sélectionné ${n}`,detail:r,failed:!1}:e.status===`simulated`?{headline:`Simulation : Tier Router aurait sélectionné ${n}`,detail:r,failed:!1}:{headline:`Tier Router a conservé ${t?t.name:`le palier courant`}`,detail:`${e.status===`rejected`?`changement refusé`:`erreur`} vers ${a(e.to)} : ${e.reason}`,failed:e.status===`error`}}var s={type:`object`,additionalProperties:!1},c={type:`object`,properties:{name:{type:`string`},providerID:{type:`string`},model:{type:`string`},variant:{type:[`string`,`null`]}},required:[`name`,`providerID`,`model`,`variant`],additionalProperties:!1},l=r.Rpc.define({id:`tier-router`,methods:{hostIdentity:{input:s,output:{type:`object`,properties:{instanceID:{type:`string`}},required:[`instanceID`],additionalProperties:!1}},getConfig:{input:s,output:{type:`object`,properties:{config:{type:`object`},models:{type:`array`,items:{type:`object`}},errors:{type:`array`,items:{type:`string`}},optionsIgnored:{type:`boolean`}},required:[`config`,`models`,`errors`,`optionsIgnored`],additionalProperties:!1}},saveConfig:{input:{type:`object`,properties:{config:{type:`object`}},required:[`config`],additionalProperties:!1},output:{type:`object`,properties:{ok:{type:`boolean`},errors:{type:`array`,items:{type:`string`}}},required:[`ok`,`errors`],additionalProperties:!1}},status:{input:s,output:{type:`object`,properties:{mode:{type:`string`},routingActive:{type:`boolean`},lastDecision:{type:[`object`,`null`]},spend:{type:`object`},lastDecisions:{type:`array`,items:{type:`object`}},cascadeStats:{type:`object`},fileErrors:{type:`array`,items:{type:`string`}},optionsIgnored:{type:`boolean`}},required:[`mode`,`routingActive`,`lastDecision`,`spend`,`lastDecisions`,`cascadeStats`,`fileErrors`,`optionsIgnored`],additionalProperties:!1}},resetConfig:{input:s,output:{type:`object`,properties:{ok:{type:`boolean`},errors:{type:`array`,items:{type:`string`}}},required:[`ok`,`errors`],additionalProperties:!1}},probeClassifier:{input:s,output:{type:`object`,properties:{ok:{type:`boolean`},model:{type:`string`},latencyMs:{type:`number`},error:{type:`string`}},required:[`ok`],additionalProperties:!1}}},events:{routing:{schema:{type:`object`,properties:{sessionID:{type:`string`},turn:{type:`number`},status:{type:`string`,enum:[`selected`,`simulated`,`rejected`,`error`]},from:c,to:c,reason:{type:`string`}},required:[`sessionID`,`turn`,`status`,`to`,`reason`],additionalProperties:!1}},changed:{schema:{type:`object`,properties:{at:{type:`number`}},required:[`at`],additionalProperties:!1}}}});function u(e){let[n,r]=(0,t.createSignal)(null),[i,a]=(0,t.createSignal)([]),[o,s]=(0,t.createSignal)(null),[c,u]=(0,t.createSignal)(null),[d,f]=(0,t.createSignal)(!1),[p,m]=(0,t.createSignal)(!1),[h,g]=(0,t.createSignal)(null),_=()=>e.client.rpc(l),v=async()=>{s(await _().status({}))},y=async()=>{let[e,t]=await Promise.all([_().getConfig({}),_().status({})]);d()||r(e.config),a(e.models??[]),s(t),u(e.errors?.[0]??null)},b=e=>{let t=n();t&&(r({...t,...e}),f(!0))};return{config:n,models:i,status:o,error:c,dirty:d,busy:p,probe:h,refresh:y,refreshStatus:v,patch:b,patchNested:(e,t)=>{let r=n();r&&b({[e]:{...r[e],...t}})},save:async()=>{let e=n();if(!e)return!1;m(!0);try{let t=await _().saveConfig({config:e});return t.ok?(u(null),await y(),!0):(u(t.errors?.[0]??`save refused`),!1)}catch(e){return u(String(e?.message??e)),!1}finally{m(!1)}},resetDefaults:async()=>{m(!0);try{let e=await _().resetConfig({});e.ok?(await y(),u(null)):u(e.errors?.[0]??`reset refused`)}catch(e){u(String(e?.message??e))}finally{m(!1)}},testClassifier:async()=>{g({ok:!0,latencyMs:void 0});try{let e=await _().probeClassifier({});g(e)}catch(e){g({ok:!1,error:String(e?.message??e)})}}}}var d=(0,e.template)(`<div style=display:flex;gap:6px;align-items:center;flex-wrap:wrap>`),f=(0,e.template)(`<span>`),p=[`opencode-go/jev-1.14`,`opencode-go/jev-1.13`,`opencode/jev-1.13-free`],m=[`plan`,`implement`,`debug`,`refactor`,`review`,`explain`,`chat`],h=e=>{let t=e.trim();if(!t)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0};function g(n){let r=()=>n.api.config(),i=()=>(r()?.tiers??[]).map(e=>e.name);return[(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.classifier`)},get footer(){return(0,e.createComponent)(t.Show,{get when(){return n.api.probe()},get children(){var t=f();return(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!n.api.probe().ok);return()=>t()?`${n.t(`classifier.probe.ok`)} ${n.api.probe().latencyMs} ms`:`${n.t(`classifier.probe.fail`)} ${n.api.probe().error??``}`})()),t}})},get children(){return[(0,e.createComponent)(n.ui.SettingsRow,{id:`classifier-model`,get title(){return n.t(`classifier.model`)},get description(){return n.t(`classifier.model.detail`)},get children(){var t=d();return(0,e.insert)(t,(0,e.createComponent)(n.ui.Select,{get label(){return n.t(`classifier.model`)},get value(){return(0,e.memo)(()=>!!p.includes(r()?.classifier?.model??``))()?r().classifier.model:`custom`},get options(){return[...p.map(e=>({value:e,label:e})),{value:`custom`,label:n.t(`classifier.custom`)}]},onChange:e=>n.api.patchNested(`classifier`,{model:e===`custom`?r().classifier.model:e})}),null),(0,e.insert)(t,(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`classifier.model`)},get value(){return r()?.classifier?.model??``},onInput:e=>n.api.patchNested(`classifier`,{model:e})}),null),(0,e.insert)(t,(0,e.createComponent)(n.ui.Button,{size:`small`,onClick:()=>void n.api.testClassifier(),get children(){return n.t(`classifier.test`)}}),null),t}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`classifier-timeout`,get title(){return n.t(`classifier.timeout`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`classifier.timeout`)},get value(){return r()?.classifier?.timeoutMs?.toString()??``},onInput:e=>n.api.patchNested(`classifier`,{timeoutMs:h(e)??900})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`classifier-confidence`,get title(){return n.t(`classifier.confidence`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`classifier.confidence`)},get value(){return r()?.classifier?.confidenceThreshold?.toString()??``},onInput:e=>n.api.patchNested(`classifier`,{confidenceThreshold:h(e)??.34})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`classifier-minchars`,get title(){return n.t(`classifier.minchars`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`classifier.minchars`)},get value(){return r()?.classifier?.minPromptChars?.toString()??``},onInput:e=>n.api.patchNested(`classifier`,{minPromptChars:h(e)??12})})}})]}}),(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.cache`)},get children(){return[(0,e.createComponent)(n.ui.SettingsRow,{id:`cache-tokens`,get title(){return n.t(`cache.tokens`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cache.tokens`)},get value(){return r()?.cache?.minTokens?.toString()??``},onInput:e=>n.api.patchNested(`cache`,{minTokens:h(e)??2e4})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`cache-delta`,get title(){return n.t(`cache.delta`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cache.delta`)},get value(){return r()?.cache?.minTierDelta?.toString()??``},onInput:e=>n.api.patchNested(`cache`,{minTierDelta:h(e)??1})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`cache-penalty`,get title(){return n.t(`cache.penalty`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cache.penalty`)},get value(){return r()?.cache?.maxPenaltyUsd?.toString()??``},onInput:e=>n.api.patchNested(`cache`,{maxPenaltyUsd:h(e)??.05})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`downgrade`,get title(){return n.t(`cache.downgrade`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cache.downgrade`)},get value(){return r()?.downgradeDelta?.toString()??``},onInput:e=>n.api.patch({downgradeDelta:h(e)??1})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`fallback`,get title(){return n.t(`cache.fallback`)},get children(){return(0,e.createComponent)(n.ui.Select,{get label(){return n.t(`cache.fallback`)},get value(){return r()?.fallbackTier??i()[0]},get options(){return i().map(e=>({value:e,label:e}))},onChange:e=>n.api.patch({fallbackTier:e})})}})]}}),(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.kinds`)},get children(){return(0,e.createComponent)(t.For,{each:m,children:t=>(0,e.createComponent)(n.ui.SettingsRow,{id:`kind-${t}`,title:t,get children(){return(0,e.createComponent)(n.ui.Select,{label:t,get value(){return r()?.kindMinimumTier?.[t]??`none`},get options(){return[{value:`none`,label:n.t(`tiers.none`)},...i().map(e=>({value:e,label:e}))]},onChange:e=>{let i={...r()?.kindMinimumTier??{}};e===`none`?delete i[t]:i[t]=e,n.api.patch({kindMinimumTier:i})}})}})})}}),(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.cascade`)},get footer(){return(()=>{var t=f();return(0,e.insert)(t,()=>n.t(`cascade.detail`)),t})()},get children(){return[(0,e.createComponent)(n.ui.SettingsRow,{id:`cascade-mode`,get title(){return n.t(`cascade.mode`)},get children(){return(0,e.createComponent)(n.ui.Select,{get label(){return n.t(`cascade.mode`)},get value(){return r()?.cascade?.mode??`off`},get options(){return[{value:`off`,label:n.t(`mode.off`)},{value:`shadow`,label:n.t(`mode.shadow`)},{value:`auto`,label:n.t(`mode.auto`)}]},onChange:e=>n.api.patchNested(`cascade`,{mode:e})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`cascade-target`,get title(){return n.t(`cascade.target`)},get children(){return(0,e.createComponent)(n.ui.Select,{get label(){return n.t(`cascade.target`)},get value(){return r()?.cascade?.targetTier??i()[0]},get options(){return i().map(e=>({value:e,label:e}))},onChange:e=>n.api.patchNested(`cascade`,{targetTier:e})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`cascade-threshold`,get title(){return n.t(`cascade.threshold`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cascade.threshold`)},get value(){return r()?.cascade?.gateThreshold?.toString()??``},onInput:e=>n.api.patchNested(`cascade`,{gateThreshold:h(e)??.5})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`cascade-gate-timeout`,get title(){return n.t(`cascade.gateTimeout`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cascade.gateTimeout`)},get value(){return r()?.cascade?.gateTimeoutMs?.toString()??``},onInput:e=>n.api.patchNested(`cascade`,{gateTimeoutMs:h(e)??1500})})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`cascade-fetch-timeout`,get title(){return n.t(`cascade.fetchTimeout`)},get children(){return(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`cascade.fetchTimeout`)},get value(){return r()?.cascade?.fetchTimeoutMs?.toString()??``},onInput:e=>n.api.patchNested(`cascade`,{fetchTimeoutMs:h(e)??3e4})})}})]}}),(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.advanced`)},get footer(){return(()=>{var t=f();return(0,e.insert)(t,()=>n.t(`advanced.providers.detail`)),t})()},get children(){return(0,e.createComponent)(n.ui.SettingsRow,{id:`providers`,get title(){return n.t(`advanced.providers`)},get children(){var t=f();return(0,e.insert)(t,()=>(r()?.providers??[]).join(`, `)),t}})}})]}var _=(0,e.template)(`<span>`),v=e=>{let t=e.trim();if(!t)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0};function y(t){let n=()=>t.api.config();return[(0,e.createComponent)(t.ui.SettingsSection,{get title(){return t.t(`section.mode`)},get children(){return[(0,e.createComponent)(t.ui.SettingsRow,{id:`mode`,get title(){return t.t(`mode.title`)},get description(){return t.t(`mode.detail`)},get children(){return(0,e.createComponent)(t.ui.Select,{get label(){return t.t(`mode.title`)},get value(){return n()?.mode??`auto`},get options(){return[{value:`auto`,label:t.t(`mode.auto`)},{value:`shadow`,label:t.t(`mode.shadow`)},{value:`off`,label:t.t(`mode.off`)}]},onChange:e=>t.api.patch({mode:e})})}}),(0,e.createComponent)(t.ui.SettingsRow,{id:`feedback`,get title(){return t.t(`feedback.title`)},get children(){return(0,e.createComponent)(t.ui.Select,{get label(){return t.t(`feedback.title`)},get value(){return n()?.feedback??`information`},get options(){return[{value:`information`,label:t.t(`feedback.information`)},{value:`confirmation`,label:t.t(`feedback.confirmation`)}]},onChange:e=>t.api.patch({feedback:e})})}})]}}),(0,e.createComponent)(t.ui.SettingsSection,{get title(){return t.t(`section.budget`)},get footer(){return(()=>{var n=_();return(0,e.insert)(n,()=>t.t(`budget.detail`)),n})()},get children(){return[(0,e.createComponent)(t.ui.SettingsRow,{id:`budget-day`,get title(){return t.t(`budget.day`)},get children(){return(0,e.createComponent)(t.ui.TextInput,{get label(){return t.t(`budget.day`)},get placeholder(){return t.t(`budget.none`)},get value(){return n()?.budget?.dailyUsd?.toString()??``},onInput:e=>t.api.patchNested(`budget`,{dailyUsd:v(e)})})}}),(0,e.createComponent)(t.ui.SettingsRow,{id:`budget-month`,get title(){return t.t(`budget.month`)},get children(){return(0,e.createComponent)(t.ui.TextInput,{get label(){return t.t(`budget.month`)},get placeholder(){return t.t(`budget.none`)},get value(){return n()?.budget?.monthlyUsd?.toString()??``},onInput:e=>t.api.patchNested(`budget`,{monthlyUsd:v(e)})})}}),(0,e.createComponent)(t.ui.SettingsRow,{id:`budget-soft`,get title(){return t.t(`budget.soft`)},get children(){return(0,e.createComponent)(t.ui.TextInput,{get label(){return t.t(`budget.soft`)},get value(){return n()?.budget?.softRatio?.toString()??``},onInput:e=>t.api.patchNested(`budget`,{softRatio:v(e)??.7})})}}),(0,e.createComponent)(t.ui.SettingsRow,{id:`budget-hard`,get title(){return t.t(`budget.hard`)},get children(){return(0,e.createComponent)(t.ui.TextInput,{get label(){return t.t(`budget.hard`)},get value(){return n()?.budget?.hardRatio?.toString()??``},onInput:e=>t.api.patchNested(`budget`,{hardRatio:v(e)??.9})})}})]}})]}var b=(0,e.template)(`<span> · `),x=(0,e.template)(`<span> <!> · <!> `),S=(0,e.template)(`<span style=font-variant-numeric:tabular-nums>p=<!> · <!> · <!>→<!> · <!>ms`),C=(0,e.template)(`<div style=display:flex;flex-direction:column;gap:2px><span style=opacity:0.7> : <!> (<!>)`),w=(0,e.template)(`<div style=display:flex;gap:4px;align-items:flex-end;height:36px>`),T=(0,e.template)(`<div style=display:flex;flex-direction:column;gap:2px;max-height:180px;overflow:auto>`),E=(0,e.template)(`<span>—`),D=(0,e.template)(`<div style=width:14px;background:currentColor;border-radius:2px>`),O=(0,e.template)(`<span style=font-variant-numeric:tabular-nums> · <!> · <!> · `),k=e=>`$${(e??0).toFixed(e!==void 0&&e<1?4:2)}`;function A(n){let r=()=>n.api.status(),i=()=>r()?.spend.daily??[],a=()=>Math.max(1e-6,...i().map(e=>e.usd));return(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.state`)},get children(){return[(0,e.createComponent)(n.ui.SettingsRow,{id:`state-routing`,get title(){return n.t(`state.routing`)},get children(){return(0,e.createComponent)(t.Show,{get when(){return r()},get fallback(){return E()},get children(){var t=b(),i=t.firstChild;return(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!r().routingActive);return()=>t()?n.t(`state.active`):n.t(`state.inactive`)})(),i),(0,e.insert)(t,()=>r().mode,null),t}})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`state-last`,get title(){return n.t(`state.last`)},get description(){return n.t(`state.last.detail`)},get children(){return(0,e.createComponent)(t.Show,{get when(){return r()?.lastDecision},get fallback(){return E()},get children(){var t=b(),n=t.firstChild;return(0,e.insert)(t,()=>r().lastDecision.tier,n),(0,e.insert)(t,()=>r().lastDecision.model,null),(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!r().lastDecision.variant);return()=>t()?`#${r().lastDecision.variant}`:``})(),null),t}})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`state-spend`,get title(){return n.t(`state.spend`)},get children(){var t=x(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling.nextSibling;return o.nextSibling,(0,e.insert)(t,()=>n.t(`state.today`),i),(0,e.insert)(t,()=>k(r()?.spend.todayUsd),a),(0,e.insert)(t,()=>n.t(`state.month`),o),(0,e.insert)(t,()=>k(r()?.spend.monthUsd),null),t}}),(0,e.createComponent)(t.Show,{get when(){return r()?.cascadeStats},get children(){return(0,e.createComponent)(n.ui.SettingsRow,{id:`state-cascade`,get title(){return n.t(`state.cascade`)},get children(){var i=C(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling;return c.nextSibling,(0,e.insert)(i,(0,e.createComponent)(t.Show,{get when(){return r().cascadeStats.last},get fallback(){return E()},get children(){var t=S(),i=t.firstChild.nextSibling,a=i.nextSibling.nextSibling,o=a.nextSibling.nextSibling,s=o.nextSibling.nextSibling,c=s.nextSibling.nextSibling;return c.nextSibling,(0,e.insert)(t,()=>r().cascadeStats.last.gateProbability??`—`,i),(0,e.insert)(t,(()=>{var t=(0,e.memo)(()=>!!r().cascadeStats.last.accepted);return()=>t()?n.t(`state.cascade.accepted`):(0,e.memo)(()=>!!r().cascadeStats.last.escalated)()?n.t(`state.cascade.escalated`):n.t(`state.cascade.rejected`)})(),a),(0,e.insert)(t,()=>r().cascadeStats.last.draftTier,o),(0,e.insert)(t,()=>r().cascadeStats.last.targetTier,s),(0,e.insert)(t,()=>r().cascadeStats.last.gateMs??`—`,c),t}}),a),(0,e.insert)(a,()=>n.t(`state.cascade.rate`),o),(0,e.insert)(a,(()=>{var t=(0,e.memo)(()=>r().cascadeStats.rate===null);return()=>t()?`—`:`${Math.round(r().cascadeStats.rate*100)}%`})(),s),(0,e.insert)(a,()=>r().cascadeStats.recentCount,c),i}})}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`state-days`,get title(){return n.t(`state.days`)},get children(){var n=w();return(0,e.insert)(n,(0,e.createComponent)(t.For,{get each(){return i()},children:t=>(()=>{var n=D();return(0,e.effect)(r=>{var i=`${t.day}: ${k(t.usd)}`,o=`${Math.max(2,t.usd/a()*34)}px`,s=t.usd>0?.8:.15;return i!==r.e&&(0,e.setAttribute)(n,`title`,r.e=i),o!==r.t&&(0,e.setStyleProperty)(n,`height`,r.t=o),s!==r.a&&(0,e.setStyleProperty)(n,`opacity`,r.a=s),r},{e:void 0,t:void 0,a:void 0}),n})()})),n}}),(0,e.createComponent)(n.ui.SettingsRow,{id:`state-decisions`,get title(){return n.t(`state.decisions`)},get children(){var n=T();return(0,e.insert)(n,(0,e.createComponent)(t.For,{get each(){return(r()?.lastDecisions??[]).slice(0,10)},children:t=>(()=>{var n=O(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,(0,e.insert)(n,()=>t.at?.slice(11,19),r),(0,e.insert)(n,()=>t.tier,i),(0,e.insert)(n,()=>t.model,a),(0,e.insert)(n,()=>t.source,null),n})()})),n}})]}})}var j=(0,e.template)(`<span style="color:var(--color-danger, #d14343)">`),M=(0,e.template)(`<div style=display:flex;flex-direction:column;gap:4px>`),N=(0,e.template)(`<div style=display:flex;gap:6px;align-items:center;flex-wrap:wrap>`),P=(0,e.template)(`<span>. `),F=(e,t,n)=>{if(n<0||n>=e.length)return e;let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r};function I(e,t,n){let r=[];e.length<2&&r.push(n(`tiers.error.count`));let i=new Set;for(let a of e){i.has(a.name)&&r.push(`${n(`tiers.error.duplicate`)}: ${a.name}`),i.add(a.name),a.model||r.push(`${n(`tiers.error.model`)}: ${a.name||`?`}`);let e=t(a.model);a.variant!==null&&e.length>0&&!e.includes(a.variant)&&r.push(`${n(`tiers.error.variant`)}: ${a.name}`)}return r}function L(n){let r=()=>n.api.config()?.tiers??[],i=()=>n.api.models(),a=e=>i().find(t=>t.model===e)?.variants??[],o=e=>n.api.patch({tiers:e}),s=(e,t)=>{o(r().map((n,r)=>r===e?{...n,...t}:n))},c=()=>I(r(),a,n.t);return(0,e.createComponent)(n.ui.SettingsSection,{get title(){return n.t(`section.tiers`)},get footer(){return(()=>{var a=M();return(0,e.insert)(a,(0,e.createComponent)(t.Show,{get when(){return c().length>0},get children(){var t=j();return(0,e.insert)(t,()=>c().join(` · `)),t}}),null),(0,e.insert)(a,(0,e.createComponent)(n.ui.Button,{size:`small`,onClick:()=>o([...r(),{name:`tier-${r().length+1}`,model:i()[0]?.model??``,variant:null}]),get children(){return n.t(`tiers.add`)}}),null),a})()},get children(){return(0,e.createComponent)(t.For,{get each(){return r()},children:(t,c)=>(0,e.createComponent)(n.ui.SettingsRow,{get id(){return`tier-${c()}`},get title(){return(()=>{var n=P(),r=n.firstChild;return(0,e.insert)(n,()=>c()+1,r),(0,e.insert)(n,()=>t.name||`?`,null),n})()},get description(){return`${t.model}${t.variant?`#${t.variant}`:``}`},get children(){var l=N();return(0,e.insert)(l,(0,e.createComponent)(n.ui.TextInput,{get label(){return n.t(`tiers.name`)},get value(){return t.name},onInput:e=>s(c(),{name:e})}),null),(0,e.insert)(l,(0,e.createComponent)(n.ui.Select,{get label(){return n.t(`tiers.model`)},get value(){return t.model},get options(){return i().map(e=>({value:e.model,label:e.model}))},onChange:e=>s(c(),{model:e,variant:a(e)[0]??null})}),null),(0,e.insert)(l,(0,e.createComponent)(n.ui.Select,{get label(){return n.t(`tiers.variant`)},get value(){return t.variant??`none`},get options(){return(0,e.memo)(()=>a(t.model).length===0)()?[{value:`none`,label:n.t(`tiers.none`)}]:a(t.model).map(e=>({value:e,label:e}))},onChange:e=>s(c(),{variant:e===`none`?null:e})}),null),(0,e.insert)(l,(0,e.createComponent)(n.ui.Button,{size:`small`,variant:`ghost`,get disabled(){return c()===0},onClick:()=>o(F(r(),c(),c()-1)),children:`↑`}),null),(0,e.insert)(l,(0,e.createComponent)(n.ui.Button,{size:`small`,variant:`ghost`,get disabled(){return c()===r().length-1},onClick:()=>o(F(r(),c(),c()+1)),children:`↓`}),null),(0,e.insert)(l,(0,e.createComponent)(n.ui.IconButton,{icon:`trash`,get label(){return n.t(`tiers.remove`)},onClick:()=>o(r().filter((e,t)=>t!==c()))}),null),l}})})}})}var R=(0,e.template)(`<span>`),z=(0,e.template)(`<span style=opacity:0.7>`),B=(0,e.template)(`<div style=display:flex;gap:8px;align-items:center>`),V=(0,e.template)(`<ul style=margin:0;padding-left:18px>`),H=(0,e.template)(`<li>`),U={title:`Tier Router`,description:`Model and effort routing for the auto model`,"section.state":`State`,"state.routing":`Routing`,"state.active":`active`,"state.inactive":`inactive`,"state.last":`Last decision`,"state.last.detail":`Most recent routed request, across all sessions`,"state.spend":`Spend`,"state.today":`Today`,"state.month":`This month`,"state.days":`Last days with decisions`,"state.decisions":`Recent decisions`,"state.cascade":`Cascade gate`,"state.cascade.accepted":`accepted`,"state.cascade.rejected":`would escalate`,"state.cascade.escalated":`escalated`,"state.cascade.rate":`Virtual escalation over recent gated steps`,"state.optionsIgnored":`Options in opencode.json were migrated into the config file once and are now ignored; remove them from opencode.json.`,"section.mode":`Mode`,"mode.title":`Routing mode`,"mode.detail":`auto applies decisions, shadow only logs them, off disables routing`,"mode.auto":`auto`,"mode.shadow":`shadow`,"mode.off":`off`,"feedback.title":`Routing feedback`,"feedback.information":`Information`,"feedback.confirmation":`Confirmation`,"section.budget":`Budget`,"budget.detail":`Machine-wide caps. Leave a field empty for no cap.`,"budget.day":`Daily cap (USD)`,"budget.month":`Monthly cap (USD)`,"budget.soft":`Soft ratio`,"budget.hard":`Hard ratio`,"budget.none":`no cap`,"section.tiers":`Tiers`,"tiers.add":`Add tier`,"tiers.name":`Name`,"tiers.model":`Model`,"tiers.variant":`Variant`,"tiers.none":`none`,"tiers.up":`Move up`,"tiers.down":`Move down`,"tiers.remove":`Remove`,"tiers.error.count":`at least 2 tiers are required`,"tiers.error.duplicate":`duplicate name`,"tiers.error.model":`missing model`,"tiers.error.variant":`unknown variant`,"section.classifier":`Classifier`,"classifier.model":`Decision model`,"classifier.model.detail":`Decision models are not in the chat catalogue; free text accepts provider/model`,"classifier.custom":`custom…`,"classifier.test":`Test`,"classifier.probe.ok":`answered in`,"classifier.probe.fail":`failed:`,"classifier.timeout":`Timeout (ms)`,"classifier.confidence":`Confidence threshold`,"classifier.minchars":`Minimum prompt characters`,"section.cache":`Cache and downgrade`,"cache.tokens":`Cache guard from (tokens)`,"cache.delta":`Minimum tier gap`,"cache.penalty":`Minimum saving (USD)`,"cache.downgrade":`Downgrade step`,"cache.fallback":`Fallback tier`,"section.kinds":`Minimum tier by task kind`,"section.cascade":`Quality cascade`,"cascade.detail":`Judges the served draft with Jev; a rejected text-final answer is replayed to the target tier. shadow only journals. Every failure falls back to the draft.`,"cascade.mode":`Cascade mode`,"cascade.target":`Escalation target tier`,"cascade.threshold":`Gate probability threshold`,"cascade.gateTimeout":`Gate timeout (ms)`,"cascade.fetchTimeout":`Escalation fetch timeout (ms)`,"section.advanced":`Advanced`,"advanced.providers":`Providers`,"advanced.providers.detail":`Changing providers needs an OpenCode restart; the config file is the only source.`,save:`Save`,saving:`Saving…`,reset:`Reset to defaults`,unsaved:`Unsaved changes`},W={...U,description:`Routage modèle et effort pour le modèle auto`,"section.state":`État`,"state.routing":`Routage`,"state.active":`actif`,"state.inactive":`inactif`,"state.last":`Dernière décision`,"state.last.detail":`Requête routée la plus récente, toutes sessions confondues`,"state.spend":`Dépense`,"state.today":`Aujourd'hui`,"state.month":`Ce mois`,"state.days":`Jours avec décisions`,"state.decisions":`Décisions récentes`,"state.cascade":`Gate de cascade`,"state.cascade.accepted":`accepté`,"state.cascade.rejected":`escaladerait`,"state.cascade.escalated":`escaladé`,"state.cascade.rate":`Escalade virtuelle sur les dernières étapes gatées`,"state.optionsIgnored":`Les options d'opencode.json ont été migrées une fois dans le fichier de config et sont désormais ignorées ; supprime-les d'opencode.json.`,"section.mode":`Mode`,"mode.title":`Mode de routage`,"mode.detail":`auto applique, shadow journalise seulement, off désactive`,"feedback.title":`Retour de routage`,"feedback.information":`Information`,"feedback.confirmation":`Confirmation`,"section.budget":`Budget`,"budget.detail":`Plafonds machine. Laisser vide = pas de plafond.`,"budget.day":`Plafond jour (USD)`,"budget.month":`Plafond mois (USD)`,"budget.soft":`Ratio soft`,"budget.hard":`Ratio hard`,"budget.none":`aucun`,"section.tiers":`Paliers`,"tiers.add":`Ajouter un palier`,"tiers.name":`Nom`,"tiers.model":`Modèle`,"tiers.variant":`Variant`,"tiers.none":`aucun`,"tiers.up":`Monter`,"tiers.down":`Descendre`,"tiers.remove":`Supprimer`,"tiers.error.count":`au moins 2 paliers sont nécessaires`,"tiers.error.duplicate":`nom en double`,"tiers.error.model":`modèle manquant`,"tiers.error.variant":`variant inconnu`,"section.classifier":`Classifieur`,"classifier.model":`Modèle de décision`,"classifier.model.detail":`Les modèles de décision ne sont pas dans le catalogue chat ; la saisie libre accepte provider/model`,"classifier.custom":`libre…`,"classifier.test":`Tester`,"classifier.probe.ok":`a répondu en`,"classifier.probe.fail":`échec :`,"classifier.timeout":`Timeout (ms)`,"classifier.confidence":`Seuil de confiance`,"classifier.minchars":`Longueur minimale du prompt`,"section.cache":`Cache et descente`,"cache.tokens":`Garde de cache à partir de (tokens)`,"cache.delta":`Écart minimal de paliers`,"cache.penalty":`Économie minimale (USD)`,"cache.downgrade":`Pas de descente`,"cache.fallback":`Palier de repli`,"section.kinds":`Palier minimal par nature de tâche`,"section.cascade":`Cascade qualité`,"cascade.detail":`Juge le draft servi avec Jev ; une réponse à texte final rejetée est rejouée vers le palier cible. shadow journalise seulement. Tout échec retombe sur le draft.`,"cascade.mode":`Mode de cascade`,"cascade.target":`Palier cible d'escalade`,"cascade.threshold":`Seuil de probabilité de la gate`,"cascade.gateTimeout":`Timeout de la gate (ms)`,"cascade.fetchTimeout":`Timeout du fetch d'escalade (ms)`,"section.advanced":`Avancé`,"advanced.providers":`Providers`,"advanced.providers.detail":`Changer de provider demande un redémarrage d'OpenCode ; le fichier de config est la seule source.`,save:`Enregistrer`,saving:`Enregistrement…`,reset:`Réinitialiser aux défauts`,unsaved:`Modifications non enregistrées`},G=n.Plugin.define({i18n:{en:U,fr:W},setup(r){let a=r.ui,s=u(r),c=e=>r.t(e),d=e=>s.models().find(t=>t.model===e)?.variants??[],f=()=>s.config()?I(s.config().tiers,d,c):[];if(r.app.platform===`desktop`){let e=new Set,n=new Map,a=new Map;(0,t.createEffect)(()=>{let s=r.servers.list().map(e=>r.servers.get(e)).find(e=>e?.builtin);if(!s?.connected)return;let c=r.client,u=!0,d=c.rpc(l).events.on(`routing`,t=>{if(!u||r.client!==c||!s.connected)return;let l=r.sessions.current(),d=t.data;if(!l||!l.server.builtin||l.id!==d.sessionID||t.location.directory!==l.location?.directory||e.has(t.id))return;e.add(t.id);let f=e=>JSON.stringify([e.name,e.providerID,e.model,e.variant]);if(!d.to||![`selected`,`simulated`,`rejected`,`error`].includes(d.status))return;let p=f(d.to);if((d.status===`selected`||d.status===`simulated`)&&d.from&&f(d.from)===p)return;if(d.status===`selected`){if(!d.from&&n.get(d.sessionID)===p)return;n.set(d.sessionID,p),a.delete(d.sessionID)}if(d.status===`simulated`){let e=JSON.stringify([d.from?f(d.from):null,p]);if(a.get(d.sessionID)===e)return;a.set(d.sessionID,e)}let{headline:m,detail:h,failed:g}=o(d);r.toast.show({title:m,description:h,variant:g?`error`:`default`,duration:i})});(0,t.onCleanup)(()=>{u=!1,d()})})}(0,t.onMount)(()=>{s.refresh().catch(()=>void 0);let e;try{e=r.client.rpc(l).events.on(`changed`,()=>{s.refresh()})}catch{}let n=setInterval(()=>{s.refreshStatus().catch(()=>void 0)},15e3);(0,t.onCleanup)(()=>{e?.(),clearInterval(n)})}),r.add(n.SettingsPage,{id:`tier-router`,icon:`server`,get title(){return c(`title`)},get entries(){return[{id:`tier-router`,title:c(`title`),description:c(`description`)},{id:`mode`,title:c(`mode.title`)},{id:`feedback`,title:c(`feedback.title`)},{id:`budget-day`,title:c(`budget.day`)},{id:`tier-0`,title:c(`section.tiers`)},{id:`classifier-model`,title:c(`classifier.model`)},{id:`cache-tokens`,title:c(`cache.tokens`)},{id:`cascade-mode`,title:c(`section.cascade`)},{id:`providers`,title:c(`advanced.providers`)}]},render:()=>(0,e.createComponent)(a.SettingsLayout,{get title(){return c(`title`)},get description(){return c(`description`)},get actions(){return(()=>{var n=B();return(0,e.insert)(n,(0,e.createComponent)(t.Show,{get when(){return s.dirty()},get children(){var t=z();return(0,e.insert)(t,()=>c(`unsaved`)),t}}),null),(0,e.insert)(n,(0,e.createComponent)(a.Button,{size:`small`,variant:`neutral`,get disabled(){return s.busy()},onClick:()=>void s.resetDefaults(),get children(){return c(`reset`)}}),null),(0,e.insert)(n,(0,e.createComponent)(a.Button,{size:`small`,variant:`contrast`,get disabled(){return s.busy()||!s.dirty()||f().length>0},onClick:()=>void s.save(),get children(){return(0,e.memo)(()=>!!s.busy())()?c(`saving`):c(`save`)}}),null),n})()},get children(){return[(0,e.createComponent)(t.Show,{get when(){return[...s.error()?[s.error()]:[],...s.status()?.fileErrors??[]].length>0},get children(){return(0,e.createComponent)(a.SettingsSection,{get footer(){return(()=>{var t=V();return(0,e.insert)(t,()=>[...s.error()?[s.error()]:[],...s.status()?.fileErrors??[]].map(t=>(()=>{var n=H();return(0,e.insert)(n,t),n})())),t})()},get children(){return(0,e.createComponent)(a.SettingsRow,{id:`error`,get title(){return s.error()??s.status()?.fileErrors?.[0]??``},get children(){return R()}})}})}}),(0,e.createComponent)(t.Show,{get when(){return s.status()?.optionsIgnored},get children(){return(0,e.createComponent)(a.SettingsSection,{get footer(){return(()=>{var t=R();return(0,e.insert)(t,()=>c(`state.optionsIgnored`)),t})()},get children(){return(0,e.createComponent)(a.SettingsRow,{id:`options-ignored`,get title(){return c(`state.optionsIgnored`)},get children(){return R()}})}})}}),(0,e.createComponent)(A,{api:s,ui:a,t:c}),(0,e.createComponent)(y,{api:s,ui:a,t:c}),(0,e.createComponent)(L,{api:s,ui:a,t:c}),(0,e.createComponent)(g,{api:s,ui:a,t:c})]}})})}});exports.default=G;
|