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/policy.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Price,
|
|
3
|
+
RouterConfig,
|
|
4
|
+
SessionState,
|
|
5
|
+
Signals,
|
|
6
|
+
Spend,
|
|
7
|
+
TaskKind,
|
|
8
|
+
Tier,
|
|
9
|
+
TierInfo,
|
|
10
|
+
} from "./types";
|
|
11
|
+
|
|
12
|
+
export type DecisionSource =
|
|
13
|
+
| "jev"
|
|
14
|
+
| "heuristic"
|
|
15
|
+
| "sticky"
|
|
16
|
+
| "forced"
|
|
17
|
+
| "fallback"
|
|
18
|
+
| "budget"
|
|
19
|
+
| "cache"
|
|
20
|
+
| "capacity"
|
|
21
|
+
| "tiny";
|
|
22
|
+
|
|
23
|
+
export interface DecisionInput {
|
|
24
|
+
config: RouterConfig;
|
|
25
|
+
tiers: TierInfo[];
|
|
26
|
+
decision: { index: number; kind: TaskKind; confidence: number } | null;
|
|
27
|
+
state: SessionState;
|
|
28
|
+
spend: Spend;
|
|
29
|
+
signals: Signals;
|
|
30
|
+
isNewTurn: boolean;
|
|
31
|
+
outputTokens: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface Decision {
|
|
35
|
+
index: number;
|
|
36
|
+
reason: string;
|
|
37
|
+
source: DecisionSource;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface StepTokens {
|
|
41
|
+
input?: number;
|
|
42
|
+
output?: number;
|
|
43
|
+
reasoning?: number;
|
|
44
|
+
cacheRead?: number;
|
|
45
|
+
cacheWrite?: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Estimated cost of one step, for accounts where OpenCode reports cost 0 (subscription plans). */
|
|
49
|
+
export function estimateStepCost(tokens: StepTokens, price: Price): number {
|
|
50
|
+
return (
|
|
51
|
+
(tokens.input ?? 0) * price.input +
|
|
52
|
+
((tokens.output ?? 0) + (tokens.reasoning ?? 0)) * price.output +
|
|
53
|
+
(tokens.cacheRead ?? 0) * price.cacheRead +
|
|
54
|
+
(tokens.cacheWrite ?? 0) * price.cacheWrite
|
|
55
|
+
) / 1_000_000;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Marginal cost of the next call, pricing the already-cached share at the cache rate. */
|
|
59
|
+
export function estimateNextCallUsd(
|
|
60
|
+
price: Price,
|
|
61
|
+
contextTokens: number,
|
|
62
|
+
cachedTokens: number,
|
|
63
|
+
outputTokens: number,
|
|
64
|
+
): number {
|
|
65
|
+
const cached = Math.min(contextTokens, Math.max(0, cachedTokens));
|
|
66
|
+
const fresh = Math.max(0, contextTokens - cached);
|
|
67
|
+
return (cached * price.cacheRead + fresh * price.input + outputTokens * price.output) / 1_000_000;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function estimateCallUsd(price: Price, inputTokens: number, outputTokens: number): number {
|
|
71
|
+
return (inputTokens * price.input + outputTokens * price.output) / 1_000_000;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const clampIndex = (index: number, tiers: TierInfo[]): number =>
|
|
75
|
+
Math.min(tiers.length - 1, Math.max(0, Number.isFinite(index) ? index : 0));
|
|
76
|
+
|
|
77
|
+
const indexOfTier = (tiers: TierInfo[], name: string | undefined): number | undefined => {
|
|
78
|
+
if (!name) return undefined;
|
|
79
|
+
return tiers.findIndex((tier) => tier.tier.name === name) >= 0
|
|
80
|
+
? tiers.findIndex((tier) => tier.tier.name === name)
|
|
81
|
+
: undefined;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const fits = (tier: TierInfo, contextTokens: number, outputTokens: number): boolean =>
|
|
85
|
+
tier.context >= contextTokens && tier.output >= outputTokens;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Applies the guards in a fixed order: forced tier, confidence, kind floor,
|
|
89
|
+
* capacity, budget, stickiness, cache. The first guard that refuses decides.
|
|
90
|
+
*/
|
|
91
|
+
export function decide(input: DecisionInput): Decision {
|
|
92
|
+
const { config, tiers, decision, state, spend, signals, isNewTurn, outputTokens } = input;
|
|
93
|
+
const current = clampIndex(state.index, tiers);
|
|
94
|
+
const at = (index: number, source: DecisionSource): Decision => ({
|
|
95
|
+
index: clampIndex(index, tiers),
|
|
96
|
+
reason: source,
|
|
97
|
+
source,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const forced = indexOfTier(tiers, state.forcedTier);
|
|
101
|
+
if (forced !== undefined) {
|
|
102
|
+
const overBudget =
|
|
103
|
+
config.budget.dailyUsd !== undefined &&
|
|
104
|
+
spend.todayUsd >= config.budget.dailyUsd * config.budget.hardRatio;
|
|
105
|
+
return overBudget ? at(0, "budget") : at(forced, "forced");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (!decision) return at(current, "sticky");
|
|
109
|
+
if (decision.confidence < config.classifier.confidenceThreshold) return at(current, "sticky");
|
|
110
|
+
|
|
111
|
+
let target = clampIndex(decision.index, tiers);
|
|
112
|
+
const minimum = indexOfTier(tiers, config.kindMinimumTier[decision.kind]);
|
|
113
|
+
if (minimum !== undefined && target < minimum) target = minimum;
|
|
114
|
+
const afterKindFloor = target;
|
|
115
|
+
|
|
116
|
+
if (!fits(tiers[target], signals.contextTokens, outputTokens)) {
|
|
117
|
+
const affordable = tiers.findIndex((tier) => fits(tier, signals.contextTokens, outputTokens));
|
|
118
|
+
if (affordable < 0) return at(current, "capacity");
|
|
119
|
+
target = affordable;
|
|
120
|
+
if (target === current) return at(current, "capacity");
|
|
121
|
+
return at(target, "capacity");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const daily = config.budget.dailyUsd;
|
|
125
|
+
if (daily !== undefined && spend.todayUsd >= daily * config.budget.hardRatio) return at(0, "budget");
|
|
126
|
+
if (daily !== undefined) {
|
|
127
|
+
const margin = daily * config.budget.softRatio - spend.todayUsd;
|
|
128
|
+
if (margin > 0) {
|
|
129
|
+
while (
|
|
130
|
+
target > 0 &&
|
|
131
|
+
estimateNextCallUsd(tiers[target].price, signals.contextTokens, signals.lastCachedTokens, outputTokens) >
|
|
132
|
+
margin
|
|
133
|
+
) {
|
|
134
|
+
target -= 1;
|
|
135
|
+
}
|
|
136
|
+
if (target !== afterKindFloor) return at(target, "budget");
|
|
137
|
+
} else {
|
|
138
|
+
return at(0, "budget");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const monthly = config.budget.monthlyUsd;
|
|
143
|
+
if (monthly !== undefined && spend.monthUsd >= monthly * config.budget.hardRatio) return at(0, "budget");
|
|
144
|
+
|
|
145
|
+
if (target !== current && signals.lastCachedTokens >= config.cache.minTokens) {
|
|
146
|
+
const delta = Math.abs(target - current);
|
|
147
|
+
const savings =
|
|
148
|
+
estimateNextCallUsd(tiers[current].price, signals.contextTokens, signals.lastCachedTokens, outputTokens) -
|
|
149
|
+
estimateNextCallUsd(tiers[target].price, signals.contextTokens, 0, outputTokens);
|
|
150
|
+
if (delta < config.cache.minTierDelta || savings <= config.cache.maxPenaltyUsd) {
|
|
151
|
+
return at(current, "cache");
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (target > current) return at(target, "jev");
|
|
156
|
+
if (target < current) {
|
|
157
|
+
const dropsFarEnough = current - target >= config.downgradeDelta;
|
|
158
|
+
if (!isNewTurn || !dropsFarEnough) return at(current, "sticky");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return at(target, "jev");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Builds the priced ladder the policy works on. */
|
|
165
|
+
export function toTierInfos(
|
|
166
|
+
tiers: Tier[],
|
|
167
|
+
models: Map<string, { price: Price; context: number; output: number }>,
|
|
168
|
+
): TierInfo[] {
|
|
169
|
+
const infos: TierInfo[] = [];
|
|
170
|
+
tiers.forEach((tier) => {
|
|
171
|
+
const model = models.get(tier.model);
|
|
172
|
+
if (!model && !tier.usd) return;
|
|
173
|
+
infos.push({
|
|
174
|
+
index: infos.length,
|
|
175
|
+
tier,
|
|
176
|
+
price: tier.usd
|
|
177
|
+
? { input: tier.usd.input, output: tier.usd.output, cacheRead: tier.usd.cacheRead, cacheWrite: tier.usd.cacheWrite ?? 0 }
|
|
178
|
+
: model!.price,
|
|
179
|
+
context: model?.context ?? 0,
|
|
180
|
+
output: model?.output ?? Number.MAX_SAFE_INTEGER,
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
return infos;
|
|
184
|
+
}
|
package/src/router.ts
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { classifyHeuristically } from "./heuristic";
|
|
3
|
+
import type { ConfirmResult, Proposal } from "./confirmation";
|
|
4
|
+
import type { JevDecision, JevInput } from "./jev";
|
|
5
|
+
import { decide } from "./policy";
|
|
6
|
+
import type { SessionStateStore } from "./session-state";
|
|
7
|
+
import type { SpendLedger } from "./spend";
|
|
8
|
+
import type { AppliedTier, FeedbackMode, Mode, RoutingEvent, RoutingSnapshot, SessionState, Signals, Spend, StoredSession, TaskKind, Tier, TierInfo, Usage } from "./types";
|
|
9
|
+
|
|
10
|
+
export interface Turn {
|
|
11
|
+
role: "user" | "assistant";
|
|
12
|
+
text: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RouterDeps {
|
|
16
|
+
snapshot: () => RoutingSnapshot;
|
|
17
|
+
stateStore: SessionStateStore;
|
|
18
|
+
confirm: (proposal: Proposal, context: { signal: AbortSignal; isCurrent(): boolean; recordFormID(formID: string): Promise<void> }) => Promise<ConfirmResult>;
|
|
19
|
+
cancelForm: (sessionID: string, formID: string) => Promise<void>;
|
|
20
|
+
emit: (event: RoutingEvent) => void;
|
|
21
|
+
ledger: SpendLedger;
|
|
22
|
+
askJev: (input: JevInput, signal?: AbortSignal) => Promise<JevDecision | null>;
|
|
23
|
+
readTurns: (sessionID: string, signal?: AbortSignal) => Promise<Turn[]>;
|
|
24
|
+
usage: (sessionID: string) => Usage;
|
|
25
|
+
log: (event: Record<string, unknown>) => void;
|
|
26
|
+
now?: () => number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RouterStatus {
|
|
30
|
+
index: number;
|
|
31
|
+
tier: Tier;
|
|
32
|
+
unavailable?: true;
|
|
33
|
+
wouldTier?: Tier;
|
|
34
|
+
spend: Spend;
|
|
35
|
+
mode: Mode;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface Router {
|
|
39
|
+
onModelResolve(event: {
|
|
40
|
+
sessionID: string;
|
|
41
|
+
kind: string;
|
|
42
|
+
model: { providerID: string; id: string; variant?: string };
|
|
43
|
+
}, context?: { signal: AbortSignal }): Promise<void>;
|
|
44
|
+
onPrompt(event: { sessionID: string }, context?: { signal: AbortSignal }): Promise<void>;
|
|
45
|
+
setForced(sessionID: string, tier: string | null, signal?: AbortSignal): Promise<void>;
|
|
46
|
+
status(sessionID: string): RouterStatus | undefined;
|
|
47
|
+
tiers(): TierInfo[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const CHEAP_KINDS = new Set(["compaction", "title", "generate"]);
|
|
51
|
+
const ACK = /^(ok|okay|oui|non|yes|no|go|continue|continue?|merci|thanks|top)[.!]?$/i;
|
|
52
|
+
|
|
53
|
+
const estimateTokens = (text: string): number => Math.ceil(text.length / 4);
|
|
54
|
+
|
|
55
|
+
export function createRouter(deps: RouterDeps): Router {
|
|
56
|
+
const states = new Map<string, { stored: StoredSession; runtime: SessionState; identity: AppliedTier | null }>();
|
|
57
|
+
const queues = new Map<string, Promise<void>>();
|
|
58
|
+
const active = new Map<string, AbortController>();
|
|
59
|
+
const blocked = new Set<string>();
|
|
60
|
+
const missingIdentities = new Set<string>();
|
|
61
|
+
const now = deps.now ?? Date.now;
|
|
62
|
+
|
|
63
|
+
const invalidate = (sessionID: string) => active.get(sessionID)?.abort();
|
|
64
|
+
const serial = <T>(sessionID: string, work: () => Promise<T>): Promise<T> => {
|
|
65
|
+
const previous = queues.get(sessionID) ?? Promise.resolve();
|
|
66
|
+
const result = previous.then(work);
|
|
67
|
+
const tail = result.then(() => {}, () => {});
|
|
68
|
+
queues.set(sessionID, tail);
|
|
69
|
+
void tail.then(() => { if (queues.get(sessionID) === tail) queues.delete(sessionID); });
|
|
70
|
+
return result;
|
|
71
|
+
};
|
|
72
|
+
const indexOf = (identity: AppliedTier, snapshot: RoutingSnapshot): number =>
|
|
73
|
+
snapshot.config.providers.includes(identity.providerID)
|
|
74
|
+
? snapshot.tiers.findIndex(({ tier }) => tier.name === identity.name && tier.model === identity.model && tier.variant === identity.variant)
|
|
75
|
+
: -1;
|
|
76
|
+
|
|
77
|
+
const stateFor = async (sessionID: string, snapshot: RoutingSnapshot, signal?: AbortSignal) => {
|
|
78
|
+
signal?.throwIfAborted();
|
|
79
|
+
let entry = states.get(sessionID);
|
|
80
|
+
if (!entry) {
|
|
81
|
+
let saved = await deps.stateStore.load(sessionID, signal);
|
|
82
|
+
signal?.throwIfAborted();
|
|
83
|
+
if (!saved) {
|
|
84
|
+
saved = { version: 2, applied: null, configRevision: snapshot.revision, turn: 0 };
|
|
85
|
+
}
|
|
86
|
+
if (saved.transition?.formID) {
|
|
87
|
+
try { await deps.cancelForm(sessionID, saved.transition.formID); } catch { /* best effort */ }
|
|
88
|
+
}
|
|
89
|
+
if (saved.transition?.phase === "pending") {
|
|
90
|
+
signal?.throwIfAborted();
|
|
91
|
+
const { transition: _transition, ...recovered } = saved;
|
|
92
|
+
await deps.stateStore.save(sessionID, recovered, signal);
|
|
93
|
+
signal?.throwIfAborted();
|
|
94
|
+
saved = recovered;
|
|
95
|
+
}
|
|
96
|
+
entry = {
|
|
97
|
+
stored: saved,
|
|
98
|
+
identity: saved.applied,
|
|
99
|
+
runtime: { index: saved.applied ? indexOf(saved.applied, snapshot) : -1, model: saved.applied?.model ?? "", variant: saved.applied?.variant ?? null, turn: saved.turn,
|
|
100
|
+
...(saved.forcedTier === undefined ? {} : { forcedTier: saved.forcedTier }),
|
|
101
|
+
...(saved.lastRoutedTurn === undefined ? {} : { lastRoutedTurn: saved.lastRoutedTurn }) },
|
|
102
|
+
};
|
|
103
|
+
states.set(sessionID, entry);
|
|
104
|
+
}
|
|
105
|
+
return entry;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const save = async (sessionID: string, state: StoredSession, signal?: AbortSignal) => {
|
|
109
|
+
try {
|
|
110
|
+
signal?.throwIfAborted();
|
|
111
|
+
await deps.stateStore.save(sessionID, state, signal);
|
|
112
|
+
signal?.throwIfAborted();
|
|
113
|
+
} catch (error) {
|
|
114
|
+
states.delete(sessionID);
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const clearPending = async (sessionID: string, entry: { stored: StoredSession }, signal?: AbortSignal) => {
|
|
120
|
+
if (entry.stored.version !== 1 || entry.stored.transition?.phase !== "pending") return;
|
|
121
|
+
if (entry.stored.transition.formID) {
|
|
122
|
+
try { await deps.cancelForm(sessionID, entry.stored.transition.formID); } catch { /* best effort */ }
|
|
123
|
+
}
|
|
124
|
+
const { transition: _transition, ...saved } = entry.stored;
|
|
125
|
+
await save(sessionID, saved, signal);
|
|
126
|
+
if (signal?.aborted) states.delete(sessionID);
|
|
127
|
+
signal?.throwIfAborted();
|
|
128
|
+
entry.stored = saved;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const serve = (
|
|
132
|
+
event: { model: { providerID: string; id: string; variant?: string } },
|
|
133
|
+
index: number,
|
|
134
|
+
sessionID: string,
|
|
135
|
+
kind: string,
|
|
136
|
+
source: string,
|
|
137
|
+
snapshot: RoutingSnapshot,
|
|
138
|
+
extra: Record<string, unknown> = {},
|
|
139
|
+
deferLog = false,
|
|
140
|
+
): void => {
|
|
141
|
+
const info = snapshot.tiers[index];
|
|
142
|
+
if (!info) return;
|
|
143
|
+
const entry = states.get(sessionID)!;
|
|
144
|
+
const state = entry.runtime;
|
|
145
|
+
state.model = info.tier.model;
|
|
146
|
+
state.variant = info.tier.variant;
|
|
147
|
+
entry.identity = { name: info.tier.name, providerID: event.model.providerID, model: info.tier.model, variant: info.tier.variant };
|
|
148
|
+
event.model = {
|
|
149
|
+
providerID: event.model.providerID,
|
|
150
|
+
id: info.tier.model,
|
|
151
|
+
...(info.tier.variant ? { variant: info.tier.variant } : {}),
|
|
152
|
+
};
|
|
153
|
+
if (!deferLog) deps.log({
|
|
154
|
+
at: new Date(now()).toISOString(),
|
|
155
|
+
sessionID,
|
|
156
|
+
kind,
|
|
157
|
+
source,
|
|
158
|
+
tier: info.tier.name,
|
|
159
|
+
model: info.tier.model,
|
|
160
|
+
variant: info.tier.variant,
|
|
161
|
+
spendTodayUsd: Number(deps.ledger.snapshot(now()).todayUsd.toFixed(4)),
|
|
162
|
+
...extra,
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
tiers: () => deps.snapshot().tiers,
|
|
168
|
+
|
|
169
|
+
async onModelResolve(event, context) {
|
|
170
|
+
const sessionID = event.sessionID;
|
|
171
|
+
// A resolve that this router will not rewrite (title/compaction utility
|
|
172
|
+
// models, another provider, or routing disabled) must not cancel an
|
|
173
|
+
// in-flight routing for the same session. OpenCode issues such resolves
|
|
174
|
+
// concurrently with the primary one, and aborting it would leave the
|
|
175
|
+
// request on the unservable `auto` alias.
|
|
176
|
+
let probe: RoutingSnapshot;
|
|
177
|
+
try { probe = deps.snapshot(); } catch { return; }
|
|
178
|
+
if (event.model.id !== probe.config.aliasID || probe.config.mode === "off" || !probe.routingAllowed || !probe.config.providers.includes(event.model.providerID)) return;
|
|
179
|
+
invalidate(sessionID);
|
|
180
|
+
const controller = new AbortController();
|
|
181
|
+
active.set(sessionID, controller);
|
|
182
|
+
const signal = context ? AbortSignal.any([controller.signal, context.signal]) : controller.signal;
|
|
183
|
+
let proposal: Proposal | undefined;
|
|
184
|
+
let snapshot: RoutingSnapshot | undefined;
|
|
185
|
+
let candidateIndex = -1;
|
|
186
|
+
let source = "sticky";
|
|
187
|
+
let routed = false;
|
|
188
|
+
let classifier: "jev" | "heuristic" | undefined;
|
|
189
|
+
let confidence: number | undefined;
|
|
190
|
+
let initial = false;
|
|
191
|
+
let modelMutated = false;
|
|
192
|
+
let capturedTurn = 0;
|
|
193
|
+
let capturedForce: string | undefined;
|
|
194
|
+
let capturedMode: Mode = "off";
|
|
195
|
+
let capturedFeedback: FeedbackMode = "information";
|
|
196
|
+
let configFingerprint = "";
|
|
197
|
+
const equal = (a: AppliedTier, b: AppliedTier) => a.name === b.name && a.providerID === b.providerID && a.model === b.model && a.variant === b.variant;
|
|
198
|
+
const isCurrent = () => {
|
|
199
|
+
if (signal.aborted || !snapshot || active.get(sessionID) !== controller) return false;
|
|
200
|
+
try {
|
|
201
|
+
const current = deps.snapshot();
|
|
202
|
+
return current.revision === snapshot.revision && current.routingAllowed && current.config.mode === capturedMode && current.config.feedback === capturedFeedback;
|
|
203
|
+
} catch { return false; }
|
|
204
|
+
};
|
|
205
|
+
try {
|
|
206
|
+
await serial(sessionID, async () => {
|
|
207
|
+
signal.throwIfAborted();
|
|
208
|
+
snapshot = deps.snapshot();
|
|
209
|
+
const { config, tiers } = snapshot;
|
|
210
|
+
capturedMode = config.mode;
|
|
211
|
+
capturedFeedback = config.feedback;
|
|
212
|
+
if (event.model.id !== config.aliasID || config.mode === "off" || !snapshot.routingAllowed || !config.providers.includes(event.model.providerID)) return;
|
|
213
|
+
configFingerprint = createHash("sha256").update(JSON.stringify(config, (_key, value) =>
|
|
214
|
+
value && typeof value === "object" && !Array.isArray(value)
|
|
215
|
+
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))
|
|
216
|
+
: value)).digest("hex");
|
|
217
|
+
const entry = await stateFor(sessionID, snapshot, signal);
|
|
218
|
+
signal.throwIfAborted();
|
|
219
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
220
|
+
const applied = entry.stored.applied;
|
|
221
|
+
if (applied && (indexOf(applied, snapshot) < 0 || (entry.identity && indexOf(entry.identity, snapshot) < 0))) {
|
|
222
|
+
if (!missingIdentities.has(sessionID)) {
|
|
223
|
+
missingIdentities.add(sessionID);
|
|
224
|
+
deps.log({ at: new Date(now()).toISOString(), sessionID, source: "identity_missing", tier: applied.name, providerID: applied.providerID, model: applied.model, variant: applied.variant });
|
|
225
|
+
}
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (applied) missingIdentities.delete(sessionID);
|
|
229
|
+
if (blocked.has(sessionID)) return;
|
|
230
|
+
await clearPending(sessionID, entry, signal);
|
|
231
|
+
signal.throwIfAborted();
|
|
232
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
233
|
+
if (entry.stored.version === 2) {
|
|
234
|
+
const tier = tiers.find(({ tier }) => tier.name === config.fallbackTier)?.tier ?? (snapshot.sourceFallback ? tiers[0]?.tier : undefined);
|
|
235
|
+
if (!tier) throw new Error("Fallback tier unavailable");
|
|
236
|
+
const applied: AppliedTier = { name: tier.name, providerID: event.model.providerID, model: tier.model, variant: tier.variant };
|
|
237
|
+
const saved: StoredSession = { ...entry.stored, version: 1, applied, configRevision: snapshot.revision };
|
|
238
|
+
await save(sessionID, saved, signal);
|
|
239
|
+
if (signal.aborted) states.delete(sessionID);
|
|
240
|
+
signal.throwIfAborted();
|
|
241
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
242
|
+
entry.stored = saved;
|
|
243
|
+
entry.identity = applied;
|
|
244
|
+
initial = true;
|
|
245
|
+
}
|
|
246
|
+
const state = entry.runtime;
|
|
247
|
+
if (!entry.identity || !entry.stored.applied || entry.stored.transition?.phase === "applying") return;
|
|
248
|
+
const previousRejections = entry.stored.rejections;
|
|
249
|
+
const previousRejection = entry.stored.lastRejected;
|
|
250
|
+
const staleRejections = previousRejections && (previousRejections.turn !== state.turn || previousRejections.configFingerprint !== configFingerprint);
|
|
251
|
+
const staleRejection = previousRejection && (previousRejection.turn !== state.turn || previousRejection.configFingerprint !== configFingerprint);
|
|
252
|
+
if (staleRejections || staleRejection) {
|
|
253
|
+
const { rejections, lastRejected, ...rest } = entry.stored;
|
|
254
|
+
const saved: StoredSession = { ...rest, ...(!staleRejections && rejections ? { rejections } : {}), ...(!staleRejection && lastRejected ? { lastRejected } : {}) };
|
|
255
|
+
await save(sessionID, saved, signal);
|
|
256
|
+
signal.throwIfAborted();
|
|
257
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
258
|
+
entry.stored = saved;
|
|
259
|
+
}
|
|
260
|
+
state.index = indexOf(entry.identity, snapshot);
|
|
261
|
+
if (entry.identity.providerID !== event.model.providerID) return;
|
|
262
|
+
capturedTurn = state.turn;
|
|
263
|
+
capturedForce = state.forcedTier;
|
|
264
|
+
candidateIndex = state.index;
|
|
265
|
+
if (CHEAP_KINDS.has(event.kind)) {
|
|
266
|
+
if (config.feedback === "information") candidateIndex = 0;
|
|
267
|
+
source = "cheap";
|
|
268
|
+
} else {
|
|
269
|
+
const usage = deps.usage(sessionID);
|
|
270
|
+
let turns: Turn[];
|
|
271
|
+
try {
|
|
272
|
+
turns = await deps.readTurns(sessionID, signal);
|
|
273
|
+
signal.throwIfAborted();
|
|
274
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
275
|
+
const promptText = ([...turns].reverse().find((turn) => turn.role === "user")?.text ?? "").trim();
|
|
276
|
+
const signals: Signals = {
|
|
277
|
+
promptText,
|
|
278
|
+
contextTokens: Math.max(usage.contextTokens, turns.reduce((total, turn) => total + estimateTokens(turn.text), 0)),
|
|
279
|
+
lastCachedTokens: usage.cachedTokens,
|
|
280
|
+
recentErrors: /error|erreur|failed|échoue|exception/i.test(promptText) ? 1 : 0,
|
|
281
|
+
};
|
|
282
|
+
const tiny = promptText.length === 0 || promptText.length < config.classifier.minPromptChars || promptText.startsWith("/") || ACK.test(promptText);
|
|
283
|
+
if (tiny && (!state.forcedTier || config.feedback !== "confirmation")) {
|
|
284
|
+
source = promptText.length ? "tiny" : "sticky";
|
|
285
|
+
} else {
|
|
286
|
+
const spend = deps.ledger.snapshot(now());
|
|
287
|
+
const jev = tiny ? null : await deps.askJev({ signals, turns: turns.map((turn) => turn.text), spendTodayUsd: spend.todayUsd }, signal);
|
|
288
|
+
signal.throwIfAborted();
|
|
289
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
290
|
+
const decision = jev ? { index: jev.index, kind: jev.kind as TaskKind, confidence: jev.confidence } : tiny ? null : classifyHeuristically(signals, tiers.length);
|
|
291
|
+
if (decision) { classifier = jev ? "jev" : "heuristic"; confidence = decision.confidence; }
|
|
292
|
+
if (jev?.costUsd) deps.ledger.record({ id: `classifier:${sessionID}:${now()}`, at: now(), costUsd: jev.costUsd });
|
|
293
|
+
const result = decide({ config, tiers, decision, state, spend, signals, isNewTurn: state.turn > (state.lastRoutedTurn ?? -1), outputTokens: Math.max(4_000, usage.outputTokens) });
|
|
294
|
+
candidateIndex = Math.min(tiers.length - 1, Math.max(0, result.index));
|
|
295
|
+
source = result.source === "jev" ? (jev ? "jev" : "heuristic") : result.source === "sticky" && jev ? "jev-held" : result.source;
|
|
296
|
+
routed = true;
|
|
297
|
+
}
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (!isCurrent()) return;
|
|
300
|
+
deps.log({ at: new Date(now()).toISOString(), sessionID, kind: event.kind, source: "error", phase: "error", outcome: "error", message: "routing input unavailable" });
|
|
301
|
+
source = "fallback";
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
signal.throwIfAborted();
|
|
305
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
306
|
+
const target = tiers[candidateIndex]?.tier;
|
|
307
|
+
if (!target) return;
|
|
308
|
+
const to: AppliedTier = { name: target.name, providerID: event.model.providerID, model: target.model, variant: target.variant };
|
|
309
|
+
const from = entry.identity;
|
|
310
|
+
if (config.mode === "shadow") {
|
|
311
|
+
state.wouldIndex = candidateIndex;
|
|
312
|
+
serve(event, state.index, sessionID, event.kind, source, snapshot, { phase: "simulated", wouldServe: target.name });
|
|
313
|
+
if (!equal(from, to)) deps.emit({ sessionID, turn: state.turn, status: "simulated", from, to, reason: source });
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (equal(from, to)) {
|
|
317
|
+
if (routed) {
|
|
318
|
+
const saved: StoredSession = { ...entry.stored, lastRoutedTurn: state.turn };
|
|
319
|
+
await save(sessionID, saved, signal);
|
|
320
|
+
if (signal.aborted) states.delete(sessionID);
|
|
321
|
+
signal.throwIfAborted();
|
|
322
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
323
|
+
entry.stored = saved;
|
|
324
|
+
state.lastRoutedTurn = state.turn;
|
|
325
|
+
}
|
|
326
|
+
serve(event, state.index, sessionID, event.kind, source, snapshot, { phase: "selected" });
|
|
327
|
+
if (initial) deps.emit({ sessionID, turn: state.turn, status: "selected", to, reason: source });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const rejected = entry.stored.lastRejected;
|
|
331
|
+
const rejections = entry.stored.rejections;
|
|
332
|
+
if (config.feedback === "confirmation" && ((rejected && rejected.turn === state.turn && rejected.configFingerprint === configFingerprint && equal(rejected.from, from) && equal(rejected.to, to)) || (rejections && rejections.turn === state.turn && rejections.configFingerprint === configFingerprint && rejections.entries.some((item) => equal(item.from, from) && equal(item.to, to))))) {
|
|
333
|
+
serve(event, state.index, sessionID, event.kind, "rejected", snapshot, { phase: "retained", outcome: "rejected" });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
proposal = { id: crypto.randomUUID(), sessionID, from, to, reason: source };
|
|
337
|
+
const pending: StoredSession = { ...entry.stored, transition: { id: proposal.id, from, to, phase: "pending" } };
|
|
338
|
+
await save(sessionID, pending, signal);
|
|
339
|
+
if (signal.aborted) states.delete(sessionID);
|
|
340
|
+
signal.throwIfAborted();
|
|
341
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
342
|
+
entry.stored = pending;
|
|
343
|
+
deps.log({ at: new Date(now()).toISOString(), sessionID, kind: event.kind, source, phase: "proposal", proposalID: proposal.id, from, to, reason: source });
|
|
344
|
+
});
|
|
345
|
+
signal.throwIfAborted();
|
|
346
|
+
if (!proposal || !snapshot) return;
|
|
347
|
+
const selected = proposal;
|
|
348
|
+
const captured = snapshot;
|
|
349
|
+
const result: ConfirmResult = (capturedFeedback as FeedbackMode) === "confirmation"
|
|
350
|
+
? await deps.confirm(selected, { signal, isCurrent, recordFormID: async (formID) => {
|
|
351
|
+
await serial(sessionID, async () => {
|
|
352
|
+
signal.throwIfAborted();
|
|
353
|
+
if (!isCurrent()) { controller.abort(); return; }
|
|
354
|
+
const entry = states.get(sessionID);
|
|
355
|
+
if (!entry || entry.stored.version !== 1 || entry.stored.transition?.id !== selected.id || entry.stored.transition.phase !== "pending") throw new Error("Stale proposal");
|
|
356
|
+
const saved: StoredSession = { ...entry.stored, transition: { ...entry.stored.transition, formID } };
|
|
357
|
+
await save(sessionID, saved, signal);
|
|
358
|
+
if (signal.aborted) states.delete(sessionID);
|
|
359
|
+
signal.throwIfAborted();
|
|
360
|
+
if (!isCurrent()) { states.delete(sessionID); controller.abort(); return; }
|
|
361
|
+
entry.stored = saved;
|
|
362
|
+
});
|
|
363
|
+
signal.throwIfAborted();
|
|
364
|
+
} })
|
|
365
|
+
: { kind: "accepted", via: "reply" };
|
|
366
|
+
await serial(sessionID, async () => {
|
|
367
|
+
const entry = states.get(sessionID);
|
|
368
|
+
if (!entry || entry.stored.version !== 1 || entry.stored.transition?.id !== selected.id || entry.stored.transition.phase !== "pending") return;
|
|
369
|
+
const latest = deps.snapshot();
|
|
370
|
+
const valid = !signal.aborted && active.get(sessionID) === controller && latest.revision === captured.revision && latest.routingAllowed && latest.config.mode === capturedMode && latest.config.feedback === capturedFeedback && entry.runtime.turn === capturedTurn && entry.runtime.forcedTier === capturedForce && entry.identity !== null && equal(entry.identity, selected.from) && equal(entry.stored.applied, selected.from) && event.model.providerID === selected.to.providerID && latest.config.providers.includes(selected.to.providerID) && indexOf(selected.to, latest) >= 0;
|
|
371
|
+
if (!valid || result.kind === "invalidated") {
|
|
372
|
+
if (isCurrent()) deps.log({ at: new Date(now()).toISOString(), sessionID, kind: event.kind, source, phase: "decision", proposalID: selected.id, outcome: "invalidated" });
|
|
373
|
+
await clearPending(sessionID, entry); return;
|
|
374
|
+
}
|
|
375
|
+
deps.log({ at: new Date(now()).toISOString(), sessionID, kind: event.kind, source, phase: "decision", proposalID: selected.id, outcome: result.kind, ...(result.kind === "accepted" ? { via: capturedFeedback === "confirmation" ? result.via : "automatic" } : {}) });
|
|
376
|
+
if (result.kind === "error") {
|
|
377
|
+
await clearPending(sessionID, entry);
|
|
378
|
+
signal.throwIfAborted();
|
|
379
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
380
|
+
serve(event, entry.runtime.index, sessionID, event.kind, "error", captured, { phase: "retained", outcome: "error", proposalID: selected.id });
|
|
381
|
+
deps.emit({ sessionID, turn: capturedTurn, status: "error", from: selected.from, to: selected.to, reason: result.code });
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (result.kind === "rejected") {
|
|
385
|
+
const { transition: _transition, ...rest } = entry.stored;
|
|
386
|
+
const entries = [...(rest.rejections?.turn === capturedTurn && rest.rejections.configFingerprint === configFingerprint ? rest.rejections.entries : [])];
|
|
387
|
+
const previous = rest.lastRejected;
|
|
388
|
+
if (previous?.turn === capturedTurn && previous.configFingerprint === configFingerprint && !entries.some((item) => equal(item.from, previous.from) && equal(item.to, previous.to))) entries.push({ from: previous.from, to: previous.to });
|
|
389
|
+
entries.push({ from: selected.from, to: selected.to });
|
|
390
|
+
const saved: StoredSession = { ...rest, lastRejected: { turn: capturedTurn, configFingerprint, from: selected.from, to: selected.to }, rejections: { turn: capturedTurn, configFingerprint, entries } };
|
|
391
|
+
await save(sessionID, saved, signal);
|
|
392
|
+
if (signal.aborted) states.delete(sessionID);
|
|
393
|
+
signal.throwIfAborted();
|
|
394
|
+
if (!isCurrent()) { states.delete(sessionID); return; }
|
|
395
|
+
entry.stored = saved;
|
|
396
|
+
serve(event, entry.runtime.index, sessionID, event.kind, "rejected", captured, { phase: "retained", outcome: "rejected", proposalID: selected.id });
|
|
397
|
+
deps.emit({ sessionID, turn: capturedTurn, status: "rejected", from: selected.from, to: selected.to, reason: source });
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const applying: StoredSession = { ...entry.stored, transition: { ...entry.stored.transition, phase: "applying" } };
|
|
401
|
+
blocked.add(sessionID);
|
|
402
|
+
await save(sessionID, applying, signal);
|
|
403
|
+
if (signal.aborted) states.delete(sessionID);
|
|
404
|
+
signal.throwIfAborted();
|
|
405
|
+
entry.stored = applying;
|
|
406
|
+
const afterApplying = deps.snapshot();
|
|
407
|
+
if (active.get(sessionID) !== controller || afterApplying.revision !== captured.revision || !afterApplying.routingAllowed || afterApplying.config.mode !== "auto" || afterApplying.config.feedback !== capturedFeedback || indexOf(selected.from, afterApplying) < 0 || indexOf(selected.to, afterApplying) < 0) return;
|
|
408
|
+
entry.runtime.index = candidateIndex;
|
|
409
|
+
modelMutated = true;
|
|
410
|
+
serve(event, candidateIndex, sessionID, event.kind, source, captured, {}, true);
|
|
411
|
+
const { transition: _transition, lastRejected: _lastRejected, ...rest } = applying;
|
|
412
|
+
const saved: StoredSession = { ...rest, applied: selected.to, configRevision: captured.revision, ...(routed ? { lastRoutedTurn: capturedTurn } : {}) };
|
|
413
|
+
try {
|
|
414
|
+
await save(sessionID, saved, signal);
|
|
415
|
+
if (signal.aborted) states.delete(sessionID);
|
|
416
|
+
signal.throwIfAborted();
|
|
417
|
+
} catch (error) {
|
|
418
|
+
// A failed write may have committed; restore the conservative marker if storage permits.
|
|
419
|
+
try { await deps.stateStore.save(sessionID, applying); } catch { /* remain blocked locally */ }
|
|
420
|
+
throw error;
|
|
421
|
+
}
|
|
422
|
+
if (!isCurrent()) { states.delete(sessionID); blocked.delete(sessionID); return; }
|
|
423
|
+
entry.stored = saved;
|
|
424
|
+
if (routed) entry.runtime.lastRoutedTurn = capturedTurn;
|
|
425
|
+
blocked.delete(sessionID);
|
|
426
|
+
deps.log({ at: new Date(now()).toISOString(), sessionID, kind: event.kind, source, phase: "selected", proposalID: selected.id, tier: selected.to.name, model: selected.to.model, variant: selected.to.variant, spendTodayUsd: Number(deps.ledger.snapshot(now()).todayUsd.toFixed(4)), ...(classifier ? { classifier, confidence } : {}) });
|
|
427
|
+
deps.emit({ sessionID, turn: capturedTurn, status: "selected", from: selected.from, to: selected.to, reason: source });
|
|
428
|
+
});
|
|
429
|
+
} catch (error) {
|
|
430
|
+
if (isCurrent()) {
|
|
431
|
+
deps.log({ at: new Date(now()).toISOString(), sessionID, kind: event.kind, source: "error", phase: "error", outcome: "error", ...(proposal ? { proposalID: proposal.id } : {}), message: "routing operation failed" });
|
|
432
|
+
if (proposal) deps.emit({ sessionID, turn: capturedTurn, status: "error", from: proposal.from, to: proposal.to, reason: modelMutated ? "selection_ambiguous" : "storage_or_transport_error" });
|
|
433
|
+
}
|
|
434
|
+
} finally {
|
|
435
|
+
if (active.get(sessionID) === controller) active.delete(sessionID);
|
|
436
|
+
}
|
|
437
|
+
},
|
|
438
|
+
|
|
439
|
+
async onPrompt(event, context) {
|
|
440
|
+
invalidate(event.sessionID);
|
|
441
|
+
await serial(event.sessionID, async () => {
|
|
442
|
+
const snapshot = deps.snapshot();
|
|
443
|
+
const entry = await stateFor(event.sessionID, snapshot, context?.signal);
|
|
444
|
+
context?.signal.throwIfAborted();
|
|
445
|
+
if (blocked.has(event.sessionID) || entry.stored.transition?.phase === "applying") return;
|
|
446
|
+
await clearPending(event.sessionID, entry, context?.signal);
|
|
447
|
+
context?.signal.throwIfAborted();
|
|
448
|
+
const { lastRejected: _lastRejected, rejections: _rejections, ...rest } = entry.stored;
|
|
449
|
+
const saved = { ...rest, turn: entry.stored.turn + 1 };
|
|
450
|
+
await save(event.sessionID, saved, context?.signal);
|
|
451
|
+
if (context?.signal.aborted) states.delete(event.sessionID);
|
|
452
|
+
context?.signal.throwIfAborted();
|
|
453
|
+
entry.stored = saved;
|
|
454
|
+
entry.runtime.turn = saved.turn;
|
|
455
|
+
});
|
|
456
|
+
},
|
|
457
|
+
|
|
458
|
+
async setForced(sessionID, tier, signal) {
|
|
459
|
+
invalidate(sessionID);
|
|
460
|
+
await serial(sessionID, async () => {
|
|
461
|
+
const snapshot = deps.snapshot();
|
|
462
|
+
const entry = await stateFor(sessionID, snapshot, signal);
|
|
463
|
+
signal?.throwIfAborted();
|
|
464
|
+
if (blocked.has(sessionID) || entry.stored.transition?.phase === "applying") throw new Error("routing transition is ambiguous");
|
|
465
|
+
await clearPending(sessionID, entry, signal);
|
|
466
|
+
signal?.throwIfAborted();
|
|
467
|
+
const { forcedTier: _forcedTier, ...rest } = entry.stored;
|
|
468
|
+
const saved = tier === null ? rest : { ...rest, forcedTier: tier };
|
|
469
|
+
await save(sessionID, saved, signal);
|
|
470
|
+
if (signal?.aborted) states.delete(sessionID);
|
|
471
|
+
signal?.throwIfAborted();
|
|
472
|
+
entry.stored = saved;
|
|
473
|
+
entry.runtime.forcedTier = tier ?? undefined;
|
|
474
|
+
});
|
|
475
|
+
},
|
|
476
|
+
|
|
477
|
+
status(sessionID) {
|
|
478
|
+
const entry = states.get(sessionID);
|
|
479
|
+
if (!entry || !entry.identity || !entry.stored.applied) return undefined;
|
|
480
|
+
const snapshot = deps.snapshot();
|
|
481
|
+
if (indexOf(entry.stored.applied, snapshot) < 0 || indexOf(entry.identity, snapshot) < 0) {
|
|
482
|
+
return { index: -1, tier: entry.stored.applied, unavailable: true, spend: deps.ledger.snapshot(now()), mode: snapshot.config.mode };
|
|
483
|
+
}
|
|
484
|
+
const state = entry.runtime;
|
|
485
|
+
const index = indexOf(entry.identity, snapshot);
|
|
486
|
+
const info = snapshot.tiers[index];
|
|
487
|
+
if (!info) return undefined;
|
|
488
|
+
const would = state.wouldIndex === undefined ? undefined : snapshot.tiers[state.wouldIndex]?.tier;
|
|
489
|
+
return {
|
|
490
|
+
index,
|
|
491
|
+
tier: info.tier,
|
|
492
|
+
...(would ? { wouldTier: would } : {}),
|
|
493
|
+
spend: deps.ledger.snapshot(now()),
|
|
494
|
+
mode: snapshot.config.mode,
|
|
495
|
+
};
|
|
496
|
+
},
|
|
497
|
+
};
|
|
498
|
+
}
|