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): humanize sessions and add yolo mode
Rahmancd8f1c9e1c0e
diff --git a/README.md b/README.mdindex d1f09cb2..67c91856 100644--- a/README.md+++ b/README.md@@ -209,15 +209,25 @@ mso 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+selects, and **Esc** cancels. No provider/model number has to be memorized. `/session` and bare+`/resume` open one recent-session picker directly: newest modified session first, human session title+as the primary label, and compact `modified …` metadata. Durable session IDs stay hidden in the normal+picker UI but remain accepted by scriptable `--resume`/`/resume` queries. In the Agent slashpalette, 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. Terminal controls follow familiar-agent/shell conventions: **Ctrl+C** clears a non-empty draft, exits from an empty idle prompt, and+The compact status line mirrors queued/invoked skill state and the current permission mode. MSO defaults+to `ask`; use `mso --yolo` or `mso -yolo` when you explicitly want write+exec calls auto-approved for+that Agent process. YOLO still computes and sends the canonical exact-payload approval digest; it only+skips the interactive `y/N` prompt. `/permission` opens the same arrow-key style selector for+`ask` / `auto-write` / `yolo`, and Tab on an empty prompt cycles those modes. `auto-write` approves+writes but still asks before exec. Permission mode is intentionally process-local and is not persisted+into a resumed session. Terminal controls follow familiar agent/shell conventions: **Ctrl+C** clears a non-empty draft, exits from an empty idle prompt, andinterrupts an active model/tool turn; **Ctrl+D** deletes the character to the right or exits on anempty prompt; **Ctrl+L** clears/repaints; **Ctrl+W** deletes the previous word; **↑/↓** or-**Ctrl+P/N** browse input history; **Ctrl+A/E** and **Ctrl+B/F** move to line boundaries or one-character. `/quit` is an alias for `/exit`. An interrupted turn is removed from durable conversation+**Ctrl+P/N** browse prompt history, including durable user prompts restored by `--continue`/`/resume`;+**Ctrl+A/E** and **Ctrl+B/F** move to line boundaries or one character, **Ctrl+U/K** delete to the+start/end of the line, and **Alt+B/F** or **Ctrl+←/→** move by word. `/quit` is an alias for `/exit`.+An interrupted turn is removed from durable conversationhistory so `--continue` never resumes a half-turn. Server-side jobs that were already created retaintheir own bounded job/cancel lifecycle.diff --git a/bin/mso b/bin/msoindex 43be39ef..669e7fd2 100755--- a/bin/mso+++ b/bin/mso@@ -42,7 +42,7 @@# status Public service status (no session needed)# health Is this CLI's session valid?# doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues-# agent [--continue|--resume <query>] Interactive MSO Agent; resume durable sessions+# agent [--continue|--resume <query>|--yolo|-yolo] Interactive MSO Agent; resume durable sessions# chat Alias for agent# model [ref] Select active model from a connected provider# onboard [-y] Guided setup: AI, apps, infrastructure, skills@@ -126,7 +126,7 @@# Docs: https://github.com/rahmanef63/msoset -euo pipefail-VERSION="1.6.0"+VERSION="1.6.1"ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"die() { echo "mso: $*" >&2; exit 1; }@@ -140,6 +140,7 @@ while [ $# -gt 0 ]; do--env) [ -n "${2-}" ] || die "--env needs a file"; ENV_OVERRIDE="$2"; shift 2 ;;--continue|-c) AGENT_START_ARGS+=("--continue"); shift ;;--resume|-r) [ -n "${2-}" ] || die "$1 needs a session query"; AGENT_START_ARGS+=("--resume" "$2"); shift 2 ;;+ --yolo|-yolo) AGENT_START_ARGS+=("--yolo"); shift ;;--) shift; break ;;*) break ;;esac@@ -673,7 +674,7 @@ U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|U_doctor="doctor [--fix]"U_provider="provider list|show <id>|set <dokploy|cloudflare|hostinger>|rm <id>|doctor [id]|projects|zones"U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"-U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>]"+U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo]"U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 30f8a8b1..4bd18248 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` humanize sessions and add yolo mode- `mcp` ship cognitive runtime p0- `agent` add interrupt-safe terminal controls- `agent` add arrow picker and skill statesdiff --git a/docs/CLI.md b/docs/CLI.mdindex 84c829bf..aa7bad47 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -82,7 +82,7 @@ Commands:status Public service status (no session needed)health Is this CLI's session valid?doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues- agent [--continue|--resume <query>] Interactive MSO Agent; resume durable sessions+ agent [--continue|--resume <query>|--yolo|-yolo] Interactive MSO Agent; resume durable sessionschat Alias for agentmodel [ref] Select active model from a connected provideronboard [-y] Guided setup: AI, apps, infrastructure, skillsdiff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex a868a74a..b5e64d4b 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -135,8 +135,20 @@ already connected. `mso models test` validates the currently selected connectionChatGPT/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.+Agent sessions are durable: `mso --continue` resumes the latest session and+`mso --resume <index|id|title>` resolves a prior session without weakening principal isolation. Inside+the Agent, `/session` and bare `/resume` open a single newest-first picker directly—there is no second+printed recent list. Rows show the human session title plus `modified …`; IDs are hidden in the normal UI+and retained only as an exact automation/debug escape hatch. Explicit `/title` renames use the durable+rename lifecycle, while new CLI sessions remain auto-titleable from their first real user prompt.++Agent permission mode defaults to `ask`. `mso --yolo` and `mso -yolo` are global Agent startup flags, so+they work without spelling `agent` (`mso --continue --yolo` is valid too). YOLO auto-approves write and+exec calls for that process only; MSO still canonicalizes the exact payload and sends its approval digest+to the server, but the interactive `allow this exact call? [y/N]` step is skipped. `/permission` opens a+native picker for `ask`, `auto-write`, or `yolo`; Tab on an empty Agent prompt cycles the same modes.+`auto-write` approves writes only and retains exec confirmation. The mode is deliberately not persisted+across Agent restarts/resumes.Hermes/OpenClaw installation is optional and uses each app's existing managed-job installer.Their model/provider configuration belongs to those applications and is not implicitly@@ -157,7 +169,9 @@ pause for terminal approval. Skill lifecycle is explicit in the slash palette anand `✓ invoked` means the skill instructions were actually attached to a model turn. The terminalcomposer also follows conventional controls: Ctrl+C clears a draft, exits an empty prompt, or interruptsan active turn; Ctrl+D deletes right/exits on empty; Ctrl+L clears the screen; Ctrl+W deletes the previous-word; ↑/↓ or Ctrl+P/N browse history; Ctrl+A/E and Ctrl+B/F navigate the line. `/quit` aliases `/exit`.+word; ↑/↓ or Ctrl+P/N browse prompt history and are seeded from durable user prompts after resume;+Ctrl+A/E and Ctrl+B/F navigate the line, Ctrl+U/K delete to the start/end, and Alt+B/F or Ctrl+←/→ move+by word. `/quit` aliases `/exit`.Interrupted model/tool turns are rolled back from durable CLI history before the session is saved. See[`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md) for the deployment/provider boundary.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 44189493..64ba29f6 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,6 +2,16 @@Running log of what shipped each phase. Newest at top.+## 2026-09-02 — Human-first session picker + durable prompt history — SHIPPED++MSO CLI **1.6.1** removes the duplicate session navigation UI. `/session` and bare `/resume` now open exactly one native picker instead of printing a recent-session list and then rendering a second completion list. Sessions are sorted by `updatedAt` descending, the human title is the primary/only identity shown in the normal UI, and each row carries compact `modified just now / Xm / Xh / Xd / YYYY-MM-DD` metadata. The internal durable id remains the hidden selection value and an accepted exact query for automation/debugging. The Agent header, Runtime row, compact status bar, `/session`, and exit summary are title-first as well; `/status` deliberately retains the exact id for diagnostics.++Prompt history now behaves like a normal terminal across process boundaries, not only inside one invocation. On startup, `--continue`, or `/resume`, the composer is seeded from durable `role:user` rows newest-first, so ↑/↓ and Ctrl+P/N traverse prior prompts and return to the current draft. Session switching replaces the readline history with the selected session's prompts so histories do not leak across sessions. The existing Ctrl+C/D/L/W/U/K, Ctrl+A/E/B/F and word-navigation behavior remains unchanged.++The same audit fixed title lifecycle correctness. Fresh CLI sessions no longer send the placeholder `MSO Agent session` as an explicit manual title, allowing the first real prompt to auto-title the session. `/title` now calls the dedicated durable `rename` action instead of trying to smuggle a rename through an auto-title history update. A compatibility rule repairs only legacy CLI records whose literal default `MSO Agent session` was incorrectly marked manual; genuine manual titles remain locked. Regression coverage verifies newest-first ordering, hidden-id title rows, relative modified metadata, immediate dropdown rendering, durable ↑/↓ traversal, explicit rename, legacy-title repair, and human-title compact status. Real PTY proof covers one `/session` dropdown with no duplicate recent list/visible id, durable Up/Up/Down/Down traversal after `--resume`, and title-first banner/status output.++Permission DX is hardened in the same CLI patch. `mso --yolo`, `mso -yolo`, and `mso agent --yolo` all enter an explicit process-local YOLO mode; the default remains `ask`. `/permission` provides a native picker for `ask`, `auto-write`, and `yolo`, while Tab on an empty prompt cycles them. Auto-write only bypasses write prompts; YOLO bypasses both write and exec prompts. Crucially, non-read calls still compute the canonical full-payload approval object/digest before execution, so bypassing the human prompt does not bypass server-side exact-call binding. A real harmless `exec_run` PTY turn in YOLO completed without any `allow this exact call? [y/N]` prompt and with the server accepting the digest. The audit also makes `/clear` clear the composer prompt history, and filters empty default CLI sessions from the human picker so opening/exiting the Agent does not flood recent navigation.+## 2026-09-02 — MCP session lookup contention hardening — SHIPPEDThe first live Cognitive Runtime P0 deployment exposed a scalability problem that unit-size fixtures did not: the host already had **2,927 durable agent session files**, while every conversation-bound `/mcp` tool call still took one global session-store lock and scanned the entire directory to find its `openai/session` hash. Parallel ChatGPT conversations could therefore exhaust the 3-second security-store lock budget and return `security store is busy; retry the operation` even though each conversation was correctly isolated.diff --git a/lib/agent/session-store.test.ts b/lib/agent/session-store.test.tsindex 6a3b1873..dd679b0d 100644--- a/lib/agent/session-store.test.ts+++ b/lib/agent/session-store.test.ts@@ -60,6 +60,23 @@ describe("durable agent session context policy", () => {await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });});+ it("allows an explicit rename to replace a manual title and refresh modified time", async () => {+ const session = await store.createAgentSession("principal:rename", "cli", { title: "Old name", titleSource: "manual" });+ const before = session.updatedAt;+ await new Promise((resolve) => setTimeout(resolve, 2));+ const renamed = await store.renameAgentSession("principal:rename", session.id, "New name");+ expect(renamed.title).toBe("New name");+ expect(renamed.titleSource).toBe("manual");+ expect(renamed.updatedAt.localeCompare(before)).toBeGreaterThan(0);+ });++ it("repairs the legacy CLI default that was incorrectly stored as a manual title", async () => {+ const session = await store.createAgentSession("principal:legacy-title", "cli", { title: "MSO Agent session", titleSource: "manual" });+ const updated = await store.updateAgentSessionHistory("principal:legacy-title", session.id, [{ role: "user", text: "Deploy Control Room" }], "Deploy Control Room", "auto");+ expect(updated.title).toBe("Deploy Control Room");+ expect(updated.titleSource).toBe("auto");+ });+it("keeps manual titles locked against later auto-title hints", async () => {const session = await store.createAgentSession("principal:title", "cli", { title: "Manual name", titleSource: "manual" });await store.maybeAutoTitleAgentSession("principal:title", session.id, "Deploy a very different project");diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.tsindex f2d803a8..2bf416af 100644--- a/lib/agent/session-store.ts+++ b/lib/agent/session-store.ts@@ -124,7 +124,8 @@ export async function updateAgentSessionHistory(principal: string, id: string, hconst oldTokens = estimateTokens(record.history), newHistory = Array.isArray(history) ? history.slice(-MAX_HISTORY) : [];record.history = newHistory;record.lifetimeEstimatedTokens += Math.max(0, estimateTokens(newHistory) - oldTokens);- if (title && (titleSource === "manual" || record.titleSource !== "manual")) {+ const legacyCliDefault = record.source === "cli" && record.titleSource === "manual" && record.title === "MSO Agent session";+ if (title && (titleSource === "manual" || record.titleSource !== "manual" || legacyCliDefault)) {record.title = safeTitle(title); record.titleSource = titleSource;}record.updatedAt = new Date().toISOString(); record = await compactIfNeeded(record, "context-threshold");diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjsindex 75497d67..0c90c66d 100644--- a/scripts/mso-agent-commands.mjs+++ b/scripts/mso-agent-commands.mjs@@ -1,9 +1,10 @@import { spawnSync } from "node:child_process";import process from "node:process";-import { C, BASE, CLI, api, listCliSessions, state } from "./mso-agent-runtime.mjs";+import { C, BASE, CLI, api, state } from "./mso-agent-runtime.mjs";import { loadSlashSkill, printSkillChoices, printSkills, resolveSlashSkill } from "./mso-agent-skills.mjs";-import { persistSession, printSessions, resumeInto, resumePicker } from "./mso-agent-session-ui.mjs";+import { persistSession, renameCurrentSession, resumeInto, resumePicker } from "./mso-agent-session-ui.mjs";import { printDetailedStatus } from "./mso-agent-status.mjs";+import { permissionCompletionItems, permissionMode } from "./mso-agent-permissions.mjs";function runCli(args) {const result = spawnSync(CLI, args, { stdio: "inherit", env: { ...process.env, MSO_BASE: BASE } });@@ -32,11 +33,11 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {function printHelp() {console.log([- " /session show current durable MSO session id",- " /sessions list recent resumable sessions",- " /resume [query] resume latest/index/id/title; no arg opens picker",+ " /session [query] open picker or resume latest/index/id/title",+ " /resume [query] alias-style resume command; bare opens same picker"," /title <name> rename the durable session"," /status model/auth/context/token/session details",+ " /permission [mode] choose ask | auto-write | yolo"," /context alias for /status"," /statusbar [on|off] toggle compact dynamic status line"," /models [args] configure AI providers/auth",@@ -56,9 +57,10 @@ function printHelp() {" Ctrl+C clear input; empty prompt exits; active turn interrupts"," Ctrl+D delete right; empty prompt exits"," Ctrl+L clear/repaint terminal",- " Ctrl+W delete previous word",- " ↑/↓ or Ctrl+P/N command history",+ " Ctrl+W · Ctrl+U/K delete word · delete to line start/end",+ " ↑/↓ or Ctrl+P/N prompt history (durable after resume)"," Ctrl+A/E · Ctrl+B/F line start/end · left/right",+ " Alt+B/F · Ctrl+←/→ move by word",].join("\n"));}@@ -66,20 +68,28 @@ export async function handleSlash(rl, line, session, { runTurn }) {const [cmd, ...args] = line.trim().split(/\s+/);switch (cmd) {case "/help": printHelp(); return "handled";- case "/session":- console.log(`${C.blue}${session.agentSession.id}${C.reset} · ${session.agentSession.title || "MSO Agent session"}`); return "handled";- case "/sessions":- printSessions(await listCliSessions(50)); return "handled";- case "/resume":- if (!args.length) await resumePicker(rl, session); else await resumeInto(session, args.join(" "));+ case "/session": case "/sessions": case "/resume":+ if (!args.length) await resumePicker(rl, session); else await resumeInto(rl, session, args.join(" "));return "refresh";case "/title": {const title = args.join(" ").trim();if (!title) console.log("usage: /title <session name>");- else { session.titleOverride = title.slice(0, 120); await persistSession(session); console.log(`${C.c}✓ session title: ${session.titleOverride}${C.reset}`); }+ else { const renamed = await renameCurrentSession(session, title); console.log(`${C.c}✓ session title: ${renamed}${C.reset}`); }return "handled";}case "/status": case "/context": printDetailedStatus(session, C); return "handled";+ case "/permission": {+ const direct = args.length ? permissionMode(args.join(" ")) : null;+ if (args.length && !direct) { console.log("usage: /permission [ask|auto-write|yolo]"); return "handled"; }+ if (direct) session.permission = direct.id;+ else {+ const selected = await rl.question(`${C.blue}${C.bold}permission ›${C.reset} `, {+ history: false, complete: (value) => permissionCompletionItems(value), panelLabel: "permission mode", selectOnEnter: true, escapeCancels: true,+ });+ if (selected) session.permission = permissionMode(selected)?.id || session.permission;+ }+ console.log(`permission ${session.permission}`); return "handled";+ }case "/statusbar": {const value = String(args[0] || "").toLowerCase();if (value === "off") session.statusBar = false; else if (value === "on") session.statusBar = true; else session.statusBar = !session.statusBar;@@ -100,7 +110,8 @@ export async function handleSlash(rl, line, session, { runTurn }) {return selectSlashSkill(rl, session, args[0], args.slice(1).join(" "), runTurn);case "/clear":Object.assign(session, { history: [], pendingSkill: null, activeSkill: null, lastInvokedSkill: null });- await persistSession(session); console.log("conversation cleared."); return "handled";+ rl.replaceHistory([]);+ await persistSession(session); console.log("conversation and prompt history cleared."); return "handled";case "/exit": case "/quit": return "exit";default: return selectSlashSkill(rl, session, cmd.slice(1), args.join(" "), runTurn);}diff --git a/scripts/mso-agent-composer-session.test.ts b/scripts/mso-agent-composer-session.test.tsnew file mode 100644index 00000000..82160b09--- /dev/null+++ b/scripts/mso-agent-composer-session.test.ts@@ -0,0 +1,68 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";+import { AgentComposer } from "./mso-agent-composer.mjs";++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 colors = { blue: "", bold: "", reset: "", dim: "" };++function composerFixture() {+ const input = new FakeInput(), output = new FakeOutput();+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });+ return { input, output, composer };+}++describe("MSO Agent session/history composer UX", () => {+ it("renders a titled session dropdown immediately and submits its hidden id without printing it", async () => {+ const { input, output, composer } = composerFixture();+ const hiddenId = "20260901_192428_255bb637";+ const answer = composer.question("session › ", {+ history: false, panelLabel: "recent sessions", selectOnEnter: true, escapeCancels: true,+ complete: () => [{ text: "Renamed session", value: hiddenId, meta: "modified 2m ago" }],+ } as never);+ const initial = output.chunks.join("");+ expect(initial).toContain("recent sessions");+ expect(initial).toContain("Renamed session");+ expect(initial).toContain("modified 2m ago");+ expect(initial).not.toContain(hiddenId);+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });+ await expect(answer).resolves.toBe(hiddenId);+ expect(output.chunks.join("")).not.toContain(hiddenId);+ composer.close();+ });++ it("recalls durable prompt history with Arrow Up and walks forward again with Arrow Down", async () => {+ const { input, composer } = composerFixture();+ composer.replaceHistory(["latest durable prompt", "older durable prompt"]);+ const answer = composer.question("› ");+ input.emit("keypress", undefined, { name: "up", sequence: "ESC-UP" });+ input.emit("keypress", undefined, { name: "up", sequence: "ESC-UP" });+ input.emit("keypress", undefined, { name: "down", sequence: "ESC-DOWN" });+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });+ await expect(answer).resolves.toBe("latest durable prompt");+ composer.close();+ });++ it("uses Tab on an empty normal prompt as a mode-cycle hook without polluting history", async () => {+ const { input, output, composer } = composerFixture();+ let cycles = 0;+ const answer = composer.question("› ", { onTab: () => { cycles++; return "permission → yolo"; } } as never);+ input.emit("keypress", "\t", { name: "tab", sequence: "\t" });+ expect(cycles).toBe(1);+ expect(output.chunks.join("")).toContain("permission → yolo");+ for (const ch of "go") input.emit("keypress", ch, { name: ch, sequence: ch });+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });+ await expect(answer).resolves.toBe("go");+ expect(composer.history[0]).toBe("go");+ composer.close();+ });+});diff --git a/scripts/mso-agent-composer-ui.mjs b/scripts/mso-agent-composer-ui.mjsnew file mode 100644index 00000000..db75daec--- /dev/null+++ b/scripts/mso-agent-composer-ui.mjs@@ -0,0 +1,55 @@+import { fit, pad } from "./mso-agent-editing.mjs";++export const CLEAR_LINE = "\x1b[2K";+export const CURSOR_UP = (n) => n > 0 ? `\x1b[${n}A` : "";+export const CURSOR_DOWN = (n) => n > 0 ? `\x1b[${n}B` : "";+export const CURSOR_RIGHT = (n) => n > 0 ? `\x1b[${n}C` : "";+export const CLEAR_SCREEN = "\x1b[2J\x1b[H";+const plain = (value) => String(value ?? "").replace(/\x1b\[[0-9;]*m/g, "");+export const chars = (value) => Array.from(String(value ?? ""));+export const width = (value) => chars(plain(value)).length;+export const clamp = (value, min, max) => Math.min(Math.max(value, min), max);++export function inputViewport(value, cursor, maxWidth) {+ const row = chars(value), max = Math.max(1, maxWidth);+ if (row.length <= max) return { display: row.join(""), cursor: clamp(cursor, 0, row.length) };+ const interior = Math.max(1, max - 2);+ let start = clamp(cursor - Math.floor(interior * 0.7), 0, Math.max(0, row.length - interior));+ let end = Math.min(row.length, start + interior);+ if (cursor > end) { end = cursor; start = Math.max(0, end - interior); }+ const prefix = start > 0 ? "…" : "", suffix = end < row.length ? "…" : "";+ return { display: `${prefix}${row.slice(start, end).join("")}${suffix}`, cursor: width(prefix) + clamp(cursor - start, 0, end - start) };+}++export function completionWindow(items, selected, size = 8) {+ const rows = Array.isArray(items) ? items : [];+ if (!rows.length) return { start: 0, items: [] };+ const count = Math.min(Math.max(1, size), rows.length), idx = clamp(selected, 0, rows.length - 1);+ const start = Math.max(0, Math.min(idx - Math.floor(count / 2), rows.length - count));+ return { start, items: rows.slice(start, start + count) };+}++export function menuLines(items, selected, columns, C, panelLabel = "commands & skills") {+ const { start, items: visible } = completionWindow(items, selected, 8);+ if (!visible.length) return [];+ const panelWidth = Math.max(38, Math.min(100, Number(columns || 100) - 2));+ const label = ` ${fit(panelLabel, Math.max(12, panelWidth - 8))} `;+ const top = `╭─${label}${"─".repeat(Math.max(0, panelWidth - width(label) - 3))}╮`;+ const nameWidth = Math.min(42, Math.max(12, ...visible.map((item) => width(item.label || item.text) + 1)));+ 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 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 displayText = item.label || item.text;+ const name = nameColor ? `${nameColor}${active ? C.bold : ""}${pad(displayText, nameWidth)}${C.reset}` : pad(displayText, nameWidth);+ const metaText = fit(item.meta || "", metaWidth), meta = metaWidth ? `${C.dim}${metaText}${C.reset}` : "";+ return `│ ${marker} ${stateMark} ${name}${meta ? ` ${meta}` : ""}${" ".repeat(Math.max(0, metaWidth - width(metaText)))} │`;+ });+ const hint = " ↑↓ navigate · Enter/Tab select · Esc close ";+ const bottomText = fit(hint, panelWidth - 3);+ const bottom = `╰─${bottomText}${"─".repeat(Math.max(0, panelWidth - width(bottomText) - 3))}╯`;+ return [`${C.blue}${top}${C.reset}`, ...body, `${C.blue}${bottom}${C.reset}`];+}diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjsindex 7e66aef5..1b081e9a 100644--- a/scripts/mso-agent-composer.mjs+++ b/scripts/mso-agent-composer.mjs@@ -1,66 +1,11 @@import readline from "node:readline";-import { fit, pad, wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";+import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";import process from "node:process";-const CLEAR_LINE = "\x1b[2K";-const CURSOR_UP = (n) => n > 0 ? `\x1b[${n}A` : "";-const CURSOR_DOWN = (n) => n > 0 ? `\x1b[${n}B` : "";-const CURSOR_RIGHT = (n) => n > 0 ? `\x1b[${n}C` : "";-const CLEAR_SCREEN = "\x1b[2J\x1b[H";-const plain = (value) => String(value ?? "").replace(/\x1b\[[0-9;]*m/g, "");-const chars = (value) => Array.from(String(value ?? ""));-const width = (value) => chars(plain(value)).length;-const clamp = (value, min, max) => Math.min(Math.max(value, min), max);--export function inputViewport(value, cursor, maxWidth) {- const row = chars(value);- const max = Math.max(1, maxWidth);- if (row.length <= max) return { display: row.join(""), cursor: clamp(cursor, 0, row.length) };- const interior = Math.max(1, max - 2);- let start = clamp(cursor - Math.floor(interior * 0.7), 0, Math.max(0, row.length - interior));- let end = Math.min(row.length, start + interior);- if (cursor > end) { end = cursor; start = Math.max(0, end - interior); }- const prefix = start > 0 ? "…" : "";- const suffix = end < row.length ? "…" : "";- return {- display: `${prefix}${row.slice(start, end).join("")}${suffix}`,- cursor: width(prefix) + clamp(cursor - start, 0, end - start),- };-}--export function completionWindow(items, selected, size = 8) {- const rows = Array.isArray(items) ? items : [];- if (!rows.length) return { start: 0, items: [] };- const count = Math.min(Math.max(1, size), rows.length);- const idx = clamp(selected, 0, rows.length - 1);- const start = Math.max(0, Math.min(idx - Math.floor(count / 2), rows.length - count));- return { start, items: rows.slice(start, start + count) };-}--function menuLines(items, selected, columns, C) {- const { start, items: visible } = completionWindow(items, selected, 8);- if (!visible.length) return [];- const panelWidth = Math.max(38, Math.min(100, Number(columns || 100) - 2));- 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 - 9);- const body = visible.map((item, offset) => {- const active = start + offset === selected;- const marker = active ? `${C.blue}${C.bold}›${C.reset}` : " ";- 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} ${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))}╯`;- return [`${C.blue}${top}${C.reset}`, ...body, `${C.blue}${bottom}${C.reset}`];-}+import {+ chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, inputViewport, menuLines, width,+} from "./mso-agent-composer-ui.mjs";+export { completionWindow, inputViewport } from "./mso-agent-composer-ui.mjs";export class AgentComposer {constructor({ input = process.stdin, output = process.stdout, colors }) {@@ -73,7 +18,7 @@ export class AgentComposer {readline.emitKeypressEvents(this.input);}- async question(prompt, { complete = null, history = true, onCancel = null } = {}) {+ async question(prompt, { complete = null, history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false } = {}) {if (this.closed) return null;const input = this.input, output = this.output, C = this.C;return new Promise((resolve) => {@@ -101,7 +46,7 @@ export class AgentComposer {const viewport = inputViewport(value, cursor, maxInput);const items = matches();selected = items.length ? clamp(selected, 0, items.length - 1) : 0;- const menu = menuLines(items, selected, output.columns, C);+ const menu = menuLines(items, selected, output.columns, C, panelLabel);reserve(menu.length);erase();output.write(`${prompt}${viewport.display}`);@@ -115,11 +60,11 @@ export class AgentComposer {if (typeof input.setRawMode === "function") input.setRawMode(wasRaw);input.pause();};- const finish = (result, echo = true) => {+ const finish = (result, echo = true, displayValue = value) => {if (settled) return;settled = true;erase();- if (echo) output.write(`${prompt}${value}\r\n`);+ if (echo) output.write(`${prompt}${displayValue}\r\n`);cleanup();if (history && result?.trim()) {this.history.unshift(result);@@ -165,13 +110,33 @@ export class AgentComposer {if (key.ctrl && key.name === "l") {output.write(CLEAR_SCREEN); reservedMenuRows = 0; return render();}- if (key.name === "escape") { dismissed = true; selected = 0; return render(); }+ if (key.name === "escape") {+ if (escapeCancels) return cancel(false);+ dismissed = true; selected = 0; return render();+ }if (items.length && (key.name === "up" || key.name === "down")) {selected = (selected + (key.name === "up" ? -1 : 1) + items.length) % items.length;return render();}- if (key.name === "tab" && items.length) return apply(items[selected]);+ if (key.name === "tab" && items.length) {+ if (selectOnEnter) {+ const item = items[selected];+ return finish(item.value ?? item.text, true, item.label || item.text);+ }+ return apply(items[selected]);+ }+ if (key.name === "tab" && !value && typeof onTab === "function") {+ const notice = onTab();+ if (notice) {+ erase(); reservedMenuRows = 0; output.write(`${notice}\r\n`); render();+ }+ return;+ }if (key.name === "return" || key.name === "enter") {+ if (selectOnEnter && items[selected]) {+ const item = items[selected];+ return finish(item.value ?? item.text, true, item.label || item.text);+ }// Exact input wins even when another prefix match is highlighted first// (`/model` vs `/models`). Enter submits what the user actually typed;// Tab is the explicit "apply highlighted completion" key.@@ -214,6 +179,13 @@ export class AgentComposer {});}+ replaceHistory(values) {+ this.history = (Array.isArray(values) ? values : [])+ .map((value) => String(value ?? "").replace(/[\r\n\t]+/g, " ").trim())+ .filter(Boolean)+ .slice(0, 100);+ }+cancelCurrent({ echo = true } = {}) {return typeof this._cancelCurrent === "function" ? this._cancelCurrent(echo) : false;}diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.tsindex 8d53b5b7..4286b981 100644--- a/scripts/mso-agent-composer.test.ts+++ b/scripts/mso-agent-composer.test.ts@@ -188,4 +188,5 @@ describe("MSO Agent interactive composer primitives", () => {composer.close();});+});diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.tsindex d39f86b6..756fc47a 100644--- a/scripts/mso-agent-contract.test.ts+++ b/scripts/mso-agent-contract.test.ts@@ -2,7 +2,7 @@ import fs from "node:fs";import path from "node:path";import { describe, expect, it } from "vitest";-const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.mjs", "mso-agent-slash.mjs", "mso-agent-status.mjs", "mso-agent-sessions.mjs"].map((name) => path.join(__dirname, name));+const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.mjs", "mso-agent-slash.mjs", "mso-agent-status.mjs", "mso-agent-sessions.mjs", "mso-agent-session-ui.mjs", "mso-agent-commands.mjs", "mso-agent-composer.mjs", "mso-agent-permissions.mjs"].map((name) => path.join(__dirname, name));const src = files.map((file) => fs.readFileSync(file, "utf8")).join("\n");describe("MSO terminal agent contract", () => {@@ -30,7 +30,7 @@ describe("MSO terminal agent contract", () => {expect(src).toContain("MSO_TITLE_COLORS");for (const command of ["/models", "/model", "/status", "/context", "/statusbar", "/title",- "/session", "/sessions", "/resume", "/setup", "/providers", "/provider",+ "/session", "/resume", "/setup", "/providers", "/provider","/doctor", "/tools", "/skills", "/skill", "/<skill>", "/clear", "/exit", "/quit",]) expect(src).toContain(command);expect(src).toContain("Configure AI providers and authentication");@@ -60,4 +60,15 @@ describe("MSO terminal agent contract", () => {expect(src).toContain("MSO_AGENT_JAR");expect(src).not.toMatch(/process\.argv.*(?:token|secret|password|apiKey)/i);});++ it("keeps session picker titles human-first and rename explicit", () => {+ expect(src).toContain("recent sessions");+ expect(src).toContain("renameCliSession");+ expect(src).toContain('action: "rename"');+ expect(src).toContain("syncPromptHistory");+ expect(src).toContain("permissionCompletionItems");+ expect(src).toContain("approvesTool");+ expect(src).toContain("--yolo");+ });+});diff --git a/scripts/mso-agent-permissions.mjs b/scripts/mso-agent-permissions.mjsnew file mode 100644index 00000000..1c903542--- /dev/null+++ b/scripts/mso-agent-permissions.mjs@@ -0,0 +1,30 @@+export const PERMISSION_MODES = [+ { id: "ask", label: "Ask", detail: "Confirm every write and exec call", tone: "safe" },+ { id: "auto", label: "Auto-write", detail: "Approve writes; still ask before exec", tone: "auto" },+ { id: "yolo", label: "YOLO", detail: "Approve write and exec automatically", tone: "danger" },+];++export function permissionMode(value) {+ const raw = String(value ?? "").trim().toLowerCase();+ const aliases = { a: "ask", ask: "ask", w: "auto", auto: "auto", "auto-write": "auto", y: "yolo", yolo: "yolo" };+ const id = aliases[raw];+ return id ? PERMISSION_MODES.find((mode) => mode.id === id) || null : null;+}++export function nextPermissionMode(current) {+ const index = Math.max(0, PERMISSION_MODES.findIndex((mode) => mode.id === current));+ return PERMISSION_MODES[(index + 1) % PERMISSION_MODES.length];+}++export function approvesTool(mode, scope) {+ if (scope === "read") return true;+ if (mode === "yolo") return true;+ return mode === "auto" && scope === "write";+}++export function permissionCompletionItems(query = "") {+ const q = String(query || "").trim().toLowerCase();+ return PERMISSION_MODES+ .map((mode) => ({ text: mode.label, label: mode.label, value: mode.id, meta: mode.detail }))+ .filter((item) => !q || `${item.label} ${item.value} ${item.meta}`.toLowerCase().includes(q));+}diff --git a/scripts/mso-agent-permissions.test.ts b/scripts/mso-agent-permissions.test.tsnew file mode 100644index 00000000..4e4726eb--- /dev/null+++ b/scripts/mso-agent-permissions.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { approvesTool, nextPermissionMode, permissionCompletionItems, permissionMode } from "./mso-agent-permissions.mjs";++describe("MSO Agent permission modes", () => {+ it("parses stable human aliases without numeric-only UX", () => {+ expect(permissionMode("ask")?.id).toBe("ask");+ expect(permissionMode("a")?.id).toBe("ask");+ expect(permissionMode("auto-write")?.id).toBe("auto");+ expect(permissionMode("w")?.id).toBe("auto");+ expect(permissionMode("yolo")?.id).toBe("yolo");+ expect(permissionMode("y")?.id).toBe("yolo");+ expect(permissionMode("3")).toBeNull();+ });++ it("keeps ask strict, auto-write scoped, and yolo explicit", () => {+ expect(approvesTool("ask", "write")).toBe(false);+ expect(approvesTool("auto", "write")).toBe(true);+ expect(approvesTool("auto", "exec")).toBe(false);+ expect(approvesTool("yolo", "exec")).toBe(true);+ expect(nextPermissionMode("yolo").id).toBe("ask");+ });++ it("builds an arrow-picker catalog", () => {+ const all = permissionCompletionItems("");+ expect(all.map((row) => row.value)).toEqual(["ask", "auto", "yolo"]);+ expect(permissionCompletionItems("write").map((row) => row.value)).toEqual(["ask", "auto", "yolo"]);+ expect(permissionCompletionItems("danger").map((row) => row.value)).toEqual([]);+ });+});diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjsindex 49fc33d2..f3f6f6dc 100644--- a/scripts/mso-agent-runtime.mjs+++ b/scripts/mso-agent-runtime.mjs@@ -54,8 +54,9 @@ export async function state() {return { config, toolsData, tools, skills, infra, models, modelMeta };}-export async function createCliSession(title = "MSO Agent session") {- const out = await api("/api/v1/agent-sessions", { method: "POST", body: JSON.stringify({ action: "create", title }) });+export async function createCliSession(title = undefined) {+ const body = { action: "create", ...(title ? { title } : {}) };+ const out = await api("/api/v1/agent-sessions", { method: "POST", body: JSON.stringify(body) });return out.session;}export async function loadCliSession(id) {@@ -77,6 +78,13 @@ export async function saveCliSession(session, history, title) {});return out.session;}+export async function renameCliSession(session, title) {+ const out = await api("/api/v1/agent-sessions", {+ method: "POST",+ body: JSON.stringify({ action: "rename", id: session.id, title }),+ });+ return out.session;+}export function printBanner(s, agentSession) {return printAgentBanner(s, agentSession, { base: BASE, version: VERSION });diff --git a/scripts/mso-agent-session-ui.mjs b/scripts/mso-agent-session-ui.mjsindex d1ece674..6f7e3df1 100644--- a/scripts/mso-agent-session-ui.mjs+++ b/scripts/mso-agent-session-ui.mjs@@ -1,11 +1,15 @@-import { C, createCliSession, listCliSessions, resumeCliSession, saveCliSession } from "./mso-agent-runtime.mjs";-import { resolveSessionQuery, sessionCompletionItems } from "./mso-agent-sessions.mjs";+import { C, createCliSession, listCliSessions, renameCliSession, resumeCliSession, saveCliSession } from "./mso-agent-runtime.mjs";+import { formatSessionModified, resolveSessionQuery, sessionCompletionItems, sessionPromptHistory, visibleSessionRows } from "./mso-agent-sessions.mjs";function autoTitle(history) {const first = history.find((row) => row?.role === "user" && typeof row.text === "string" && row.text.trim());return first ? String(first.text).replace(/[\r\n\t]+/g, " ").trim().slice(0, 100) : undefined;}+export function syncPromptHistory(rl, session) {+ rl.replaceHistory(sessionPromptHistory(session?.history));+}+export async function persistSession(session) {const title = session.titleOverride || autoTitle(session.history);const saved = await saveCliSession(session.agentSession, session.history, title);@@ -13,15 +17,24 @@ export async function persistSession(session) {if (Array.isArray(saved?.history)) session.history = saved.history;}+export async function renameCurrentSession(session, title) {+ const nextTitle = String(title || "").replace(/[\r\n\t]+/g, " ").trim().slice(0, 120);+ if (!nextTitle) throw new Error("session title is required");+ const saved = await renameCliSession(session.agentSession, nextTitle);+ session.agentSession = { ...session.agentSession, ...saved };+ session.titleOverride = saved?.title || nextTitle;+ return session.titleOverride;+}+export function printSessions(rows) {if (!rows.length) { console.log("No MSO Agent sessions yet."); return; }- console.log(`${C.bold}Recent MSO Agent sessions${C.reset}`);+ console.log(`${C.bold}Matching MSO Agent sessions${C.reset}`);rows.forEach((row, index) => {- const when = String(row.updatedAt || row.createdAt || "").replace("T", " ").slice(0, 19);- const title = String(row.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").slice(0, 48);- console.log(` ${String(index + 1).padStart(2)} ${C.blue}${row.id}${C.reset} ${C.dim}${when}${C.reset} ${String(row.historyTurns || 0).padStart(2)}t ${title}`);+ const title = String(row.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").trim().slice(0, 72);+ const modified = formatSessionModified(row.updatedAt || row.createdAt);+ console.log(` ${String(index + 1).padStart(2)} ${C.blue}${title}${C.reset} ${C.dim}· modified ${modified}${C.reset}`);});- console.log(`${C.dim}Resume: /resume latest | /resume 2 | /resume <id/title> · CLI: mso --continue / mso --resume <query>${C.reset}`);+ console.log(`${C.dim}Resume by title or list index; exact ids remain accepted as a scriptable escape hatch.${C.reset}`);}async function resolveResume(query, rows = null) {@@ -36,7 +49,7 @@ async function resolveResume(query, rows = null) {throw new Error(`no resumable MSO Agent session matches: ${query || "latest"}`);}-export async function resumeInto(session, query, rows = null) {+export async function resumeInto(rl, session, query, rows = null) {const target = await resolveResume(query, rows);if (!target) return false;const loaded = await resumeCliSession(target.id);@@ -51,19 +64,22 @@ export async function resumeInto(session, query, rows = null) {usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },lastElapsedMs: 0,});- console.log(`${C.c}resumed ${loaded.id}${C.reset} · ${loaded.title || "MSO Agent session"} · ${session.history.length} history rows`);+ syncPromptHistory(rl, session);+ console.log(`${C.c}resumed ${loaded.title || "MSO Agent session"}${C.reset} · ${session.history.length} history rows`);return true;}export async function resumePicker(rl, session) {- const rows = await listCliSessions(100);- if (!rows.length) { console.log("No MSO Agent sessions yet."); return; }- printSessions(rows.slice(0, 20));- const answer = await rl.question(`${C.blue}${C.bold}resume ›${C.reset} `, {+ const rows = visibleSessionRows(await listCliSessions(100));+ if (!rows.length) { console.log("No resumable MSO Agent sessions yet."); return false; }+ const answer = await rl.question(`${C.blue}${C.bold}session ›${C.reset} `, {history: false,- complete: (value) => sessionCompletionItems(rows, value),+ complete: (value) => sessionCompletionItems(rows, value, Date.now(), session.agentSession?.id),+ panelLabel: "recent sessions",+ selectOnEnter: true,+ escapeCancels: true,});- if (answer?.trim()) await resumeInto(session, answer.trim(), rows);+ return answer?.trim() ? resumeInto(rl, session, answer.trim(), rows) : false;}export function resumeArg(argv) {diff --git a/scripts/mso-agent-sessions.mjs b/scripts/mso-agent-sessions.mjsindex f54a08f3..6bcc9a49 100644--- a/scripts/mso-agent-sessions.mjs+++ b/scripts/mso-agent-sessions.mjs@@ -1,7 +1,31 @@function clean(value) { return String(value ?? "").replace(/[\r\n\t]+/g, " ").trim(); }+function modifiedMs(row) {+ const value = Date.parse(String(row?.updatedAt || row?.createdAt || ""));+ return Number.isFinite(value) ? value : 0;+}++export function formatSessionModified(value, now = Date.now()) {+ const at = Date.parse(String(value || ""));+ if (!Number.isFinite(at)) return "recently";+ const diff = Math.max(0, Number(now) - at);+ if (diff < 60_000) return "just now";+ if (diff < 3_600_000) return `${Math.max(1, Math.floor(diff / 60_000))}m ago`;+ if (diff < 86_400_000) return `${Math.max(1, Math.floor(diff / 3_600_000))}h ago`;+ if (diff < 604_800_000) return `${Math.max(1, Math.floor(diff / 86_400_000))}d ago`;+ return new Date(at).toISOString().slice(0, 10);+}++export function sessionPromptHistory(history) {+ return (Array.isArray(history) ? history : [])+ .filter((row) => row?.role === "user" && typeof row.text === "string" && row.text.trim())+ .map((row) => clean(row.text))+ .reverse()+ .slice(0, 100);+}+export function resolveSessionQuery(rows, query) {- const sessions = Array.isArray(rows) ? rows : [];+ const sessions = (Array.isArray(rows) ? rows : []).slice().sort((a, b) => modifiedMs(b) - modifiedMs(a));if (!sessions.length) return { session: null, ambiguous: [], reason: "empty" };const raw = clean(query);if (!raw || raw.toLowerCase() === "latest" || raw.toLowerCase() === "continue") return { session: sessions[0], ambiguous: [] };@@ -24,10 +48,26 @@ export function resolveSessionQuery(rows, query) {return { session: null, ambiguous: [], reason: "not_found" };}-export function sessionCompletionItems(rows, input) {+export function visibleSessionRows(rows) {+ return (Array.isArray(rows) ? rows : []).filter((row) => {+ const emptyDefaultCli = row?.source === "cli" && Number(row?.historyTurns || 0) === 0+ && clean(row?.title) === "MSO Agent session" && ["default", "manual"].includes(String(row?.titleSource || "default"));+ return !emptyDefaultCli;+ });+}++export function sessionCompletionItems(rows, input, now = Date.now(), currentId = "") {const q = clean(input).toLowerCase();- return (Array.isArray(rows) ? rows : []).map((row, index) => ({- text: row.id,- meta: `${index + 1} · ${row.source || "cli"} · ${row.historyTurns || 0} turns · ${clean(row.title || "MSO Agent session")}`,- })).filter((item) => !q || item.text.toLowerCase().includes(q) || item.meta.toLowerCase().includes(q)).slice(0, 20);+ return visibleSessionRows(rows)+ .slice()+ .sort((a, b) => modifiedMs(b) - modifiedMs(a))+ .map((row) => {+ const text = clean(row.title) || "MSO Agent session";+ const modified = `modified ${formatSessionModified(row.updatedAt || row.createdAt, now)}`;+ const meta = String(row.id) === String(currentId) ? `current · ${modified}` : modified;+ return { text, value: String(row.id), meta, search: `${text} ${row.id} ${meta}`.toLowerCase() };+ })+ .filter((item) => !q || item.search.includes(q))+ .slice(0, 20)+ .map(({ search: _search, ...item }) => item);}diff --git a/scripts/mso-agent-sessions.test.ts b/scripts/mso-agent-sessions.test.tsindex 1a1eaa02..603bf27e 100644--- a/scripts/mso-agent-sessions.test.ts+++ b/scripts/mso-agent-sessions.test.ts@@ -1,16 +1,17 @@import { describe, expect, it } from "vitest";-import { resolveSessionQuery, sessionCompletionItems } from "./mso-agent-sessions.mjs";+import { formatSessionModified, resolveSessionQuery, sessionCompletionItems, sessionPromptHistory, visibleSessionRows } from "./mso-agent-sessions.mjs";const rows = [- { id: "20260901_120000_aaaaaaaa", title: "Deploy Baton", source: "cli", historyTurns: 10 },- { id: "20260901_110000_bbbbbbbb", title: "Audit MSO", source: "cli", historyTurns: 4 },- { id: "20260901_100000_cccccccc", title: "Older Baton notes", source: "cli", historyTurns: 2 },+ { id: "20260901_120000_aaaaaaaa", title: "Deploy Baton", source: "cli", historyTurns: 10, createdAt: "2026-09-01T11:50:00.000Z", updatedAt: "2026-09-01T12:00:00.000Z" },+ { id: "20260901_110000_bbbbbbbb", title: "Audit MSO", source: "cli", historyTurns: 4, createdAt: "2026-09-01T10:50:00.000Z", updatedAt: "2026-09-01T11:00:00.000Z" },+ { id: "20260901_100000_cccccccc", title: "Older Baton notes", source: "cli", historyTurns: 2, createdAt: "2026-09-01T09:50:00.000Z", updatedAt: "2026-09-01T10:00:00.000Z" },];describe("MSO Agent session resolver", () => {- it("resumes latest, list index, exact id, short id and unique title", () => {- expect(resolveSessionQuery(rows, "latest").session?.id).toBe(rows[0].id);- expect(resolveSessionQuery(rows, "2").session?.id).toBe(rows[1].id);+ it("resumes newest, list index, exact id, short id and unique title", () => {+ const unordered = [rows[2], rows[0], rows[1]];+ expect(resolveSessionQuery(unordered, "latest").session?.id).toBe(rows[0].id);+ expect(resolveSessionQuery(unordered, "2").session?.id).toBe(rows[1].id);expect(resolveSessionQuery(rows, rows[1].id).session?.id).toBe(rows[1].id);expect(resolveSessionQuery(rows, "bbbbbbbb").session?.id).toBe(rows[1].id);expect(resolveSessionQuery(rows, "Audit MSO").session?.id).toBe(rows[1].id);@@ -22,8 +23,41 @@ describe("MSO Agent session resolver", () => {expect(result.ambiguous).toHaveLength(2);});- it("builds searchable session picker items", () => {- expect(sessionCompletionItems(rows, "audit")).toHaveLength(1);- expect(sessionCompletionItems(rows, "")[0].meta).toContain("10 turns");+ it("builds a newest-first title picker with hidden ids and last-modified metadata", () => {+ const now = Date.parse("2026-09-01T12:05:00.000Z");+ const items = sessionCompletionItems([rows[1], rows[0], rows[2]], "", now);+ expect(items.map((item) => item.text)).toEqual(["Deploy Baton", "Audit MSO", "Older Baton notes"]);+ expect(items[0]).toMatchObject({ text: "Deploy Baton", value: rows[0].id, meta: "modified 5m ago" });+ expect(`${items[0].text} ${items[0].meta}`).not.toContain(rows[0].id);+ expect(sessionCompletionItems(rows, "audit", now)).toHaveLength(1);+ expect(sessionCompletionItems(rows, "bbbbbbbb", now)[0]?.text).toBe("Audit MSO");});++ it("formats last-modified time compactly", () => {+ const now = Date.parse("2026-09-02T12:00:00.000Z");+ expect(formatSessionModified("2026-09-02T11:59:40.000Z", now)).toBe("just now");+ expect(formatSessionModified("2026-09-02T11:55:00.000Z", now)).toBe("5m ago");+ expect(formatSessionModified("2026-09-02T09:00:00.000Z", now)).toBe("3h ago");+ expect(formatSessionModified("2026-08-20T09:00:00.000Z", now)).toBe("2026-08-20");+ });++ it("seeds terminal history from durable user prompts newest first", () => {+ expect(sessionPromptHistory([+ { role: "user", text: "first prompt" },+ { role: "assistant", text: "answer" },+ { role: "tool", text: "ignored" },+ { role: "user", text: "second\nprompt" },+ ])).toEqual(["second prompt", "first prompt"]);+ });++ it("hides empty default CLI clutter but keeps named and non-CLI sessions", () => {+ const clutter = { id: "empty", source: "cli", title: "MSO Agent session", titleSource: "default", historyTurns: 0, updatedAt: "2026-09-02T10:00:00Z" };+ const named = { id: "named", source: "cli", title: "Deploy MSO", titleSource: "manual", historyTurns: 0, updatedAt: "2026-09-02T09:00:00Z" };+ const mcp = { id: "mcp", source: "mcp", title: "ChatGPT task", titleSource: "auto", historyTurns: 0, updatedAt: "2026-09-02T08:00:00Z" };+ expect(visibleSessionRows([clutter, named, mcp]).map((row) => row.id)).toEqual(["named", "mcp"]);+ const items = sessionCompletionItems([clutter, named, mcp], "", Date.parse("2026-09-02T10:05:00Z"), "named");+ expect(items.map((row) => row.text)).toEqual(["Deploy MSO", "ChatGPT task"]);+ expect(items[0].meta).toContain("current");+ });+});diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjsindex 7b6bfc3a..1ec7b1e5 100644--- a/scripts/mso-agent-slash.mjs+++ b/scripts/mso-agent-slash.mjs@@ -5,11 +5,11 @@ export const BUILTIN_SLASH_ITEMS = [{ text: "/help", meta: "Show commands and shortcuts", kind: "command" },{ text: "/models", meta: "Configure AI providers and authentication", kind: "command" },{ text: "/model", meta: "Select the active model from connected providers", kind: "command" },- { text: "/session", meta: "Show the current durable session id", kind: "command" },- { text: "/sessions", meta: "List resumable MSO Agent sessions", kind: "command" },- { text: "/resume", meta: "Resume latest/index/id/title; no arg opens picker", kind: "command" },+ { text: "/session", meta: "Open the recent-session picker", kind: "command" },+ { text: "/resume", meta: "Resume a session; no arg opens the same picker", kind: "command" },{ text: "/title", meta: "Rename the durable session", kind: "command" },{ text: "/status", meta: "Show model, auth, context, tokens, session", kind: "command" },+ { text: "/permission", meta: "Choose ask, auto-write, or yolo approval mode", kind: "command" },{ text: "/context", meta: "Show context/token/session status", kind: "command" },{ text: "/statusbar", meta: "Toggle the compact dynamic status line", kind: "command" },{ text: "/setup", meta: "Run full MSO onboarding", kind: "command" },diff --git a/scripts/mso-agent-slash.test.ts b/scripts/mso-agent-slash.test.tsindex 9f0feb6d..703cbb5a 100644--- a/scripts/mso-agent-slash.test.ts+++ b/scripts/mso-agent-slash.test.ts@@ -20,7 +20,7 @@ describe("MSO Agent slash completion catalog", () => {});it("filters live as the command token is typed", () => {- expect(slashCompletionItems(skills, "/sess", "/home/rahman").map((row) => row.text)).toEqual(["/session", "/sessions"]);+ expect(slashCompletionItems(skills, "/sess", "/home/rahman").map((row) => row.text)).toEqual(["/session"]);expect(slashCompletionItems(skills, "/skills anything", "/home/rahman")).toEqual([]);});diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjsindex d3eba959..4133cbfe 100644--- a/scripts/mso-agent-status.mjs+++ b/scripts/mso-agent-status.mjs@@ -47,6 +47,13 @@ export function addUsage(total, next) {};}++function compactLabel(value, max = 28) {+ const clean = String(value || "MSO Agent session").replace(/[\r\n\t]+/g, " ").trim();+ const row = Array.from(clean);+ return row.length <= max ? clean : `${row.slice(0, Math.max(1, max - 1)).join("")}…`;+}+function homeShort(cwd) {const home = os.homedir();if (cwd === home) return "~";@@ -66,7 +73,7 @@ export function statusParts(session, cwd = process.cwd()) {const model = String(session?.state?.config?.model || "—");const ctx = contextStatus(session?.history, session?.state?.modelMeta);const turns = (session?.history || []).filter((row) => row?.role === "user").length;- const shortSession = String(session?.agentSession?.id || "—").replace(/^\d{8}_\d{6}_/, "");+ const sessionTitle = compactLabel(session?.agentSession?.title || "MSO Agent session");const usage = session?.usage || { totalTokens: 0 };const elapsed = Number(session?.lastElapsedMs || 0);const skill = skillStatus(session);@@ -76,9 +83,10 @@ export function statusParts(session, cwd = process.cwd()) {ctx.limit ? `ctx ~${compactNumber(ctx.used)}/${compactNumber(ctx.limit)} ${ctx.percent}%` : `ctx ~${compactNumber(ctx.used)}/?`,session?.agentSession?.compactThresholdTokens ? `session ~${compactNumber(session.agentSession.estimatedTokens)}/${compactNumber(session.agentSession.compactThresholdTokens)}` : null,usage.totalTokens > 0 ? `tokens ${compactNumber(usage.totalTokens)}` : null,+ `permission ${session?.permission || "ask"}`,`turns ${turns}`,elapsed > 0 ? `${(elapsed / 1000).toFixed(elapsed >= 10_000 ? 0 : 1)}s` : null,- `session ${shortSession}`,+ `session ${sessionTitle}`,homeShort(cwd),].filter(Boolean);}@@ -110,6 +118,7 @@ export function detailedStatus(session, cwd = process.cwd()) {turns: (session?.history || []).filter((row) => row?.role === "user").length,session: session?.agentSession?.id || null,title: session?.agentSession?.title || null,+ permission: session?.permission || "ask",cwd: homeShort(cwd),};}@@ -125,6 +134,7 @@ export function printDetailedStatus(session, C, cwd = process.cwd()) {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(` permission ${row.permission}`);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 a4c3ea56..1f3c2eb7 100644--- a/scripts/mso-agent-status.test.ts+++ b/scripts/mso-agent-status.test.ts@@ -33,4 +33,17 @@ describe("MSO Agent dynamic status", () => {expect(invoked).toContain("skill ✓ /design");});++ it("uses the human session title in compact status while keeping the id for detailed diagnostics", () => {+ const session = {+ 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", title: "test tui mso" },+ };+ const compact = statusParts(session, "/tmp").join(" · ");+ expect(compact).toContain("session test tui mso");+ expect(compact).toContain("permission ask");+ expect(compact).not.toContain("deadbeef");+ });+});diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjsindex 9189585c..526ccb43 100644--- a/scripts/mso-agent-ui.mjs+++ b/scripts/mso-agent-ui.mjs@@ -116,8 +116,8 @@ export function printAgentBanner(s, agentSession, { base, version }) {const tools = groupedToolLines(s.tools, 5);const skills = groupedSkillLines(s.skills?.skills, 5);const model = `${s.config?.provider ?? "—"}/${s.config?.model ?? "—"}`;- const sessionId = agentSession?.id || "—";- const title = `MSO Agent${version ? ` v${version}` : ""} · ${sessionId}`;+ const sessionTitle = fit(agentSession?.title || "MSO Agent session", 52);+ const title = fit(`MSO Agent${version ? ` v${version}` : ""} · ${sessionTitle}`, inner - 2);console.log(panelTitle(title, inner));if (totalWidth >= 94) {@@ -125,7 +125,7 @@ export function printAgentBanner(s, agentSession, { base, version }) {const leftWidth = Math.max(30, Math.floor((inner - gap) * 0.37));const rightWidth = inner - gap - leftWidth;const left = [- `${C.bold}Runtime${C.reset}`, kv("model", model, leftWidth), kv("session", sessionId, leftWidth),+ `${C.bold}Runtime${C.reset}`, kv("model", model, leftWidth), kv("session", sessionTitle, leftWidth),kv("endpoint", base, leftWidth), "", `${C.bold}Capabilities${C.reset}`,fit(`${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec`, leftWidth),fit("write/exec approval-gated", leftWidth), "", `${C.bold}Infrastructure${C.reset}`,@@ -140,7 +140,7 @@ export function printAgentBanner(s, agentSession, { base, version }) {for (let i = 0; i < rows; i++) console.log(panelLine(left[i] || "", right[i] || "", leftWidth, rightWidth, gap));} else {const lines = [- `${C.bold}Runtime${C.reset}`, kv("model", model, inner), kv("session", sessionId, inner), kv("endpoint", base, inner), "",+ `${C.bold}Runtime${C.reset}`, kv("model", model, inner), kv("session", sessionTitle, inner), kv("endpoint", base, inner), "",`${C.bold}Available Tools${C.reset}`, ...tools.map((row) => kv(row.label, row.value, inner)), "",`${C.bold}Available Skills${C.reset}`, ...skills.map((row) => kv(row.label, row.value, inner)), "",`${C.bold}Capabilities${C.reset}`, `${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec · write/exec approval-gated`,diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex 31950c1e..66cdc223 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -6,26 +6,30 @@ import { AgentComposer } from "./mso-agent-composer.mjs";import { AgentInterruptManager, isAbortError } from "./mso-agent-interrupt.mjs";import { slashCompletionItems } from "./mso-agent-slash.mjs";import { addUsage, renderStatusBar } from "./mso-agent-status.mjs";-import { persistSession, resumeArg, startupSession } from "./mso-agent-session-ui.mjs";+import { persistSession, resumeArg, startupSession, syncPromptHistory } from "./mso-agent-session-ui.mjs";import { C, api, printBanner, state, streamTurn } from "./mso-agent-runtime.mjs";import { handleSlash } from "./mso-agent-commands.mjs";+import { approvesTool, nextPermissionMode } from "./mso-agent-permissions.mjs";-async function executeTool(rl, tool, call, agentSession, signal = undefined, onInterrupt = null) {+async function executeTool(rl, tool, call, agentSession, permission = "ask", signal = undefined, onInterrupt = null) {if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };- let approved = tool.scope === "read";+ const needsApprovalDigest = tool.scope !== "read";let approval = null;+ if (needsApprovalDigest) {+ try { approval = canonicalAgentApproval(tool.name, call.input || {}); }+ catch (error) { return { ok: false, result: `cannot safely approve tool call: ${error instanceof Error ? error.message : String(error)}` }; }+ }+ let approved = approvesTool(permission, tool.scope);if (!approved) {- try {- approval = canonicalAgentApproval(tool.name, call.input || {});- } catch (error) {- return { ok: false, result: `cannot safely approve tool call: ${error instanceof Error ? error.message : String(error)}` };- }console.log(`${C.warn}${C.bold}[${tool.scope.toUpperCase()}] exact tool call${C.reset}`);console.log(approval.display);console.log(`${C.dim}sha256 ${approval.digest} · ${approval.bytes} bytes${C.reset}`);const answer = String(await rl.question(" allow this exact call? [y/N]: ", { history: false, onCancel: onInterrupt }) ?? "").trim().toLowerCase();if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");if (answer === "y" || answer === "yes") approved = true;+ } else if (needsApprovalDigest) {+ const mode = permission === "yolo" ? "YOLO" : "AUTO-WRITE";+ console.log(`${C.c}${C.bold}[${tool.scope.toUpperCase()} · ${mode}]${C.reset} ${tool.name}`);}if (!approved) return { ok: false, result: "denied by user" };process.stdout.write(`${C.dim} ↳ ${tool.name}…${C.reset}`);@@ -65,7 +69,7 @@ async function agentRound(rl, session, skillContext = null, signal = undefined,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, signal, onInterrupt);+ const outcome = await executeTool(rl, tool, call, session.agentSession, session.permission, signal, onInterrupt);results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });}session.history.push({ role: "tool", results });@@ -99,7 +103,9 @@ async function main() {console.error("mso agent needs an interactive terminal. For one-shot automation use: mso ai <prompt>");process.exit(2);}- const requested = resumeArg(process.argv.slice(2));+ const argv = process.argv.slice(2);+ const requested = resumeArg(argv);+ const forcedPermission = argv.some((arg) => ["--yolo", "-yolo", "-y"].includes(arg)) ? "yolo" : "ask";const [s, agentSession] = await Promise.all([state(),startupSession(requested),@@ -117,8 +123,10 @@ async function main() {usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },lastElapsedMs: 0,statusBar: true,+ permission: forcedPermission,};const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C });+ syncPromptHistory(rl, session);const interrupts = new AgentInterruptManager({ output: process.stdout, colors: C });const onSigint = () => {const action = interrupts.handleSigint();@@ -137,7 +145,13 @@ async function main() {try {console.log();if (session.statusBar) console.log(renderStatusBar(session, C));- const answer = await rl.question(`${C.blue}${C.bold}›${C.reset} `, { complete: completeSlash });+ const answer = await rl.question(`${C.blue}${C.bold}›${C.reset} `, {+ complete: completeSlash,+ onTab: () => {+ session.permission = nextPermissionMode(session.permission).id;+ return `${C.dim}permission → ${session.permission}${C.reset}`;+ },+ });if (answer === null) break;line = answer.trim();} catch { break; }@@ -162,7 +176,8 @@ async function main() {} finally {process.off("SIGINT", onSigint);await persistSession(session).catch(() => undefined);- console.log(`${C.dim}session ${session.agentSession.id} · resume: mso --continue | mso --resume ${session.agentSession.id}${C.reset}`);+ const sessionTitle = String(session.agentSession.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").trim().slice(0, 80);+ console.log(`${C.dim}session ${sessionTitle} · resume: mso --continue · switch: /sessions${C.reset}`);rl.close();}}diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.tsindex 0b31a356..3354af3f 100644--- a/scripts/mso-model-dx-contract.test.ts+++ b/scripts/mso-model-dx-contract.test.ts@@ -14,7 +14,7 @@ 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.6.0"');+ expect(cli).toContain('VERSION="1.6.1"');expect(cli).toContain("models * Configure AI providers/auth");expect(cli).toContain("model [ref] Select active model");expect(agentCli).toContain("run_models()");@@ -56,4 +56,10 @@ describe("MSO model/provider/session CLI contract", () => {expect(slash).toContain('text: "/resume"');expect(slash).toContain('text: "/status"');});++ it("accepts yolo as a global Agent startup flag instead of treating it as a command", () => {+ expect(cli).toContain('--yolo|-yolo) AGENT_START_ARGS+=("--yolo")');+ expect(cli).toContain('agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo]');+ });+});