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/src/gui.tsx
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { createEffect, onCleanup, onMount, Show } from "solid-js";
|
|
2
|
+
import { Plugin, SettingsPage } from "@opencode/plugin/gui";
|
|
3
|
+
import { ROUTING_TOAST_DURATION_MS, routingToast } from "./feedback";
|
|
4
|
+
import { TierRouterRpc } from "./rpc";
|
|
5
|
+
import { createApi } from "./gui/api";
|
|
6
|
+
import { Advanced } from "./gui/advanced";
|
|
7
|
+
import { ModeBudget } from "./gui/budget";
|
|
8
|
+
import { StatusBlock } from "./gui/status";
|
|
9
|
+
import { TiersEditor, tierProblems } from "./gui/tiers";
|
|
10
|
+
import type { AppliedTier, RoutingEvent } from "./types";
|
|
11
|
+
|
|
12
|
+
const en = {
|
|
13
|
+
title: "Tier Router",
|
|
14
|
+
description: "Model and effort routing for the auto model",
|
|
15
|
+
"section.state": "State",
|
|
16
|
+
"state.routing": "Routing",
|
|
17
|
+
"state.active": "active",
|
|
18
|
+
"state.inactive": "inactive",
|
|
19
|
+
"state.last": "Last decision",
|
|
20
|
+
"state.last.detail": "Most recent routed request, across all sessions",
|
|
21
|
+
"state.spend": "Spend",
|
|
22
|
+
"state.today": "Today",
|
|
23
|
+
"state.month": "This month",
|
|
24
|
+
"state.days": "Last days with decisions",
|
|
25
|
+
"state.decisions": "Recent decisions",
|
|
26
|
+
"state.cascade": "Cascade gate",
|
|
27
|
+
"state.cascade.accepted": "accepted",
|
|
28
|
+
"state.cascade.rejected": "would escalate",
|
|
29
|
+
"state.cascade.escalated": "escalated",
|
|
30
|
+
"state.cascade.rate": "Virtual escalation over recent gated steps",
|
|
31
|
+
"state.optionsIgnored":
|
|
32
|
+
"Options in opencode.json were migrated into the config file once and are now ignored; remove them from opencode.json.",
|
|
33
|
+
"section.mode": "Mode",
|
|
34
|
+
"mode.title": "Routing mode",
|
|
35
|
+
"mode.detail": "auto applies decisions, shadow only logs them, off disables routing",
|
|
36
|
+
"mode.auto": "auto",
|
|
37
|
+
"mode.shadow": "shadow",
|
|
38
|
+
"mode.off": "off",
|
|
39
|
+
"feedback.title": "Routing feedback",
|
|
40
|
+
"feedback.information": "Information",
|
|
41
|
+
"feedback.confirmation": "Confirmation",
|
|
42
|
+
"section.budget": "Budget",
|
|
43
|
+
"budget.detail": "Machine-wide caps. Leave a field empty for no cap.",
|
|
44
|
+
"budget.day": "Daily cap (USD)",
|
|
45
|
+
"budget.month": "Monthly cap (USD)",
|
|
46
|
+
"budget.soft": "Soft ratio",
|
|
47
|
+
"budget.hard": "Hard ratio",
|
|
48
|
+
"budget.none": "no cap",
|
|
49
|
+
"section.tiers": "Tiers",
|
|
50
|
+
"tiers.add": "Add tier",
|
|
51
|
+
"tiers.name": "Name",
|
|
52
|
+
"tiers.model": "Model",
|
|
53
|
+
"tiers.variant": "Variant",
|
|
54
|
+
"tiers.none": "none",
|
|
55
|
+
"tiers.up": "Move up",
|
|
56
|
+
"tiers.down": "Move down",
|
|
57
|
+
"tiers.remove": "Remove",
|
|
58
|
+
"tiers.error.count": "at least 2 tiers are required",
|
|
59
|
+
"tiers.error.duplicate": "duplicate name",
|
|
60
|
+
"tiers.error.model": "missing model",
|
|
61
|
+
"tiers.error.variant": "unknown variant",
|
|
62
|
+
"section.classifier": "Classifier",
|
|
63
|
+
"classifier.model": "Decision model",
|
|
64
|
+
"classifier.model.detail": "Decision models are not in the chat catalogue; free text accepts provider/model",
|
|
65
|
+
"classifier.custom": "custom…",
|
|
66
|
+
"classifier.test": "Test",
|
|
67
|
+
"classifier.probe.ok": "answered in",
|
|
68
|
+
"classifier.probe.fail": "failed:",
|
|
69
|
+
"classifier.timeout": "Timeout (ms)",
|
|
70
|
+
"classifier.confidence": "Confidence threshold",
|
|
71
|
+
"classifier.minchars": "Minimum prompt characters",
|
|
72
|
+
"section.cache": "Cache and downgrade",
|
|
73
|
+
"cache.tokens": "Cache guard from (tokens)",
|
|
74
|
+
"cache.delta": "Minimum tier gap",
|
|
75
|
+
"cache.penalty": "Minimum saving (USD)",
|
|
76
|
+
"cache.downgrade": "Downgrade step",
|
|
77
|
+
"cache.fallback": "Fallback tier",
|
|
78
|
+
"section.kinds": "Minimum tier by task kind",
|
|
79
|
+
"section.cascade": "Quality cascade",
|
|
80
|
+
"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.",
|
|
81
|
+
"cascade.mode": "Cascade mode",
|
|
82
|
+
"cascade.target": "Escalation target tier",
|
|
83
|
+
"cascade.threshold": "Gate probability threshold",
|
|
84
|
+
"cascade.gateTimeout": "Gate timeout (ms)",
|
|
85
|
+
"cascade.fetchTimeout": "Escalation fetch timeout (ms)",
|
|
86
|
+
"section.advanced": "Advanced",
|
|
87
|
+
"advanced.providers": "Providers",
|
|
88
|
+
"advanced.providers.detail": "Changing providers needs an OpenCode restart; the config file is the only source.",
|
|
89
|
+
save: "Save",
|
|
90
|
+
saving: "Saving…",
|
|
91
|
+
reset: "Reset to defaults",
|
|
92
|
+
unsaved: "Unsaved changes",
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const fr: typeof en = {
|
|
96
|
+
...en,
|
|
97
|
+
description: "Routage modèle et effort pour le modèle auto",
|
|
98
|
+
"section.state": "État",
|
|
99
|
+
"state.routing": "Routage",
|
|
100
|
+
"state.active": "actif",
|
|
101
|
+
"state.inactive": "inactif",
|
|
102
|
+
"state.last": "Dernière décision",
|
|
103
|
+
"state.last.detail": "Requête routée la plus récente, toutes sessions confondues",
|
|
104
|
+
"state.spend": "Dépense",
|
|
105
|
+
"state.today": "Aujourd'hui",
|
|
106
|
+
"state.month": "Ce mois",
|
|
107
|
+
"state.days": "Jours avec décisions",
|
|
108
|
+
"state.decisions": "Décisions récentes",
|
|
109
|
+
"state.cascade": "Gate de cascade",
|
|
110
|
+
"state.cascade.accepted": "accepté",
|
|
111
|
+
"state.cascade.rejected": "escaladerait",
|
|
112
|
+
"state.cascade.escalated": "escaladé",
|
|
113
|
+
"state.cascade.rate": "Escalade virtuelle sur les dernières étapes gatées",
|
|
114
|
+
"state.optionsIgnored":
|
|
115
|
+
"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.",
|
|
116
|
+
"section.mode": "Mode",
|
|
117
|
+
"mode.title": "Mode de routage",
|
|
118
|
+
"mode.detail": "auto applique, shadow journalise seulement, off désactive",
|
|
119
|
+
"feedback.title": "Retour de routage",
|
|
120
|
+
"feedback.information": "Information",
|
|
121
|
+
"feedback.confirmation": "Confirmation",
|
|
122
|
+
"section.budget": "Budget",
|
|
123
|
+
"budget.detail": "Plafonds machine. Laisser vide = pas de plafond.",
|
|
124
|
+
"budget.day": "Plafond jour (USD)",
|
|
125
|
+
"budget.month": "Plafond mois (USD)",
|
|
126
|
+
"budget.soft": "Ratio soft",
|
|
127
|
+
"budget.hard": "Ratio hard",
|
|
128
|
+
"budget.none": "aucun",
|
|
129
|
+
"section.tiers": "Paliers",
|
|
130
|
+
"tiers.add": "Ajouter un palier",
|
|
131
|
+
"tiers.name": "Nom",
|
|
132
|
+
"tiers.model": "Modèle",
|
|
133
|
+
"tiers.variant": "Variant",
|
|
134
|
+
"tiers.none": "aucun",
|
|
135
|
+
"tiers.up": "Monter",
|
|
136
|
+
"tiers.down": "Descendre",
|
|
137
|
+
"tiers.remove": "Supprimer",
|
|
138
|
+
"tiers.error.count": "au moins 2 paliers sont nécessaires",
|
|
139
|
+
"tiers.error.duplicate": "nom en double",
|
|
140
|
+
"tiers.error.model": "modèle manquant",
|
|
141
|
+
"tiers.error.variant": "variant inconnu",
|
|
142
|
+
"section.classifier": "Classifieur",
|
|
143
|
+
"classifier.model": "Modèle de décision",
|
|
144
|
+
"classifier.model.detail": "Les modèles de décision ne sont pas dans le catalogue chat ; la saisie libre accepte provider/model",
|
|
145
|
+
"classifier.custom": "libre…",
|
|
146
|
+
"classifier.test": "Tester",
|
|
147
|
+
"classifier.probe.ok": "a répondu en",
|
|
148
|
+
"classifier.probe.fail": "échec :",
|
|
149
|
+
"classifier.timeout": "Timeout (ms)",
|
|
150
|
+
"classifier.confidence": "Seuil de confiance",
|
|
151
|
+
"classifier.minchars": "Longueur minimale du prompt",
|
|
152
|
+
"section.cache": "Cache et descente",
|
|
153
|
+
"cache.tokens": "Garde de cache à partir de (tokens)",
|
|
154
|
+
"cache.delta": "Écart minimal de paliers",
|
|
155
|
+
"cache.penalty": "Économie minimale (USD)",
|
|
156
|
+
"cache.downgrade": "Pas de descente",
|
|
157
|
+
"cache.fallback": "Palier de repli",
|
|
158
|
+
"section.kinds": "Palier minimal par nature de tâche",
|
|
159
|
+
"section.cascade": "Cascade qualité",
|
|
160
|
+
"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.",
|
|
161
|
+
"cascade.mode": "Mode de cascade",
|
|
162
|
+
"cascade.target": "Palier cible d'escalade",
|
|
163
|
+
"cascade.threshold": "Seuil de probabilité de la gate",
|
|
164
|
+
"cascade.gateTimeout": "Timeout de la gate (ms)",
|
|
165
|
+
"cascade.fetchTimeout": "Timeout du fetch d'escalade (ms)",
|
|
166
|
+
"section.advanced": "Avancé",
|
|
167
|
+
"advanced.providers": "Providers",
|
|
168
|
+
"advanced.providers.detail": "Changer de provider demande un redémarrage d'OpenCode ; le fichier de config est la seule source.",
|
|
169
|
+
save: "Enregistrer",
|
|
170
|
+
saving: "Enregistrement…",
|
|
171
|
+
reset: "Réinitialiser aux défauts",
|
|
172
|
+
unsaved: "Modifications non enregistrées",
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
export default Plugin.define({
|
|
176
|
+
i18n: { en, fr },
|
|
177
|
+
setup(ctx) {
|
|
178
|
+
const ui = ctx.ui;
|
|
179
|
+
const api = createApi(ctx);
|
|
180
|
+
const t = (key: string) => ctx.t(key);
|
|
181
|
+
|
|
182
|
+
const variantsOf = (model: string): string[] =>
|
|
183
|
+
api.models().find((option) => option.model === model)?.variants ?? [];
|
|
184
|
+
|
|
185
|
+
const problems = () =>
|
|
186
|
+
api.config() ? tierProblems(api.config()!.tiers, variantsOf, t) : [];
|
|
187
|
+
|
|
188
|
+
if (ctx.app.platform === "desktop") {
|
|
189
|
+
const seen = new Set<string>();
|
|
190
|
+
const selected = new Map<string, string>();
|
|
191
|
+
const simulated = new Map<string, string>();
|
|
192
|
+
createEffect(() => {
|
|
193
|
+
const server = ctx.servers.list().map((id) => ctx.servers.get(id)).find((item) => item?.builtin);
|
|
194
|
+
if (!server?.connected) return;
|
|
195
|
+
const client = ctx.client;
|
|
196
|
+
let current = true;
|
|
197
|
+
const stop = client.rpc(TierRouterRpc).events.on("routing", (event) => {
|
|
198
|
+
if (!current || ctx.client !== client || !server.connected) return;
|
|
199
|
+
const session = ctx.sessions.current();
|
|
200
|
+
const data = event.data as unknown as RoutingEvent;
|
|
201
|
+
if (!session || !session.server.builtin || session.id !== data.sessionID || event.location.directory !== session.location?.directory || seen.has(event.id)) return;
|
|
202
|
+
seen.add(event.id);
|
|
203
|
+
const identity = (tier: AppliedTier) => JSON.stringify([tier.name, tier.providerID, tier.model, tier.variant]);
|
|
204
|
+
if (!data.to || !["selected", "simulated", "rejected", "error"].includes(data.status)) return;
|
|
205
|
+
const to = identity(data.to);
|
|
206
|
+
if ((data.status === "selected" || data.status === "simulated") && data.from && identity(data.from) === to) return;
|
|
207
|
+
if (data.status === "selected") {
|
|
208
|
+
if (!data.from && selected.get(data.sessionID) === to) return;
|
|
209
|
+
selected.set(data.sessionID, to);
|
|
210
|
+
simulated.delete(data.sessionID);
|
|
211
|
+
}
|
|
212
|
+
if (data.status === "simulated") {
|
|
213
|
+
const change = JSON.stringify([data.from ? identity(data.from) : null, to]);
|
|
214
|
+
if (simulated.get(data.sessionID) === change) return;
|
|
215
|
+
simulated.set(data.sessionID, change);
|
|
216
|
+
}
|
|
217
|
+
const { headline, detail, failed } = routingToast(data);
|
|
218
|
+
ctx.toast.show({ title: headline, description: detail, variant: failed ? "error" : "default", duration: ROUTING_TOAST_DURATION_MS });
|
|
219
|
+
});
|
|
220
|
+
onCleanup(() => { current = false; stop(); });
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
onMount(() => {
|
|
225
|
+
void api.refresh().catch(() => undefined);
|
|
226
|
+
let unsubscribe: (() => void) | undefined;
|
|
227
|
+
try {
|
|
228
|
+
unsubscribe = (ctx.client.rpc(TierRouterRpc) as any).events.on("changed", () => {
|
|
229
|
+
void api.refresh();
|
|
230
|
+
});
|
|
231
|
+
} catch {
|
|
232
|
+
/* events are optional; the page still works on open */
|
|
233
|
+
}
|
|
234
|
+
const timer = setInterval(() => {
|
|
235
|
+
void api.refreshStatus().catch(() => undefined);
|
|
236
|
+
}, 15_000);
|
|
237
|
+
onCleanup(() => {
|
|
238
|
+
unsubscribe?.();
|
|
239
|
+
clearInterval(timer);
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
ctx.add(SettingsPage, {
|
|
244
|
+
id: "tier-router",
|
|
245
|
+
icon: "server",
|
|
246
|
+
get title() {
|
|
247
|
+
return t("title");
|
|
248
|
+
},
|
|
249
|
+
get entries() {
|
|
250
|
+
return [
|
|
251
|
+
{ id: "tier-router", title: t("title"), description: t("description") },
|
|
252
|
+
{ id: "mode", title: t("mode.title") },
|
|
253
|
+
{ id: "feedback", title: t("feedback.title") },
|
|
254
|
+
{ id: "budget-day", title: t("budget.day") },
|
|
255
|
+
{ id: "tier-0", title: t("section.tiers") },
|
|
256
|
+
{ id: "classifier-model", title: t("classifier.model") },
|
|
257
|
+
{ id: "cache-tokens", title: t("cache.tokens") },
|
|
258
|
+
{ id: "cascade-mode", title: t("section.cascade") },
|
|
259
|
+
{ id: "providers", title: t("advanced.providers") },
|
|
260
|
+
];
|
|
261
|
+
},
|
|
262
|
+
render: () => (
|
|
263
|
+
<ui.SettingsLayout
|
|
264
|
+
title={t("title")}
|
|
265
|
+
description={t("description")}
|
|
266
|
+
actions={
|
|
267
|
+
<div style={{ display: "flex", gap: "8px", "align-items": "center" }}>
|
|
268
|
+
<Show when={api.dirty()}>
|
|
269
|
+
<span style={{ opacity: 0.7 }}>{t("unsaved")}</span>
|
|
270
|
+
</Show>
|
|
271
|
+
<ui.Button
|
|
272
|
+
size="small"
|
|
273
|
+
variant="neutral"
|
|
274
|
+
disabled={api.busy()}
|
|
275
|
+
onClick={() => void api.resetDefaults()}
|
|
276
|
+
>
|
|
277
|
+
{t("reset")}
|
|
278
|
+
</ui.Button>
|
|
279
|
+
<ui.Button
|
|
280
|
+
size="small"
|
|
281
|
+
variant="contrast"
|
|
282
|
+
disabled={api.busy() || !api.dirty() || problems().length > 0}
|
|
283
|
+
onClick={() => void api.save()}
|
|
284
|
+
>
|
|
285
|
+
{api.busy() ? t("saving") : t("save")}
|
|
286
|
+
</ui.Button>
|
|
287
|
+
</div>
|
|
288
|
+
}
|
|
289
|
+
>
|
|
290
|
+
<Show when={[...(api.error() ? [api.error()!] : []), ...(api.status()?.fileErrors ?? [])].length > 0}>
|
|
291
|
+
<ui.SettingsSection
|
|
292
|
+
footer={
|
|
293
|
+
<ul style={{ margin: "0", "padding-left": "18px" }}>
|
|
294
|
+
{[...(api.error() ? [api.error()!] : []), ...(api.status()?.fileErrors ?? [])].map((line) => (
|
|
295
|
+
<li>{line}</li>
|
|
296
|
+
))}
|
|
297
|
+
</ul>
|
|
298
|
+
}
|
|
299
|
+
>
|
|
300
|
+
<ui.SettingsRow id="error" title={api.error() ?? api.status()?.fileErrors?.[0] ?? ""}>
|
|
301
|
+
<span />
|
|
302
|
+
</ui.SettingsRow>
|
|
303
|
+
</ui.SettingsSection>
|
|
304
|
+
</Show>
|
|
305
|
+
<Show when={api.status()?.optionsIgnored}>
|
|
306
|
+
<ui.SettingsSection footer={<span>{t("state.optionsIgnored")}</span>}>
|
|
307
|
+
<ui.SettingsRow id="options-ignored" title={t("state.optionsIgnored")}>
|
|
308
|
+
<span />
|
|
309
|
+
</ui.SettingsRow>
|
|
310
|
+
</ui.SettingsSection>
|
|
311
|
+
</Show>
|
|
312
|
+
|
|
313
|
+
<StatusBlock api={api} ui={ui} t={t} />
|
|
314
|
+
<ModeBudget api={api} ui={ui} t={t} />
|
|
315
|
+
<TiersEditor api={api} ui={ui} t={t} />
|
|
316
|
+
<Advanced api={api} ui={ui} t={t} />
|
|
317
|
+
</ui.SettingsLayout>
|
|
318
|
+
),
|
|
319
|
+
});
|
|
320
|
+
},
|
|
321
|
+
});
|
package/src/heuristic.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Signals, TaskKind } from "./types";
|
|
2
|
+
|
|
3
|
+
const RULES: Array<{ kind: TaskKind; pattern: RegExp; weight: number }> = [
|
|
4
|
+
{ kind: "plan", pattern: /\b(architecture|architectur|plan|con[çc]ois|design|migration|roadmap)\b/i, weight: 3 },
|
|
5
|
+
{ kind: "debug", pattern: /\b(debug|d[ée]bogue|échoue|echoue|error|erreur|trace|race|crash|panic|r[ée]gression)\b/i, weight: 2 },
|
|
6
|
+
{ kind: "refactor", pattern: /\b(refactor|refacto|nettoie|renomme|d[ée]place|extrais)\b/i, weight: 1 },
|
|
7
|
+
{ kind: "review", pattern: /\b(review|relis|audit|v[ée]rifie)\b/i, weight: 1 },
|
|
8
|
+
{ kind: "explain", pattern: /\b(explique|explain|pourquoi|why)\b/i, weight: 0 },
|
|
9
|
+
];
|
|
10
|
+
|
|
11
|
+
export interface HeuristicResult {
|
|
12
|
+
index: number;
|
|
13
|
+
kind: TaskKind;
|
|
14
|
+
confidence: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Cheap, offline fallback when Jev is slow or unavailable. */
|
|
18
|
+
export function classifyHeuristically(signals: Signals, tierCount: number): HeuristicResult {
|
|
19
|
+
const text = signals.promptText ?? "";
|
|
20
|
+
let score = 0;
|
|
21
|
+
let kind: TaskKind = "chat";
|
|
22
|
+
let best = 0;
|
|
23
|
+
for (const rule of RULES) {
|
|
24
|
+
const hits = new Set(
|
|
25
|
+
(text.toLowerCase().match(new RegExp(rule.pattern.source, "gi")) ?? []).map((m) => m.toLowerCase()),
|
|
26
|
+
);
|
|
27
|
+
if (hits.size === 0) continue;
|
|
28
|
+
score += rule.weight * hits.size;
|
|
29
|
+
if (rule.weight > best) {
|
|
30
|
+
best = rule.weight;
|
|
31
|
+
kind = rule.weight === 3 ? "plan" : rule.kind;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (text.length > 1_200) score += 1;
|
|
35
|
+
if (signals.contextTokens > 40_000) score += 1;
|
|
36
|
+
if (signals.contextTokens > 150_000) score += 2;
|
|
37
|
+
if (signals.recentErrors > 0) score += 1;
|
|
38
|
+
|
|
39
|
+
const span = Math.max(1, tierCount - 1);
|
|
40
|
+
const bucket = score <= 1 ? 0 : score <= 3 ? 1 : score <= 5 ? 2 : score <= 7 ? 3 : score <= 9 ? 4 : 5;
|
|
41
|
+
const index = Math.min(tierCount - 1, Math.max(0, Math.round((bucket * span) / 5)));
|
|
42
|
+
return { index, kind, confidence: 0.5 };
|
|
43
|
+
}
|
package/src/jev.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { RouterConfig, Signals, TaskKind, Tier } from "./types";
|
|
2
|
+
|
|
3
|
+
export interface DecisionQuestion {
|
|
4
|
+
type: "choice" | "score" | "predicate";
|
|
5
|
+
name: string;
|
|
6
|
+
instructions: string;
|
|
7
|
+
choices?: Array<{ value: string | boolean; description?: string }>;
|
|
8
|
+
levels?: Array<{ label: string; description?: string }>;
|
|
9
|
+
criteria?: { true?: string; false?: string };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface DecisionPart {
|
|
13
|
+
type: "text" | "json" | "file";
|
|
14
|
+
text?: string;
|
|
15
|
+
value?: unknown;
|
|
16
|
+
data?: string;
|
|
17
|
+
mime?: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DecisionAnswer {
|
|
22
|
+
type: string;
|
|
23
|
+
name?: string;
|
|
24
|
+
choice?: string | boolean;
|
|
25
|
+
score?: number;
|
|
26
|
+
confidence?: number;
|
|
27
|
+
probabilities?: unknown[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface DecisionResult {
|
|
31
|
+
answers: DecisionAnswer[];
|
|
32
|
+
cost?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface JevDecision {
|
|
36
|
+
index: number;
|
|
37
|
+
kind: TaskKind;
|
|
38
|
+
confidence: number;
|
|
39
|
+
costUsd: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface JevDeps {
|
|
43
|
+
decisions: (input: {
|
|
44
|
+
model: { providerID: string; id: string };
|
|
45
|
+
input: DecisionPart[];
|
|
46
|
+
questions: DecisionQuestion[];
|
|
47
|
+
}, signal: AbortSignal) => Promise<DecisionResult>;
|
|
48
|
+
config: RouterConfig;
|
|
49
|
+
onError?: (message: string) => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface JevInput {
|
|
53
|
+
signals: Signals;
|
|
54
|
+
turns: string[];
|
|
55
|
+
spendTodayUsd: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const TASK_KINDS: TaskKind[] = ["plan", "implement", "debug", "refactor", "review", "explain", "chat"];
|
|
59
|
+
const FALLBACK_MODEL = "opencode-go/jev-1.13";
|
|
60
|
+
const MAX_TURN_CHARS = 2_000;
|
|
61
|
+
const MAX_COST_USD = 0.0005;
|
|
62
|
+
|
|
63
|
+
/** Exactly the four axes the hermes-jev-routing plugin asks, in the same order. */
|
|
64
|
+
export function buildQuestions(tiers: Tier[]): DecisionQuestion[] {
|
|
65
|
+
return [
|
|
66
|
+
{
|
|
67
|
+
type: "choice",
|
|
68
|
+
name: "task_kind",
|
|
69
|
+
instructions: "Classify what the user is asking the coding agent to do right now.",
|
|
70
|
+
choices: [
|
|
71
|
+
{ value: "plan", description: "Design work: architecture, migration strategy, breaking a goal into steps." },
|
|
72
|
+
{ value: "implement", description: "Write or change code to add behavior." },
|
|
73
|
+
{ value: "debug", description: "Find and fix a failure, a crash, a failing test, a race condition." },
|
|
74
|
+
{ value: "refactor", description: "Restructure or rename without changing behavior." },
|
|
75
|
+
{ value: "review", description: "Review, audit or verify existing work." },
|
|
76
|
+
{ value: "explain", description: "Explain how something works." },
|
|
77
|
+
{ value: "chat", description: "Small talk, acknowledgement, or a trivial lookup." },
|
|
78
|
+
],
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
type: "score",
|
|
82
|
+
name: "complexity",
|
|
83
|
+
instructions: "How hard is this step, from routine to architectural?",
|
|
84
|
+
levels: [
|
|
85
|
+
{ label: "trivial" },
|
|
86
|
+
{ label: "moderate" },
|
|
87
|
+
{ label: "substantial" },
|
|
88
|
+
{ label: "hard" },
|
|
89
|
+
{ label: "architectural" },
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
type: "predicate",
|
|
94
|
+
name: "deep_reasoning",
|
|
95
|
+
instructions: "Does this step likely need extended chain-of-thought rather than pattern matching?",
|
|
96
|
+
criteria: {
|
|
97
|
+
true: "The step involves subtle invariants, concurrency, performance tradeoffs or multi-file reasoning.",
|
|
98
|
+
false: "The step is mechanical, local, or answerable from the immediate context.",
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
type: "score",
|
|
103
|
+
name: "deserved_tier",
|
|
104
|
+
instructions: "Pick the model tier this step deserves. Higher tiers cost more, so do not overspend.",
|
|
105
|
+
levels: tiers.map((tier) => ({
|
|
106
|
+
label: tier.name,
|
|
107
|
+
description: `${tier.model}${tier.variant ? ` at ${tier.variant} effort` : ""}`,
|
|
108
|
+
})),
|
|
109
|
+
},
|
|
110
|
+
];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Bounded, text-only evidence: never tool output, never file contents. */
|
|
114
|
+
export function buildInput(input: JevInput): DecisionPart[] {
|
|
115
|
+
const parts: DecisionPart[] = [];
|
|
116
|
+
for (const turn of input.turns.slice(-3)) {
|
|
117
|
+
if (!turn.trim()) continue;
|
|
118
|
+
parts.push({ type: "text", text: turn.slice(0, MAX_TURN_CHARS) });
|
|
119
|
+
}
|
|
120
|
+
const prompt = input.signals.promptText?.trim();
|
|
121
|
+
if (prompt && !input.turns.some((turn) => turn.includes(prompt.slice(0, 40)))) {
|
|
122
|
+
parts.push({ type: "text", text: prompt.slice(0, MAX_TURN_CHARS) });
|
|
123
|
+
}
|
|
124
|
+
parts.push({
|
|
125
|
+
type: "text",
|
|
126
|
+
text: `context≈${input.signals.contextTokens} tokens; spend today=$${input.spendTodayUsd.toFixed(4)}`,
|
|
127
|
+
});
|
|
128
|
+
return parts;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Maps a decisions response onto the configured ladder. Returns null when unusable. */
|
|
132
|
+
export function interpret(result: DecisionResult, tiers: Tier[]): JevDecision | null {
|
|
133
|
+
const answers = Array.isArray(result.answers) ? result.answers : [];
|
|
134
|
+
const tierAnswer = answers.find((a) => a.name === "deserved_tier" && a.type === "score");
|
|
135
|
+
if (!tierAnswer || typeof tierAnswer.score !== "number" || !Number.isFinite(tierAnswer.score)) {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
const kindAnswer = answers.find((a) => a.name === "task_kind" && a.type === "choice");
|
|
139
|
+
const kind = TASK_KINDS.find((k) => k === kindAnswer?.choice) ?? "chat";
|
|
140
|
+
const index = Math.min(tiers.length - 1, Math.max(0, Math.round(tierAnswer.score)));
|
|
141
|
+
const confidence =
|
|
142
|
+
typeof tierAnswer.confidence === "number" && Number.isFinite(tierAnswer.confidence)
|
|
143
|
+
? tierAnswer.confidence
|
|
144
|
+
: 0;
|
|
145
|
+
const cost = typeof result.cost === "number" && Number.isFinite(result.cost) ? result.cost : 0;
|
|
146
|
+
return { index, kind, confidence, costUsd: Math.min(cost, MAX_COST_USD) };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export const parseModel = (ref: string): { providerID: string; id: string } => {
|
|
150
|
+
const slash = ref.indexOf("/");
|
|
151
|
+
if (slash <= 0) return { providerID: "opencode", id: ref };
|
|
152
|
+
return { providerID: ref.slice(0, slash), id: ref.slice(slash + 1) };
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** Asks Jev, with a hard time budget and one model fallback. Never throws. */
|
|
156
|
+
export async function askJev(deps: JevDeps, input: JevInput, signal: AbortSignal = new AbortController().signal): Promise<JevDecision | null> {
|
|
157
|
+
const questions = buildQuestions(deps.config.tiers);
|
|
158
|
+
const parts = buildInput(input);
|
|
159
|
+
const models = [parseModel(deps.config.classifier.model)];
|
|
160
|
+
if (deps.config.classifier.model !== FALLBACK_MODEL) models.push(parseModel(FALLBACK_MODEL));
|
|
161
|
+
|
|
162
|
+
for (const model of models) {
|
|
163
|
+
if (signal.aborted) return null;
|
|
164
|
+
const attempt = Promise.resolve().then(() => {
|
|
165
|
+
signal.throwIfAborted();
|
|
166
|
+
return deps.decisions({ model, input: parts, questions }, signal);
|
|
167
|
+
}).then(
|
|
168
|
+
(result) => ({ ok: true as const, result }),
|
|
169
|
+
(error: unknown) => ({ ok: false as const, error }),
|
|
170
|
+
);
|
|
171
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
172
|
+
let abort: (() => void) | undefined;
|
|
173
|
+
const timeout = new Promise<{ ok: false; error: Error }>((resolve) => {
|
|
174
|
+
abort = () => resolve({ ok: false, error: new Error("aborted") });
|
|
175
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
176
|
+
timer = setTimeout(() => resolve({ ok: false, error: new Error("timeout") }), deps.config.classifier.timeoutMs);
|
|
177
|
+
});
|
|
178
|
+
let outcome: Awaited<typeof attempt>;
|
|
179
|
+
try { outcome = await Promise.race([attempt, timeout]); }
|
|
180
|
+
finally {
|
|
181
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
182
|
+
if (abort) signal.removeEventListener("abort", abort);
|
|
183
|
+
}
|
|
184
|
+
if (signal.aborted) return null;
|
|
185
|
+
if (outcome.ok) {
|
|
186
|
+
const decision = interpret(outcome.result, deps.config.tiers);
|
|
187
|
+
if (decision) return decision;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const message = String((outcome.error as Error)?.message ?? "");
|
|
191
|
+
deps.onError?.(message.slice(0, 200));
|
|
192
|
+
if (!/model|not found|unknown|unsupported/i.test(message)) return null;
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
package/src/log.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Appends one metadata-only JSON object per line. Logging must never break a
|
|
6
|
+
* request, so every filesystem error is swallowed.
|
|
7
|
+
*/
|
|
8
|
+
export function createJsonlLogger(path: string): (event: Record<string, unknown>) => void {
|
|
9
|
+
return (event) => {
|
|
10
|
+
try {
|
|
11
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
12
|
+
appendFileSync(path, `${JSON.stringify(event)}\n`, "utf8");
|
|
13
|
+
} catch {
|
|
14
|
+
/* ignore */
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Last `limit` decision entries, newest first. Bad lines are skipped. */
|
|
20
|
+
export function readDecisions(path: string, limit: number): Record<string, unknown>[] {
|
|
21
|
+
let text = "";
|
|
22
|
+
try {
|
|
23
|
+
text = readFileSync(path, "utf8");
|
|
24
|
+
} catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
const lines = text.trim().split("\n").filter(Boolean).slice(-limit).reverse();
|
|
28
|
+
const entries: Record<string, unknown>[] = [];
|
|
29
|
+
for (const line of lines) {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(line) as unknown;
|
|
32
|
+
if (typeof parsed === "object" && parsed !== null) entries.push(parsed as Record<string, unknown>);
|
|
33
|
+
} catch {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return entries;
|
|
38
|
+
}
|