opencode-model-router 2.4.0 → 2.6.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,220 @@
1
+ /**
2
+ * #90 P1.2 (amendments A1, A3): the server side of the TUI effort channel. OpenCode v2 only — the v2 adapter
3
+ * (src/compat/v2-hooks.ts) records, per session (root and child), what its `chat.params` bridge applied to the latest turn and
4
+ * answers the TUI's `effortOf` rpc from this store. Nothing here runs on OpenCode v1.
5
+ */
6
+ import { isClaudeModel } from "../router/protocol";
7
+ import { effortRpc, type EffortOfOutput } from "./effort-rpc";
8
+
9
+ /** The store's default bound: the sessions of one location the TUI can still ask about. */
10
+ export const EFFORT_STORE_MAX_SESSIONS = 1000;
11
+
12
+ /** How long the registration waits for the host's `rpc.register` before it resolves without the channel (a late one is kept). */
13
+ export const EFFORT_REGISTER_TIMEOUT_MS = 2000;
14
+
15
+ /** One turn as the adapter saw it; fields that are not strings (or a finite `at`, a positive integer budget) are dropped. */
16
+ export interface EffortTurn {
17
+ readonly effort?: unknown;
18
+ readonly variant?: unknown;
19
+ readonly providerID?: unknown;
20
+ readonly modelID?: unknown;
21
+ readonly agent?: unknown;
22
+ readonly at?: unknown;
23
+ readonly thinkingBudget?: unknown;
24
+ }
25
+
26
+ export interface EffortStore {
27
+ /** The latest turn of `sessionID` replaces the previous one (an absent effort clears a stale one). */
28
+ record(sessionID: string, turn: EffortTurn): void;
29
+ /** A copy of the latest turn of `sessionID`, or `{}` when nothing is known. */
30
+ lookup(sessionID: string): EffortOfOutput;
31
+ /** Drops what is known about `sessionID` (the session was deleted, or its latest request did not go out). */
32
+ forget(sessionID: string): void;
33
+ /** How many sessions are held. */
34
+ size(): number;
35
+ }
36
+
37
+ type Mutable<T> = { -readonly [K in keyof T]: T[K] };
38
+ const TEXT_FIELDS = ["effort", "variant", "providerID", "modelID", "agent"] as const;
39
+
40
+ const nonEmptyString = (value: unknown): value is string => typeof value === "string" && value !== "";
41
+ const positiveInteger = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
42
+
43
+ /** Only the fields the rpc output declares, each only when it has a usable value (the output schema has no other keys). */
44
+ function sanitize(turn: EffortTurn): EffortOfOutput {
45
+ const out: Mutable<EffortOfOutput> = {};
46
+ for (const field of TEXT_FIELDS) {
47
+ const value = turn[field];
48
+ if (nonEmptyString(value)) out[field] = value;
49
+ }
50
+ if (typeof turn.at === "number" && Number.isFinite(turn.at)) out.at = turn.at;
51
+ if (positiveInteger(turn.thinkingBudget)) out.thinkingBudget = turn.thinkingBudget;
52
+ return out;
53
+ }
54
+
55
+ /** A bounded in-memory store; above `maxSessions` the least recently WRITTEN session is evicted. */
56
+ export function createEffortStore(maxSessions: number = EFFORT_STORE_MAX_SESSIONS): EffortStore {
57
+ const max = Number.isSafeInteger(maxSessions) && maxSessions > 0 ? maxSessions : EFFORT_STORE_MAX_SESSIONS;
58
+ const entries = new Map<string, EffortOfOutput>();
59
+ return {
60
+ record(sessionID, turn) {
61
+ if (!nonEmptyString(sessionID)) return;
62
+ entries.delete(sessionID); // re-inserted last: the write order is the eviction order
63
+ entries.set(sessionID, sanitize(turn));
64
+ while (entries.size > max) entries.delete(entries.keys().next().value!);
65
+ },
66
+ lookup(sessionID) {
67
+ const entry = nonEmptyString(sessionID) ? entries.get(sessionID) : undefined;
68
+ return entry === undefined ? {} : { ...entry };
69
+ },
70
+ forget(sessionID) {
71
+ if (nonEmptyString(sessionID)) entries.delete(sessionID);
72
+ },
73
+ size: () => entries.size,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * The effort a turn's (already normalised) request options carry. Two keys can hold it: `effort` (what `buildAgentOptions`
79
+ * writes for a Claude model, and what the escalation override replaces there) and `reasoningEffort` (every other family; the
80
+ * `reasoning_effort` alias once normalised). For a Claude model (the router's own `isClaudeModel`, on `provider/model`)
81
+ * `effort` is read first, otherwise `reasoningEffort`; each falls back to the other. Undefined when neither is a non-empty string.
82
+ */
83
+ export function appliedEffort(
84
+ options: Readonly<Record<string, unknown>>,
85
+ model: { readonly providerID?: unknown; readonly modelID?: unknown } = {},
86
+ ): string | undefined {
87
+ // `provider/model` as the router spells a model (a provider alone stays `anthropic/`, which the predicate still matches).
88
+ const id = nonEmptyString(model.modelID) ? model.modelID : "";
89
+ const ref = nonEmptyString(model.providerID) ? `${model.providerID}/${id}` : id;
90
+ const order = isClaudeModel(ref) ? ["effort", "reasoningEffort"] as const : ["reasoningEffort", "effort"] as const;
91
+ for (const key of order) {
92
+ const value = options[key];
93
+ if (nonEmptyString(value)) return value;
94
+ }
95
+ return undefined;
96
+ }
97
+
98
+ /**
99
+ * The thinking budget a turn's (already normalised) request options carry, in the shape the router writes it
100
+ * (src/router/agent-options.ts `buildAgentOptions`: `thinking: { type: "enabled", budgetTokens }`; the `budget_tokens` alias once
101
+ * normalised): `budgetTokens` when `type` is `"enabled"` and the budget a positive integer, else undefined.
102
+ */
103
+ export function appliedThinkingBudget(options: Readonly<Record<string, unknown>>): number | undefined {
104
+ const thinking = options.thinking;
105
+ if (thinking === null || typeof thinking !== "object") return undefined;
106
+ const { type, budgetTokens } = thinking as { type?: unknown; budgetTokens?: unknown };
107
+ return type === "enabled" && positiveInteger(budgetTokens) ? budgetTokens : undefined;
108
+ }
109
+
110
+ /** The `effortOf` handler: defensive about its input (anything but a non-empty `sessionID` string answers `{}`). */
111
+ export function effortOfHandler(store: EffortStore): (input: unknown) => Promise<EffortOfOutput> {
112
+ return async (input) => {
113
+ try {
114
+ if (input === null || typeof input !== "object") return {};
115
+ const sessionID = (input as { sessionID?: unknown }).sessionID;
116
+ return nonEmptyString(sessionID) ? store.lookup(sessionID) : {};
117
+ } catch {
118
+ return {};
119
+ }
120
+ };
121
+ }
122
+
123
+ type EffortHandlers = { readonly effortOf: (input: unknown) => Promise<EffortOfOutput> };
124
+ interface RpcLike {
125
+ register(definition: typeof effortRpc, handlers: EffortHandlers): unknown;
126
+ }
127
+ interface Disposable {
128
+ dispose(): unknown;
129
+ }
130
+ export interface EffortChannelLog {
131
+ warn(message: string): void;
132
+ }
133
+ export interface EffortChannelOptions {
134
+ /** How long to wait for `register` (default {@link EFFORT_REGISTER_TIMEOUT_MS}); injectable for tests. */
135
+ readonly timeoutMs?: number;
136
+ }
137
+
138
+ const isDisposable = (value: unknown): value is Disposable =>
139
+ value !== null && typeof value === "object" && typeof (value as { dispose?: unknown }).dispose === "function";
140
+
141
+ /** Disposes a registration, best effort: the host drops the registry with the location anyway. */
142
+ async function disposeQuietly(registration: unknown): Promise<void> {
143
+ try {
144
+ if (isDisposable(registration)) await registration.dispose();
145
+ } catch {
146
+ // Never thrown out of a dispose path.
147
+ }
148
+ }
149
+
150
+ const defaultLog: EffortChannelLog = { warn: (message) => console.warn(`[model-router] ${message}`) };
151
+ const NO_OP = async (): Promise<void> => {};
152
+ const TIMED_OUT: unique symbol = Symbol("effort-channel-timeout");
153
+
154
+ /**
155
+ * Registers `effortOf` on the host's rpc domain (`ctx.rpc.register(definition, handlers)`, OpenCode v2 ≥ 2.0.22 (types), verified
156
+ * 2.0.24–2.0.26). Feature-detected (no `register` function: nothing, silently); a throwing or rejecting `register` is logged once
157
+ * and swallowed — the channel is optional and must never fail the plugin's setup. The returned promise waits for `register` a
158
+ * bounded time (default 2 s): past it, it resolves without the channel (logged once); the v2 adapter does not await it (GA-4). A
159
+ * registration that arrives later is kept (logged once) and disposed with the channel; one that arrives after the channel was
160
+ * disposed is disposed at once; a late rejection is swallowed. Resolves to a dispose function that never throws.
161
+ */
162
+ export async function registerEffortChannel(
163
+ rpcLike: unknown,
164
+ store: EffortStore,
165
+ log: EffortChannelLog = defaultLog,
166
+ options: EffortChannelOptions = {},
167
+ ): Promise<() => Promise<void>> {
168
+ const note = (message: string): void => {
169
+ try {
170
+ log.warn(message);
171
+ } catch {
172
+ // A failing log sink must not turn an optional channel into a setup failure.
173
+ }
174
+ };
175
+ const warn = (message: string): void => note(`TUI effort channel not registered (effortOf unavailable): ${message}`);
176
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
177
+ let pending: Promise<unknown>;
178
+ try {
179
+ // The host's `ctx.rpc` is callable (`Object.assign(client, { register })`, @opencode/plugin promise/adapter.js): a function
180
+ // or an object carrying `register` both qualify.
181
+ const rpc = rpcLike as Partial<RpcLike> | null | undefined;
182
+ if (rpc === null || (typeof rpc !== "object" && typeof rpc !== "function") || typeof rpc.register !== "function") return NO_OP;
183
+ pending = Promise.resolve(rpc.register(effortRpc, { effortOf: effortOfHandler(store) }));
184
+ } catch (error) {
185
+ warn(messageOf(error));
186
+ return NO_OP;
187
+ }
188
+ const requested = options.timeoutMs;
189
+ const timeoutMs = typeof requested === "number" && Number.isFinite(requested) && requested >= 0 ? requested : EFFORT_REGISTER_TIMEOUT_MS;
190
+ let timer: ReturnType<typeof setTimeout> | undefined;
191
+ const outcome = await Promise.race([
192
+ pending.then((registration) => ({ registration }), (error: unknown) => ({ error })),
193
+ new Promise<typeof TIMED_OUT>((resolve) => { timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs); }),
194
+ ]);
195
+ clearTimeout(timer);
196
+ if (outcome !== TIMED_OUT && "error" in outcome) {
197
+ warn(messageOf(outcome.error));
198
+ return NO_OP;
199
+ }
200
+ let disposed = false;
201
+ let registration: unknown = outcome === TIMED_OUT ? undefined : outcome.registration;
202
+ if (outcome === TIMED_OUT) {
203
+ note(`TUI effort channel: rpc.register did not settle within ${timeoutMs} ms; continuing without it (a late registration is kept)`);
204
+ pending.then((late) => {
205
+ if (disposed) {
206
+ void disposeQuietly(late); // the channel is gone already: never leave a registration behind
207
+ return;
208
+ }
209
+ registration = late;
210
+ note(`TUI effort channel registered late (after the ${timeoutMs} ms wait); effortOf is available`);
211
+ }, () => {
212
+ // A late rejection: the channel stays unavailable, as the timeout already said.
213
+ });
214
+ }
215
+ return async () => {
216
+ if (disposed) return;
217
+ disposed = true;
218
+ await disposeQuietly(registration);
219
+ };
220
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * #90 P1.2 (amendment A1): the server→TUI effort channel, as a plain rpc definition shared by the v2 server plugin (which
3
+ * registers it, src/compat/v2-hooks.ts) and the TUI entry (which calls it). No imports on purpose: the TUI entry loads this
4
+ * file as is, so it must not pull the server side (or any host package) in.
5
+ *
6
+ * `effortOf({ sessionID })` answers what the router's own `chat.params` bridge applied to that session's latest turn (root and
7
+ * child sessions alike); `{}` when nothing is known.
8
+ */
9
+ export const effortRpc = {
10
+ id: "opencode-model-router.effort",
11
+ methods: {
12
+ effortOf: {
13
+ input: {
14
+ type: "object",
15
+ properties: { sessionID: { type: "string" } },
16
+ required: ["sessionID"],
17
+ additionalProperties: false,
18
+ },
19
+ output: {
20
+ type: "object",
21
+ properties: {
22
+ effort: { type: "string" },
23
+ variant: { type: "string" },
24
+ providerID: { type: "string" },
25
+ modelID: { type: "string" },
26
+ agent: { type: "string" },
27
+ at: { type: "number" },
28
+ thinkingBudget: { type: "number" },
29
+ },
30
+ additionalProperties: false,
31
+ },
32
+ },
33
+ },
34
+ events: {},
35
+ } as const;
36
+
37
+ export type EffortRpc = typeof effortRpc;
38
+
39
+ /** The input of `effortOf`. */
40
+ export interface EffortOfInput {
41
+ readonly sessionID: string;
42
+ }
43
+
44
+ /** The output of `effortOf`; every field is absent when unknown (`{}` for a session the router never saw). */
45
+ export interface EffortOfOutput {
46
+ /**
47
+ * The effort the turn's request carried after the router's hook: the Anthropic `effort` key first for a Claude model,
48
+ * `reasoningEffort` first for any other (each falling back to the other).
49
+ */
50
+ readonly effort?: string;
51
+ /** The turn's model variant (`Model.Ref.variant`). */
52
+ readonly variant?: string;
53
+ readonly providerID?: string;
54
+ readonly modelID?: string;
55
+ readonly agent?: string;
56
+ /** When the turn was recorded (epoch ms). */
57
+ readonly at?: number;
58
+ /** The Anthropic thinking budget the request carried (`thinking: { type: "enabled", budgetTokens }`), a positive integer. */
59
+ readonly thinkingBudget?: number;
60
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * #90 P1.3 (amendment A2): the subset of the OpenCode v2 TUI plugin context the status plugin reads, typed
3
+ * structurally so the shipped code imports no host package. Shapes copied from `@opencode/plugin/tui` `Context`,
4
+ * `SlotMap`, `SlotClaim`, `Data` and `UI` (v2.0.24 `packages/plugin/src/tui/context.ts`, unchanged through 2.0.26).
5
+ *
6
+ * Every member is optional: the plugin feature-detects each one at runtime, and a missing member turns off what needs
7
+ * it (never a throw). No imports and no runtime code on purpose.
8
+ */
9
+
10
+ /** `SlotMap["prompt.footer.status"]` (`PromptFooterInput`): `sessionID` is absent on the home/new-session prompt. */
11
+ export interface PromptFooterInput {
12
+ readonly sessionID?: string;
13
+ readonly mode?: "normal" | "shell";
14
+ readonly showDetails?: boolean;
15
+ }
16
+
17
+ /** `SlotMap["session.composer.top"]`: rendered in root and child session views. */
18
+ export interface ComposerTopInput {
19
+ readonly sessionID: string;
20
+ }
21
+
22
+ /**
23
+ * The `SlotClaim`s the plugin makes (placement `append`). The host calls `render` once, untracked, with reactive
24
+ * props; it returns a host element (`JSX.Element` on the host side).
25
+ */
26
+ export type HostSlotClaim =
27
+ | { readonly append: "prompt.footer.status"; readonly render: (input: PromptFooterInput) => unknown }
28
+ | { readonly append: "session.composer.top"; readonly render: (input: ComposerTopInput) => unknown };
29
+
30
+ /** `Model.Ref`. */
31
+ export interface HostModelRef {
32
+ readonly id: string;
33
+ readonly providerID: string;
34
+ readonly variant?: string;
35
+ }
36
+
37
+ /** Epoch milliseconds, or an Effect `DateTime.Utc`. */
38
+ export type HostTime = number | { readonly epochMilliseconds: number };
39
+
40
+ /** The read subset of `SessionInfo`. */
41
+ export interface HostSession {
42
+ readonly id: string;
43
+ readonly parentID?: string;
44
+ readonly agent?: string;
45
+ readonly title?: string;
46
+ readonly model?: HostModelRef;
47
+ readonly time?: { readonly created?: HostTime | null };
48
+ /** `LocationRef`: passed as is to the rpc call options and to `data.location.model.list`. */
49
+ readonly location?: unknown;
50
+ }
51
+
52
+ /** The read subset of `SessionMessageInfo` (tagged by `type`; assistant messages carry `agent` and `model`). */
53
+ export interface HostMessage {
54
+ readonly id: string;
55
+ readonly type?: string;
56
+ readonly role?: string;
57
+ readonly agent?: string;
58
+ readonly model?: HostModelRef;
59
+ readonly time?: { readonly created?: HostTime | null };
60
+ }
61
+
62
+ /** The read subset of an entry of `data.location.model.list()`. */
63
+ export interface HostModelInfo {
64
+ readonly id: string;
65
+ readonly providerID: string;
66
+ readonly name?: string;
67
+ readonly variants?: ReadonlyArray<{ readonly id: string }>;
68
+ }
69
+
70
+ export type HostSessionStatus = "idle" | "running";
71
+
72
+ /** `Data` (reactive when read in a Solid computation). */
73
+ export interface HostData {
74
+ readonly session?: {
75
+ get?(sessionID: string): HostSession | undefined;
76
+ family?(sessionID: string): readonly string[];
77
+ status?(sessionID: string): HostSessionStatus;
78
+ readonly message?: {
79
+ list?(sessionID: string): readonly HostMessage[];
80
+ sync?(sessionID: string): Promise<void>;
81
+ };
82
+ };
83
+ readonly location?: {
84
+ readonly model?: {
85
+ /** Undefined while the location's list is not loaded. */
86
+ list?(location?: unknown): readonly HostModelInfo[] | undefined;
87
+ sync?(location?: unknown): Promise<void>;
88
+ };
89
+ };
90
+ }
91
+
92
+ export type HostToastVariant = "info" | "success" | "warning" | "error";
93
+
94
+ /** `Toast`. */
95
+ export interface HostToast {
96
+ show?(options: {
97
+ readonly title?: string;
98
+ readonly message: string;
99
+ readonly variant?: HostToastVariant;
100
+ readonly duration?: number;
101
+ }): void;
102
+ }
103
+
104
+ /** `ui.model.current()`: the prompt's selected model; `variant` is absent for the model default. */
105
+ export interface HostCurrentModel {
106
+ readonly providerID: string;
107
+ readonly modelID: string;
108
+ readonly variant?: string;
109
+ }
110
+
111
+ /** `UI`. `slot` returns its dispose function. */
112
+ export interface HostUI {
113
+ readonly toast?: HostToast;
114
+ readonly model?: {
115
+ current?(): HostCurrentModel | undefined;
116
+ };
117
+ readonly slot?: (claim: HostSlotClaim) => unknown;
118
+ }
119
+
120
+ /** A plugin rpc definition, as passed to `client.rpc(definition)`. */
121
+ export interface HostRpcDefinition {
122
+ readonly id: string;
123
+ readonly methods: object;
124
+ readonly events: object;
125
+ }
126
+
127
+ /** `OpenCodeClient`: `rpc(definition)` returns a client with one method per definition method. */
128
+ export interface HostClient {
129
+ rpc?(definition: HostRpcDefinition): unknown;
130
+ }
131
+
132
+ export type HostResizeListener = (...args: unknown[]) => void;
133
+
134
+ /** `CliRenderer` (an event emitter): its width in columns and its `resize` event. */
135
+ export interface HostRenderer {
136
+ readonly width?: number;
137
+ on?(event: "resize", listener: HostResizeListener): unknown;
138
+ off?(event: "resize", listener: HostResizeListener): unknown;
139
+ }
140
+
141
+ /** `ResolvedTheme`: only the muted text colour is read. */
142
+ export interface HostTheme {
143
+ readonly textMuted?: unknown;
144
+ }
145
+
146
+ /** `Context` (the TUI plugin `setup` argument). `options` is whatever the user configured. */
147
+ export interface HostContext {
148
+ readonly options?: unknown;
149
+ readonly renderer?: HostRenderer;
150
+ readonly client?: HostClient;
151
+ readonly data?: HostData;
152
+ readonly theme?: HostTheme;
153
+ readonly ui?: HostUI;
154
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * #90 P1.3 (amendment A2): the three `@opentui/solid` reconciler primitives the TUI entry uses, declared locally so the
3
+ * repository needs neither `@opentui/solid` nor `@opentui/core` installed. At runtime the host serves the module (its
4
+ * runtime plugin answers the bare import); nothing here is bundled.
5
+ *
6
+ * Mirrors `@opentui/solid@0.5.14` `src/reconciler.d.ts` (the `solid-js/universal` renderer functions), with the
7
+ * `BaseRenderable` node type simplified to `unknown`.
8
+ */
9
+ declare module "@opentui/solid" {
10
+ /** Creates a host element (`"box"`, `"text"`, …). */
11
+ export function createElement(tag: string): unknown;
12
+ /** Inserts a value or a reactive accessor (string, node or array of nodes) as the children of `parent`. */
13
+ export function insert(parent: unknown, accessor: unknown, marker?: unknown, initial?: unknown): unknown;
14
+ /** Sets one property of a host element; returns `value`. */
15
+ export function setProp<T>(node: unknown, name: string, value: T, prev?: T): T;
16
+ }