Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent): add arrow picker and skill states
Rahman55acfa66de2f
diff --git a/README.md b/README.mdindex 38d20f8b..734ddc37 100644--- a/README.md+++ b/README.md@@ -196,7 +196,7 @@ On the normal Ubuntu/WSL PATH (which includes `/usr/local/bin`) these work immedmso # interactive MSO setup/operations agentmso -hmso models # configure AI provider/API/OAuth connections (does not switch model)-mso model # select the active model from connected providers+mso model # arrow-key model picker from connected providersmso --continue # resume the latest durable MSO Agent sessionmso doctormso onboard # run/re-run guided setup; starts the built loopback runtime on WSL when needed@@ -207,6 +207,12 @@ mso skills available # reviewed installable skill listmso skills install ponytail caveman rtk -y```+Interactive model/provider menus use a native picker: **↑/↓** moves, typing filters, **Enter**+selects, and **Esc** cancels. No provider/model number has to be memorized. In the Agent slash+palette, executable skills carry lifecycle markers so their state is visible before and after use:+`◇ ready` → `◆ queued` (selected for the next message) → `✓ invoked` (actually sent with a model turn).+The compact status line mirrors queued/invoked skill state.+If it explicitly says the current shell cannot see the user launcher yet, run the one-line`export PATH="$HOME/.local/bin:$PATH"` it prints; new shells use the persisted profile entry.@@ -327,7 +333,7 @@ covers anything without one.mso # interactive setup/operations agent with MSO ASCII terminal UImso -h # grouped command list; `mso <command> --help` per commandmso models # configure AI provider/API/OAuth connections-mso model # select/switch the active model+mso model # arrow-key model picker / switch active modelmso --continue # resume the latest MSO Agent sessionmso --resume "session title" # resume by index/id/short id/title querymso doctor # includes HTTPS/login-origin diagnosisdiff --git a/bin/mso b/bin/msoindex 3f6a866e..516af1c4 100755--- a/bin/mso+++ b/bin/mso@@ -126,7 +126,7 @@# Docs: https://github.com/rahmanef63/msoset -euo pipefail-VERSION="1.5.5"+VERSION="1.5.6"ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"die() { echo "mso: $*" >&2; exit 1; }diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex a9a5dad5..c77ff470 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `agent` add arrow picker and skill states- `agent` align model and session terminal UX- `install` make upgrades agent-friendly- `agent` add interactive slash palettediff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.mdindex 7b87e7cd..b9f87724 100644--- a/docs/INFRASTRUCTURE-PROVIDERS.md+++ b/docs/INFRASTRUCTURE-PROVIDERS.md@@ -37,6 +37,8 @@ AI provider authentication and model selection are intentionally separate. `msocredentials/authentication and does **not** switch the active model; `mso model` owns selection.When no AI provider is connected, bare `mso` opens the provider manager first and then the modelpicker. If credentials already exist but the selection is unusable, only the model picker runs.+Both interactive surfaces use the same native picker: **↑/↓** navigate, typing filters, **Enter**+selects, and **Esc** cancels. Provider/model selection never falls back to a numbered prompt.The connection choices are OpenAI ChatGPT/Codex device OAuth plus the built-in API-key providers documented in[`INSTALL.md`](./INSTALL.md).@@ -52,6 +54,11 @@ Agent slash commands are:/doctor /tools /skills /clear /exit```+Slash skills expose runtime state instead of looking identical to ordinary commands: `◇ ready`+uses the normal skill color, `◆ queued` is amber after selection for the next message, and `✓ invoked`+is green after the skill was actually attached to a model request. `/skills` and the compact status line+show the same state, so the signal is consistent rather than decorative.+The prompt status line is dynamic: active `provider/model`, approximate current context (`ctx ~…`)with a catalog context-window denominator when available, provider-reported token usage when theupstream exposes it, turn count, last-turn duration, durable session id and working directory.diff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex a2e13b8f..b5f46cf2 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -133,6 +133,8 @@ After onboarding, use the two AI commands deliberately: `mso models` manages proconnections without changing the active model; `mso model` selects a model from providers that arealready connected. `mso models test` validates the currently selected connection (including theChatGPT/Codex subscription path), while `mso model list [provider]` shows selectable model IDs.+Interactive `mso model` / `mso models` menus are arrow-key pickers: **↑/↓** moves, typing filters,+**Enter** selects, and **Esc** cancels; numeric provider/model prompts are not part of the UX.Agent sessions are durable: `mso --continue` resumes the latest CLI session and`mso --resume <index|id|title>` resolves a prior session without weakening principal isolation.@@ -150,8 +152,10 @@ verify with `mso provider doctor`.After an AI provider is connected, bare `mso` launches the interactive MSO Agent. The agentuses the canonical MCP tool catalog internally: reads run directly, while write/exec calls-pause for terminal approval. See [`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md)-for the deployment/provider boundary.+pause for terminal approval. Skill lifecycle is explicit in the slash palette and status line:+`◇ ready` means discoverable/executable, `◆ queued` means selected for the next user message,+and `✓ invoked` means the skill instructions were actually attached to a model turn. See+[`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md) for the deployment/provider boundary.### WSL2diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 16c5a7dc..9f8a6b5f 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,6 +2,14 @@Running log of what shipped each phase. Newest at top.+## 2026-09-01 — Arrow-key model/provider picker + visible skill lifecycle — SHIPPED++MSO Agent 1.5.6 removes the last numeric prompt from the AI provider/model interaction path. `mso model`, the no-argument `mso models` manager, provider connect/remove selection, and catalog-provider selection now share one dependency-free native TTY picker. The current provider/model is preselected, ↑/↓ redraw in place with zero added newline scrollback, typing filters candidates, Enter selects, and Esc cancels. Direct scriptable forms such as `mso model openai-codex/gpt-5.6-terra` and `mso models add openrouter` remain unchanged.++Skill invocation state is now explicit and consistent across the slash palette, `/skills`, the invocation badge and the compact status line: `◇ ready` means trusted/executable, `◆ queued` means selected for the next message, and `✓ invoked` means the skill instructions were actually attached to a model turn. Queued state is amber; invoking/invoked state is green. Resuming or clearing a session clears ephemeral skill UI state so one session cannot visually leak the previous session's skill marker.++Regression coverage locks the picker/filter/wrap primitives, absence of numeric model/provider prompts, exact `/model` vs `/models` behavior, skill ready/queued/invoked state, and status propagation. Real PTY smoke verifies model current-item highlighting, ↓/↑ with zero LF output, Esc cancellation, and preservation of the active model.+## 2026-09-01 — Agent model/session UX parity + dynamic status — SHIPPEDMSO Agent 1.5.5 aligns the useful interaction contract of mature agent harnesses without copying their branding/runtime. The startup banner now uses the owner-specified 12-line Hybrid MSO geometry and exact six-stop True Color gradient (purple/indigo → blue → cyan → teal/emerald). AI configuration is split into two explicit surfaces: `mso models` manages provider API keys/OAuth/custom-provider connections **without switching the active model**, while `mso model` validates and selects only models available through connected providers. Exact `/model` now wins over the `/models` prefix in the slash palette; OpenRouter-style model IDs containing `/` are resolved against the current provider before being interpreted as a provider/model ref.diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjsindex 1e1f5e4f..5ff0f8ed 100644--- a/scripts/mso-agent-composer.mjs+++ b/scripts/mso-agent-composer.mjs@@ -53,13 +53,18 @@ function menuLines(items, selected, columns, C) {const label = " commands & skills ";const top = `╭─${label}${"─".repeat(Math.max(0, panelWidth - width(label) - 3))}╮`;const nameWidth = Math.min(32, Math.max(12, ...visible.map((item) => width(item.text) + 1)));- const metaWidth = Math.max(0, panelWidth - nameWidth - 7);+ const metaWidth = Math.max(0, panelWidth - nameWidth - 9);const body = visible.map((item, offset) => {const active = start + offset === selected;const marker = active ? `${C.blue}${C.bold}›${C.reset}` : " ";- const name = active ? `${C.blue}${C.bold}${pad(item.text, nameWidth)}${C.reset}` : pad(item.text, nameWidth);+ const stateColor = item.state === "queued" ? C.warn : ["invoking", "invoked"].includes(item.state) ? C.c : C.blue;+ const stateMark = item.kind === "skill"+ ? `${stateColor}${item.state === "invoked" ? "✓" : item.state === "ready" ? "◇" : "◆"}${C.reset}`+ : " ";+ const nameColor = item.kind === "skill" ? stateColor : active ? C.blue : "";+ const name = nameColor ? `${nameColor}${active ? C.bold : ""}${pad(item.text, nameWidth)}${C.reset}` : pad(item.text, nameWidth);const meta = metaWidth ? `${C.dim}${fit(item.meta || "", metaWidth)}${C.reset}` : "";- return `│ ${marker} ${name}${meta ? ` ${meta}` : ""}${" ".repeat(Math.max(0, metaWidth - width(fit(item.meta || "", metaWidth))))} │`;+ return `│ ${marker} ${stateMark} ${name}${meta ? ` ${meta}` : ""}${" ".repeat(Math.max(0, metaWidth - width(fit(item.meta || "", metaWidth))))} │`;});const hint = " ↑↓ navigate · Enter/Tab select · Esc close ";const bottom = `╰─${fit(hint, panelWidth - 3)}${"─".repeat(Math.max(0, panelWidth - width(fit(hint, panelWidth - 3)) - 3))}╯`;diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.tsindex ea6a0e3d..fef3e31b 100644--- a/scripts/mso-agent-composer.test.ts+++ b/scripts/mso-agent-composer.test.ts@@ -81,4 +81,30 @@ describe("MSO Agent interactive composer primitives", () => {composer.close();});++ it("renders skill lifecycle markers distinctly from commands", async () => {+ class FakeInput extends EventEmitter {+ isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; }+ }+ class FakeOutput { columns = 96; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }+ const input = new FakeInput(); const output = new FakeOutput();+ const colors = { blue: "<b>", warn: "<w>", c: "<g>", bold: "<B>", reset: "</>", dim: "<d>" };+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });+ const answer = composer.question("› ", { complete: (value: string) => value.startsWith("/") ? [+ { text: "/ready", meta: "ready", kind: "skill", state: "ready" },+ { text: "/queued", meta: "queued", kind: "skill", state: "queued" },+ { text: "/invoked", meta: "invoked", kind: "skill", state: "invoked" },+ ] : [] } as never);+ input.emit("keypress", "/", { name: "/", sequence: "/" });+ const rendered = output.chunks.join("");+ expect(rendered).toContain("◇");+ expect(rendered).toContain("◆");+ expect(rendered).toContain("✓");+ expect(rendered).toContain("<w>");+ expect(rendered).toContain("<g>");+ input.emit("keypress", undefined, { ctrl: true, name: "c" });+ input.emit("keypress", undefined, { ctrl: true, name: "c" });+ await answer; composer.close();+ });+});diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.tsindex b6c919ce..43fd9df2 100644--- a/scripts/mso-agent-contract.test.ts+++ b/scripts/mso-agent-contract.test.ts@@ -35,7 +35,9 @@ describe("MSO terminal agent contract", () => {]) expect(src).toContain(command);expect(src).toContain("Configure AI providers and authentication");expect(src).toContain("Select the active model from connected providers");- expect(src).toContain("selected for the next message");+ expect(src).toContain("queued");+ expect(src).toContain("invoking");+ expect(src).toContain("lastInvokedSkill");expect(src).toContain("AgentComposer");expect(src).toContain("slashCompletionItems");expect(src).toContain("renderStatusBar");diff --git a/scripts/mso-agent-session-ui.mjs b/scripts/mso-agent-session-ui.mjsindex ea844236..afb80fb5 100644--- a/scripts/mso-agent-session-ui.mjs+++ b/scripts/mso-agent-session-ui.mjs@@ -44,6 +44,8 @@ export async function resumeInto(session, query, rows = null) {agentSession: loaded,history: Array.isArray(loaded.history) ? loaded.history.slice(-48) : [],pendingSkill: null,+ activeSkill: null,+ lastInvokedSkill: null,titleOverride: loaded.title || null,usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },lastElapsedMs: 0,diff --git a/scripts/mso-agent-skills.mjs b/scripts/mso-agent-skills.mjsindex 75ca8834..7ff58a09 100644--- a/scripts/mso-agent-skills.mjs+++ b/scripts/mso-agent-skills.mjs@@ -11,6 +11,37 @@ function inside(root, cwd) {return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));}+function sameSkill(a, b) {+ return Boolean(a?.id && b?.id && String(a.id) === String(b.id));+}++export function skillRuntimeState(session, skill) {+ if (skill?.trust === "untrusted") return "blocked";+ if (sameSkill(session?.activeSkill, skill)) return "invoking";+ if (sameSkill(session?.pendingSkill, skill)) return "queued";+ if (sameSkill(session?.lastInvokedSkill, skill)) return "invoked";+ return "ready";+}++export function skillStateVisual(state, C) {+ if (state === "blocked") return { marker: "!", label: "blocked", color: C.warn };+ if (state === "queued") return { marker: "◆", label: "queued", color: C.warn };+ if (state === "invoking") return { marker: "◆", label: "invoking", color: C.c };+ if (state === "invoked") return { marker: "✓", label: "invoked", color: C.c };+ return { marker: "◇", label: "ready", color: C.blue };+}++export function beginSkillInvocation(session, skill, C) {+ if (!skill) return;+ session.activeSkill = skill;+ const scope = skill.project?.name ? `project ${skill.project.name}` : "global";+ console.log(`${C.c}${C.bold}◆ skill /${skill.name} invoking${C.reset}${C.dim} · ${scope} · ${skill.trust || "trusted"}${C.reset}`);+}++export function endSkillInvocation(session, skill) {+ if (skill) session.activeSkill = null;+}+export function currentSkillProject(skillsData, cwd = process.cwd()) {const projects = new Map();for (const skill of skillRows(skillsData)) {@@ -109,11 +140,13 @@ export function printSkills(session, C, query = "", cwd = process.cwd()) {const visible = rows.slice(0, 80);for (const skill of visible) {const scope = skill.project?.name ? `project:${skill.project.name}` : "global";- const trust = skill.trust === "untrusted" ? `${C.warn}untrusted${C.reset}` : skill.trust || "";+ const trust = skill.trust === "untrusted" ? "untrusted" : skill.trust || "";+ const state = skillRuntimeState(session, skill);+ const visual = skillStateVisual(state, C);const description = skill.description? ` — ${String(skill.description).replace(/[\r\n\t]+/g, " ").slice(0, 120)}`: "";- console.log(` ${C.blue}/${skill.name}${C.reset} ${C.dim}${scope}${trust ? ` · ${trust}` : ""}${C.reset}${description}`);+ console.log(` ${visual.color}${visual.marker} /${skill.name}${C.reset} ${C.dim}${visual.label} · ${scope}${trust ? ` · ${trust}` : ""}${C.reset}${description}`);}if (rows.length > visible.length) console.log(`${C.dim}… ${rows.length - visible.length} more; refine with /skills <query>${C.reset}`);console.log(`${C.dim}Use /<skill> [prompt], or /skill <exact-id> [prompt] for an ambiguous project skill.${C.reset}`);diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjsindex 9f9db6e3..6c01cb29 100644--- a/scripts/mso-agent-slash.mjs+++ b/scripts/mso-agent-slash.mjs@@ -1,5 +1,5 @@import process from "node:process";-import { currentSkillProject, resolveSlashSkill, slashSkillNames } from "./mso-agent-skills.mjs";+import { currentSkillProject, resolveSlashSkill, skillRuntimeState, slashSkillNames } from "./mso-agent-skills.mjs";export const BUILTIN_SLASH_ITEMS = [{ text: "/help", meta: "Show commands and shortcuts", kind: "command" },@@ -23,20 +23,23 @@ export const BUILTIN_SLASH_ITEMS = [{ text: "/exit", meta: "Exit MSO Agent", kind: "command" },];-function skillItem(skillsData, name, cwd) {+function skillItem(skillsData, name, cwd, session) {const { skill } = resolveSlashSkill(skillsData, name, cwd);if (!skill || skill.trust === "untrusted") return null;const scope = skill.project?.name ? `skill · ${skill.project.name}` : "skill · global";const description = String(skill.description || "").replace(/[\r\n\t]+/g, " ").trim();+ const state = skillRuntimeState(session, skill);return {text: `/${name}`,- meta: `${scope}${description ? ` — ${description}` : ""}`,+ meta: `${state} · ${scope}${description ? ` — ${description}` : ""}`,kind: "skill",+ state,+ skillId: String(skill.id),project: skill.project || null,};}-export function slashCompletionItems(skillsData, input, cwd = process.cwd()) {+export function slashCompletionItems(skillsData, input, cwd = process.cwd(), session = /** @type {any} */ (null)) {const text = String(input || "").trimStart();if (!text.startsWith("/") || /\s/.test(text)) return [];const query = text.toLowerCase();@@ -45,7 +48,7 @@ export function slashCompletionItems(skillsData, input, cwd = process.cwd()) {const projectSkills = [];const globalSkills = [];for (const name of names) {- const item = skillItem(skillsData, name, cwd);+ const item = skillItem(skillsData, name, cwd, session);if (!item) continue;if (current && item.project?.id === current.id) projectSkills.push(item);else globalSkills.push(item);diff --git a/scripts/mso-agent-slash.test.ts b/scripts/mso-agent-slash.test.tsindex c7777759..be194cec 100644--- a/scripts/mso-agent-slash.test.ts+++ b/scripts/mso-agent-slash.test.ts@@ -37,4 +37,22 @@ describe("MSO Agent slash completion catalog", () => {expect(project?.id).toBe("root/a");expect(row.meta).toContain("project design helper");});++ it("exposes ready, queued, and invoked skill state to the slash palette", () => {+ const ready = slashCompletionItems(skills, "/design", "/home/rahman")[0];+ expect(ready).toMatchObject({ kind: "skill", state: "ready", skillId: "global-design" });++ const queued = slashCompletionItems(skills, "/design", "/home/rahman", {+ pendingSkill: { id: "global-design", name: "design" },+ })[0];+ expect(queued).toMatchObject({ state: "queued" });+ expect(queued.meta).toContain("queued");++ const invoked = slashCompletionItems(skills, "/design", "/home/rahman", {+ lastInvokedSkill: { id: "global-design", name: "design" },+ })[0];+ expect(invoked).toMatchObject({ state: "invoked" });+ expect(invoked.meta).toContain("invoked");+ });+});diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjsindex 58859321..cf7696e0 100644--- a/scripts/mso-agent-status.mjs+++ b/scripts/mso-agent-status.mjs@@ -50,6 +50,13 @@ function homeShort(cwd) {return cwd;}+function skillStatus(session) {+ if (session?.activeSkill?.name) return { state: "invoking", name: session.activeSkill.name };+ if (session?.pendingSkill?.name) return { state: "queued", name: session.pendingSkill.name };+ if (session?.lastInvokedSkill?.name) return { state: "invoked", name: session.lastInvokedSkill.name };+ return null;+}+export function statusParts(session, cwd = process.cwd()) {const provider = String(session?.state?.config?.provider || "—");const model = String(session?.state?.config?.model || "—");@@ -58,8 +65,10 @@ export function statusParts(session, cwd = process.cwd()) {const shortSession = String(session?.agentSession?.id || "—").replace(/^\d{8}_\d{6}_/, "");const usage = session?.usage || { totalTokens: 0 };const elapsed = Number(session?.lastElapsedMs || 0);+ const skill = skillStatus(session);return [`${provider}/${model}`,+ skill ? `skill ${skill.state === "invoked" ? "✓" : "◆"} /${skill.name}${skill.state === "queued" ? " queued" : skill.state === "invoking" ? " invoking" : ""}` : null,ctx.limit ? `ctx ~${compactNumber(ctx.used)}/${compactNumber(ctx.limit)} ${ctx.percent}%` : `ctx ~${compactNumber(ctx.used)}/?`,usage.totalTokens > 0 ? `tokens ${compactNumber(usage.totalTokens)}` : null,`turns ${turns}`,@@ -86,6 +95,7 @@ export function detailedStatus(session, cwd = process.cwd()) {contextWindow: ctx.limit,contextPercent: ctx.percent,providerReportedUsage: usage,+ skill: skillStatus(session),turns: (session?.history || []).filter((row) => row?.role === "user").length,session: session?.agentSession?.id || null,title: session?.agentSession?.title || null,@@ -102,6 +112,7 @@ export function printDetailedStatus(session, C, cwd = process.cwd()) {if (row.providerReportedUsage.totalTokens > 0) {console.log(` tokens ${row.providerReportedUsage.totalTokens} total · ${row.providerReportedUsage.inputTokens} in · ${row.providerReportedUsage.outputTokens} out`);} else console.log(" tokens provider has not reported usage in this process; context remains estimated");+ if (row.skill) console.log(` skill ${row.skill.state} /${row.skill.name}`);console.log(` turns ${row.turns}`);console.log(` session ${row.session}`);console.log(` title ${row.title || "MSO Agent session"}`);diff --git a/scripts/mso-agent-status.test.ts b/scripts/mso-agent-status.test.tsindex 80676fe3..a4c3ea56 100644--- a/scripts/mso-agent-status.test.ts+++ b/scripts/mso-agent-status.test.ts@@ -20,4 +20,17 @@ describe("MSO Agent dynamic status", () => {expect(parts.join(" ")).toContain("openai-codex/gpt-5.6-sol");expect(parts.join(" ")).toContain("tokens 22");});++ it("shows whether a skill is queued or really invoked", () => {+ const base = {+ state: { config: { provider: "openai-codex", model: "gpt-5.6-sol" }, modelMeta: null },+ history: [], usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },+ agentSession: { id: "20260901_120000_deadbeef" },+ };+ const queued = statusParts({ ...base, pendingSkill: { id: "design", name: "design" } }, "/tmp").join(" ");+ expect(queued).toContain("skill ◆ /design queued");+ const invoked = statusParts({ ...base, lastInvokedSkill: { id: "design", name: "design" } }, "/tmp").join(" ");+ expect(invoked).toContain("skill ✓ /design");+ });+});diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex 47c5d91a..1fcfa50f 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -2,7 +2,7 @@import { spawnSync } from "node:child_process";import process from "node:process";import { canonicalAgentApproval } from "../lib/agent/approval.mjs";-import { loadSlashSkill, printSkillChoices, printSkills, resolveSlashSkill } from "./mso-agent-skills.mjs";+import { beginSkillInvocation, endSkillInvocation, loadSlashSkill, printSkillChoices, printSkills, resolveSlashSkill } from "./mso-agent-skills.mjs";import { AgentComposer } from "./mso-agent-composer.mjs";import { slashCompletionItems } from "./mso-agent-slash.mjs";import { addUsage, printDetailedStatus, renderStatusBar } from "./mso-agent-status.mjs";@@ -50,22 +50,26 @@ async function executeTool(rl, tool, call, agentSession) {}async function agentRound(rl, session, skillContext = null) {- const startedAt = Date.now();- for (let turn = 0; turn < 10; turn++) {- const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext);- session.usage = addUsage(session.usage, result.usage);- session.lastElapsedMs = Date.now() - startedAt;- session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });- if (!result.toolUses.length) return;- const results = [];- for (const call of result.toolUses) {- const tool = session.state.tools.find((row) => row.name === call.name);- const outcome = await executeTool(rl, tool, call, session.agentSession);- results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });+ const startedAt = Date.now(); beginSkillInvocation(session, skillContext, C);+ try {+ for (let turn = 0; turn < 10; turn++) {+ const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext); if (skillContext) session.lastInvokedSkill = skillContext;+ session.usage = addUsage(session.usage, result.usage);+ session.lastElapsedMs = Date.now() - startedAt;+ session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });+ if (!result.toolUses.length) return;+ const results = [];+ for (const call of result.toolUses) {+ const tool = session.state.tools.find((row) => row.name === call.name);+ const outcome = await executeTool(rl, tool, call, session.agentSession);+ results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });+ }+ session.history.push({ role: "tool", results });}- session.history.push({ role: "tool", results });+ console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);+ } finally {+ endSkillInvocation(session, skillContext);}- console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);}function runCli(args) {@@ -84,7 +88,7 @@ async function selectSlashSkill(rl, session, requested, prompt = "") {const scope = loaded.project?.name ? `project ${loaded.project.name}` : "global";if (!prompt.trim()) {session.pendingSkill = loaded;- console.log(`${C.c}✓ /${loaded.name}${C.reset} selected for the next message · ${scope}`);+ console.log(`${C.warn}${C.bold}◆ /${loaded.name} queued${C.reset}${C.dim} · next message · ${scope}${C.reset}`);return "handled";}session.history.push({ role: "user", text: prompt.trim() });@@ -149,7 +153,7 @@ async function slash(rl, line, session) {case "/tools": for (const tool of session.state.tools) console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`); return "handled";case "/skills": printSkills(session, C, args.join(" ")); return "handled";case "/skill": if (!args[0]) { console.log("usage: /skill <name-or-exact-id> [prompt]"); return "handled"; } return selectSlashSkill(rl, session, args[0], args.slice(1).join(" "));- case "/clear": session.history = []; session.pendingSkill = null; await persistSession(session); console.log("conversation cleared."); return "handled";+ case "/clear": Object.assign(session, { history: [], pendingSkill: null, activeSkill: null, lastInvokedSkill: null }); await persistSession(session); console.log("conversation cleared."); return "handled";case "/exit": return "exit";default: return selectSlashSkill(rl, session, cmd.slice(1), args.join(" "));}@@ -172,13 +176,15 @@ async function main() {agentSession,history: Array.isArray(agentSession.history) ? agentSession.history.slice(-48) : [],pendingSkill: null,+ activeSkill: null,+ lastInvokedSkill: null,titleOverride: requested ? (agentSession.title || null) : null,usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },lastElapsedMs: 0,statusBar: true,};const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C });- const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd());+ const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session);try {while (true) {let line = "";diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.shindex c3f71c53..76458563 100755--- a/scripts/mso-cli-agent.sh+++ b/scripts/mso-cli-agent.sh@@ -56,6 +56,62 @@ ai_provider_connected() {' <<<"$cfg" >/dev/null 2>&1}+# Reusable native arrow-key selector. Candidate rows arrive as TSV on stdin:+# value<TAB>label<TAB>metadata<TAB>state. UI is rendered directly on /dev/tty;+# stdout contains only the selected value so callers can safely use command substitution.+tui_select() {+ local title="$1" active="${2-}"+ tty_ok || return 2+ node "$ROOT/scripts/mso-tui-select.mjs" "$title" "$active"+}++connected_ai_provider_ids() {+ local cfg="$1"+ { jq -r '.providers[]?.id' <<<"$cfg"; if [ "$(jq -r '.hasApiKey // false' <<<"$cfg")" = true ]; then jq -r '.provider // empty' <<<"$cfg"; fi; } |+ awk 'NF && !seen[$0]++'+}++connected_ai_provider_picker_rows() {+ local cfg="$1" active="${2-}" id kind auth state+ while IFS= read -r id; do+ kind=$(jq -r --arg p "$id" 'first(.providers[]? | select(.id==$p) | .kind) // (if .provider==$p and .hasApiKey then "key/env" else "configured" end)' <<<"$cfg")+ auth=$(jq -r --arg p "$id" 'first(.providers[]? | select(.id==$p) | .masked) // (if .provider==$p and .hasApiKey then "configured" else "" end)' <<<"$cfg")+ [ "$id" = "$active" ] && state=current || state=""+ printf '%s %s %s%s%s %s+' "$id" "$id" "$kind" "$([ -n "$auth" ] && printf ' · ' || true)" "$auth" "$state"+ done < <(connected_ai_provider_ids "$cfg")+}++known_ai_provider_picker_rows() {+ cat <<'ROWS'+openai-codex openai-codex ChatGPT subscription · device OAuth+anthropic anthropic API key+openai openai OpenAI Platform API key+openrouter openrouter API key · multi-model router+google google Gemini API key+groq groq API key+xai xai API key+deepseek deepseek API key+mistral mistral API key+custom custom OpenAI/Anthropic-compatible endpoint+ROWS+}++model_picker_rows() {+ local data="$1" current="${2-}"+ jq -r --arg current "$current" '.models[] |+ [+ .id,+ .id,+ ((if (.context // 0) > 0 then "ctx " + ((.context // 0)|tostring) else "ctx —" end)+ + " · tools " + (if .tools then "yes" else "—" end)+ + " · reasoning " + (if .reasoning then "yes" else "—" end)),+ (if .id==$current then "current" else "" end)+ ] | @tsv' <<<"$data"+}++picker_cancelled() { echo " — selection cancelled"; }+print_ai_providers() {local cfg="$1"echo "AI providers/auth"@@ -179,12 +235,13 @@ select_model_ref() {}run_model_setup() {- local sub="${1:-}" cfg provider data choice count selected+ local sub="${1:-}" cfg provider data model active_provider active_model rcensure_local_cli_device; ensure_onboard_runtime; jget "/api/auth/me" >/dev/nullcfg=$(ai_model_config)case "$sub" incurrent|show)- printf '%s/%s\n' "$(jq -r '.provider // "—"' <<<"$cfg")" "$(jq -r '.model // "—"' <<<"$cfg")"; return ;;+ printf '%s/%s+' "$(jq -r '.provider // "—"' <<<"$cfg")" "$(jq -r '.model // "—"' <<<"$cfg")"; return ;;list)provider="${2:-$(jq -r '.provider // ""' <<<"$cfg")}"; [ -n "$provider" ] || die "no active provider"ai_provider_connected "$provider" "$cfg" || die "$provider is not connected; run: mso models add $provider"@@ -197,36 +254,45 @@ run_model_setup() {*) select_model_ref "$sub"; return ;;esactty_ok || die "mso model without a ref needs an interactive terminal; use: mso model list"- echo "Active model: $(jq -r '.provider+"/"+.model' <<<"$cfg")"- echo "Connected providers:"- mapfile -t providers < <({ jq -r '.providers[]?.id' <<<"$cfg"; if [ "$(jq -r '.hasApiKey // false' <<<"$cfg")" = true ]; then jq -r '.provider' <<<"$cfg"; fi; } | awk 'NF && !seen[$0]++')- [ "${#providers[@]}" -gt 0 ] || die "no AI provider connected; run: mso models"- for i in "${!providers[@]}"; do printf ' %d) %s%s\n' "$((i+1))" "${providers[$i]}" "$([ "${providers[$i]}" = "$(jq -r '.provider' <<<"$cfg")" ] && printf ' [active]' || true)"; done- tty_line "Provider [1]: " 1; choice="$REPLY"; [[ "$choice" =~ ^[0-9]+$ ]] || die "choose a provider number"- selected=$((choice-1)); [ "$selected" -ge 0 ] && [ "$selected" -lt "${#providers[@]}" ] || die "provider choice out of range"- provider="${providers[$selected]}"- data=$(ai_model_catalog "$provider" "$cfg"); count=$(jq '.models|length' <<<"$data")- [ "$count" -gt 0 ] || die "no discoverable models for $provider"- echo; print_model_catalog "$provider" "$cfg"- echo- mapfile -t model_ids < <(jq -r '.models[].id' <<<"$data")- for i in "${!model_ids[@]}"; do printf ' %d) %s\n' "$((i+1))" "${model_ids[$i]}"; done- tty_line "Model [1]: " 1; choice="$REPLY"; [[ "$choice" =~ ^[0-9]+$ ]] || die "choose a model number"- selected=$((choice-1)); [ "$selected" -ge 0 ] && [ "$selected" -lt "${#model_ids[@]}" ] || die "model choice out of range"- select_model_ref "$provider/${model_ids[$selected]}"+ active_provider=$(jq -r '.provider // ""' <<<"$cfg"); active_model=$(jq -r '.model // ""' <<<"$cfg")+ echo "Active model: ${active_provider:-—}/${active_model:-—}"+ if ! connected_ai_provider_ids "$cfg" | grep -q .; then die "no AI provider connected; run: mso models"; fi+ provider=$(connected_ai_provider_picker_rows "$cfg" "$active_provider" | tui_select "Select AI provider" "$active_provider") || {+ rc=$?; [ "$rc" -eq 130 ] && { picker_cancelled; return 0; }; return "$rc";+ }+ data=$(ai_model_catalog "$provider" "$cfg")+ jq -e '.models | length > 0' <<<"$data" >/dev/null 2>&1 || die "no discoverable models for $provider"+ [ "$provider" = "$active_provider" ] && model="$active_model" || model=""+ model=$(model_picker_rows "$data" "$model" | tui_select "Select model · $provider" "$model") || {+ rc=$?; [ "$rc" -eq 130 ] && { picker_cancelled; return 0; }; return "$rc";+ }+ select_model_ref "$provider/$model"}run_models() {- local sub="${1:-}" cfg provider choice+ local sub="${1:-}" cfg provider action rcensure_local_cli_device; ensure_onboard_runtime; jget "/api/auth/me" >/dev/nullcfg=$(ai_model_config)case "$sub" instatus|list) print_ai_providers "$cfg" ;;add|auth)- provider="${2-}"; [ -n "$provider" ] || die "usage: mso models $sub <provider>"+ provider="${2-}"+ if [ -z "$provider" ] && tty_ok; then+ provider=$(known_ai_provider_picker_rows | tui_select "Connect AI provider" "openai-codex") || {+ rc=$?; [ "$rc" -eq 130 ] && { picker_cancelled; return 0; }; return "$rc";+ }+ fi+ [ -n "$provider" ] || die "usage: mso models $sub <provider>"configure_ai_provider "$provider" ;;rm|remove)- provider="${2-}"; [ -n "$provider" ] || die "usage: mso models rm <provider>"+ provider="${2-}"+ if [ -z "$provider" ] && tty_ok; then+ if ! connected_ai_provider_ids "$cfg" | grep -q .; then echo " · no connected providers to remove"; return; fi+ provider=$(connected_ai_provider_picker_rows "$cfg" "" | tui_select "Remove AI provider" "") || {+ rc=$?; [ "$rc" -eq 130 ] && { picker_cancelled; return 0; }; return "$rc";+ }+ fi+ [ -n "$provider" ] || die "usage: mso models rm <provider>"jdel "/api/config?provider=$(enc "$provider")" >/dev/null; echo " ✓ removed AI provider: $provider" ;;catalog)provider="${2:-$(jq -r '.provider // ""' <<<"$cfg")}"; [ -n "$provider" ] || die "provider required"@@ -234,18 +300,39 @@ run_models() {test) jpost "/api/models/test" ;;'')tty_ok || { print_ai_providers "$cfg"; return; }- print_ai_providers "$cfg"; echo- echo " 0) Done"- echo " 1) Add/auth provider"- echo " 2) Remove provider"- echo " 3) Browse model catalog"- tty_line "Choose [0]: " 0; choice="$REPLY"- case "$choice" in- 1) tty_line "Provider [openai-codex|anthropic|openai|openrouter|google|groq|xai|deepseek|mistral|custom]: " "openai-codex"; configure_ai_provider "$REPLY" ;;- 2) tty_line "Provider id: " ""; [ -n "$REPLY" ] && run_models rm "$REPLY" ;;- 3) tty_line "Provider [$(jq -r '.provider // ""' <<<"$cfg")]: " "$(jq -r '.provider // ""' <<<"$cfg")"; print_model_catalog "$REPLY" "$cfg" ;;- *) : ;;- esac ;;+ while true; do+ cfg=$(ai_model_config)+ echo; print_ai_providers "$cfg"; echo+ action=$(cat <<'ROWS' | tui_select "AI provider/auth manager" "done"+done Done Return to MSO Agent+add Add / authenticate provider API key, OAuth, or custom endpoint+remove Remove provider Forget one stored provider credential+catalog Browse model catalog Inspect models for a connected provider+test Test active connection Validate the selected provider/model+ROWS+) || { rc=$?; [ "$rc" -eq 130 ] && return 0; return "$rc"; }+ case "$action" in+ done) return ;;+ add)+ provider=$(known_ai_provider_picker_rows | tui_select "Connect AI provider" "openai-codex") || {+ rc=$?; [ "$rc" -eq 130 ] && continue; return "$rc";+ }+ configure_ai_provider "$provider" ;;+ remove)+ if ! connected_ai_provider_ids "$cfg" | grep -q .; then echo " · no connected providers to remove"; continue; fi+ provider=$(connected_ai_provider_picker_rows "$cfg" "" | tui_select "Remove AI provider" "") || {+ rc=$?; [ "$rc" -eq 130 ] && continue; return "$rc";+ }+ run_models rm "$provider" ;;+ catalog)+ if ! connected_ai_provider_ids "$cfg" | grep -q .; then echo " · connect a provider first"; continue; fi+ provider=$(connected_ai_provider_picker_rows "$cfg" "$(jq -r '.provider // ""' <<<"$cfg")" | tui_select "Browse provider models" "$(jq -r '.provider // ""' <<<"$cfg")") || {+ rc=$?; [ "$rc" -eq 130 ] && continue; return "$rc";+ }+ echo; print_model_catalog "$provider" "$cfg" || true ;;+ test) echo; jpost "/api/models/test" | jq . ;;+ esac+ done ;;*) die "usage: mso models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]" ;;esac}diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.tsindex 4d68ebb1..afa59b41 100644--- a/scripts/mso-model-dx-contract.test.ts+++ b/scripts/mso-model-dx-contract.test.ts@@ -8,12 +8,13 @@ const agentCli = fs.readFileSync(path.join(__dirname, "mso-cli-agent.sh"), "utf8const configRoute = fs.readFileSync(path.join(root, "app/api/config/route.ts"), "utf8");const oauthRoute = fs.readFileSync(path.join(root, "app/api/oauth/[provider]/route.ts"), "utf8");const slash = fs.readFileSync(path.join(__dirname, "mso-agent-slash.mjs"), "utf8");+const picker = fs.readFileSync(path.join(__dirname, "mso-tui-select.mjs"), "utf8");-const all = [cli, agentCli, configRoute, oauthRoute, slash].join("\n");+const all = [cli, agentCli, configRoute, oauthRoute, slash, picker].join("\n");describe("MSO model/provider/session CLI contract", () => {it("keeps provider auth (`models`) separate from active selection (`model`)", () => {- expect(cli).toContain('VERSION="1.5.5"');+ expect(cli).toContain('VERSION="1.5.6"');expect(cli).toContain("models * Configure AI providers/auth");expect(cli).toContain("model [ref] Select active model");expect(agentCli).toContain("run_models()");@@ -27,6 +28,19 @@ describe("MSO model/provider/session CLI contract", () => {expect(slash).toContain('text: "/model", meta: "Select the active model from connected providers"');});++ it("uses one native arrow-key picker instead of numeric provider/model prompts", () => {+ expect(agentCli).toContain('tui_select "Select AI provider"');+ expect(agentCli).toContain('tui_select "Select model · $provider"');+ expect(agentCli).toContain('tui_select "AI provider/auth manager"');+ expect(agentCli).not.toContain('Provider [1]:');+ expect(agentCli).not.toContain('Model [1]:');+ expect(agentCli).not.toContain('choose a provider number');+ expect(agentCli).not.toContain('choose a model number');+ expect(picker).toContain("↑↓ navigate · type filter · Enter select · Esc cancel");+ expect(picker).toContain("nextPickerIndex");+ });+it("supports explicit and slash-containing model IDs without losing provider intent", () => {expect(agentCli).toContain("Model IDs themselves may contain slashes");expect(agentCli).toContain("mso model set <provider> <model>");diff --git a/scripts/mso-tui-select.mjs b/scripts/mso-tui-select.mjsnew file mode 100755index 00000000..0b4e1db4--- /dev/null+++ b/scripts/mso-tui-select.mjs@@ -0,0 +1,161 @@+#!/usr/bin/env node+import fs from "node:fs";+import process from "node:process";+import readline from "node:readline";+import tty from "node:tty";++const CLEAR = "\x1b[2K";+const UP = (n) => n > 0 ? `\x1b[${n}A` : "";+const DOWN = (n) => n > 0 ? `\x1b[${n}B` : "";+const DIM = process.env.NO_COLOR ? "" : "\x1b[2m";+const BOLD = process.env.NO_COLOR ? "" : "\x1b[1m";+const BLUE = process.env.NO_COLOR ? "" : "\x1b[38;2;69;142;255m";+const GREEN = process.env.NO_COLOR ? "" : "\x1b[38;2;46;229;157m";+const RESET = process.env.NO_COLOR ? "" : "\x1b[0m";++const clean = (value) => String(value ?? "").replace(/[\r\n\t]+/g, " ").trim();+const visibleWidth = (value) => Array.from(String(value ?? "").replace(/\x1b\[[0-9;]*m/g, "")).length;+const fit = (value, max) => {+ const chars = Array.from(clean(value));+ if (chars.length <= max) return chars.join("");+ return max <= 1 ? "…".slice(0, max) : `${chars.slice(0, max - 1).join("")}…`;+};+const pad = (value, max) => {+ const out = fit(value, max);+ return out + " ".repeat(Math.max(0, max - visibleWidth(out)));+};++export function parsePickerItems(raw) {+ return String(raw || "").split(/\r?\n/).filter(Boolean).map((line) => {+ const [value = "", label = "", meta = "", state = ""] = line.split("\t");+ return { value, label: label || value, meta, state };+ }).filter((item) => item.value);+}++export function filterPickerItems(items, query) {+ const q = clean(query).toLowerCase();+ if (!q) return items.slice();+ return items.filter((item) => `${item.label} ${item.value} ${item.meta}`.toLowerCase().includes(q));+}++export function pickerWindow(items, selected, size = 9) {+ if (!items.length) return { start: 0, rows: [] };+ const count = Math.min(Math.max(1, size), items.length);+ const idx = Math.min(Math.max(0, selected), items.length - 1);+ const start = Math.max(0, Math.min(idx - Math.floor(count / 2), items.length - count));+ return { start, rows: items.slice(start, start + count) };+}++export function nextPickerIndex(length, selected, direction) {+ if (!length) return 0;+ return (selected + direction + length) % length;+}++function panel(items, selected, title, query, columns) {+ const width = Math.max(48, Math.min(96, Number(columns || 96) - 2));+ const { start, rows } = pickerWindow(items, selected, 9);+ const titleText = ` ${title} `;+ const top = `╭─${titleText}${"─".repeat(Math.max(0, width - visibleWidth(titleText) - 3))}╮`;+ const search = query ? `filter: ${query}` : "type to filter";+ const lines = [`${BLUE}${top}${RESET}`, `│ ${DIM}${pad(search, width - 4)}${RESET} │`];+ if (!rows.length) lines.push(`│ ${DIM}${pad("No matches", width - 4)}${RESET} │`);+ for (let offset = 0; offset < rows.length; offset++) {+ const item = rows[offset];+ const active = start + offset === selected;+ const current = item.state === "current";+ const marker = active ? `${BLUE}${BOLD}›${RESET}` : " ";+ const currentMark = current ? `${GREEN}●${RESET}` : " ";+ const prefixWidth = 5;+ const labelWidth = Math.max(14, Math.min(38, Math.floor((width - prefixWidth) * 0.48)));+ const metaWidth = Math.max(0, width - prefixWidth - labelWidth - 4);+ const label = active ? `${BLUE}${BOLD}${pad(item.label, labelWidth)}${RESET}` : pad(item.label, labelWidth);+ const meta = metaWidth ? `${DIM}${pad(item.meta, metaWidth)}${RESET}` : "";+ lines.push(`│ ${marker} ${currentMark} ${label}${meta ? ` ${meta}` : ""} │`);+ }+ const hint = " ↑↓ navigate · type filter · Enter select · Esc cancel ";+ lines.push(`${BLUE}╰─${fit(hint, width - 3)}${"─".repeat(Math.max(0, width - visibleWidth(fit(hint, width - 3)) - 3))}╯${RESET}`);+ return lines;+}++async function run() {+ const title = clean(process.argv[2] || "Select");+ const activeValue = String(process.argv[3] || "");+ const items = parsePickerItems(fs.readFileSync(0, "utf8"));+ if (!items.length) process.exit(2);++ const inFd = fs.openSync("/dev/tty", "r");+ const outFd = fs.openSync("/dev/tty", "w");+ const input = new tty.ReadStream(inFd);+ const output = new tty.WriteStream(outFd);+ readline.emitKeypressEvents(input);+ const wasRaw = Boolean(input.isRaw);+ let query = "";+ let visible = items.slice();+ let selected = Math.max(0, visible.findIndex((item) => item.value === activeValue));+ let reserved = 0;++ const reserve = (rows) => {+ if (rows <= reserved) return;+ if (reserved) output.write(DOWN(reserved));+ for (let i = reserved; i < rows; i++) output.write("\r\n");+ output.write(`${UP(rows)}\r`);+ reserved = rows;+ };+ const erase = () => {+ output.write(`\r${CLEAR}`);+ for (let i = 0; i < reserved; i++) output.write(`${DOWN(1)}\r${CLEAR}`);+ if (reserved) output.write(`${UP(reserved)}\r`);+ };+ const render = () => {+ const lines = panel(visible, selected, title, query, output.columns);+ reserve(lines.length - 1);+ erase();+ output.write(lines[0]);+ for (const line of lines.slice(1)) output.write(`${DOWN(1)}\r${CLEAR}${line}`);+ if (lines.length > 1) output.write(UP(lines.length - 1));+ output.write("\r");+ };+ const cleanup = () => {+ input.off("keypress", onKey);+ if (typeof input.setRawMode === "function") input.setRawMode(wasRaw);+ input.pause();+ erase();+ };+ const refilter = () => {+ visible = filterPickerItems(items, query);+ const activeIndex = visible.findIndex((item) => item.value === activeValue);+ selected = activeIndex >= 0 ? activeIndex : 0;+ render();+ };+ const finish = (code, value = "") => {+ cleanup();+ if (value) process.stdout.write(value);+ process.exit(code);+ };+ const onKey = (str, key = {}) => {+ if (key.ctrl && key.name === "c") return finish(130);+ if (key.name === "escape") return finish(130);+ if (key.name === "up") { selected = nextPickerIndex(visible.length, selected, -1); return render(); }+ if (key.name === "down") { selected = nextPickerIndex(visible.length, selected, 1); return render(); }+ if (key.name === "home") { selected = 0; return render(); }+ if (key.name === "end") { selected = Math.max(0, visible.length - 1); return render(); }+ if (key.name === "return" || key.name === "enter") {+ return visible[selected] ? finish(0, visible[selected].value) : undefined;+ }+ if (key.name === "backspace") { query = Array.from(query).slice(0, -1).join(""); return refilter(); }+ if (key.ctrl && key.name === "u") { query = ""; return refilter(); }+ if (str && !key.ctrl && !key.meta && !/[\u0000-\u001f\u007f]/u.test(str)) { query += str; return refilter(); }+ };++ input.on("keypress", onKey);+ input.resume();+ if (typeof input.setRawMode === "function") input.setRawMode(true);+ render();+}++if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) {+ run().catch((error) => {+ process.stderr.write(`mso picker: ${error instanceof Error ? error.message : String(error)}\n`);+ process.exit(2);+ });+}diff --git a/scripts/mso-tui-select.test.ts b/scripts/mso-tui-select.test.tsnew file mode 100644index 00000000..2d6e7dd4--- /dev/null+++ b/scripts/mso-tui-select.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import { filterPickerItems, nextPickerIndex, parsePickerItems, pickerWindow } from "./mso-tui-select.mjs";++const rows = parsePickerItems([+ "gpt-5.6-sol\tgpt-5.6-sol\tcurrent model\tcurrent",+ "gpt-5.6-terra\tgpt-5.6-terra\treasoning\t",+ "gpt-5.6-luna\tgpt-5.6-luna\tfast\t",+].join("\n"));++describe("MSO native TUI picker", () => {+ it("parses value/label/meta/state rows without numeric choice semantics", () => {+ expect(rows[0]).toEqual({ value: "gpt-5.6-sol", label: "gpt-5.6-sol", meta: "current model", state: "current" });+ });++ it("filters by labels, values, and metadata", () => {+ expect(filterPickerItems(rows, "terra").map((row: { value: string }) => row.value)).toEqual(["gpt-5.6-terra"]);+ expect(filterPickerItems(rows, "fast").map((row: { value: string }) => row.value)).toEqual(["gpt-5.6-luna"]);+ });++ it("wraps arrow selection and keeps the selected row visible", () => {+ expect(nextPickerIndex(3, 0, -1)).toBe(2);+ expect(nextPickerIndex(3, 2, 1)).toBe(0);+ const many = Array.from({ length: 14 }, (_, index) => ({ value: String(index), label: String(index), meta: "", state: "" }));+ const window = pickerWindow(many, 11, 8);+ expect(window.start).toBeGreaterThan(0);+ expect(window.rows.some((row: { value: string }) => row.value === "11")).toBe(true);+ });+});