opencode-model-router 2.3.0 → 2.5.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/CHANGELOG.md +171 -0
- package/README.md +86 -11
- package/package.json +6 -1
- package/src/commands/output.ts +21 -1
- package/src/compat/v2-hooks.ts +1374 -24
- package/src/escalate/ladder.ts +12 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +718 -29
- package/src/router/config.ts +247 -1
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +133 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +92 -0
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +193 -1
- package/src/routing/advisor/index.ts +13 -5
- package/src/routing/classify/index.ts +23 -5
- package/src/routing/classify/route-line.ts +67 -3
- package/src/routing/classify/rules.ts +80 -20
- package/src/routing/classify/types.ts +34 -4
- package/src/routing/commands/stats.ts +3 -0
- package/src/routing/engine/kernel.ts +163 -0
- package/src/routing/engine/ladders.ts +242 -1
- package/src/routing/engine/protocol-line.ts +17 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/types.ts +99 -1
- package/src/routing/outcomes/beta.ts +10 -4
- package/src/routing/outcomes/index.ts +44 -1
- package/src/routing/outcomes/ingest.ts +163 -15
- package/src/routing/outcomes/persist.ts +23 -1
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +273 -2
- package/src/routing/outcomes/store.ts +25 -5
- package/src/routing/outcomes/types.ts +145 -6
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +1306 -17
- package/src/routing/wire/hint.ts +14 -0
- package/src/routing/wire/runtime.ts +117 -28
- package/src/tui/effort-channel.ts +220 -0
- package/src/tui/effort-rpc.ts +60 -0
- package/src/tui/host-types.ts +154 -0
- package/src/tui/opentui-solid.d.ts +16 -0
- package/src/tui/plugin.ts +1007 -0
- package/src/tui/status-model.ts +561 -0
- package/src/v2.ts +26 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
- package/tui.ts +4 -0
package/src/routing/wire/hint.ts
CHANGED
|
@@ -12,13 +12,23 @@
|
|
|
12
12
|
* The hint and the generated `R:` line come from the same kernel, but the hint is only emitted when the kernel says
|
|
13
13
|
* `switched` for the class's static tier, i.e. when it agrees with a move the line itself could make (QA focus: a hint
|
|
14
14
|
* must never contradict the `R:` line). Errors are logged and the system prompt stays as the legacy hook built it.
|
|
15
|
+
*
|
|
16
|
+
* Roles mode (`routing.delegation: "roles"`, plan #84 T2.2.1): nothing is added or rewritten — no per-turn hint, no tier
|
|
17
|
+
* `R:` line, no route-line paragraph. The roles protocol carries its own class → role line and route-line keys, and a
|
|
18
|
+
* hint or a tier line would name tiers; a system part that changes per turn would also cost the orchestrator its
|
|
19
|
+
* prompt cache. The check is the roles protocol's heading among the router's own parts, i.e. the text the orchestrator
|
|
20
|
+
* actually carries: a roles config with no enabled role falls back to the tiers protocol, augmented as in tiers mode.
|
|
15
21
|
*/
|
|
16
22
|
|
|
17
23
|
import {
|
|
18
24
|
DELEGATION_PROTOCOL_HEADING,
|
|
25
|
+
ROLES_PROTOCOL_HEADING,
|
|
19
26
|
buildRouteLineProtocol,
|
|
20
27
|
swapTaxonomyLine,
|
|
21
28
|
} from "../../router/protocol";
|
|
29
|
+
/** The roles heading only counts at the start of a line (QA-P22-2-4): a part that merely quotes it mid-line is not the roles protocol. */
|
|
30
|
+
const ROLES_HEADING_LINE = /^## Role Delegation Protocol \(MANDATORY\)$/m;
|
|
31
|
+
|
|
22
32
|
import { classify } from "../classify";
|
|
23
33
|
import { CLASS_STATIC_TIER, type TaskFacts } from "../classify/types";
|
|
24
34
|
import { buildLadder, decide, floorRankOf, generateTaxonomy, resolveChosen } from "../engine";
|
|
@@ -175,6 +185,10 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
|
|
|
175
185
|
return {
|
|
176
186
|
async augment(input, system, added): Promise<void> {
|
|
177
187
|
try {
|
|
188
|
+
// Roles mode: no hint part, and the protocol text stays exactly as the legacy hook built it. Keyed on the roles
|
|
189
|
+
// protocol the orchestrator actually carries (QA-P22-1-5): `delegation: "roles"` with no enabled role keeps the
|
|
190
|
+
// tiers protocol, which is then augmented like tiers mode.
|
|
191
|
+
if (system.some((text) => added.has(text) && ROLES_HEADING_LINE.test(text))) return;
|
|
178
192
|
const protocolAt: number[] = [];
|
|
179
193
|
system.forEach((text, index) => {
|
|
180
194
|
if (added.has(text) && text.includes(DELEGATION_PROTOCOL_HEADING)) protocolAt.push(index);
|
|
@@ -15,11 +15,13 @@
|
|
|
15
15
|
import type { LadderSessionPolicyInput } from "../../escalate/ladder";
|
|
16
16
|
import {
|
|
17
17
|
resolveClassifierForPreset,
|
|
18
|
+
resolveRolesRouting,
|
|
18
19
|
resolveRouting,
|
|
19
20
|
resolveVariantSteps,
|
|
20
21
|
type ResolvedRouting,
|
|
21
22
|
type RouterConfig,
|
|
22
23
|
} from "../../router/config";
|
|
24
|
+
import { resolveRoles, type RoleSpec } from "../../router/roles";
|
|
23
25
|
import { createClassifierBackend, type ClassifyDeps } from "../classify";
|
|
24
26
|
import type { ClassifierBackend, ClassifierSettings, HostGenerate } from "../classify/types";
|
|
25
27
|
import type { EngineStoreView } from "../engine/types";
|
|
@@ -74,12 +76,42 @@ export interface Prepared {
|
|
|
74
76
|
readonly enqueue: (row: LogRow) => void;
|
|
75
77
|
}
|
|
76
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Everything one ROLE dispatch needs (#84 P2.1 T2.1.2). Unlike {@link Prepared} it exists in every engine mode, `static`
|
|
81
|
+
* included: a role dispatch always gets a router-set model (I2). Only `routing.delegation: "roles"` on v2 produces one.
|
|
82
|
+
*/
|
|
83
|
+
export interface RolePrepared {
|
|
84
|
+
readonly cfg: RouterConfig;
|
|
85
|
+
/** The resolved role table (`resolveRoles(cfg, "v2")`). */
|
|
86
|
+
readonly roles: ReadonlyMap<string, RoleSpec>;
|
|
87
|
+
/** The dispatched role. */
|
|
88
|
+
readonly spec: RoleSpec;
|
|
89
|
+
readonly routing: ResolvedRouting;
|
|
90
|
+
/** `routing.engine`: `static` decides the static default and writes no row. */
|
|
91
|
+
readonly engine: ResolvedRouting["engine"];
|
|
92
|
+
/** `routing.exploration.rate` (0 unless roles mode; the kernel clamps it). */
|
|
93
|
+
readonly exploration: number;
|
|
94
|
+
readonly catalog: WireCatalog;
|
|
95
|
+
readonly session: LadderSessionPolicyInput;
|
|
96
|
+
/** The outcome store (posteriors); `null` when the engine is static. */
|
|
97
|
+
readonly store: EngineStoreView | null;
|
|
98
|
+
/** The decision-log queue; `null` when the engine is static (no rows). */
|
|
99
|
+
readonly enqueue: ((row: LogRow) => void) | null;
|
|
100
|
+
readonly classifyDeps: ClassifyDeps;
|
|
101
|
+
}
|
|
102
|
+
|
|
77
103
|
export interface EngineRuntime {
|
|
78
104
|
/**
|
|
79
105
|
* `null` when the engine is static (or the host is not v2): nothing was touched. Never throws. `cfg` is the config the caller
|
|
80
106
|
* already loaded (one `loadConfig` per hook call); without it the runtime loads its own.
|
|
81
107
|
*/
|
|
82
108
|
prepare(cfg?: RouterConfig): Promise<Prepared | null>;
|
|
109
|
+
/**
|
|
110
|
+
* #84 P2.1: `null` unless `agent` is an enabled role agent of `routing.delegation: "roles"` on v2 (tiers mode: `null` before any
|
|
111
|
+
* host call). For a role agent it THROWS when the dispatch cannot be prepared: the caller refuses the role dispatch (fail closed).
|
|
112
|
+
* Optional so that hand-made runtimes keep compiling; `createEngineRuntime` always provides it.
|
|
113
|
+
*/
|
|
114
|
+
prepareRoles?(agent: string, cfg?: RouterConfig): Promise<RolePrepared | null>;
|
|
83
115
|
/** The dispatching session's view of the host's agents (evaluated permissions included). */
|
|
84
116
|
agents(parentAgent: string | undefined, sessionRules: readonly PermissionRule[]): Promise<AgentView | null>;
|
|
85
117
|
/** The classifier dependencies for this config (backend memoized). */
|
|
@@ -146,7 +178,48 @@ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
|
|
|
146
178
|
return routingMemo.routing;
|
|
147
179
|
};
|
|
148
180
|
|
|
149
|
-
|
|
181
|
+
const classifyDepsFor = (cfg: RouterConfig, routing: ResolvedRouting): ClassifyDeps => {
|
|
182
|
+
const settings = resolveClassifierForPreset(routing.classifier, cfg.activePreset);
|
|
183
|
+
const key = JSON.stringify([
|
|
184
|
+
settings.backend, settings.model, settings.baseUrl, settings.apiKeyEnv, settings.timeoutMs, settings.samples, settings.maxStateChars,
|
|
185
|
+
]);
|
|
186
|
+
if (classifierMemo === null || classifierMemo.key !== key) {
|
|
187
|
+
const memoSettings: ClassifierSettings = {
|
|
188
|
+
backend: settings.backend,
|
|
189
|
+
model: settings.model,
|
|
190
|
+
baseUrl: settings.baseUrl,
|
|
191
|
+
apiKeyEnv: settings.apiKeyEnv,
|
|
192
|
+
timeoutMs: settings.timeoutMs,
|
|
193
|
+
samples: settings.samples,
|
|
194
|
+
maxStateChars: settings.maxStateChars,
|
|
195
|
+
};
|
|
196
|
+
classifierMemo = {
|
|
197
|
+
key,
|
|
198
|
+
settings: memoSettings,
|
|
199
|
+
backend: createClassifierBackend(memoSettings, {
|
|
200
|
+
...(deps.generate === undefined ? {} : { generate: deps.generate }),
|
|
201
|
+
logger: deps.logger,
|
|
202
|
+
}),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
cfg,
|
|
207
|
+
settings: classifierMemo.settings,
|
|
208
|
+
minClassConfidence: routing.minClassConfidence,
|
|
209
|
+
backend: classifierMemo.backend,
|
|
210
|
+
logger: deps.logger,
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const sessionPolicyOf = (cfg: RouterConfig, routing: ResolvedRouting): LadderSessionPolicyInput => ({
|
|
215
|
+
host: "v2",
|
|
216
|
+
variantSteps: resolveVariantSteps(cfg, "v2"),
|
|
217
|
+
maxContextFraction: routing.sessionReuse.maxContextFraction,
|
|
218
|
+
catalog: (model) => catalog.entry(model),
|
|
219
|
+
warn: (message) => deps.logger.warn(message),
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
const self: EngineRuntime = {
|
|
150
223
|
async prepare(given): Promise<Prepared | null> {
|
|
151
224
|
try {
|
|
152
225
|
const cfg = given ?? deps.loadConfig();
|
|
@@ -209,35 +282,50 @@ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
|
|
|
209
282
|
},
|
|
210
283
|
|
|
211
284
|
classifyDeps(prepared): ClassifyDeps {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
if (
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
};
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
285
|
+
return classifyDepsFor(prepared.cfg, prepared.routing);
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
async prepareRoles(agent, given): Promise<RolePrepared | null> {
|
|
289
|
+
if (disposed) return null;
|
|
290
|
+
let cfg: RouterConfig;
|
|
291
|
+
let roles: ReadonlyMap<string, RoleSpec>;
|
|
292
|
+
try {
|
|
293
|
+
cfg = given ?? deps.loadConfig();
|
|
294
|
+
// Tiers mode (and v1, which never reaches this v2 runtime): an empty table before any host call (I1).
|
|
295
|
+
roles = resolveRoles(cfg, "v2");
|
|
296
|
+
} catch (error) {
|
|
297
|
+
// Not known to be a role dispatch: the tier path decides (and fails safe) as before.
|
|
298
|
+
deps.logger.warn("[router] routing: the role table could not be resolved", { error: describeError(error) });
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
const spec = roles.get(agent);
|
|
302
|
+
if (spec === undefined) return null;
|
|
303
|
+
const routing = routingOf(cfg);
|
|
304
|
+
let store: EngineStoreView | null = null;
|
|
305
|
+
let enqueue: ((row: LogRow) => void) | null = null;
|
|
306
|
+
if (routing.engine !== "static") {
|
|
307
|
+
// The tier engine's own preparation: the same store and decision-log queue (A3: one writer per process).
|
|
308
|
+
const prepared = await self.prepare(cfg);
|
|
309
|
+
if (prepared !== null) {
|
|
310
|
+
store = prepared.store;
|
|
311
|
+
enqueue = prepared.enqueue;
|
|
312
|
+
}
|
|
313
|
+
} else {
|
|
314
|
+
await catalog.ensure(); // static: no store, no rows, but the catalog decides whether a tier variant exists
|
|
234
315
|
}
|
|
316
|
+
if (disposed) return null;
|
|
235
317
|
return {
|
|
236
|
-
cfg
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
318
|
+
cfg,
|
|
319
|
+
roles,
|
|
320
|
+
spec,
|
|
321
|
+
routing,
|
|
322
|
+
engine: routing.engine,
|
|
323
|
+
exploration: resolveRolesRouting(cfg, "v2").exploration.rate,
|
|
324
|
+
catalog,
|
|
325
|
+
session: sessionPolicyOf(cfg, routing),
|
|
326
|
+
store,
|
|
327
|
+
enqueue,
|
|
328
|
+
classifyDeps: classifyDepsFor(cfg, routing),
|
|
241
329
|
};
|
|
242
330
|
},
|
|
243
331
|
|
|
@@ -251,6 +339,7 @@ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
|
|
|
251
339
|
while (releasing.size > 0) await Promise.allSettled([...releasing]);
|
|
252
340
|
},
|
|
253
341
|
};
|
|
342
|
+
return self;
|
|
254
343
|
}
|
|
255
344
|
|
|
256
345
|
/** The session's own permission rules (`Session.Info.permissions`). */
|
|
@@ -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
|
+
}
|