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.
@@ -0,0 +1,274 @@
1
+ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { DEFAULT_FALLBACK_TIER, DEFAULT_KIND_MINIMUM, DEFAULT_TIERS, parseConfigObject } from "./config";
5
+ import type { RouterConfig } from "./types";
6
+
7
+ export const CONFIG_DIR = join(homedir(), ".local", "share", "opencode", "tier-router");
8
+ export const CONFIG_PATH = join(CONFIG_DIR, "config.json");
9
+
10
+ export interface StoredConfig {
11
+ config: RouterConfig;
12
+ source: "defaults" | "file" | "migrated";
13
+ errors: string[];
14
+ optionsIgnored: boolean;
15
+ mtimeMs: number;
16
+ routingAllowed: boolean;
17
+ }
18
+
19
+ /** The document a fresh install gets. Every key is explicit, no implicit defaults. */
20
+ export function defaultsJson(): Record<string, unknown> {
21
+ return {
22
+ version: 1,
23
+ providers: ["opencode-go"],
24
+ mode: "auto",
25
+ feedback: "information",
26
+ tiers: DEFAULT_TIERS.map((tier) => ({ ...tier })),
27
+ classifier: {
28
+ model: "opencode-go/jev-1.14",
29
+ timeoutMs: 900,
30
+ minPromptChars: 12,
31
+ confidenceThreshold: 0.34,
32
+ },
33
+ kindMinimumTier: { ...DEFAULT_KIND_MINIMUM },
34
+ budget: { softRatio: 0.7, hardRatio: 0.9 },
35
+ cache: { minTokens: 20_000, minTierDelta: 1, maxPenaltyUsd: 0.05 },
36
+ downgradeDelta: 1,
37
+ fallbackTier: DEFAULT_FALLBACK_TIER,
38
+ cascade: { mode: "off", targetTier: "pro", gateThreshold: 0.5, gateTimeoutMs: 1_500, fetchTimeoutMs: 30_000 },
39
+ };
40
+ }
41
+
42
+ /** Serialises a parsed config back into the stored document shape. */
43
+ export function documentOf(config: RouterConfig): Record<string, unknown> {
44
+ return {
45
+ version: 1,
46
+ providers: config.providers,
47
+ mode: config.mode,
48
+ feedback: config.feedback,
49
+ tiers: config.tiers.map((tier) => ({ ...tier })),
50
+ classifier: { ...config.classifier },
51
+ kindMinimumTier: { ...config.kindMinimumTier },
52
+ budget: {
53
+ ...(config.budget.dailyUsd === undefined ? {} : { dailyUsd: config.budget.dailyUsd }),
54
+ ...(config.budget.monthlyUsd === undefined ? {} : { monthlyUsd: config.budget.monthlyUsd }),
55
+ softRatio: config.budget.softRatio,
56
+ hardRatio: config.budget.hardRatio,
57
+ },
58
+ cache: { ...config.cache },
59
+ downgradeDelta: config.downgradeDelta,
60
+ fallbackTier: config.fallbackTier,
61
+ cascade: { ...config.cascade },
62
+ };
63
+ }
64
+
65
+ const CONFIG_KEYS = [
66
+ "providers",
67
+ "mode",
68
+ "feedback",
69
+ "tiers",
70
+ "classifier",
71
+ "kindMinimumTier",
72
+ "budget",
73
+ "cache",
74
+ "downgradeDelta",
75
+ "fallbackTier",
76
+ "cascade",
77
+ ];
78
+
79
+ const hasConfigKeys = (options: unknown): boolean => {
80
+ if (typeof options !== "object" || options === null) return false;
81
+ return CONFIG_KEYS.some((key) => key in (options as Record<string, unknown>));
82
+ };
83
+
84
+ const writeAtomic = (path: string, document: unknown): void => {
85
+ mkdirSync(dirname(path), { recursive: true });
86
+ const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
87
+ writeFileSync(tmp, `${JSON.stringify(document, null, 2)}\n`, "utf8");
88
+ renameSync(tmp, path);
89
+ };
90
+
91
+ /**
92
+ * Reads the single config file. Creates it from defaults when missing, copies
93
+ * `options` into it once when that is the case, and never rewrites an existing
94
+ * file. A schema-invalid file leaves the defaults active and reports why.
95
+ */
96
+ export async function loadConfigFile(path: string, options: unknown): Promise<StoredConfig> {
97
+ let text: string | undefined;
98
+ try {
99
+ text = readFileSync(path, "utf8");
100
+ } catch (error) {
101
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
102
+ return {
103
+ config: parseConfigObject(defaultsJson()), source: "defaults",
104
+ errors: [String((error as Error)?.message ?? error)], optionsIgnored: false, mtimeMs: 0,
105
+ routingAllowed: false,
106
+ };
107
+ }
108
+ text = undefined;
109
+ }
110
+
111
+ if (text === undefined) {
112
+ const migrate = hasConfigKeys(options);
113
+ let document: Record<string, unknown>;
114
+ let config: RouterConfig;
115
+ const errors: string[] = [];
116
+ if (migrate) {
117
+ try {
118
+ config = parseConfigObject(options);
119
+ document = documentOf(config);
120
+ } catch (error) {
121
+ return {
122
+ config: parseConfigObject(defaultsJson()), source: "defaults",
123
+ errors: [String((error as Error)?.message ?? error)], optionsIgnored: true, mtimeMs: 0,
124
+ routingAllowed: false,
125
+ };
126
+ }
127
+ } else {
128
+ document = defaultsJson();
129
+ config = parseConfigObject(document);
130
+ }
131
+ try {
132
+ writeAtomic(path, document);
133
+ } catch (error) {
134
+ errors.push(`config file not written: ${String((error as Error)?.message ?? error)}`);
135
+ }
136
+ return {
137
+ config,
138
+ source: migrate ? "migrated" : "defaults",
139
+ errors,
140
+ optionsIgnored: migrate,
141
+ mtimeMs: 0,
142
+ routingAllowed: true,
143
+ };
144
+ }
145
+
146
+ try {
147
+ const document = JSON.parse(text) as unknown;
148
+ if (typeof document !== "object" || document === null || Array.isArray(document)) throw new TypeError("config must be an object");
149
+ return {
150
+ config: parseConfigObject(document),
151
+ source: "file",
152
+ errors: [],
153
+ optionsIgnored: false,
154
+ mtimeMs: 0,
155
+ routingAllowed: true,
156
+ };
157
+ } catch (error) {
158
+ return {
159
+ config: parseConfigObject(defaultsJson()),
160
+ source: "defaults",
161
+ errors: [String((error as Error)?.message ?? error)],
162
+ optionsIgnored: false,
163
+ mtimeMs: 0,
164
+ routingAllowed: false,
165
+ };
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Validates and writes the config document atomically. A refused document
171
+ * leaves the existing file untouched.
172
+ */
173
+ export async function writeConfigFile(
174
+ path: string,
175
+ config: unknown,
176
+ ): Promise<{ ok: true } | { ok: false; errors: string[] }> {
177
+ let document: Record<string, unknown>;
178
+ try {
179
+ const parsed = parseConfigObject(config);
180
+ document = documentOf(parsed);
181
+ } catch (error) {
182
+ return { ok: false, errors: [String((error as Error)?.message ?? error)] };
183
+ }
184
+ try {
185
+ writeAtomic(path, document);
186
+ return { ok: true };
187
+ } catch (error) {
188
+ return { ok: false, errors: [`config file not written: ${String((error as Error)?.message ?? error)}`] };
189
+ }
190
+ }
191
+
192
+ export interface ConfigSnapshot {
193
+ config: RouterConfig;
194
+ revision: number;
195
+ routingAllowed: boolean;
196
+ }
197
+
198
+ export interface ConfigStore {
199
+ current(): RouterConfig;
200
+ snapshot(): ConfigSnapshot;
201
+ errors: string[];
202
+ optionsIgnored: boolean;
203
+ replace(config: RouterConfig): void;
204
+ refresh(force?: boolean): void;
205
+ }
206
+
207
+ const RECHECK_MS = 1_000;
208
+
209
+ /**
210
+ * Keeps the active config in memory and re-reads the shared file when its mtime
211
+ * changes, so a save made by any instance reaches every running server. A file
212
+ * that disappears or stops parsing leaves the last valid config in place.
213
+ */
214
+ export async function openConfigStore(deps: { path: string; options: unknown }): Promise<ConfigStore> {
215
+ const stored = await loadConfigFile(deps.path, deps.options);
216
+ let config = stored.config;
217
+ let revision = 0;
218
+ let routingAllowed = stored.routingAllowed;
219
+ let errors = [...stored.errors];
220
+ let lastCheck = 0;
221
+ let lastMtime = stored.routingAllowed ? mtimeOf(deps.path) : undefined;
222
+
223
+ const refresh = (force = false): void => {
224
+ const now = Date.now();
225
+ if (!force && now - lastCheck < RECHECK_MS) return;
226
+ lastCheck = now;
227
+ const mtime = mtimeOf(deps.path);
228
+ if (mtime === undefined || (!force && mtime === lastMtime)) return;
229
+ try {
230
+ const document = JSON.parse(readFileSync(deps.path, "utf8")) as unknown;
231
+ if (typeof document !== "object" || document === null || Array.isArray(document)) throw new TypeError("config must be an object");
232
+ config = parseConfigObject(document);
233
+ lastMtime = mtime;
234
+ revision++;
235
+ routingAllowed = true;
236
+ errors = [];
237
+ } catch (error) {
238
+ errors = [String((error as Error)?.message ?? error)];
239
+ }
240
+ };
241
+
242
+ return {
243
+ current() {
244
+ refresh();
245
+ return config;
246
+ },
247
+ snapshot() {
248
+ refresh();
249
+ return { config, revision, routingAllowed };
250
+ },
251
+ get errors() {
252
+ return errors;
253
+ },
254
+ get optionsIgnored() {
255
+ return stored.optionsIgnored;
256
+ },
257
+ replace(next) {
258
+ config = next;
259
+ revision++;
260
+ routingAllowed = true;
261
+ errors = [];
262
+ lastMtime = mtimeOf(deps.path);
263
+ },
264
+ refresh,
265
+ };
266
+ }
267
+
268
+ function mtimeOf(path: string): number | undefined {
269
+ try {
270
+ return statSync(path).mtimeMs;
271
+ } catch {
272
+ return undefined;
273
+ }
274
+ }
@@ -0,0 +1,162 @@
1
+ import { OpenCode, type FormCancelled, type FormInfo, type FormReplied, type ServerInfo, type SessionFormCancelInput, type SessionFormCreateInput, type V2EventServerConnected } from "@opencode/client";
2
+ import { Service, type Endpoint } from "@opencode/client/service";
3
+ import { TierRouterRpc } from "./rpc";
4
+ import type { AppliedTier } from "./types";
5
+
6
+ export type Proposal = { id: string; sessionID: string; from: AppliedTier; to: AppliedTier; reason: string };
7
+ export type ConfirmResult = { kind: "accepted"; via: "reply" | "timeout" } | { kind: "rejected" } | { kind: "invalidated" } | { kind: "error"; code: string };
8
+ export type ConfirmationEvent = FormReplied | FormCancelled | V2EventServerConnected;
9
+ type Timer = number | NodeJS.Timeout;
10
+ export interface ConfirmationClient {
11
+ info(signal: AbortSignal): Promise<ServerInfo>;
12
+ identity(location: string, signal: AbortSignal): Promise<{ instanceID: string }>;
13
+ subscribe(signal: AbortSignal): AsyncIterable<ConfirmationEvent>;
14
+ create(input: SessionFormCreateInput, signal: AbortSignal): Promise<FormInfo>;
15
+ cancel(input: SessionFormCancelInput, signal: AbortSignal): Promise<void>;
16
+ }
17
+ export interface ConfirmationDeps {
18
+ location: string;
19
+ version: string;
20
+ instanceID: string;
21
+ pid?: number;
22
+ discover?: () => Promise<Endpoint | undefined>;
23
+ makeClient?: (endpoint: Endpoint) => ConfirmationClient;
24
+ setTimeout?: (fn: () => void, ms: number) => Timer;
25
+ clearTimeout?: (id: Timer) => void;
26
+ }
27
+
28
+ const networkTimeout = 10_000;
29
+
30
+ function makeClient(endpoint: Endpoint): ConfirmationClient {
31
+ const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) });
32
+ return {
33
+ info: (signal) => client.server.info({ signal }),
34
+ identity: async (location, signal) => {
35
+ const value = await client.rpc(TierRouterRpc).hostIdentity({}, { location: { directory: location }, signal });
36
+ if (typeof value !== "object" || value === null || !("instanceID" in value) || typeof value.instanceID !== "string") throw new Error("host_mismatch");
37
+ return { instanceID: value.instanceID };
38
+ },
39
+ subscribe: (signal) => client.event.subscribe({ types: ["form.replied", "form.cancelled"], signal }),
40
+ create: (input, signal) => client.session.form.create(input, { signal }),
41
+ cancel: (input, signal) => client.session.form.cancel(input, { signal }),
42
+ };
43
+ }
44
+
45
+ export function createConfirmation(deps: ConfirmationDeps) {
46
+ const later = deps.setTimeout ?? setTimeout;
47
+ const clear = deps.clearTimeout ?? clearTimeout;
48
+ const active = new Map<AbortController, Promise<void>>();
49
+ let disposed = false;
50
+
51
+ async function verified(signal: AbortSignal): Promise<ConfirmationClient> {
52
+ const endpoint = await (deps.discover ?? Service.discover)();
53
+ if (!endpoint || signal.aborted) throw new Error("service_unavailable");
54
+ const client = (deps.makeClient ?? makeClient)(endpoint);
55
+ const info = await client.info(signal);
56
+ if (signal.aborted || info.version !== deps.version || info.pid !== (deps.pid ?? process.pid)) throw new Error("host_mismatch");
57
+ const identity = await client.identity(deps.location, signal);
58
+ if (signal.aborted || identity.instanceID !== deps.instanceID) throw new Error("host_mismatch");
59
+ return client;
60
+ }
61
+
62
+ async function boundedCancel(client: ConfirmationClient, sessionID: string, formID: string): Promise<void> {
63
+ const controller = new AbortController();
64
+ let timer: Timer | undefined;
65
+ try {
66
+ await Promise.race([
67
+ client.cancel({ sessionID, formID }, controller.signal),
68
+ new Promise<void>((resolve) => { timer = later(() => { controller.abort(); resolve(); }, networkTimeout); }),
69
+ ]);
70
+ } catch { /* cancellation is best effort */ }
71
+ finally { if (timer !== undefined) clear(timer); controller.abort(); }
72
+ }
73
+
74
+ async function cancel(sessionID: string, formID: string): Promise<void> {
75
+ const controller = new AbortController();
76
+ let timer: Timer | undefined;
77
+ try {
78
+ await Promise.race([
79
+ (async () => { const client = await verified(controller.signal); await boundedCancel(client, sessionID, formID); })(),
80
+ new Promise<void>((resolve) => { timer = later(() => { controller.abort(); resolve(); }, networkTimeout); }),
81
+ ]);
82
+ } catch { /* stale forms may already be gone */ }
83
+ finally { if (timer !== undefined) clear(timer); controller.abort(); }
84
+ }
85
+
86
+ async function confirm(proposal: Proposal, context: { signal: AbortSignal; isCurrent(): boolean; recordFormID(formID: string): Promise<void> }): Promise<ConfirmResult> {
87
+ if (disposed || context.signal.aborted) return { kind: "invalidated" };
88
+ const controller = new AbortController();
89
+ let completed!: () => void;
90
+ active.set(controller, new Promise<void>((resolve) => { completed = resolve; }));
91
+ let done = false;
92
+ let acknowledged = false;
93
+ let posted = false;
94
+ let early: ConfirmResult | undefined;
95
+ let client: ConfirmationClient | undefined;
96
+ const formID = `frm_${crypto.randomUUID().replaceAll("-", "")}`;
97
+ let resolveResult!: (result: ConfirmResult) => void;
98
+ const result = new Promise<ConfirmResult>((resolve) => { resolveResult = resolve; });
99
+ const finish = (value: ConfirmResult) => { if (!done) { done = true; resolveResult(value); } };
100
+ const abort = () => finish({ kind: "invalidated" });
101
+ context.signal.addEventListener("abort", abort, { once: true });
102
+ controller.signal.addEventListener("abort", abort, { once: true });
103
+ let setupTimer: Timer | undefined = later(() => finish({ kind: "error", code: "network_timeout" }), networkTimeout);
104
+ let decisionTimer: Timer | undefined;
105
+ void (async () => {
106
+ try {
107
+ client = await verified(controller.signal);
108
+ if (done) return;
109
+ const iterator = client.subscribe(controller.signal)[Symbol.asyncIterator]();
110
+ const first = await iterator.next();
111
+ if (done) return;
112
+ if (first.done || first.value.type !== "server.connected") throw new Error("event_unavailable");
113
+ void (async () => {
114
+ try {
115
+ while (!done) {
116
+ const next = await iterator.next();
117
+ if (done) return;
118
+ if (next.done) throw new Error("event_unavailable");
119
+ const event = next.value;
120
+ if (event.type === "server.connected") throw new Error("event_reconnected");
121
+ if (event.location?.directory !== deps.location || event.data.sessionID !== proposal.sessionID || event.data.id !== formID) continue;
122
+ const decision: ConfirmResult = event.type === "form.replied" && event.data.answer.decision === "accept" ? { kind: "accepted", via: "reply" } : { kind: "rejected" };
123
+ if (acknowledged) finish(decision); else early ??= decision;
124
+ }
125
+ } catch { if (!done) finish({ kind: "error", code: "event_unavailable" }); }
126
+ })();
127
+ await context.recordFormID(formID);
128
+ if (done) return;
129
+ if (!context.isCurrent()) { finish({ kind: "invalidated" }); return; }
130
+ const describe = (tier: AppliedTier) => `${tier.name} (${tier.providerID}/${tier.model}, variant: ${tier.variant ?? "none"})`;
131
+ const input: SessionFormCreateInput = {
132
+ id: formID, sessionID: proposal.sessionID,
133
+ title: `Routing: ${describe(proposal.from)} → ${describe(proposal.to)}. ${proposal.reason}. Auto-accept after 60 seconds.`,
134
+ metadata: { kind: "question" },
135
+ fields: [{ key: "decision", type: "string", required: true, custom: true, options: [{ value: "accept", label: "Accept" }, { value: "reject", label: "Reject" }] }],
136
+ };
137
+ posted = true;
138
+ const created = await client.create(input, controller.signal);
139
+ if (done) { void boundedCancel(client, proposal.sessionID, formID); return; }
140
+ if (created.id !== formID || created.sessionID !== proposal.sessionID) throw new Error("form_mismatch");
141
+ acknowledged = true;
142
+ if (setupTimer !== undefined) { clear(setupTimer); setupTimer = undefined; }
143
+ if (early) finish(early);
144
+ else decisionTimer = later(() => finish({ kind: "accepted", via: "timeout" }), 60_000);
145
+ } catch { if (!done) finish(context.isCurrent() ? { kind: "error", code: "transport_error" } : { kind: "invalidated" }); }
146
+ })();
147
+ const outcome = await result;
148
+ if (setupTimer !== undefined) clear(setupTimer);
149
+ if (decisionTimer !== undefined) clear(decisionTimer);
150
+ context.signal.removeEventListener("abort", abort);
151
+ controller.signal.removeEventListener("abort", abort);
152
+ controller.abort();
153
+ if (posted && client && (outcome.kind === "invalidated" || outcome.kind === "error" || (outcome.kind === "accepted" && outcome.via === "timeout"))) {
154
+ await boundedCancel(client, proposal.sessionID, formID);
155
+ }
156
+ active.delete(controller);
157
+ completed();
158
+ return outcome;
159
+ }
160
+
161
+ return { confirm, cancel, async dispose() { disposed = true; for (const controller of active.keys()) controller.abort(); await Promise.all(active.values()); } };
162
+ }
package/src/control.ts ADDED
@@ -0,0 +1,80 @@
1
+ import type { Router, RouterStatus } from "./router";
2
+ import type { RouterConfig } from "./types";
3
+
4
+ export function formatStatus(status: RouterStatus): string {
5
+ if (status.unavailable) return `tier-router: selected tier unavailable in configuration: ${status.tier.name} (${status.tier.model}${status.tier.variant ? `#${status.tier.variant}` : ""})`;
6
+ const parts = [
7
+ `tier: ${status.tier.name} (${status.tier.model}${status.tier.variant ? `#${status.tier.variant}` : ""})`,
8
+ `mode: ${status.mode}`,
9
+ ];
10
+ if (status.wouldTier) parts.push(`would: ${status.wouldTier.name}`);
11
+ parts.push(`today: $${status.spend.todayUsd.toFixed(2)}`);
12
+ parts.push(`month: $${status.spend.monthUsd.toFixed(2)}`);
13
+ return parts.join(" · ");
14
+ }
15
+
16
+ export interface ControlDeps {
17
+ router: Router;
18
+ config: RouterConfig;
19
+ notify: (sessionID: string, text: string) => Promise<void>;
20
+ }
21
+
22
+ export interface Control {
23
+ command: {
24
+ name: string;
25
+ description: string;
26
+ execute: (input: { sessionID: string; prompt: { text: string } }) => Promise<void>;
27
+ };
28
+ tool: {
29
+ name: string;
30
+ description: string;
31
+ input: unknown;
32
+ execute: (
33
+ input: { tier: string | null },
34
+ context: { sessionID: string },
35
+ ) => Promise<{ content: string }>;
36
+ };
37
+ }
38
+
39
+ export function createControl(deps: ControlDeps): Control {
40
+ const known = () => deps.router.tiers().map((info) => info.tier.name);
41
+
42
+ return {
43
+ command: {
44
+ name: "tier-router",
45
+ description: "Show the active routing tier, mode and spend; /tier-router last shows the last decision",
46
+ async execute({ sessionID }) {
47
+ const status = deps.router.status(sessionID);
48
+ const text = status ? formatStatus(status) : "tier-router: no routing status available in this session";
49
+ await deps.notify(sessionID, text);
50
+ },
51
+ },
52
+ tool: {
53
+ name: "tier_router",
54
+ description:
55
+ "Force this session onto a routing tier, or release the override with null. The daily hard budget can still lower it.",
56
+ input: {
57
+ type: "object",
58
+ properties: {
59
+ tier: {
60
+ type: ["string", "null"],
61
+ description: `Tier name, one of: ${known().join(", ")}; null releases the override`,
62
+ },
63
+ },
64
+ required: ["tier"],
65
+ additionalProperties: false,
66
+ },
67
+ async execute({ tier }, context) {
68
+ if (tier === null) {
69
+ await deps.router.setForced(context.sessionID, null);
70
+ return { content: "tier override released" };
71
+ }
72
+ if (!known().includes(tier)) {
73
+ throw new Error(`tier-router: unknown tier ${tier}; known tiers: ${known().join(", ")}`);
74
+ }
75
+ await deps.router.setForced(context.sessionID, tier);
76
+ return { content: `tier override requested: ${tier} for this session` };
77
+ },
78
+ },
79
+ };
80
+ }
@@ -0,0 +1,39 @@
1
+ import type { AppliedTier, RoutingEvent } from "./types";
2
+
3
+ /**
4
+ * How long an informational routing toast stays on screen. The app default (5
5
+ * seconds) was too short to read a full tier transition.
6
+ */
7
+ export const ROUTING_TOAST_DURATION_MS = 15_000;
8
+
9
+ export interface RoutingToast {
10
+ /** Short headline: tier names only, so a client never truncates it. */
11
+ headline: string;
12
+ /** Models, variants and the reason, shown on the lines under the headline. */
13
+ detail: string;
14
+ /** Whether the event reports a failure. */
15
+ failed: boolean;
16
+ }
17
+
18
+ const describe = (tier: AppliedTier): string => `${tier.name} (${tier.model}, variante ${tier.variant ?? "aucune"})`;
19
+
20
+ /**
21
+ * Splits a routing event into a headline and a detail line. Clients render the
22
+ * headline on one line and truncate it; the detail is what carries the model
23
+ * names, so it must not sit in the headline.
24
+ */
25
+ export function routingToast(data: RoutingEvent): RoutingToast {
26
+ const from = data.from;
27
+ const transition = `${from ? `${from.name} → ` : ""}${data.to.name}`;
28
+ const details = `${from ? `${describe(from)} → ` : ""}${describe(data.to)} : ${data.reason}`;
29
+ if (data.status === "error" && data.reason === "selection_ambiguous") {
30
+ return { headline: "Tier Router : état de sélection ambigu après une erreur", detail: "le modèle final est inconnu.", failed: true };
31
+ }
32
+ if (data.status === "selected") return { headline: `Tier Router a sélectionné ${transition}`, detail: details, failed: false };
33
+ if (data.status === "simulated") return { headline: `Simulation : Tier Router aurait sélectionné ${transition}`, detail: details, failed: false };
34
+ return {
35
+ headline: `Tier Router a conservé ${from ? from.name : "le palier courant"}`,
36
+ detail: `${data.status === "rejected" ? "changement refusé" : "erreur"} vers ${describe(data.to)} : ${data.reason}`,
37
+ failed: data.status === "error",
38
+ };
39
+ }