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,561 @@
1
+ /**
2
+ * Pure status model for the v2 TUI status views (#90, plan §2 D2–D5/D7, amendments A3, A5, A9, A12). No host
3
+ * imports: the host shapes are mirrored structurally and minimally; the TUI views (P1.3) read the host
4
+ * context, call these functions and render the strings.
5
+ *
6
+ * - G1 main footer: {@link effectiveMainEffort} (A3): nothing when a variant is selected (the host row shows
7
+ * it), the applied effort of the prompt's current model when the server channel reports one for a turn that
8
+ * ran without a variant, else `default`.
9
+ * - G2 child view: {@link childStatus} (A5): the latest assistant message's model, before it the session's.
10
+ * - G3 running row: {@link runningChildren}: every running delegate of the family, stable order, at most `max`
11
+ * rows. Opt-in (A12): the `runningRow` option is off by default.
12
+ * - Labels and layout: {@link modelLabel}, {@link effortLabel}, {@link formatRow}, width-aware
13
+ * {@link displayWidth} / {@link truncate}; rendered text is sanitised (control, bidi and line-separator
14
+ * characters → space) and measured as rendered.
15
+ * - Options (D7): {@link parseOptions}, defaults plus at most one notice.
16
+ *
17
+ * Empty and whitespace-only strings count as absent everywhere, and an effort or variant `"default"` too, except
18
+ * `selectedVariant` in {@link effectiveMainEffort}: it follows the host row's truthiness, so any non-empty
19
+ * string (`" "` and `"default"` included) counts as selected.
20
+ */
21
+
22
+ /** Mirrors the host's `Model.Ref`: `variant` is absent when none was selected. */
23
+ export interface ModelRef {
24
+ id: string;
25
+ providerID: string;
26
+ variant?: string;
27
+ }
28
+
29
+ /**
30
+ * Mirrors an entry of the host's model list (`data.location.model.list()`). Only `id`, `providerID`, `name` and
31
+ * `variants` are read; the host's entries, with all their other fields, are assignable as they are.
32
+ */
33
+ export interface ModelInfo {
34
+ readonly id: string;
35
+ readonly providerID: string;
36
+ readonly name?: string;
37
+ readonly variants?: ReadonlyArray<{ readonly id: string }>;
38
+ }
39
+
40
+ /**
41
+ * A host timestamp: epoch milliseconds, or an Effect `DateTime.Utc` (v2 decodes `time.created` to one; it carries
42
+ * `epochMilliseconds`). `time.created` may also be `null`: it sorts as the oldest.
43
+ */
44
+ export type CreatedTime = number | { readonly epochMilliseconds: number };
45
+
46
+ export interface SessionLike {
47
+ id: string;
48
+ parentID?: string;
49
+ agent?: string;
50
+ title?: string;
51
+ model?: ModelRef;
52
+ time?: { created?: CreatedTime | null };
53
+ }
54
+
55
+ /** A session message. v2 tags it with `type` (`"assistant"`, `"user"`, `"model-switched"`, …); a legacy `role` is read when `type` is absent. */
56
+ export interface MessageLike {
57
+ id: string;
58
+ type?: string;
59
+ role?: string;
60
+ agent?: string;
61
+ model?: ModelRef;
62
+ time?: { created?: CreatedTime | null };
63
+ }
64
+
65
+ /** The effort a session's own turn actually applied, as reported by the server channel (P1.2); may be absent. */
66
+ export interface AppliedEffort {
67
+ effort: string;
68
+ /** The recorded turn's variant; absent (or blank, or `"default"`) when the turn ran without one. */
69
+ variant?: string;
70
+ providerID: string;
71
+ modelID: string;
72
+ }
73
+
74
+ /** The prompt's current model (`ui.model.current()`). */
75
+ export interface CurrentModel {
76
+ providerID: string;
77
+ modelID: string;
78
+ }
79
+
80
+ /** Mirrors the host's `data.session.status(id)`. */
81
+ export type SessionStatus = "idle" | "running";
82
+
83
+ /** An assistant message that carries a usable model ref. */
84
+ export type AssistantWithModel = MessageLike & { model: ModelRef };
85
+
86
+ export interface MainEffortInput {
87
+ /** The selected variant (`ui.model.current()?.variant`); any non-empty string counts as selected. */
88
+ selectedVariant?: string;
89
+ /** The applied effort of the main session, from the server channel. */
90
+ applied?: AppliedEffort;
91
+ /** The prompt's current model; `applied` is used only when it was recorded for this model. */
92
+ current?: CurrentModel;
93
+ }
94
+
95
+ export interface ChildStatusInput {
96
+ session: SessionLike;
97
+ messages: readonly MessageLike[];
98
+ models: readonly ModelInfo[];
99
+ applied?: AppliedEffort;
100
+ }
101
+
102
+ export interface ChildStatus {
103
+ model: string;
104
+ effort: string;
105
+ agent?: string;
106
+ }
107
+
108
+ export interface RunningChildrenInput {
109
+ rootID: string;
110
+ /** Ids of the root's family, root included (`data.session.family(rootID)`). */
111
+ family: readonly string[];
112
+ status(id: string): SessionStatus;
113
+ sessions(id: string): SessionLike | undefined;
114
+ messages(id: string): readonly MessageLike[];
115
+ models: readonly ModelInfo[];
116
+ /** The server channel's applied effort per session; absent when there is no channel. */
117
+ applied?(id: string): AppliedEffort | undefined;
118
+ /** Row limit, see {@link clampMax}: floored, below 1 or NaN → 1, Infinity → all rows. */
119
+ max: number;
120
+ }
121
+
122
+ export interface RunningRow {
123
+ id: string;
124
+ agent: string;
125
+ model: string;
126
+ effort: string;
127
+ }
128
+
129
+ export interface RunningChildren {
130
+ rows: RunningRow[];
131
+ /** Running children beyond `max` (rendered as `+k`). */
132
+ overflow: number;
133
+ }
134
+
135
+ export interface StatusOptions {
136
+ enabled: boolean;
137
+ /** G1: effort in the main prompt footer. */
138
+ footer: boolean;
139
+ /** G2: model and effort in a child session view. */
140
+ childView: boolean;
141
+ /** G3: running delegates above the main composer. Opt-in (A12): off by default. */
142
+ runningRow: boolean;
143
+ maxRows: number;
144
+ }
145
+
146
+ export interface ParsedOptions {
147
+ options: StatusOptions;
148
+ /** At most one notice, listing every problem. */
149
+ notices: string[];
150
+ }
151
+
152
+ export const DEFAULT_EFFORT = "default";
153
+ /** Model label of a running child for which neither a message nor the session carries a model ref. */
154
+ export const UNKNOWN_MODEL = "unknown";
155
+ /** Agent label of a running child without agent and title. */
156
+ export const FALLBACK_AGENT = "subagent";
157
+ /**
158
+ * `…` (U+2026) and `·` (U+00B7, in {@link ROW_SEPARATOR}) are East Asian Ambiguous; like every Ambiguous
159
+ * character they are counted as 1 column (narrow terminals).
160
+ */
161
+ export const ELLIPSIS = "…";
162
+ export const ROW_SEPARATOR = " · ";
163
+ export const STATUS_NOTICE_PREFIX = "model-router status: ";
164
+ export const MAX_ROWS_MIN = 1;
165
+ export const MAX_ROWS_MAX = 20;
166
+ export const STATUS_OPTION_KEYS = ["enabled", "footer", "childView", "runningRow", "maxRows"] as const;
167
+ export const DEFAULT_STATUS_OPTIONS: Readonly<StatusOptions> = Object.freeze({
168
+ enabled: true,
169
+ footer: true,
170
+ childView: true,
171
+ runningRow: false,
172
+ maxRows: 4,
173
+ });
174
+
175
+ const FLAG_KEYS = ["enabled", "footer", "childView", "runningRow"] as const;
176
+ const KNOWN_KEYS: ReadonlySet<string> = new Set<string>(STATUS_OPTION_KEYS);
177
+ /** `formatRow` shrinks this many leading parts before it cuts the whole row. */
178
+ const SHRINK_PARTS = 2;
179
+
180
+ /** The trimmed value, or undefined when absent, not a string, or blank. */
181
+ function nonEmpty(value: string | undefined): string | undefined {
182
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
183
+ }
184
+
185
+ /** An effort or variant worth showing: non-blank and not `"default"`. */
186
+ function effortValue(value: string | undefined): string | undefined {
187
+ const text = nonEmpty(value);
188
+ return text === DEFAULT_EFFORT ? undefined : text;
189
+ }
190
+
191
+ function hasRef(ref: ModelRef | undefined): ref is ModelRef {
192
+ return ref !== undefined && nonEmpty(ref.id) !== undefined;
193
+ }
194
+
195
+ function sameModel(applied: AppliedEffort, providerID: string, modelID: string): boolean {
196
+ return applied.providerID === providerID && applied.modelID === modelID;
197
+ }
198
+
199
+ /** Epoch milliseconds of `time.created` (a number or a `DateTime.Utc`); missing, null or non-finite sorts as the oldest. */
200
+ function createdOf(time: { created?: CreatedTime | null } | undefined): number {
201
+ const created = time?.created;
202
+ const millis = created !== null && typeof created === "object" ? created.epochMilliseconds : created;
203
+ return typeof millis === "number" && Number.isFinite(millis) ? millis : Number.NEGATIVE_INFINITY;
204
+ }
205
+
206
+ /** -1, 0 or 1, locale-independent. */
207
+ function compare(a: number | string, b: number | string): number {
208
+ return Number(a > b) - Number(a < b);
209
+ }
210
+
211
+ function displayName(info: ModelInfo): string {
212
+ return nonEmpty(info.name) ?? info.id;
213
+ }
214
+
215
+ function labelOf(ref: ModelRef, models: readonly ModelInfo[]): string {
216
+ const own = models.find((m) => m.providerID === ref.providerID && m.id === ref.id);
217
+ const label = own === undefined ? ref.id : displayName(own);
218
+ const shared = models.some((m) => m.providerID !== ref.providerID && displayName(m) === label);
219
+ return shared && ref.providerID !== "" ? `${label} (${ref.providerID})` : label;
220
+ }
221
+
222
+ /**
223
+ * Display label of a model ref: the `name` of the list entry with the same `providerID` and `id`, else the raw
224
+ * `id`. When another provider's entry shows the same label, ` (<providerID>)` is appended (this also covers an
225
+ * unknown ref whose id equals another provider's display name). Undefined ref or blank id → undefined.
226
+ */
227
+ export function modelLabel(ref: ModelRef | undefined, models: readonly ModelInfo[]): string | undefined {
228
+ return hasRef(ref) ? labelOf(ref, models) : undefined;
229
+ }
230
+
231
+ /**
232
+ * Effort label: `effectiveEffort`, else the ref's variant, else `"default"`; blank values and `"default"` count
233
+ * as absent. A variant is shown as recorded even when the model's `variants` list does not contain it.
234
+ */
235
+ export function effortLabel(ref: ModelRef | undefined, effectiveEffort?: string): string {
236
+ return effortValue(effectiveEffort) ?? effortValue(ref?.variant) ?? DEFAULT_EFFORT;
237
+ }
238
+
239
+ /**
240
+ * G1 (A3): undefined when a variant is selected (any non-empty string, as the host row decides; the row already
241
+ * shows it). Otherwise the applied effort when it was recorded for the prompt's current model by a turn without
242
+ * a variant; a turn that ran with a variant the user has since cleared is stale. Otherwise `"default"`.
243
+ */
244
+ export function effectiveMainEffort(input: MainEffortInput): string | undefined {
245
+ const { selectedVariant, applied, current } = input;
246
+ if (selectedVariant !== undefined && selectedVariant !== "") return undefined;
247
+ if (
248
+ applied !== undefined &&
249
+ current !== undefined &&
250
+ sameModel(applied, current.providerID, current.modelID) &&
251
+ effortValue(applied.variant) === undefined
252
+ ) {
253
+ return effortValue(applied.effort) ?? DEFAULT_EFFORT;
254
+ }
255
+ return DEFAULT_EFFORT;
256
+ }
257
+
258
+ function isAssistantWithModel(message: MessageLike): message is AssistantWithModel {
259
+ return (message.type ?? message.role) === "assistant" && hasRef(message.model);
260
+ }
261
+
262
+ /**
263
+ * The latest assistant message (`type`, else legacy `role`, `"assistant"`) with a usable model ref, by
264
+ * `time.created` (missing → oldest); on equal times the later array entry wins.
265
+ */
266
+ export function latestAssistant(messages: readonly MessageLike[]): AssistantWithModel | undefined {
267
+ let latest: AssistantWithModel | undefined;
268
+ let latestTime = Number.NEGATIVE_INFINITY;
269
+ for (const message of messages) {
270
+ if (!isAssistantWithModel(message)) continue;
271
+ const created = createdOf(message.time);
272
+ if (created >= latestTime) {
273
+ latest = message;
274
+ latestTime = created;
275
+ }
276
+ }
277
+ return latest;
278
+ }
279
+
280
+ /**
281
+ * G2 (A5): model and effort of a session. Ref: the latest assistant message's model, else `session.model`;
282
+ * no ref → undefined. Effort: `applied.effort` when it was recorded for the ref's provider/model, else the
283
+ * ref's variant, else `"default"`. Agent: `session.agent`, else the latest assistant message's agent.
284
+ */
285
+ export function childStatus(input: ChildStatusInput): ChildStatus | undefined {
286
+ const { session, messages, models, applied } = input;
287
+ const latest = latestAssistant(messages);
288
+ const ref = latest?.model ?? (hasRef(session.model) ? session.model : undefined);
289
+ if (ref === undefined) return undefined;
290
+ const effective = applied !== undefined && sameModel(applied, ref.providerID, ref.id) ? applied.effort : undefined;
291
+ const model = labelOf(ref, models);
292
+ const effort = effortLabel(ref, effective);
293
+ const agent = nonEmpty(session.agent) ?? nonEmpty(latest?.agent);
294
+ return agent === undefined ? { model, effort } : { model, effort, agent };
295
+ }
296
+
297
+ /**
298
+ * @internal Row limit of {@link runningChildren}: a number ≥ 1 is floored (Infinity → all rows); anything else
299
+ * (below 1, NaN, not a number) → 1.
300
+ */
301
+ export function clampMax(value: unknown): number {
302
+ return typeof value === "number" && value >= MAX_ROWS_MIN ? Math.floor(value) : MAX_ROWS_MIN;
303
+ }
304
+
305
+ /**
306
+ * G3: every running delegate of the family. Kept: ids other than the root (duplicates once) whose status is
307
+ * `"running"` and whose session exists and has a `parentID`; the session is looked up only for running ids.
308
+ * Grandchildren (`parentID` ≠ root) are kept too: the row lists every running delegate of the family. Order:
309
+ * `session.time.created` ascending (missing → first), then id. At most `max` rows ({@link clampMax});
310
+ * `overflow` counts the rest. A running child without any model ref gets `model: "unknown"`,
311
+ * `effort: "default"`; agent falls back to `session.title`, then `"subagent"`.
312
+ */
313
+ export function runningChildren(input: RunningChildrenInput): RunningChildren {
314
+ const limit = clampMax(input.max);
315
+ const seen = new Set<string>();
316
+ const running: Array<{ id: string; session: SessionLike; created: number }> = [];
317
+ for (const id of input.family) {
318
+ if (id === input.rootID || seen.has(id)) continue;
319
+ seen.add(id);
320
+ if (input.status(id) !== "running") continue;
321
+ const session = input.sessions(id);
322
+ if (session === undefined || nonEmpty(session.parentID) === undefined) continue;
323
+ running.push({ id, session, created: createdOf(session.time) });
324
+ }
325
+ running.sort((a, b) => compare(a.created, b.created) || compare(a.id, b.id));
326
+ const rows = running.slice(0, limit).map(({ id, session }): RunningRow => {
327
+ const status = childStatus({
328
+ session,
329
+ messages: input.messages(id),
330
+ models: input.models,
331
+ applied: input.applied?.(id),
332
+ });
333
+ return {
334
+ id,
335
+ agent: status?.agent ?? nonEmpty(session.agent) ?? nonEmpty(session.title) ?? FALLBACK_AGENT,
336
+ model: status?.model ?? UNKNOWN_MODEL,
337
+ effort: status?.effort ?? DEFAULT_EFFORT,
338
+ };
339
+ });
340
+ return { rows, overflow: running.length - rows.length };
341
+ }
342
+
343
+ const ZWJ = 0x200d;
344
+ const VS16 = 0xfe0f;
345
+ const SOFT_HYPHEN = 0x00ad;
346
+ const RE_ZERO_WIDTH = /^[\p{Cf}\p{M}]$/u;
347
+ const RE_MARK = /^\p{M}$/u;
348
+ const RE_SPACING_MARK = /^\p{Mc}$/u;
349
+ const RE_EMOJI_PRESENTATION = /^\p{Emoji_Presentation}$/u;
350
+ const RE_PICTOGRAPHIC = /^\p{Extended_Pictographic}$/u;
351
+ /**
352
+ * Control characters (`\p{Cc}`), bidi controls (ALM U+061C, LRM, RLM, LRE–RLO, LRI–PDI) and the line and
353
+ * paragraph separators (U+2028, U+2029): each becomes one space in rendered and measured text.
354
+ */
355
+ const RE_UNSAFE = /[\p{Cc}\u061C\u200E\u200F\u2028\u2029\u202A-\u202E\u2066-\u2069]/gu;
356
+ const RE_WHITESPACE_RUN = /\s+/gu;
357
+
358
+ /** East Asian Wide and Fullwidth ranges (emoji-presentation code points are matched separately). */
359
+ const WIDE_RANGES: ReadonlyArray<readonly [number, number]> = [
360
+ [0x1100, 0x115f],
361
+ [0x2329, 0x232a],
362
+ [0x2e80, 0x303e],
363
+ [0x3041, 0x33ff],
364
+ [0x3400, 0x4dbf],
365
+ [0x4e00, 0x9fff],
366
+ [0xa000, 0xa4cf],
367
+ [0xa960, 0xa97f],
368
+ [0xac00, 0xd7a3],
369
+ [0xf900, 0xfaff],
370
+ [0xfe10, 0xfe19],
371
+ [0xfe30, 0xfe6f],
372
+ [0xff00, 0xff60],
373
+ [0xffe0, 0xffe6],
374
+ [0x16fe0, 0x16fe4],
375
+ [0x17000, 0x18cff],
376
+ [0x1b000, 0x1b2ff],
377
+ [0x1f200, 0x1f265],
378
+ [0x20000, 0x2fffd],
379
+ [0x30000, 0x3fffd],
380
+ ];
381
+
382
+ function isRegional(cp: number): boolean {
383
+ return cp >= 0x1f1e6 && cp <= 0x1f1ff;
384
+ }
385
+
386
+ /** Joins the previous cluster: combining marks (variation selectors included), ZWJ, skin tones, tag characters. */
387
+ function isExtender(ch: string, cp: number): boolean {
388
+ return RE_MARK.test(ch) || cp === ZWJ || (cp >= 0x1f3fb && cp <= 0x1f3ff) || (cp >= 0xe0020 && cp <= 0xe007f);
389
+ }
390
+
391
+ /**
392
+ * Spacing marks (`\p{Mc}`) and the soft hyphen take 1 column; other marks and format characters 0; wide,
393
+ * fullwidth and emoji-presentation 2; everything else (East Asian Ambiguous included) 1.
394
+ */
395
+ function codePointWidth(ch: string, cp: number): number {
396
+ if (cp === SOFT_HYPHEN || RE_SPACING_MARK.test(ch)) return 1;
397
+ if (RE_ZERO_WIDTH.test(ch)) return 0;
398
+ if (RE_EMOJI_PRESENTATION.test(ch) || WIDE_RANGES.some(([lo, hi]) => cp >= lo && cp <= hi)) return 2;
399
+ return 1;
400
+ }
401
+
402
+ interface Cluster {
403
+ text: string;
404
+ width: number;
405
+ }
406
+
407
+ interface OpenCluster extends Cluster {
408
+ /** The base is `\p{Extended_Pictographic}`. */
409
+ pictographic: boolean;
410
+ /** A pictographic cluster that ends in a ZWJ: the next pictograph joins it. */
411
+ afterZwj: boolean;
412
+ regional: number;
413
+ }
414
+
415
+ function joins(open: OpenCluster, ch: string, cp: number): boolean {
416
+ return (open.afterZwj && RE_PICTOGRAPHIC.test(ch)) || isExtender(ch, cp) || (open.regional === 1 && isRegional(cp));
417
+ }
418
+
419
+ /**
420
+ * Splits text into display clusters: a base code point with its combining marks, variation selectors, skin
421
+ * tones and tags, pictographic ZWJ sequences, and regional-indicator pairs. Surrogate pairs are never split. A
422
+ * ZWJ joins the next code point only when the open cluster is pictographic and that code point is
423
+ * `\p{Extended_Pictographic}`; a leading or orphan ZWJ joins nothing after it. Width: the base's (see
424
+ * `codePointWidth`), plus 1 per joined spacing mark; at least 2 once a pictograph joins after a ZWJ, and 2 when
425
+ * a narrow base takes VS16 (emoji presentation). Expects sanitised text (see {@link sanitise}).
426
+ */
427
+ function clusters(text: string): Cluster[] {
428
+ const out: Cluster[] = [];
429
+ let open: OpenCluster | undefined;
430
+ for (const ch of text) {
431
+ const cp = ch.codePointAt(0) as number;
432
+ if (open !== undefined && joins(open, ch, cp)) {
433
+ if (open.afterZwj && RE_PICTOGRAPHIC.test(ch)) open.width = Math.max(open.width, 2);
434
+ else if (RE_SPACING_MARK.test(ch)) open.width += 1;
435
+ else if (cp === VS16 && open.width === 1) open.width = 2;
436
+ open.text += ch;
437
+ if (isRegional(cp)) open.regional += 1;
438
+ open.afterZwj = cp === ZWJ && open.pictographic;
439
+ continue;
440
+ }
441
+ if (open !== undefined) out.push({ text: open.text, width: open.width });
442
+ open = {
443
+ text: ch,
444
+ width: codePointWidth(ch, cp),
445
+ pictographic: RE_PICTOGRAPHIC.test(ch),
446
+ afterZwj: false,
447
+ regional: isRegional(cp) ? 1 : 0,
448
+ };
449
+ }
450
+ if (open !== undefined) out.push({ text: open.text, width: open.width });
451
+ return out;
452
+ }
453
+
454
+ /**
455
+ * Terminal columns of `text` as rendered: East Asian wide/fullwidth and emoji 2; combining (non-spacing) marks
456
+ * and format characters 0; spacing marks, the soft hyphen and East Asian Ambiguous characters 1; every
457
+ * character that {@link sanitise} turns into a space (control, bidi control, line/paragraph separator) 1, so
458
+ * raw and sanitised text measure the same.
459
+ */
460
+ export function displayWidth(text: string): number {
461
+ let width = 0;
462
+ for (const cluster of clusters(sanitise(text))) width += cluster.width;
463
+ return width;
464
+ }
465
+
466
+ /** Each control character, bidi control and line/paragraph separator (`RE_UNSAFE`) replaced by one space. */
467
+ function sanitise(text: string): string {
468
+ return text.replace(RE_UNSAFE, " ");
469
+ }
470
+
471
+ /**
472
+ * `text`, sanitised (see {@link sanitise}), cut to at most `width` columns
473
+ * (floored); a cut appends `…` (1 column) and never splits a cluster (surrogate pair, base + combining marks,
474
+ * ZWJ sequence, flag). Width ≤ 0 or NaN → `""`.
475
+ */
476
+ export function truncate(text: string, width: number): string {
477
+ const limit = Math.floor(width);
478
+ if (!(limit > 0)) return "";
479
+ const safe = sanitise(text);
480
+ const parts = clusters(safe);
481
+ let total = 0;
482
+ for (const part of parts) total += part.width;
483
+ if (total <= limit) return safe;
484
+ const budget = limit - 1;
485
+ let used = 0;
486
+ let out = "";
487
+ for (const part of parts) {
488
+ if (used + part.width > budget) break;
489
+ used += part.width;
490
+ out += part.text;
491
+ }
492
+ return out + ELLIPSIS;
493
+ }
494
+
495
+ /** A row part as rendered: sanitised, whitespace runs collapsed to one space, trimmed. */
496
+ function cleanPart(part: string): string {
497
+ return sanitise(part).replace(RE_WHITESPACE_RUN, " ").trim();
498
+ }
499
+
500
+ /**
501
+ * Non-blank parts (sanitised, whitespace runs collapsed, trimmed) joined with ` · ` in at most `width` columns
502
+ * (floored). Too wide: the first part shrinks first, to the room left by the trailing parts and separators
503
+ * (at least 1 column, `…` included); still too wide: the second part the same way; only then the whole row is
504
+ * cut from the end. Width ≤ 0 or NaN → `""`.
505
+ */
506
+ export function formatRow(parts: readonly string[], width: number): string {
507
+ const limit = Math.floor(width);
508
+ if (!(limit > 0)) return "";
509
+ const cells = parts.map(cleanPart).filter((part) => part !== "");
510
+ let row = cells.join(ROW_SEPARATOR);
511
+ for (let i = 0; i < SHRINK_PARTS && i < cells.length && displayWidth(row) > limit; i++) {
512
+ const rest = displayWidth(row) - displayWidth(cells[i]);
513
+ cells[i] = truncate(cells[i], Math.max(1, limit - rest));
514
+ row = cells.join(ROW_SEPARATOR);
515
+ }
516
+ return truncate(row, limit);
517
+ }
518
+
519
+ /** `record[key]` when `key` is an own property; inherited keys count as absent. */
520
+ function ownValue(record: object, key: string): unknown {
521
+ return Object.hasOwn(record, key) ? (record as Record<string, unknown>)[key] : undefined;
522
+ }
523
+
524
+ /** The one options notice, sanitised (a key may carry bidi or separator characters). */
525
+ function optionsNotice(problems: readonly string[], fallback: string): string {
526
+ return sanitise(`${STATUS_NOTICE_PREFIX}invalid TUI options (${problems.join("; ")}); ${fallback}`);
527
+ }
528
+
529
+ /**
530
+ * D7: TUI plugin options. Undefined/null → defaults, no notice. Not an object (or an array) → defaults and the
531
+ * notice `model-router status: invalid TUI options (not an object); using the defaults`. Only own keys are read.
532
+ * Each flag must be a boolean and `maxRows` an integer from 1 to 20; an invalid value keeps the default. Unknown
533
+ * keys are ignored. All problems (flags, then `maxRows`, then unknown keys) go into one sanitised notice:
534
+ * `model-router status: invalid TUI options (<problem>; …); using defaults for those keys`.
535
+ */
536
+ export function parseOptions(raw: unknown): ParsedOptions {
537
+ const options: StatusOptions = { ...DEFAULT_STATUS_OPTIONS };
538
+ if (raw === undefined || raw === null) return { options, notices: [] };
539
+ if (typeof raw !== "object" || Array.isArray(raw)) {
540
+ return { options, notices: [optionsNotice(["not an object"], "using the defaults")] };
541
+ }
542
+ const problems: string[] = [];
543
+ for (const key of FLAG_KEYS) {
544
+ const value = ownValue(raw, key);
545
+ if (value === undefined) continue;
546
+ if (typeof value === "boolean") options[key] = value;
547
+ else problems.push(`"${key}" must be true or false`);
548
+ }
549
+ const maxRows = ownValue(raw, "maxRows");
550
+ if (maxRows !== undefined) {
551
+ if (typeof maxRows === "number" && Number.isInteger(maxRows) && maxRows >= MAX_ROWS_MIN && maxRows <= MAX_ROWS_MAX) {
552
+ options.maxRows = maxRows;
553
+ } else {
554
+ problems.push(`"maxRows" must be an integer from ${MAX_ROWS_MIN} to ${MAX_ROWS_MAX}`);
555
+ }
556
+ }
557
+ const unknownKeys = Object.keys(raw).filter((key) => !KNOWN_KEYS.has(key));
558
+ if (unknownKeys.length > 0) problems.push(`unknown keys ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}`);
559
+ const notices = problems.length === 0 ? [] : [optionsNotice(problems, "using defaults for those keys")];
560
+ return { options, notices };
561
+ }