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/index.ts ADDED
@@ -0,0 +1,382 @@
1
+ import { Model, Plugin, Tool } from "@opencode/plugin/effect";
2
+ import { Effect, Queue, Schema, Stream, type JsonSchema } from "effect";
3
+ import { ALIAS_ID, ALIAS_NAME } from "./src/alias";
4
+ import { checkTiers } from "./src/catalog";
5
+ import { createCascade } from "./src/cascade";
6
+ import { createConfirmation } from "./src/confirmation";
7
+ import { CONFIG_PATH, openConfigStore } from "./src/configstore";
8
+ import { createControl } from "./src/control";
9
+ import { askJev, parseModel } from "./src/jev";
10
+ import { createJsonlLogger, readDecisions } from "./src/log";
11
+ import { estimateStepCost, toTierInfos } from "./src/policy";
12
+ import { createRouter, type Turn } from "./src/router";
13
+ import { createSessionStateStore } from "./src/session-state";
14
+ import { TierRouterRpc } from "./src/rpc";
15
+ import { createHandlers, type ModelOption } from "./src/rpc-handlers";
16
+ import { openLedger } from "./src/spend";
17
+ import type { RouterConfig, RoutingEvent, TierInfo } from "./src/types";
18
+
19
+ const MAX_TURN_CHARS = 2_000;
20
+
21
+ const fullTextOf = (message: Record<string, unknown>): string => {
22
+ if (typeof message.text === "string") return message.text;
23
+ const content: unknown[] = Array.isArray(message.content) ? message.content : [];
24
+ return content
25
+ .flatMap((part) => typeof part === "object" && part !== null && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" ? [part.text] : [])
26
+ .join("\n");
27
+ };
28
+
29
+ const textOf = (message: Record<string, unknown>): string => {
30
+ if (typeof message.text === "string") return message.text.slice(0, MAX_TURN_CHARS);
31
+ const content: unknown[] = Array.isArray(message.content) ? message.content : [];
32
+ return content
33
+ .flatMap((part) => typeof part === "object" && part !== null && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" ? [part.text] : [])
34
+ .join("\n")
35
+ .slice(0, MAX_TURN_CHARS);
36
+ };
37
+
38
+ export default Plugin.define({
39
+ id: "tier-router",
40
+ effect: (ctx) => Effect.gen(function* () {
41
+ const attempt = <A>(run: (signal: AbortSignal) => Promise<A>) => Effect.tryPromise({ try: run, catch: () => new Error("tier-router operation failed") });
42
+ const instanceID = crypto.randomUUID();
43
+ const store = yield* attempt(() => openConfigStore({ path: CONFIG_PATH, options: ctx.options }));
44
+ const log = createJsonlLogger(store.current().decisionsLogPath);
45
+ log({
46
+ at: new Date().toISOString(),
47
+ source: "config",
48
+ path: CONFIG_PATH,
49
+ mode: store.current().mode,
50
+ errors: store.errors.map(() => "invalid or unreadable configuration"),
51
+ optionsIgnored: store.optionsIgnored,
52
+ });
53
+
54
+ const providers = store.current().providers;
55
+ const catalog = new Map<string, { variants: string[] }>();
56
+ const prices = new Map<string, { price: { input: number; output: number; cacheRead: number; cacheWrite: number }; context: number; output: number }>();
57
+ const modelOptions: ModelOption[] = [];
58
+ const listed = yield* ctx.model.list();
59
+ for (const model of listed.data) {
60
+ if (!providers.includes(model.providerID)) continue;
61
+ const id = model.modelID;
62
+ const variants = (model.variants ?? []).map((variant) => variant.id);
63
+ catalog.set(id, { variants });
64
+ const cost = model.cost?.[0];
65
+ if (!cost) continue;
66
+ const price = {
67
+ input: cost.input,
68
+ output: cost.output,
69
+ cacheRead: cost.cache?.read ?? 0,
70
+ cacheWrite: cost.cache?.write ?? 0,
71
+ };
72
+ prices.set(id, { price, context: model.limit.context, output: model.limit.output });
73
+ modelOptions.push({
74
+ model: id,
75
+ variants,
76
+ inputPrice: price.input,
77
+ outputPrice: price.output,
78
+ cacheReadPrice: price.cacheRead,
79
+ context: model.limit.context,
80
+ maxOutput: model.limit.output,
81
+ });
82
+ }
83
+
84
+ const priced = new Set(prices.keys());
85
+ const tiersCheck = (config: Parameters<typeof checkTiers>[0]) => checkTiers(config, catalog, priced);
86
+
87
+ let currentTiers: TierInfo[] = [];
88
+ const tiersFor = (config: RouterConfig): { tiers: TierInfo[]; sourceFallback: boolean } => {
89
+ let tiers = toTierInfos(config.tiers, prices);
90
+ let sourceFallback = false;
91
+ if (tiers.length < 2) {
92
+ const source = prices.get(config.sourceModelID);
93
+ if (source) {
94
+ sourceFallback = true;
95
+ tiers = [
96
+ {
97
+ index: 0,
98
+ tier: { name: "fallback", model: config.sourceModelID, variant: null },
99
+ price: source.price,
100
+ context: source.context,
101
+ output: source.output,
102
+ },
103
+ ];
104
+ }
105
+ }
106
+ return { tiers, sourceFallback };
107
+ };
108
+ const refreshTiers = (): void => {
109
+ currentTiers = tiersFor(store.current()).tiers;
110
+ if (currentTiers.length < 2) {
111
+ log({ at: new Date().toISOString(), source: "config", error: "routing inactive: no usable tier" });
112
+ }
113
+ };
114
+ refreshTiers();
115
+
116
+ const ledger = yield* attempt(() => openLedger(store.current().ledgerPath));
117
+ const lastStep = new Map<string, { input: number; output: number; cacheRead: number; cacheWrite: number }>();
118
+ const stepModels = new Map<string, string>();
119
+ const autoSessions = new Set<string>();
120
+
121
+ const confirmation = createConfirmation({ location: ctx.location.directory, version: ctx.app.version, instanceID });
122
+ yield* Effect.addFinalizer(() => attempt(() => confirmation.dispose()).pipe(Effect.ignore));
123
+ const routingEvents = yield* Queue.unbounded<{ type: "routing"; event: RoutingEvent } | { type: "changed"; at: number }>();
124
+ const stateStore = createSessionStateStore({
125
+ get: async (key, signal) => {
126
+ signal?.throwIfAborted();
127
+ const value = await Effect.runPromise(ctx.storage.get(key), signal ? { signal } : undefined);
128
+ signal?.throwIfAborted();
129
+ return value;
130
+ },
131
+ set: async (key, value, signal) => {
132
+ signal?.throwIfAborted();
133
+ if (!Schema.is(Schema.Json)(value)) throw new TypeError("Session state must be JSON");
134
+ await Effect.runPromise(ctx.storage.set(key, value), signal ? { signal } : undefined);
135
+ signal?.throwIfAborted();
136
+ },
137
+ });
138
+ const router = createRouter({
139
+ snapshot: () => {
140
+ const snapshot = store.snapshot();
141
+ return { ...snapshot, ...tiersFor(snapshot.config) };
142
+ },
143
+ stateStore,
144
+ confirm: confirmation.confirm,
145
+ cancelForm: confirmation.cancel,
146
+ emit: (event) => { Queue.offerUnsafe(routingEvents, { type: "routing", event }); },
147
+ ledger,
148
+ log: (event) => log(event.source === "error" ? { ...event, message: "routing operation failed" } : event),
149
+ askJev: (input, signal) =>
150
+ askJev(
151
+ {
152
+ decisions: async (request, requestSignal) => {
153
+ const apiRequest = { ...request, model: Schema.decodeUnknownSync(Model.Ref)(request.model) } as Parameters<typeof ctx.experimental.generate.decisions>[0];
154
+ const result = await Effect.runPromise(ctx.experimental.generate.decisions(apiRequest), { signal: requestSignal });
155
+ return { ...result, answers: result.answers.map((answer) => answer.type === "choice" || answer.type === "score" ? { ...answer, probabilities: [...answer.probabilities] } : answer) };
156
+ },
157
+ config: store.current(),
158
+ onError: () => log({ at: new Date().toISOString(), source: "jev-error", message: "classifier request failed" }),
159
+ },
160
+ input,
161
+ signal,
162
+ ),
163
+ readTurns: async (sessionID, signal) => {
164
+ signal?.throwIfAborted();
165
+ const result = await Effect.runPromise(ctx.session.context({ sessionID: sessionID as Parameters<typeof ctx.session.context>[0]["sessionID"] }), signal ? { signal } : undefined);
166
+ signal?.throwIfAborted();
167
+ const messages: unknown[] = Array.isArray(result) ? result : typeof result === "object" && result !== null && "messages" in result && Array.isArray(result.messages) ? result.messages : [];
168
+ const turns = messages
169
+ .flatMap<Turn>((message) => {
170
+ if (typeof message !== "object" || message === null || !("type" in message) || (message.type !== "user" && message.type !== "assistant")) return [];
171
+ return [{ role: message.type, text: textOf(message as Record<string, unknown>) }];
172
+ })
173
+ .filter((turn) => turn.text.length > 0);
174
+ let lastUser = turns.length - 1;
175
+ while (lastUser >= 0 && turns[lastUser].role !== "user") lastUser -= 1;
176
+ if (lastUser < 0) return turns.slice(-4);
177
+ return turns.slice(Math.max(0, lastUser - 2));
178
+ },
179
+ usage: (sessionID) => {
180
+ const last = lastStep.get(sessionID);
181
+ return {
182
+ contextTokens: last ? last.input + last.cacheRead + last.cacheWrite : 0,
183
+ cachedTokens: last?.cacheRead ?? 0,
184
+ outputTokens: last?.output ?? 0,
185
+ };
186
+ },
187
+ });
188
+
189
+ const cascade = createCascade({
190
+ config: () => store.current(),
191
+ tiers: () => currentTiers,
192
+ ledger,
193
+ log,
194
+ decisions: async (request) => {
195
+ const apiRequest = { ...request, model: Schema.decodeUnknownSync(Model.Ref)(request.model) } as Parameters<typeof ctx.experimental.generate.decisions>[0];
196
+ const result = await Effect.runPromise(ctx.experimental.generate.decisions(apiRequest));
197
+ return { ...result, answers: result.answers.map((answer) => answer.type === "choice" || answer.type === "score" ? { ...answer, probabilities: [...answer.probabilities] } : answer) } as never;
198
+ },
199
+ now: () => Date.now(),
200
+ isAutoSession: (sessionID) => autoSessions.has(sessionID),
201
+ lastUserPrompt: async (sessionID) => {
202
+ try {
203
+ const result = await Effect.runPromise(ctx.session.context({ sessionID: sessionID as Parameters<typeof ctx.session.context>[0]["sessionID"] }));
204
+ const messages: unknown[] = Array.isArray(result) ? result : typeof result === "object" && result !== null && "messages" in result && Array.isArray(result.messages) ? result.messages : [];
205
+ const last = [...messages].reverse().find((message) => typeof message === "object" && message !== null && "type" in message && message.type === "user");
206
+ if (!last || typeof last !== "object") return "";
207
+ return fullTextOf(last as Record<string, unknown>);
208
+ } catch {
209
+ return "";
210
+ }
211
+ },
212
+ });
213
+
214
+ const handlers = createHandlers({
215
+ path: CONFIG_PATH,
216
+ store,
217
+ router,
218
+ ledger,
219
+ models: modelOptions,
220
+ checkTiers: tiersCheck,
221
+ tiersFor: (config) => tiersFor(config).tiers,
222
+ decisions: () =>
223
+ readDecisions(store.current().decisionsLogPath, 60).filter((entry) => typeof entry.tier === "string").slice(0, 30),
224
+ cascadeDecisions: () => readDecisions(store.current().decisionsLogPath, 30),
225
+ probe: async () => {
226
+ const started = Date.now();
227
+ const model = parseModel(store.current().classifier.model);
228
+ await Effect.runPromise(ctx.experimental.generate.decisions({
229
+ model: Schema.decodeUnknownSync(Model.Ref)(model),
230
+ input: [{ type: "text", text: "ping" }],
231
+ questions: [{ type: "predicate", name: "ping", instructions: "Is this a ping?" }],
232
+ }));
233
+ return { model: `${model.providerID}/${model.id}`, latencyMs: Date.now() - started };
234
+ },
235
+ emit: () => {},
236
+ });
237
+
238
+ const registration = yield* ctx.rpc.register(TierRouterRpc, {
239
+ hostIdentity: () => Effect.succeed({ instanceID }),
240
+ getConfig: () => attempt(() => handlers.getConfig({})).pipe(Effect.orDie),
241
+ saveConfig: (input) => Effect.gen(function* () {
242
+ const result = yield* attempt(() => handlers.saveConfig(input as { config: unknown }));
243
+ if (result.ok) {
244
+ refreshTiers();
245
+ Queue.offerUnsafe(routingEvents, { type: "changed", at: Date.now() });
246
+ }
247
+ return result;
248
+ }).pipe(Effect.orDie),
249
+ resetConfig: () => Effect.gen(function* () {
250
+ const result = yield* attempt(() => handlers.resetConfig({}));
251
+ if (result.ok) {
252
+ refreshTiers();
253
+ Queue.offerUnsafe(routingEvents, { type: "changed", at: Date.now() });
254
+ }
255
+ return result;
256
+ }).pipe(Effect.orDie),
257
+ status: () => attempt(() => handlers.status({})).pipe(Effect.orDie),
258
+ probeClassifier: () => attempt(() => handlers.probeClassifier({})).pipe(Effect.orDie),
259
+ });
260
+ yield* Effect.forever(Effect.flatMap(Queue.take(routingEvents), (item) => (item.type === "routing"
261
+ ? registration.events.emit("routing", { ...item.event })
262
+ : registration.events.emit("changed", { at: item.at })).pipe(Effect.ignore))).pipe(Effect.forkScoped);
263
+
264
+ const control = createControl({
265
+ router,
266
+ config: store.current(),
267
+ notify: async (sessionID, text) => {
268
+ await Effect.runPromise(ctx.session.synthetic({ sessionID: sessionID as Parameters<typeof ctx.session.synthetic>[0]["sessionID"], text }));
269
+ },
270
+ });
271
+ yield* ctx.command.transform((editor) => {
272
+ editor.add({
273
+ name: control.command.name,
274
+ description: control.command.description,
275
+ execute: (input) => attempt(() => control.command.execute(input)),
276
+ });
277
+ });
278
+ yield* ctx.tool.transform((editor) => {
279
+ editor.add({
280
+ name: control.tool.name,
281
+ description: control.tool.description,
282
+ input: control.tool.input as JsonSchema.JsonSchema,
283
+ execute: (input, context) => Effect.tryPromise({
284
+ try: () => control.tool.execute(Schema.decodeUnknownSync(Schema.Struct({ tier: Schema.NullOr(Schema.String) }))(input), context),
285
+ catch: (error) => new Tool.Error({ message: String((error as Error)?.message ?? error) }),
286
+ }),
287
+ });
288
+ });
289
+
290
+ if (currentTiers.length > 0) {
291
+ const missing: string[] = [];
292
+ yield* ctx.model.transform((editor) => {
293
+ for (const providerID of providers) {
294
+ const source = editor.get(providerID, store.current().sourceModelID);
295
+ if (!source) { missing.push(providerID); continue; }
296
+ const limit = { ...source.limit };
297
+ editor.update(providerID, ALIAS_ID, (model) => {
298
+ model.name = ALIAS_NAME;
299
+ model.limit = limit;
300
+ model.capabilities = { tools: true, input: ["text"], output: ["text"] };
301
+ model.variants = [];
302
+ });
303
+ }
304
+ });
305
+ if (missing.length) {
306
+ log({ at: new Date().toISOString(), source: "config", error: "source model not found" });
307
+ } else {
308
+ for (const providerID of providers) {
309
+ yield* ctx.session.hook(
310
+ "experimental.model.resolve",
311
+ (event) => {
312
+ // Only the primary kind decides the marker: title/compaction
313
+ // resolves (decision models like gpt-6-luna) must not clear it.
314
+ if (event.kind === "primary") {
315
+ if (event.model.id === store.current().aliasID) autoSessions.add(event.sessionID);
316
+ else autoSessions.delete(event.sessionID);
317
+ if (autoSessions.size > 512) autoSessions.clear();
318
+ }
319
+ return attempt((signal) => router.onModelResolve(event, { signal })).pipe(Effect.orDie);
320
+ },
321
+ { providerID },
322
+ );
323
+ yield* ctx.session.hook(
324
+ "http.response",
325
+ (event) => attempt(() => cascade.onHttpResponse(event as never)).pipe(Effect.orDie),
326
+ { providerID },
327
+ );
328
+ }
329
+ yield* ctx.session.hook("prompt", (event) => attempt((signal) => router.onPrompt(event, { signal })).pipe(Effect.orDie));
330
+ }
331
+ }
332
+
333
+ yield* ctx.event.subscribe({ types: ["session.step.started", "session.step.ended"] }).pipe(
334
+ Stream.runForEach((event) => Effect.sync(() => {
335
+ const data = (event as any).data ?? {};
336
+ if ((event as any).type === "session.step.started") {
337
+ if (typeof data.assistantMessageID === "string" && typeof data.model?.id === "string") {
338
+ stepModels.set(data.assistantMessageID, data.model.id);
339
+ }
340
+ return;
341
+ }
342
+ if (typeof data.assistantMessageID === "string") {
343
+ if (stepModels.size > 512) stepModels.clear();
344
+ // On escalation the cascade recorded the corrected strong cost and
345
+ // the hidden draft pass itself; the native record prices the step
346
+ // at the announced (draft) model, so it must be skipped.
347
+ if (!cascade.takeEscalated(data.sessionID)) {
348
+ const reported = typeof data.cost === "number" ? data.cost : 0;
349
+ const status = router.status(data.sessionID);
350
+ const served = stepModels.get(data.assistantMessageID) ?? (status?.unavailable ? undefined : status?.tier.model);
351
+ const price = served ? prices.get(served)?.price : undefined;
352
+ const estimate = price
353
+ ? estimateStepCost(
354
+ {
355
+ input: data.tokens?.input,
356
+ output: data.tokens?.output,
357
+ reasoning: data.tokens?.reasoning,
358
+ cacheRead: data.tokens?.cache?.read ?? data.tokens?.cacheRead,
359
+ cacheWrite: data.tokens?.cache?.write ?? data.tokens?.cacheWrite,
360
+ },
361
+ price,
362
+ )
363
+ : 0;
364
+ const costUsd = reported > 0 ? reported : estimate;
365
+ if (costUsd > 0) ledger.record({ id: data.assistantMessageID, at: Date.now(), costUsd });
366
+ }
367
+ }
368
+ if (typeof data.sessionID === "string") {
369
+ const tokens = data.tokens ?? {};
370
+ lastStep.set(data.sessionID, {
371
+ input: tokens.input ?? 0,
372
+ output: (tokens.output ?? 0) + (tokens.reasoning ?? 0),
373
+ cacheRead: tokens.cache?.read ?? tokens.cacheRead ?? 0,
374
+ cacheWrite: tokens.cache?.write ?? tokens.cacheWrite ?? 0,
375
+ });
376
+ }
377
+ })),
378
+ Effect.ignore,
379
+ Effect.forkScoped,
380
+ );
381
+ }).pipe(Effect.orDie),
382
+ });
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "opencode-tier-router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "OpenCode V2 plugin: routes the auto model across a configurable model+variant ladder using Jev, with budget, cache and capacity guards",
5
+ "license": "MIT",
6
+ "author": "bsauvajon",
7
+ "homepage": "https://github.com/bsauvajon/opencode-tier-router#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/bsauvajon/opencode-tier-router.git"
11
+ },
12
+ "bugs": "https://github.com/bsauvajon/opencode-tier-router/issues",
13
+ "keywords": [
14
+ "opencode",
15
+ "opencode-plugin",
16
+ "model-router",
17
+ "tier-router",
18
+ "jev"
19
+ ],
20
+ "type": "module",
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "files": [
25
+ "index.ts",
26
+ "src",
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "test": "bun test",
33
+ "build": "vite build",
34
+ "check:dist": "bun test test/dist.test.ts"
35
+ },
36
+ "devDependencies": {
37
+ "@types/bun": "^1.3.0",
38
+ "typescript": "^5.9.0",
39
+ "vite": "^8.4.0",
40
+ "vite-plugin-solid": "^2.11.17"
41
+ },
42
+ "exports": {
43
+ ".": "./index.ts",
44
+ "./tui": "./src/tui.ts",
45
+ "./gui-experimental": "./dist/gui-experimental.cjs",
46
+ "./rpc": "./src/rpc.ts"
47
+ },
48
+ "dependencies": {
49
+ "@opencode/client": "2.4.2",
50
+ "@opencode/plugin": "2.4.2",
51
+ "effect": "4.1.0",
52
+ "solid-js": "^1.9.0"
53
+ }
54
+ }
package/src/alias.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const ALIAS_ID = "auto";
2
+ export const ALIAS_NAME = "Auto (tier router)";