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.
Files changed (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -0,0 +1,1007 @@
1
+ /**
2
+ * #90 P1.3: the OpenCode v2 TUI entry (root `tui.ts` re-exports it), plan §2 D2–D7 as amended by §8 A1–A9, A12.
3
+ *
4
+ * - G1 (`footer`): `prompt.footer.status` shows `effort <value>` in a root session (or the home prompt) when no variant
5
+ * is selected ({@link effectiveMainEffort}); nothing when one is (the host row shows it).
6
+ * - G2 (`childView`): `session.composer.top` of a delegated session shows `<agent> · <model> · <effort>`
7
+ * ({@link childStatus}); the agent identifies the delegate (without one: the session title, else `subagent`, as G3).
8
+ * - G3 (`runningRow`, opt-in, off by default, A12): `session.composer.top` of a root session shows one
9
+ * `<agent> · <model> · <effort>` row per running delegate ({@link runningChildren}), then `+<k> more`.
10
+ *
11
+ * One claim serves G2 and G3: they target the same slot and a session is either a child or a root, so one box (empty
12
+ * when there is nothing to show) is enough. With the default options the claim exists for G2, and a root session's box
13
+ * stays empty. The effort comes from the server's `effortOf` rpc (A1, per-session pollers
14
+ * created while a view needs them), else from the message/session variant.
15
+ *
16
+ * No JSX: views are built with the `@opentui/solid` reconciler primitives and `solid-js`, the only runtime imports
17
+ * besides `./status-model.ts` and `./effort-rpc.ts` (both import-free). Relative specifiers carry the explicit `.ts`
18
+ * extension: the host loads this file from `node_modules` and, for an extensionless one, resolves the bare imports
19
+ * outside its own runtime (`Cannot find package 'solid-js'`, A9 run on 2.0.24–2.0.26).
20
+ *
21
+ * Every host member is feature-detected; `setup` never throws and never calls rpc; a view never throws (errors render
22
+ * no rows). Reporting: the host swallows a TUI plugin's `console` output, so the two notices the user must see (invalid
23
+ * options, and a render without a Solid owner) go to `ui.toast` (once each, `console.warn` as a second sink); every
24
+ * other error is logged once per area with `console.warn` only (the context has no logging API).
25
+ */
26
+ import { createMemo, createRenderEffect, createRoot, createSignal, getOwner, onCleanup, untrack } from "solid-js";
27
+ import { createElement, insert, setProp } from "@opentui/solid";
28
+ import { effortRpc } from "./effort-rpc.ts";
29
+ import type {
30
+ ComposerTopInput,
31
+ HostClient,
32
+ HostContext,
33
+ HostCurrentModel,
34
+ HostMessage,
35
+ HostModelInfo,
36
+ HostResizeListener,
37
+ HostSession,
38
+ HostSlotClaim,
39
+ PromptFooterInput,
40
+ } from "./host-types.ts";
41
+ import {
42
+ childStatus,
43
+ DEFAULT_EFFORT,
44
+ effectiveMainEffort,
45
+ FALLBACK_AGENT,
46
+ formatRow,
47
+ parseOptions,
48
+ runningChildren,
49
+ STATUS_NOTICE_PREFIX,
50
+ type AppliedEffort,
51
+ type CurrentModel,
52
+ type SessionStatus,
53
+ type StatusOptions,
54
+ } from "./status-model.ts";
55
+
56
+ /** The TUI plugin id (A4): deliberately not the package name. */
57
+ export const STATUS_PLUGIN_ID = "opencode-model-router.status";
58
+ export const FOOTER_SLOT = "prompt.footer.status";
59
+ export const COMPOSER_SLOT = "session.composer.top";
60
+ /** Poll interval while a session runs, and the debounce of trigger-driven pulls (A1). */
61
+ export const POLL_INTERVAL_MS = 5_000;
62
+ /** How long a session's channel stays off after an error other than `unavailable` or a timeout. */
63
+ export const FAILURE_COOLDOWN_MS = 30_000;
64
+ /**
65
+ * First retry delay after an `unavailable` error or a timeout; doubled per retry up to {@link BACKOFF_MAX_MS}. Also the
66
+ * delay of a quick re-pull ({@link QUICK_REPULLS}).
67
+ */
68
+ export const BACKOFF_START_MS = 1_000;
69
+ export const BACKOFF_MAX_MS = 30_000;
70
+ /**
71
+ * GA-2, R2-2: while a delegated session (one with a `parentID`) runs and no answer with an effort has been seen for it
72
+ * yet, an answer without one is pulled again after {@link BACKOFF_START_MS}, at most this many times per session (the
73
+ * count is kept with the pull state of the last {@link PULL_STATE_MAX} sessions). Root sessions keep the normal cadence.
74
+ */
75
+ export const QUICK_REPULLS = 3;
76
+ /** An `effortOf` call that has not settled by then is aborted and retried like `rpc.unavailable`. */
77
+ export const CALL_TIMEOUT_MS = 10_000;
78
+ /** Sessions whose pull state (last pull, cooldown, backoff) is kept across poller close/reopen. */
79
+ export const PULL_STATE_MAX = 200;
80
+ /** Sessions remembered as already message-synced. */
81
+ export const SYNCED_MAX = 200;
82
+ /** Locations whose model list was asked to sync (R2-1). */
83
+ export const MODEL_SYNC_MAX = 50;
84
+ /** Terminal width used when the renderer reports none. */
85
+ export const DEFAULT_WIDTH = 80;
86
+ /** Columns kept free around a row (composer padding). */
87
+ export const WIDTH_MARGIN = 4;
88
+ /** Shown once when a slot renders outside any Solid owner (P13-2); names the effect, not a cause (GA-5). */
89
+ export const NO_OWNER_NOTICE = "render has no Solid owner: the views are static (no live updates)";
90
+
91
+ type Timer = ReturnType<typeof setTimeout>;
92
+ type Rows = readonly string[];
93
+
94
+ const NO_ROWS: Rows = Object.freeze([]);
95
+ const NO_MESSAGES: readonly HostMessage[] = Object.freeze([]);
96
+ const NO_IDS: readonly string[] = Object.freeze([]);
97
+ /** The rejection of an `effortOf` call that did not settle within {@link CALL_TIMEOUT_MS}. */
98
+ const CALL_TIMEOUT = Object.freeze({ type: "rpc.timeout", message: `effortOf did not answer within ${CALL_TIMEOUT_MS} ms` });
99
+ /** The rejection of an `effortOf` call aborted because its poller closed. */
100
+ const CALL_ABORTED = Object.freeze({ type: "rpc.aborted", message: "effortOf aborted" });
101
+
102
+ function isObject(value: unknown): value is object {
103
+ return (typeof value === "object" && value !== null) || typeof value === "function";
104
+ }
105
+
106
+ /** `value` when it is a string with a non-blank character, as is (untrimmed). */
107
+ function nonBlank(value: unknown): string | undefined {
108
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
109
+ }
110
+
111
+ function arrayOf<T>(value: readonly T[] | null | undefined): readonly T[] {
112
+ return Array.isArray(value) ? value : [];
113
+ }
114
+
115
+ function sameRows(a: Rows, b: Rows): boolean {
116
+ return a.length === b.length && a.every((row, index) => row === b[index]);
117
+ }
118
+
119
+ function sameApplied(a: AppliedEffort | undefined, b: AppliedEffort | undefined): boolean {
120
+ if (a === undefined || b === undefined) return a === b;
121
+ return a.effort === b.effort && a.variant === b.variant && a.providerID === b.providerID && a.modelID === b.modelID;
122
+ }
123
+
124
+ /** Puts `key` last in `map` (most recent) and drops the oldest entries beyond `max`. */
125
+ function remember<K, V>(map: Map<K, V>, key: K, value: V, max: number): V {
126
+ map.delete(key);
127
+ map.set(key, value);
128
+ for (const oldest of map.keys()) {
129
+ if (map.size <= max) break;
130
+ map.delete(oldest);
131
+ }
132
+ return value;
133
+ }
134
+
135
+ /**
136
+ * An error as one line: an `Error`'s message; a host rpc failure (a plain `{ type, message, data? }`, P13-1) by its
137
+ * `message`, else its `type`; anything else as a string.
138
+ */
139
+ function describeError(error: unknown): string {
140
+ try {
141
+ if (error instanceof Error) return error.message || error.name;
142
+ if (isObject(error)) {
143
+ return nonBlank(Reflect.get(error, "message")) ?? nonBlank(Reflect.get(error, "type")) ?? "unknown error";
144
+ }
145
+ return String(error);
146
+ } catch {
147
+ return "unknown error";
148
+ }
149
+ }
150
+
151
+ /** Once-per-key reports for the lifetime of a `setup`. */
152
+ interface Log {
153
+ /** `model-router status: <area> failed: <error>`, once per area, `console.warn` only (invisible on the host). */
154
+ failed(area: string, error: unknown): void;
155
+ /**
156
+ * A notice the user must see, once per key: shown with `toast` (the visible channel; the host swallows console
157
+ * output), then written with `console.warn`. `text` is the full line, `model-router status: …` included.
158
+ */
159
+ notice(key: string, text: string): void;
160
+ }
161
+
162
+ /** @param toast shows a warning toast; may throw (logged as `notice failed`). */
163
+ function createLog(toast: (message: string) => void): Log {
164
+ const seen = new Set<string>();
165
+ const first = (key: string): boolean => {
166
+ if (seen.has(key)) return false;
167
+ seen.add(key);
168
+ return true;
169
+ };
170
+ const warn = (text: string): void => {
171
+ try {
172
+ console.warn(text);
173
+ } catch {
174
+ // No console: nothing else to report to.
175
+ }
176
+ };
177
+ const failed = (area: string, error: unknown): void => {
178
+ if (first(`failed:${area}`)) warn(`${STATUS_NOTICE_PREFIX}${area} failed: ${describeError(error)}`);
179
+ };
180
+ return {
181
+ failed,
182
+ notice: (key, text) => {
183
+ if (!first(`notice:${key}`)) return;
184
+ try {
185
+ toast(text);
186
+ } catch (error) {
187
+ failed("notice", error);
188
+ }
189
+ warn(text);
190
+ },
191
+ };
192
+ }
193
+
194
+ /**
195
+ * The channel's `effortOf` output as an {@link AppliedEffort}: only when it carries a non-blank `effort`, `providerID`
196
+ * and `modelID` (strings kept as sent); `variant` when it is a non-blank string.
197
+ */
198
+ export function appliedOf(output: unknown): AppliedEffort | undefined {
199
+ if (!isObject(output)) return undefined;
200
+ const effort = nonBlank(Reflect.get(output, "effort"));
201
+ const providerID = nonBlank(Reflect.get(output, "providerID"));
202
+ const modelID = nonBlank(Reflect.get(output, "modelID"));
203
+ if (effort === undefined || providerID === undefined || modelID === undefined) return undefined;
204
+ const variant = nonBlank(Reflect.get(output, "variant"));
205
+ return variant === undefined ? { effort, providerID, modelID } : { effort, variant, providerID, modelID };
206
+ }
207
+
208
+ /**
209
+ * QA-6 (P1.2 hand-off): the channel's effort, followed by the recorded variant in parentheses when both are set and
210
+ * differ (`high (max)`). A blank or `default` effort or variant, or an equal one (case-insensitive), leaves the effort
211
+ * as is.
212
+ */
213
+ export function effortWithVariant(effort: string, variant?: string): string {
214
+ const shown = effort.trim();
215
+ const recorded = typeof variant === "string" ? variant.trim() : "";
216
+ if (shown === "" || shown === DEFAULT_EFFORT || recorded === "" || recorded === DEFAULT_EFFORT) return effort;
217
+ return shown.toLowerCase() === recorded.toLowerCase() ? effort : `${shown} (${recorded})`;
218
+ }
219
+
220
+ /** The applied effort as the child views show it (QA-6). */
221
+ function childApplied(applied: AppliedEffort | undefined): AppliedEffort | undefined {
222
+ return applied === undefined ? undefined : { ...applied, effort: effortWithVariant(applied.effort, applied.variant) };
223
+ }
224
+
225
+ /**
226
+ * An error the host reports while the server plugin's rpc is not (yet) registered. The client rethrows rpc failures as
227
+ * plain `{ type, message, data? }` objects: an error with a string `type` is unavailable exactly when that type is
228
+ * `rpc.unavailable` (R2-3). Without a `type`, any `name`, `message`, `_tag` or `code` (or the error itself, as a
229
+ * string) containing `unavailable` counts.
230
+ */
231
+ export function isUnavailable(error: unknown): boolean {
232
+ try {
233
+ const type = isObject(error) ? Reflect.get(error, "type") : undefined;
234
+ if (typeof type === "string") return type === "rpc.unavailable";
235
+ const parts: unknown[] = [error];
236
+ if (isObject(error)) {
237
+ for (const key of ["name", "message", "_tag", "code"]) parts.push(Reflect.get(error, key));
238
+ }
239
+ return parts.some((part) => typeof part === "string" && part.toLowerCase().includes("unavailable"));
240
+ } catch {
241
+ return false;
242
+ }
243
+ }
244
+
245
+ /** Retried with backoff instead of a cooldown: `unavailable`, or a call that timed out. */
246
+ function isRetryable(error: unknown): boolean {
247
+ return error === CALL_TIMEOUT || isUnavailable(error);
248
+ }
249
+
250
+ /** Reads of the host context. Missing members give empty answers; a throwing host member throws to the view. */
251
+ interface Host {
252
+ session(id: string): HostSession | undefined;
253
+ isChild(id: string): boolean;
254
+ /** The session's `location` (its rpc and model-list scope); undefined when absent. */
255
+ location(id: string): unknown;
256
+ messages(id: string): readonly HostMessage[];
257
+ family(id: string): readonly string[];
258
+ status(id: string): SessionStatus;
259
+ models(location?: unknown): readonly HostModelInfo[];
260
+ current(): HostCurrentModel | undefined;
261
+ muted(): unknown;
262
+ }
263
+
264
+ /**
265
+ * The key of a location for {@link Host.models}' sync bookkeeping: its `directory` and `workspaceID`, as JSON.
266
+ */
267
+ export function locationKey(location: unknown): string {
268
+ try {
269
+ const field = (name: string): unknown => (isObject(location) ? Reflect.get(location, name) : undefined);
270
+ const directory = field("directory");
271
+ const workspaceID = field("workspaceID");
272
+ return JSON.stringify([
273
+ typeof directory === "string" ? directory : null,
274
+ typeof workspaceID === "string" ? workspaceID : null,
275
+ ]);
276
+ } catch {
277
+ return "[null,null]";
278
+ }
279
+ }
280
+
281
+ /**
282
+ * @param syncModels called when a location's model list is not loaded yet (`list(location)` gave no array); the views
283
+ * then use the default location's list meanwhile (R2-1).
284
+ */
285
+ function createHost(context: HostContext | undefined, syncModels: (location: unknown) => void): Host {
286
+ const sessions = () => context?.data?.session;
287
+ const session = (id: string): HostSession | undefined => {
288
+ const value = sessions()?.get?.(id);
289
+ return typeof value === "object" && value !== null ? value : undefined;
290
+ };
291
+ return {
292
+ session,
293
+ isChild: (id) => nonBlank(session(id)?.parentID) !== undefined,
294
+ location: (id) => {
295
+ const location = session(id)?.location;
296
+ return location === null ? undefined : location;
297
+ },
298
+ messages: (id) => {
299
+ const list = sessions()?.message?.list?.(id);
300
+ if (list === undefined || list === null) return NO_MESSAGES;
301
+ return arrayOf(list).filter((message) => typeof message === "object" && message !== null);
302
+ },
303
+ family: (id) => {
304
+ const ids = sessions()?.family?.(id);
305
+ if (ids === undefined || ids === null) return NO_IDS;
306
+ return arrayOf(ids).filter((item) => typeof item === "string");
307
+ },
308
+ status: (id) => (sessions()?.status?.(id) === "running" ? "running" : "idle"),
309
+ models: (location) => {
310
+ const model = context?.data?.location?.model;
311
+ let list = location === undefined || location === null ? undefined : model?.list?.(location);
312
+ if (!Array.isArray(list)) {
313
+ if (location !== undefined && location !== null) syncModels(location);
314
+ list = model?.list?.();
315
+ }
316
+ return arrayOf(list).filter(
317
+ (entry) =>
318
+ typeof entry === "object" &&
319
+ entry !== null &&
320
+ typeof entry.id === "string" &&
321
+ typeof entry.providerID === "string",
322
+ );
323
+ },
324
+ current: () => {
325
+ const value = context?.ui?.model?.current?.();
326
+ return typeof value === "object" && value !== null ? value : undefined;
327
+ },
328
+ muted: () => context?.theme?.textMuted,
329
+ };
330
+ }
331
+
332
+ /** The prompt's current model as `effectiveMainEffort` reads it; undefined unless both ids are strings. */
333
+ function currentModelOf(current: HostCurrentModel | undefined): CurrentModel | undefined {
334
+ if (current === undefined || typeof current.providerID !== "string" || typeof current.modelID !== "string") {
335
+ return undefined;
336
+ }
337
+ return { providerID: current.providerID, modelID: current.modelID };
338
+ }
339
+
340
+ /** The rpc call options of the host client (`{ location?, signal?, headers? }`). */
341
+ interface CallOptions {
342
+ readonly signal: AbortSignal;
343
+ readonly location?: unknown;
344
+ }
345
+
346
+ interface EffortClient {
347
+ effortOf(input: { readonly sessionID: string }, options?: CallOptions): unknown;
348
+ }
349
+
350
+ function isEffortClient(value: unknown): value is EffortClient {
351
+ return isObject(value) && typeof Reflect.get(value, "effortOf") === "function";
352
+ }
353
+
354
+ interface EffortChannel {
355
+ /**
356
+ * The applied effort the server reported for `sessionID` (reactive). Call it inside a tracked computation: it keeps
357
+ * the session's poller alive until that computation re-runs or is disposed. Undefined without an rpc client.
358
+ */
359
+ applied(sessionID: string): AppliedEffort | undefined;
360
+ dispose(): void;
361
+ }
362
+
363
+ /** A channel that never polls: for views rendered without a Solid owner. */
364
+ const NO_CHANNEL: EffortChannel = { applied: () => undefined, dispose: () => undefined };
365
+
366
+ interface ChannelDeps {
367
+ client(): HostClient | undefined;
368
+ status(id: string): SessionStatus;
369
+ /** The session has a `parentID` (a delegated session). */
370
+ isChild(id: string): boolean;
371
+ messages(id: string): readonly HostMessage[];
372
+ location(id: string): unknown;
373
+ log: Log;
374
+ }
375
+
376
+ /**
377
+ * Per-session pull timing and last value, kept across poller close/reopen (P13-5) for the last {@link PULL_STATE_MAX}
378
+ * sessions.
379
+ */
380
+ interface PullState {
381
+ lastPull: number;
382
+ failedUntil: number;
383
+ /** Current retry delay after `unavailable` or a timeout; 0 after a success. */
384
+ backoff: number;
385
+ /** GA-1: the last value written (undefined after a failure); a reopened poller starts from it. */
386
+ value?: AppliedEffort;
387
+ /** GA-2: an answer with an effort was seen for the session. */
388
+ effortSeen: boolean;
389
+ /** GA-2: quick re-pulls done (at most {@link QUICK_REPULLS}); reset by the first answer with an effort. */
390
+ quick: number;
391
+ }
392
+
393
+ interface Poller {
394
+ readonly id: string;
395
+ readonly state: PullState;
396
+ refs: number;
397
+ closed: boolean;
398
+ read(): AppliedEffort | undefined;
399
+ write(value: AppliedEffort | undefined): void;
400
+ timer: Timer | undefined;
401
+ inFlight: boolean;
402
+ /** Aborts the call in flight. */
403
+ controller: AbortController | undefined;
404
+ /** A trigger fired while a pull was in flight. */
405
+ dirty: boolean;
406
+ disposeRoot(): void;
407
+ }
408
+
409
+ /** What makes a session's poller pull again: its status, message count and latest message id. */
410
+ function triggerKey(deps: ChannelDeps, id: string): string {
411
+ let status = "idle";
412
+ let count = 0;
413
+ let last = "";
414
+ try {
415
+ status = deps.status(id);
416
+ } catch {
417
+ // An unreadable status counts as idle.
418
+ }
419
+ try {
420
+ const list = deps.messages(id);
421
+ count = list.length;
422
+ const tail = count > 0 ? list[count - 1] : undefined;
423
+ last = typeof tail?.id === "string" ? tail.id : "";
424
+ } catch {
425
+ // An unreadable list counts as empty.
426
+ }
427
+ return `${status}\u0000${count}\u0000${last}`;
428
+ }
429
+
430
+ /**
431
+ * A1: per-session pull of `effortOf`. A poller exists while a view needs its session (released pollers close on the
432
+ * next microtask unless re-acquired). It pulls right away (on a timer, never synchronously), again when the trigger key
433
+ * changes (debounced to {@link POLL_INTERVAL_MS} since the last pull, which survives a close/reopen), and every
434
+ * {@link POLL_INTERVAL_MS} while the session runs. While a running delegated session has no answer with an effort yet,
435
+ * an answer without one is pulled again after {@link BACKOFF_START_MS}, at most {@link QUICK_REPULLS} times (GA-2,
436
+ * R2-2; root sessions keep the normal cadence). A reopened
437
+ * poller starts from the session's last value (GA-1). A call carries the session's `location` and an abort signal; it
438
+ * is aborted when its poller closes or after {@link CALL_TIMEOUT_MS}. `unavailable` errors and timeouts retry with
439
+ * backoff 1 s, 2 s, 4 s … {@link BACKOFF_MAX_MS}; any other error drops the value (views fall back to the message
440
+ * variant) for {@link FAILURE_COOLDOWN_MS}.
441
+ */
442
+ function createEffortChannel(deps: ChannelDeps): EffortChannel {
443
+ const pollers = new Map<string, Poller>();
444
+ const states = new Map<string, PullState>();
445
+ let closed = false;
446
+ let client: EffortClient | undefined;
447
+
448
+ const hasRpc = (): boolean => {
449
+ try {
450
+ return typeof deps.client()?.rpc === "function";
451
+ } catch {
452
+ return false;
453
+ }
454
+ };
455
+
456
+ const resolveClient = (): EffortClient | undefined => {
457
+ if (client !== undefined) return client;
458
+ const host = deps.client();
459
+ if (host === undefined || host === null || typeof host.rpc !== "function") return undefined;
460
+ const value = host.rpc(effortRpc);
461
+ if (!isEffortClient(value)) throw new Error("the rpc client has no effortOf method");
462
+ client = value;
463
+ return client;
464
+ };
465
+
466
+ const isRunning = (id: string): boolean => {
467
+ try {
468
+ return untrack(() => deps.status(id)) === "running";
469
+ } catch {
470
+ return false;
471
+ }
472
+ };
473
+
474
+ const isChild = (id: string): boolean => {
475
+ try {
476
+ return untrack(() => deps.isChild(id));
477
+ } catch {
478
+ return false;
479
+ }
480
+ };
481
+
482
+ const locationOf = (id: string): unknown => {
483
+ try {
484
+ return untrack(() => deps.location(id));
485
+ } catch {
486
+ return undefined;
487
+ }
488
+ };
489
+
490
+ const schedule = (poller: Poller, delay: number): void => {
491
+ poller.timer = setTimeout(() => {
492
+ void pull(poller);
493
+ }, delay);
494
+ };
495
+
496
+ const request = (poller: Poller): void => {
497
+ if (poller.closed) return;
498
+ if (poller.inFlight) {
499
+ poller.dirty = true;
500
+ return;
501
+ }
502
+ if (poller.timer !== undefined) return;
503
+ const now = Date.now();
504
+ const { lastPull, failedUntil } = poller.state;
505
+ schedule(poller, Math.max(0, lastPull + POLL_INTERVAL_MS - now, failedUntil - now));
506
+ };
507
+
508
+ /** One `effortOf` call, settled by its answer, by {@link CALL_TIMEOUT_MS}, or by the poller's abort. */
509
+ const call = async (poller: Poller, effort: EffortClient): Promise<unknown> => {
510
+ const controller = new AbortController();
511
+ poller.controller = controller;
512
+ let timer: Timer | undefined;
513
+ let onAbort: (() => void) | undefined;
514
+ const stopped = new Promise<never>((_resolve, reject) => {
515
+ timer = setTimeout(() => {
516
+ reject(CALL_TIMEOUT);
517
+ controller.abort();
518
+ }, CALL_TIMEOUT_MS);
519
+ onAbort = () => reject(CALL_ABORTED);
520
+ controller.signal.addEventListener("abort", onAbort, { once: true });
521
+ });
522
+ stopped.catch(() => undefined);
523
+ try {
524
+ const location = locationOf(poller.id);
525
+ const options: CallOptions =
526
+ location === undefined ? { signal: controller.signal } : { location, signal: controller.signal };
527
+ return await Promise.race([effort.effortOf({ sessionID: poller.id }, options), stopped]);
528
+ } finally {
529
+ if (timer !== undefined) clearTimeout(timer);
530
+ if (onAbort !== undefined) controller.signal.removeEventListener("abort", onAbort);
531
+ if (poller.controller === controller) poller.controller = undefined;
532
+ }
533
+ };
534
+
535
+ const pull = async (poller: Poller): Promise<void> => {
536
+ poller.timer = undefined;
537
+ if (poller.closed) return;
538
+ const state = remember(states, poller.id, poller.state, PULL_STATE_MAX);
539
+ poller.inFlight = true;
540
+ poller.dirty = false;
541
+ state.lastPull = Date.now();
542
+ let result: { ok: true; value: unknown } | { ok: false; error: unknown };
543
+ try {
544
+ const effort = resolveClient();
545
+ if (effort === undefined) {
546
+ poller.inFlight = false;
547
+ return;
548
+ }
549
+ result = { ok: true, value: await call(poller, effort) };
550
+ } catch (error) {
551
+ result = { ok: false, error };
552
+ }
553
+ poller.inFlight = false;
554
+ if (poller.closed) return;
555
+ if (result.ok) {
556
+ state.backoff = 0;
557
+ const applied = appliedOf(result.value);
558
+ poller.write(applied);
559
+ if (applied !== undefined) {
560
+ state.effortSeen = true;
561
+ state.quick = 0;
562
+ } else if (!state.effortSeen && state.quick < QUICK_REPULLS && isRunning(poller.id) && isChild(poller.id)) {
563
+ // GA-2, R2-2: a delegate's running turn may not be recorded yet; ask again soon instead of after the poll
564
+ // interval. Root sessions normally carry no effort (A3), so they keep the normal cadence.
565
+ state.quick += 1;
566
+ schedule(poller, BACKOFF_START_MS);
567
+ return;
568
+ }
569
+ } else if (isRetryable(result.error)) {
570
+ state.backoff = state.backoff === 0 ? BACKOFF_START_MS : Math.min(state.backoff * 2, BACKOFF_MAX_MS);
571
+ schedule(poller, state.backoff);
572
+ return;
573
+ } else {
574
+ deps.log.failed("effort channel", result.error);
575
+ state.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;
576
+ poller.write(undefined);
577
+ }
578
+ if (poller.dirty || isRunning(poller.id)) request(poller);
579
+ };
580
+
581
+ const close = (poller: Poller): void => {
582
+ if (poller.closed) return;
583
+ poller.closed = true;
584
+ if (poller.timer !== undefined) clearTimeout(poller.timer);
585
+ poller.timer = undefined;
586
+ poller.controller?.abort();
587
+ try {
588
+ poller.disposeRoot();
589
+ } catch (error) {
590
+ deps.log.failed("effort channel", error);
591
+ }
592
+ if (pollers.get(poller.id) === poller) pollers.delete(poller.id);
593
+ };
594
+
595
+ const open = (id: string): Poller => {
596
+ const state = remember(
597
+ states,
598
+ id,
599
+ states.get(id) ?? {
600
+ lastPull: Number.NEGATIVE_INFINITY,
601
+ failedUntil: Number.NEGATIVE_INFINITY,
602
+ backoff: 0,
603
+ effortSeen: false,
604
+ quick: 0,
605
+ },
606
+ PULL_STATE_MAX,
607
+ );
608
+ // GA-1: seeded with the last value, so a view reopened within the debounce shows it at once.
609
+ const [read, write] = createSignal<AppliedEffort | undefined>(state.value, { equals: sameApplied });
610
+ const poller: Poller = {
611
+ id,
612
+ state,
613
+ refs: 0,
614
+ closed: false,
615
+ read,
616
+ write: (value) => {
617
+ state.value = value;
618
+ write(value);
619
+ },
620
+ timer: undefined,
621
+ inFlight: false,
622
+ controller: undefined,
623
+ dirty: false,
624
+ disposeRoot: () => undefined,
625
+ };
626
+ // Detached (P13-13): the poller outlives the view computation that opened it.
627
+ poller.disposeRoot = createRoot((dispose) => {
628
+ createRenderEffect((previous: string | undefined) => {
629
+ const key = triggerKey(deps, id);
630
+ if (key !== previous) untrack(() => request(poller));
631
+ return key;
632
+ }, undefined);
633
+ return dispose;
634
+ }, null);
635
+ return poller;
636
+ };
637
+
638
+ const release = (poller: Poller): void => {
639
+ poller.refs -= 1;
640
+ if (poller.refs > 0 || poller.closed) return;
641
+ queueMicrotask(() => {
642
+ if (poller.refs <= 0) close(poller);
643
+ });
644
+ };
645
+
646
+ return {
647
+ applied(sessionID) {
648
+ if (closed || !hasRpc()) return undefined;
649
+ let poller = pollers.get(sessionID);
650
+ if (poller === undefined) {
651
+ poller = open(sessionID);
652
+ pollers.set(sessionID, poller);
653
+ }
654
+ const held = poller;
655
+ held.refs += 1;
656
+ onCleanup(() => release(held));
657
+ return held.read();
658
+ },
659
+ dispose() {
660
+ closed = true;
661
+ for (const poller of [...pollers.values()]) close(poller);
662
+ pollers.clear();
663
+ states.clear();
664
+ },
665
+ };
666
+ }
667
+
668
+ interface Views {
669
+ readonly options: StatusOptions;
670
+ readonly host: Host;
671
+ readonly channel: EffortChannel;
672
+ readonly log: Log;
673
+ /** False for a view rendered without a Solid owner: no channel and no G3 (R2-2). */
674
+ readonly live: boolean;
675
+ columns(): number;
676
+ requestSync(id: string): void;
677
+ }
678
+
679
+ /** G1: `effort <value>` in a root session or the home prompt, nothing when a variant is selected. */
680
+ function footerRows(input: PromptFooterInput | undefined, views: Views): Rows {
681
+ const id = nonBlank(input?.sessionID);
682
+ if (id !== undefined && views.host.isChild(id)) return NO_ROWS;
683
+ const current = views.host.current();
684
+ const selectedVariant = typeof current?.variant === "string" ? current.variant : undefined;
685
+ if (effectiveMainEffort({ selectedVariant }) === undefined) return NO_ROWS;
686
+ const model = currentModelOf(current);
687
+ const applied = id === undefined || model === undefined ? undefined : views.channel.applied(id);
688
+ const value = effectiveMainEffort({ selectedVariant, applied, current: model });
689
+ return value === undefined ? NO_ROWS : [formatRow([`effort ${value}`], views.columns())];
690
+ }
691
+
692
+ /** G2 in a child session, G3 in a root session; nothing until the session is known. */
693
+ function composerRows(input: ComposerTopInput | undefined, views: Views): Rows {
694
+ const id = nonBlank(input?.sessionID);
695
+ if (id === undefined) return NO_ROWS;
696
+ const { host, channel, options } = views;
697
+ const session = host.session(id);
698
+ if (session === undefined) return NO_ROWS;
699
+ const messages = (child: string): readonly HostMessage[] => {
700
+ const list = host.messages(child);
701
+ if (list.length === 0) views.requestSync(child);
702
+ return list;
703
+ };
704
+ const width = views.columns();
705
+ const models = (): readonly HostModelInfo[] => host.models(host.location(id));
706
+ if (nonBlank(session.parentID) !== undefined) {
707
+ if (!options.childView) return NO_ROWS;
708
+ const status = childStatus({
709
+ session,
710
+ messages: messages(id),
711
+ models: models(),
712
+ applied: childApplied(channel.applied(id)),
713
+ });
714
+ if (status === undefined) return NO_ROWS;
715
+ // GA-7: the running row's agent fallback (session title, then `subagent`).
716
+ const agent = status.agent ?? nonBlank(session.title) ?? FALLBACK_AGENT;
717
+ return [formatRow([agent, status.model, status.effort], width)];
718
+ }
719
+ // G3 lists delegates that start and stop: a static view would show a stale list, so it shows none (R2-2).
720
+ if (!options.runningRow || !views.live) return NO_ROWS;
721
+ const running = runningChildren({
722
+ rootID: id,
723
+ family: host.family(id),
724
+ status: host.status,
725
+ sessions: host.session,
726
+ messages,
727
+ models: models(),
728
+ applied: (child) => childApplied(channel.applied(child)),
729
+ max: options.maxRows,
730
+ });
731
+ const rows = running.rows.map((row) => formatRow([row.agent, row.model, row.effort], width));
732
+ if (running.overflow > 0) rows.push(formatRow([`+${running.overflow} more`], width));
733
+ return rows;
734
+ }
735
+
736
+ function readMuted(views: Views): unknown {
737
+ try {
738
+ return views.host.muted();
739
+ } catch {
740
+ return undefined;
741
+ }
742
+ }
743
+
744
+ /** A `text` element for one row: never wraps (P13-7; ignored by a host that lacks the prop). */
745
+ function textElement(): unknown {
746
+ const node = createElement("text");
747
+ setProp(node, "wrapMode", "none");
748
+ return node;
749
+ }
750
+
751
+ interface Row {
752
+ readonly node: unknown;
753
+ dispose(): void;
754
+ }
755
+
756
+ /**
757
+ * One reactive `text` row in its own root, disposed when the row goes away. Not detached: `createElement` reads the
758
+ * renderer from the owner's context. A failure disposes the root before it propagates (P13-14).
759
+ */
760
+ function rowNode(rows: () => Rows, index: number, views: Views): Row {
761
+ return createRoot((dispose) => {
762
+ try {
763
+ const node = textElement();
764
+ createRenderEffect((previous: unknown) => {
765
+ const fg = readMuted(views);
766
+ return fg === undefined || fg === previous ? previous : setProp(node, "fg", fg, previous);
767
+ }, undefined);
768
+ insert(node, () => rows()[index] ?? "");
769
+ return { node, dispose };
770
+ } catch (error) {
771
+ dispose();
772
+ throw error;
773
+ }
774
+ });
775
+ }
776
+
777
+ /** A column `box`, the element every slot render returns. */
778
+ function boxElement(): unknown {
779
+ const box = createElement("box");
780
+ setProp(box, "flexDirection", "column");
781
+ return box;
782
+ }
783
+
784
+ /**
785
+ * P13-2: without a Solid owner (for example when the plugin's `solid-js` is not the host's; not reproduced on a real
786
+ * host, GA-5) nothing reactive would update or ever be disposed. The rows are computed once, untracked, without the
787
+ * effort channel, and rendered as static text: G1 and G2 only, G3 (running delegates) would be stale at once (R2-2).
788
+ */
789
+ function staticView(compute: (views: Views) => Rows, area: string, views: Views): unknown {
790
+ let rows: Rows;
791
+ try {
792
+ rows = untrack(() => compute({ ...views, channel: NO_CHANNEL, live: false }));
793
+ } catch (error) {
794
+ views.log.failed(area, error);
795
+ rows = NO_ROWS;
796
+ }
797
+ const box = boxElement();
798
+ const muted = readMuted(views);
799
+ const nodes = rows.map((row) => {
800
+ const node = textElement();
801
+ if (muted !== undefined) setProp(node, "fg", muted);
802
+ insert(node, row);
803
+ return node;
804
+ });
805
+ if (nodes.length > 0) insert(box, nodes);
806
+ return box;
807
+ }
808
+
809
+ /**
810
+ * A column `box` with one `text` per row of `compute` (re-run reactively). The box always exists (a slot render must
811
+ * return an element); with no rows it has no children and no size of its own, so it takes no height. Rows are created
812
+ * and disposed as the count changes, never reused (a removed host node may be destroyed). A throwing `compute` gives
813
+ * no rows and one warning for `area`.
814
+ */
815
+ function rowsView(compute: (views: Views) => Rows, area: string, views: Views): unknown {
816
+ try {
817
+ if (getOwner() === null) {
818
+ views.log.notice("owner", `${STATUS_NOTICE_PREFIX}${NO_OWNER_NOTICE}`);
819
+ return staticView(compute, area, views);
820
+ }
821
+ const rows = createMemo<Rows>(
822
+ () => {
823
+ try {
824
+ return compute(views);
825
+ } catch (error) {
826
+ views.log.failed(area, error);
827
+ return NO_ROWS;
828
+ }
829
+ },
830
+ NO_ROWS,
831
+ { equals: sameRows },
832
+ );
833
+ const count = createMemo(() => rows().length);
834
+ const made: Row[] = [];
835
+ const box = boxElement();
836
+ const children = createMemo(() => {
837
+ const wanted = count();
838
+ untrack(() => {
839
+ while (made.length > wanted) made.pop()?.dispose();
840
+ while (made.length < wanted) {
841
+ try {
842
+ made.push(rowNode(rows, made.length, views));
843
+ } catch (error) {
844
+ views.log.failed(area, error);
845
+ break;
846
+ }
847
+ }
848
+ });
849
+ return made.map((row) => row.node);
850
+ });
851
+ onCleanup(() => {
852
+ for (const row of made.splice(0)) row.dispose();
853
+ });
854
+ insert(box, children);
855
+ return box;
856
+ } catch (error) {
857
+ views.log.failed(area, error);
858
+ return undefined;
859
+ }
860
+ }
861
+
862
+ /** The renderer's width in columns (re-read on its `resize` event when it emits one). */
863
+ function createWidth(context: HostContext | undefined, log: Log): { width: () => number; dispose: () => void } {
864
+ const read = (): number => {
865
+ try {
866
+ const width = context?.renderer?.width;
867
+ return typeof width === "number" && Number.isFinite(width) && width > 0 ? Math.floor(width) : DEFAULT_WIDTH;
868
+ } catch {
869
+ return DEFAULT_WIDTH;
870
+ }
871
+ };
872
+ const [width, setWidth] = createSignal(read());
873
+ let dispose = (): void => undefined;
874
+ try {
875
+ const renderer = context?.renderer;
876
+ if (renderer !== undefined && renderer !== null && typeof renderer.on === "function") {
877
+ const listener: HostResizeListener = () => {
878
+ setWidth(read());
879
+ };
880
+ renderer.on("resize", listener);
881
+ dispose = () => {
882
+ if (typeof renderer.off === "function") renderer.off("resize", listener);
883
+ };
884
+ }
885
+ } catch (error) {
886
+ log.failed("renderer", error);
887
+ }
888
+ return { width, dispose: () => dispose() };
889
+ }
890
+
891
+ function isDispose(value: unknown): value is () => void {
892
+ return typeof value === "function";
893
+ }
894
+
895
+ function register(context: HostContext | undefined, claim: HostSlotClaim, cleanups: Array<() => void>, log: Log): void {
896
+ try {
897
+ const ui = context?.ui;
898
+ if (ui === undefined || ui === null || typeof ui.slot !== "function") return;
899
+ const dispose = ui.slot(claim);
900
+ if (isDispose(dispose)) cleanups.push(() => dispose());
901
+ } catch (error) {
902
+ log.failed(`slot ${claim.append}`, error);
903
+ }
904
+ }
905
+
906
+ /**
907
+ * The TUI `setup`: options (one toast for invalid ones), then the slot claims. Returns the cleanup that disposes the
908
+ * claims, the pollers with their timers and calls, and the resize listener. Never throws; makes no rpc call.
909
+ */
910
+ function setup(context: HostContext | undefined): () => void {
911
+ const log = createLog((message) => context?.ui?.toast?.show?.({ message, variant: "warning" }));
912
+ const cleanups: Array<() => void> = [];
913
+ let closed = false;
914
+ const cleanup = (): void => {
915
+ if (closed) return;
916
+ closed = true;
917
+ for (const dispose of cleanups.splice(0).reverse()) {
918
+ try {
919
+ dispose();
920
+ } catch (error) {
921
+ log.failed("cleanup", error);
922
+ }
923
+ }
924
+ };
925
+ try {
926
+ const { options, notices } = parseOptions(context?.options);
927
+ // parseOptions gives at most one notice, already prefixed with `model-router status: `.
928
+ if (notices.length > 0) log.notice("options", notices[0]);
929
+ if (!options.enabled || !(options.footer || options.childView || options.runningRow)) return cleanup;
930
+
931
+ /**
932
+ * Runs `run` on the next microtask unless `key` is already in `seen` (kept to the last `max` keys); a rejected or
933
+ * throwing run forgets the key, so the next view tries again (P13-6, R2-1).
934
+ */
935
+ const syncOnce = (seen: Set<string>, key: string, max: number, run: () => unknown): void => {
936
+ if (seen.has(key)) return;
937
+ seen.add(key);
938
+ for (const oldest of seen) {
939
+ if (seen.size <= max) break;
940
+ seen.delete(oldest);
941
+ }
942
+ queueMicrotask(() => {
943
+ if (closed) return;
944
+ try {
945
+ Promise.resolve(run()).catch(() => seen.delete(key));
946
+ } catch {
947
+ seen.delete(key);
948
+ }
949
+ });
950
+ };
951
+ const modelsSynced = new Set<string>();
952
+ const host = createHost(context, (location) =>
953
+ syncOnce(modelsSynced, locationKey(location), MODEL_SYNC_MAX, () => context?.data?.location?.model?.sync?.(location)),
954
+ );
955
+ const channel = createEffortChannel({
956
+ client: () => context?.client,
957
+ status: host.status,
958
+ isChild: host.isChild,
959
+ messages: host.messages,
960
+ location: host.location,
961
+ log,
962
+ });
963
+ cleanups.push(() => channel.dispose());
964
+ const width = createWidth(context, log);
965
+ cleanups.push(width.dispose);
966
+ const synced = new Set<string>();
967
+ const views: Views = {
968
+ options,
969
+ host,
970
+ channel,
971
+ log,
972
+ live: true,
973
+ columns: () => Math.max(0, width.width() - WIDTH_MARGIN),
974
+ requestSync: (id) => syncOnce(synced, id, SYNCED_MAX, () => context?.data?.session?.message?.sync?.(id)),
975
+ };
976
+
977
+ if (options.footer) {
978
+ register(
979
+ context,
980
+ { append: FOOTER_SLOT, render: (input) => rowsView((v) => footerRows(input, v), "footer view", views) },
981
+ cleanups,
982
+ log,
983
+ );
984
+ }
985
+ if (options.childView || options.runningRow) {
986
+ register(
987
+ context,
988
+ { append: COMPOSER_SLOT, render: (input) => rowsView((v) => composerRows(input, v), "composer view", views) },
989
+ cleanups,
990
+ log,
991
+ );
992
+ }
993
+ } catch (error) {
994
+ log.failed("setup", error);
995
+ }
996
+ return cleanup;
997
+ }
998
+
999
+ /** A plain `{ id, setup }` (what `Plugin.define` returns); no `@opencode/plugin` import at runtime. */
1000
+ export interface StatusPluginDefinition {
1001
+ readonly id: string;
1002
+ readonly setup: (context: HostContext | undefined) => () => void;
1003
+ }
1004
+
1005
+ const plugin: StatusPluginDefinition = { id: STATUS_PLUGIN_ID, setup };
1006
+
1007
+ export default plugin;