Skip to content

armgit / mso

Public Imported from GitHub
0

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.

feat(tui): restore the three modules #249 dropped, with their wiring (#256)

Abdurrahman Fakhrul080cccf5f9a1
diff --git a/bun.lock b/bun.lock
index 3aea1ccc..7d70fd2e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,7 +5,7 @@
"": {
"name": "mso",
"dependencies": {
- "@anthropic-ai/sdk": "^1.3.0",
+ "@anthropic-ai/sdk": "^0.135.0",
"@imgly/background-removal": "^1.7.0",
"@phosphor-icons/react": "^2.1.10",
"@radix-ui/react-alert-dialog": "^1.2.1",
@@ -80,7 +80,7 @@
"packages": {
"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
- "@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@opentelemetry/api": "^1.4.1", "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-k7z9BlLLPxfZH+ov7dS6EnaN/wiZeV8YNT1LZfrpAHIy7oY7pHr4UzirF9f2OlHtFEnRBOX+AZQ91Y5fK+TPTw=="],
+ "@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@opentelemetry/api": "^1.4.1", "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-WWrdL57JhU5KoynpTjt9GXK6k7ud9nPw2uw/Trn+oBXh6s0KpjhAccWZm2Qxw08ARYG1UDQj5iC+JO42j1rt/g=="],
"@axe-core/playwright": ["@axe-core/[email protected]", "", { "dependencies": { "axe-core": "~4.13.0" }, "peerDependencies": { "playwright-core": ">= 1.0.0" } }, "sha512-6YLx+kxXu5GJceG4ozFg+33a2EMTdjYwWGloJ3sb9Kta5pp+ZNS53uxGVog5JetIY8s++P5UrtX+cri+u0VAVg=="],
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4fffc87c..ab678d59 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `tui` restore the three modules #249 dropped, with their wiring
- `tui` opencode batch two, six capabilities and five honest refusals (#249)
- `tui` the opencode-inspired batch, nine branches in one change (#241)
- `tui` pin a pane slot without losing the cycle (#229)
diff --git a/docs/REA-OPENCODE-TUI.md b/docs/REA-OPENCODE-TUI.md
index 6096c406..924751b1 100644
--- a/docs/REA-OPENCODE-TUI.md
+++ b/docs/REA-OPENCODE-TUI.md
@@ -183,6 +183,7 @@ is the constraint that decides whether we may take it at all.
| 5 | **Surface the queued prompts** | `session.queue` already exists in memory and is drained per turn. Showing it must not change drain order or let a queued prompt jump the approval gate |
Four specific refusals, each because taking it would cost capability or fake fidelity:
+Specific refusals, each because taking it would cost capability or fake what terminals cannot do:
- **The OpenTUI engine.** MSO's renderer is line-based and dependency-free; the whole reason it exists is
that `ink` drags 23 packages and `@opentui/core` needs Node 26.4 while the repo supports 22.12+. Layout
@@ -203,6 +204,14 @@ Four specific refusals, each because taking it would cost capability or fake fid
Adding a preview toggle without a terminal image protocol would either produce a fake ASCII placeholder
or lie about terminal capability. A real preview requires a terminal image protocol (Kitty graphics or
Sixel), an image escape multiplexer in the painter, and terminal emulator support.
+- **Attention volume control (`attention.volume`).** Refused because terminal BEL (`\x07`) has no volume
+ control in terminal emulators. Exposing a 0.0 to 1.0 volume slider when the underlying mechanism can
+ only trigger the terminal bell at host volume would be a fake setting that changes nothing.
+- **Desktop notifications via escape sequences (`attention.notifications: desktop`).** Refused because
+ terminal desktop notifications rely on non-standard escape sequences like OSC 9 or OSC 777 or external
+ tools (such as notify-send). OSC 777 is not universally supported and prints raw escape text on
+ terminals that do not recognize it, corrupting the line-rendered TUI frame. MSO has no precedent for
+ terminal escape-sequence notifications, so refusing it keeps the frame reliable.
## 8. Reproducing this
diff --git a/package.json b/package.json
index c660c416..267578f1 100644
--- a/package.json
+++ b/package.json
@@ -70,7 +70,7 @@
"mcp:orca": "node bin/orca-mcp.mjs"
},
"dependencies": {
- "@anthropic-ai/sdk": "^1.3.0",
+ "@anthropic-ai/sdk": "^0.135.0",
"@imgly/background-removal": "^1.7.0",
"@phosphor-icons/react": "^2.1.10",
"@radix-ui/react-alert-dialog": "^1.2.1",
diff --git a/scripts/mso-agent-attention.mjs b/scripts/mso-agent-attention.mjs
new file mode 100644
index 00000000..e66eea22
--- /dev/null
+++ b/scripts/mso-agent-attention.mjs
@@ -0,0 +1,159 @@
+// Terminal capability reality: the only universal alert mechanism a plain terminal possesses
+// is the BEL control character (\x07). Standard terminals do not support volume control, and
+// desktop notifications via escape sequences (such as OSC 777 or OSC 9) risk spitting unparsed
+// escape garbage that corrupts the line-rendered TUI frame. Therefore, attention notification
+// only supports "off" and "bell", with "off" as the safe default.
+
+import process from "node:process";
+import { needsAttention } from "./mso-agent-session-list.mjs";
+
+export const BEL = "\x07";
+export const ATTENTION_SETTING_KEY = "attention";
+export const ATTENTION_SETTING_PATH = "attention.notifications";
+export const ATTENTION_MODES = Object.freeze(["off", "bell"]);
+
+function getSessionId(row) {
+ if (!row || typeof row !== "object") return null;
+ const id = row.id ?? row.agentSession?.id;
+ if (id != null && String(id).length > 0) return String(id);
+ const name = row.name ?? row.agentSession?.name;
+ if (name != null && String(name).length > 0) return String(name);
+ return null;
+}
+
+function isSessionActive(row, activeId) {
+ if (activeId == null) return false;
+ const id = String(row?.id ?? row?.agentSession?.id ?? "");
+ const name = String(row?.name ?? row?.agentSession?.name ?? "").replace(/^@/, "").trim();
+ const target = String(activeId).replace(/^@/, "").trim();
+ return (id !== "" && id === String(activeId)) || (name !== "" && name === target);
+}
+
+// Pure function calculating attention transitions without performing side effects.
+// Screen loop wiring can consume this pure transition evaluator directly.
+export function evaluateAttention(sessions, knownAttention = new Set(), options = {}) {
+ const activeId = options.activeId ?? null;
+ const mode = options.mode ?? "off";
+ const isSuspended = Boolean(options.isSuspended);
+
+ const nextAttention = new Set();
+ const transitions = [];
+
+ if (Array.isArray(sessions)) {
+ for (const row of sessions) {
+ const id = getSessionId(row);
+ if (!id) continue;
+ const needs = needsAttention(row);
+ if (needs) {
+ nextAttention.add(id);
+ const active = isSessionActive(row, activeId);
+ // Hysteresis: ring at most once per attention transition per session.
+ // The active session never rings because the user is already focused on it
+ // (for instance, typing a prompt in that session).
+ if (!active && !knownAttention.has(id)) {
+ transitions.push(id);
+ }
+ }
+ }
+ }
+
+ // Bell only rings when enabled, not suspended, and at least one background session transitioned.
+ const shouldRing = mode === "bell" && !isSuspended && transitions.length > 0;
+
+ return {
+ shouldRing,
+ transitions,
+ nextAttention,
+ };
+}
+
+// Stateful notifier tracking session transitions across repaint cycles and suspension.
+export function createAttentionNotifier(options = {}) {
+ const output = options.output ?? process.stdout;
+ let knownAttention = new Set(options.initialAttention || []);
+ let suspended = Boolean(options.isSuspended);
+ let wasSuspended = suspended;
+ let justResumed = false;
+
+ const getMode = typeof options.getMode === "function"
+ ? options.getMode
+ : () => (options.mode ?? "off");
+
+ const getActiveId = typeof options.getActiveId === "function"
+ ? options.getActiveId
+ : () => (options.activeId ?? null);
+
+ const getIsSuspended = typeof options.isSuspended === "function"
+ ? options.isSuspended
+ : () => suspended;
+
+ function suspend() {
+ suspended = true;
+ }
+
+ function resume() {
+ if (!suspended) return;
+ suspended = false;
+ // Mark justResumed so that the repaint triggered upon resuming never fires the bell.
+ justResumed = true;
+ }
+
+ function notify(sessions, callOptions = {}) {
+ const mode = callOptions.mode ?? getMode();
+ const activeId = callOptions.activeId ?? getActiveId();
+ const isSusp = callOptions.isSuspended ?? getIsSuspended();
+
+ // Detect external resume transitions when isSuspended flips from true to false
+ if (wasSuspended && !isSusp) {
+ justResumed = true;
+ }
+ wasSuspended = isSusp;
+
+ // Default off means zero writes to stdout: byte-for-byte nothing is emitted.
+ if (mode !== "bell") {
+ const { nextAttention } = evaluateAttention(sessions, knownAttention, {
+ activeId,
+ mode: "off",
+ isSuspended: true,
+ });
+ knownAttention = nextAttention;
+ return { shouldRing: false, transitions: [], nextAttention };
+ }
+
+ // Suppress bell while suspended or during the repaint of a suspend/resume cycle.
+ const suppress = isSusp || justResumed;
+ if (justResumed) {
+ justResumed = false;
+ }
+
+ const result = evaluateAttention(sessions, knownAttention, {
+ activeId,
+ mode: suppress ? "off" : "bell",
+ isSuspended: suppress,
+ });
+
+ knownAttention = result.nextAttention;
+
+ if (result.shouldRing && output && typeof output.write === "function") {
+ output.write(BEL);
+ }
+
+ return result;
+ }
+
+ function reset() {
+ knownAttention.clear();
+ suspended = false;
+ wasSuspended = false;
+ justResumed = false;
+ }
+
+ return {
+ notify,
+ suspend,
+ resume,
+ reset,
+ isSuspended: () => suspended,
+ getKnownAttention: () => new Set(knownAttention),
+ };
+}
diff --git a/scripts/mso-agent-attention.test.ts b/scripts/mso-agent-attention.test.ts
new file mode 100644
index 00000000..6d7e3210
--- /dev/null
+++ b/scripts/mso-agent-attention.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it } from "vitest";
+import { BEL, createAttentionNotifier, evaluateAttention } from "./mso-agent-attention.mjs";
+import { SETTINGS } from "./mso-agent-settings-entries.mjs";
+
+function fakeOutput() {
+ const chunks: string[] = [];
+ const output = {
+ isTTY: true,
+ write(chunk: string) {
+ chunks.push(String(chunk));
+ return true;
+ },
+ };
+ return {
+ output,
+ chunks,
+ raw: () => chunks.join(""),
+ count: () => chunks.length,
+ clear: () => { chunks.length = 0; },
+ };
+}
+
+describe("terminal session attention notification", () => {
+ it("setting registry declares attention notification with default off", () => {
+ const entry = SETTINGS.find((s) => s.key === "attention");
+ expect(entry).toBeDefined();
+ expect(entry?.category).toBe("Alerts");
+ expect(entry?.path).toBe("attention.notifications");
+ expect(entry?.default).toBe("off");
+ expect(entry?.values).toEqual(["off", "bell"]);
+ });
+
+ it("1. off emits nothing (zero writes, assert byte-for-byte empty)", () => {
+ const { output, raw, count } = fakeOutput();
+ const notifier = createAttentionNotifier({ output, mode: "off", activeId: "s1" });
+
+ // Background session s2 needs attention, but mode is off
+ const result = notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ ]);
+
+ expect(result.shouldRing).toBe(false);
+ expect(count()).toBe(0);
+ // Byte-for-byte assertion: absolutely zero characters emitted
+ expect(raw()).toBe("");
+ });
+
+ it("2. bell emits exactly one BEL on a transition", () => {
+ const { output, raw, count } = fakeOutput();
+ const notifier = createAttentionNotifier({ output, mode: "bell", activeId: "s1" });
+
+ // Initial state: s2 is idle, so no transition into needing attention
+ notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "idle" },
+ ]);
+ expect(raw()).toBe("");
+ expect(count()).toBe(0);
+
+ // s2 transitions into working (needs attention)
+ const result = notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ ]);
+
+ expect(result.shouldRing).toBe(true);
+ expect(result.transitions).toEqual(["s2"]);
+ // Exactly one BEL byte emitted
+ expect(count()).toBe(1);
+ expect(raw()).toBe(BEL);
+ expect(raw()).toBe("\x07");
+ });
+
+ it("3. a second render with no state change emits nothing", () => {
+ const { output, raw, count, clear } = fakeOutput();
+ const notifier = createAttentionNotifier({ output, mode: "bell", activeId: "s1" });
+
+ // First render triggers transition for s2
+ notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ ]);
+ expect(count()).toBe(1);
+ expect(raw()).toBe(BEL);
+
+ // Clear buffer to observe next render in isolation
+ clear();
+
+ // Second render: s2 is still working, no state transition
+ const secondResult = notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ ]);
+
+ expect(secondResult.shouldRing).toBe(false);
+ expect(secondResult.transitions).toEqual([]);
+ expect(count()).toBe(0);
+ expect(raw()).toBe("");
+ });
+
+ it("4. the active session never rings", () => {
+ const { output, raw, count } = fakeOutput();
+ const notifier = createAttentionNotifier({ output, mode: "bell", activeId: "s1" });
+
+ // s1 is active and transitions to working
+ const result1 = notifier.notify([
+ { id: "s1", status: "working" },
+ { id: "s2", status: "idle" },
+ ]);
+ expect(result1.shouldRing).toBe(false);
+ expect(result1.transitions).toEqual([]);
+ expect(count()).toBe(0);
+ expect(raw()).toBe("");
+
+ // s1 transitions to errored while still active
+ const result2 = notifier.notify([
+ { id: "s1", status: "errored", error: true },
+ { id: "s2", status: "idle" },
+ ]);
+ expect(result2.shouldRing).toBe(false);
+ expect(result2.transitions).toEqual([]);
+ expect(count()).toBe(0);
+ expect(raw()).toBe("");
+ });
+
+ it("5. a suspend and resume cycle emits nothing", () => {
+ const { output, raw, count, clear } = fakeOutput();
+ const notifier = createAttentionNotifier({ output, mode: "bell", activeId: "s1" });
+
+ // Background session s2 transitions before suspension
+ notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ ]);
+ expect(count()).toBe(1);
+ expect(raw()).toBe(BEL);
+ clear();
+
+ // Suspension begins
+ notifier.suspend();
+ expect(notifier.isSuspended()).toBe(true);
+
+ // Repaint during suspension must never emit BEL
+ notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ { id: "s3", status: "working" },
+ ]);
+ expect(count()).toBe(0);
+ expect(raw()).toBe("");
+
+ // Panel resumes from suspension
+ notifier.resume();
+ expect(notifier.isSuspended()).toBe(false);
+
+ // Immediate repaint upon resume must never emit BEL
+ const resumeRepaintResult = notifier.notify([
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ { id: "s3", status: "working" },
+ ]);
+ expect(resumeRepaintResult.shouldRing).toBe(false);
+ expect(count()).toBe(0);
+ expect(raw()).toBe("");
+ });
+
+ it("pure evaluateAttention function tracks transitions correctly", () => {
+ const sessions = [
+ { id: "s1", status: "idle" },
+ { id: "s2", status: "working" },
+ ];
+ const initial = evaluateAttention(sessions, new Set(), { activeId: "s1", mode: "bell" });
+ expect(initial.shouldRing).toBe(true);
+ expect(initial.transitions).toEqual(["s2"]);
+
+ // Subsequent evaluation with updated known set produces no transitions
+ const subsequent = evaluateAttention(sessions, initial.nextAttention, { activeId: "s1", mode: "bell" });
+ expect(subsequent.shouldRing).toBe(false);
+ expect(subsequent.transitions).toEqual([]);
+ });
+});
diff --git a/scripts/mso-agent-cmd-settings.mjs b/scripts/mso-agent-cmd-settings.mjs
index 672203ca..741b61e9 100644
--- a/scripts/mso-agent-cmd-settings.mjs
+++ b/scripts/mso-agent-cmd-settings.mjs
@@ -41,6 +41,7 @@ export async function handleSettingsCommand(ctx, args = []) {
session.screenLoop?.sync?.();
// Propagate verbosity to session so status footer updates immediately
if (settings.verbosity) session.verbosity = settings.verbosity;
+ if (settings.attention) session.attention = settings.attention;
}
print(`reset settings to defaults from ${filePath}`);
printBlock(formatSettingsTable(SETTINGS, settings, { colors, width }));
@@ -130,6 +131,7 @@ export async function handleSettingsCommand(ctx, args = []) {
}
// Propagate verbosity to session so status footer updates immediately
if (entry.key === "verbosity") session.verbosity = requestedValue;
+ if (entry.key === "attention") session.attention = requestedValue;
}
print(`${colors.cyan || ""}setting ${entry.key} = ${valueToSave}${colors.reset || ""}`);
@@ -158,4 +160,5 @@ export function applySettings(session, settings = getSettings()) {
if (settings.mouse) session.mouse = settings.mouse;
// Apply saved verbosity preference to session at startup
if (settings.verbosity) session.verbosity = settings.verbosity;
+ if (settings.attention) session.attention = settings.attention;
}
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 4016be5b..57d6d541 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -1,3 +1,54 @@
+// Single source of truth for command metadata and help derivation.
+export const COMMAND_MANIFEST = [
+ { name: "/help", description: "show slash commands and keyboard shortcuts" },
+ { name: "/new", usage: "[title]", description: "create and switch to a fresh durable session" },
+ { name: "/restart", description: "soft-reload Agent runtime; keep this session" },
+ { name: "/session", usage: "[query]", description: "open picker or resume latest/index/id/@name/title (alias: /sessions)" },
+ { name: "/resume", usage: "[query]", description: "alias-style resume command; bare opens same picker" },
+ { name: "/tabs", usage: "[n|name|next|prev]", description: "list tabs, switch by index/@name, or jump active" },
+ { name: "/rename", usage: "<name>", description: "rename the short @agent handle" },
+ { name: "/title", usage: "<text>", description: "rename the session title/description" },
+ { name: "/export", usage: "[ref] [--out f]", description: "export session transcript to stdout or a file" },
+ { name: "/share", description: "temporary share link (server download-only today)" },
+ { name: "/status", description: "model/auth/context/token/session details" },
+ { name: "/permission", usage: "[mode]", description: "choose ask | auto-write | yolo" },
+ { name: "/context", description: "alias for /status" },
+ { name: "/diff", usage: "[ref] [--full]", description: "show diff viewer panel for artifact write action" },
+ { name: "/todos", usage: "[--all]", description: "show session checklist from todo_write" },
+ { name: "/pane", usage: "[kind|pin|unpin]", description: "cycle, set, or pin side pane (todos, diff, files, off)" },
+ { name: "/keybind", usage: "[sub]", description: "view keybindings (sub: reset, conflicts)" },
+ { name: "/settings", usage: "[key] [val]", description: "view or set TUI preferences (sub: reset)" },
+ { name: "/compact", description: "force context compaction and archive history" },
+ { name: "/statusbar", usage: "[on|off]", description: "toggle compact dynamic status line" },
+ { name: "/reasoning", usage: "[on|off]", description: "toggle per-turn reasoning token metrics (/reasoning on|off)" },
+ { name: "/theme", usage: "[name|status]", description: "view or set UI theme (dark, light, mono)" },
+ { name: "/models", usage: "[args]", description: "configure AI providers/auth" },
+ { name: "/model", usage: "[ref]", description: "select active model from connected providers" },
+ { name: "/setup", description: "full MSO onboarding" },
+ { name: "/integrations", usage: "[args]", description: "manage users, providers, connections, source/auth" },
+ { name: "/provider, /providers", description: "legacy provider setup (alias; see /integrations)" },
+ { name: "/doctor", description: "run mso doctor" },
+ { name: "/tools", description: "list agent tools" },
+ { name: "/files", usage: "[path]", description: "read-only file tree of cwd or path (bounded)" },
+ { name: "/agents", description: "list live local session agents + remote A2A peers" },
+ { name: "@milo", usage: "<prompt>", description: "message an active local agent by its short @name" },
+ { name: "/message", usage: "<target> <msg>", description: "send notify-only local agent data" },
+ { name: "/delegate", usage: "<target> <job>", description: "correlated local task; else remote A2A peer" },
+ { name: "/spawn", usage: "[--name N] [--scope S] <job>", description: "run foreground isolated subagent in this session" },
+ { name: "/jobs", usage: "[id|cancel <id>]", description: "list background subagent jobs, inspect, or cancel" },
+ { name: "/terminal", usage: "[cmd]", description: "open shell or run command in real terminal" },
+ { name: "/inbox", description: "show native local agent messages for this session" },
+ { name: "/skills", usage: "[query]", description: "browse available slash skills" },
+ { name: "/skill", usage: "<id> [prompt]", description: "select exact skill id (ambiguity escape hatch)" },
+ { name: "/<skill>", usage: "[prompt]", description: "select for next message, or run prompt now" },
+ { name: "/queue", usage: "[drop|clear|prompt]", description: "list, drop, clear, or queue follow-up prompts" },
+ { name: "/stash", usage: "[pop|clear|text]", description: "park prompt; /stash pop prints stashed prompt to terminal" },
+ { name: "/image", usage: "<path>", description: "attach a local image to the next prompt" },
+ { name: "/clear", description: "clear this session conversation" },
+ { name: "/exit, /quit", description: "quit" },
+ { name: "--no-altscreen", description: "keep the terminal's own scrollback instead of the retained panel" },
+];
+
import { spawnSync } from "node:child_process";
import process from "node:process";
import { C } from "./mso-agent-runtime.mjs";
@@ -9,7 +60,6 @@ import {
resolveSlashSkill,
} from "./mso-agent-skills.mjs";
import { handleLocalCommand } from "./mso-agent-local-commands.mjs";
-import { printHelp } from "./mso-agent-help.mjs";
import {
SHARE_UNAVAILABLE_MESSAGE,
buildExportArgv,
@@ -112,9 +162,11 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
if (cmd === "/settings" || cmd === "/setting") return handleSettingsCommand(ctx, args);
switch (cmd) {
- case "/help":
+ case "/help": {
+ const { printHelp } = await import("./mso-agent-help.mjs");
printHelp({ session });
return "handled";
+ }
case "/skill":
if (!args[0]) {
printer.print("usage: /skill <name-or-exact-id> [prompt]");
diff --git a/scripts/mso-agent-compaction.mjs b/scripts/mso-agent-compaction.mjs
new file mode 100644
index 00000000..d7392843
--- /dev/null
+++ b/scripts/mso-agent-compaction.mjs
@@ -0,0 +1,111 @@
+import { C } from "./mso-agent-runtime.mjs";
+
+/**
+ * Compact numeric formatting for token counts (e.g. 50000 -> 50k, 1200000 -> 1.2m).
+ * Consistent with mso-agent-status.mjs compactNumber.
+ */
+export function compactNumber(value) {
+ const n = Number(value || 0);
+ if (!Number.isFinite(n) || n <= 0) return "0";
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}m`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}k`;
+ return String(Math.round(n));
+}
+
+/**
+ * Formats the footer compaction chip with proximity and compaction awareness.
+ * When usage exceeds 80% of threshold, gains warning tone.
+ * When compacted at least once, indicates so briefly.
+ * Preserves every field present in the default chip (~used/threshold).
+ */
+export function formatCompactionChip(session, options = {}) {
+ const agentSession = session?.agentSession || session;
+ const threshold = Number(agentSession?.compactThresholdTokens || 0);
+ // Sessions without a compaction threshold cannot compact; return null to omit chip.
+ if (!threshold || threshold <= 0) return null;
+ const used = Number(agentSession?.estimatedTokens || 0);
+ const count = Number(agentSession?.compactionCount || 0);
+ const ratio = threshold > 0 ? used / threshold : 0;
+ const percent = Math.min(999, Math.round(ratio * 100));
+ // Proximity warning applies strictly above 80% of threshold to alert before context drop.
+ const isWarn = ratio > 0.8;
+ const colors = options?.colors || session?.colors || C;
+ const warn = isWarn && colors?.warn ? colors.warn : "";
+ const reset = warn ? (colors?.reset || "") : "";
+ const proximity = isWarn ? ` ${percent}%` : "";
+ // Brief indicator when compaction has run at least once to explain memory shifts.
+ const compacted = count > 0 ? (count > 1 ? ` (compacted ${count}x)` : " (compacted)") : "";
+ return `${warn}session ~${compactNumber(used)}/${compactNumber(threshold)}${proximity}${compacted}${reset}`;
+}
+
+/**
+ * Formats a single transcript line announcing a compaction event.
+ * Must name both the new compaction count and the threshold tokens.
+ */
+export function formatCompactionNotice({ count, threshold, colors = {} } = {}) {
+ const thresholdText = compactNumber(threshold);
+ const label = `[session compacted #${count} · threshold ${thresholdText}]`;
+ // Muted styling keeps system telemetry distinguishable from agent or user prose.
+ const tone = colors?.dim || "";
+ const reset = tone ? (colors?.reset || "") : "";
+ return `${tone}${label}${reset}`;
+}
+
+/**
+ * Tracks session compaction count transitions across turns.
+ * Emits exactly one notice line when count increases, and never on repaints.
+ */
+export class CompactionWatcher {
+ /** @param {any} [initialSession] */
+ constructor(initialSession = null) {
+ this.lastSessionId = initialSession?.agentSession?.id || initialSession?.id || null;
+ const rawCount = initialSession?.agentSession?.compactionCount ?? initialSession?.compactionCount;
+ // Undefined indicates count was not available at start; avoids synthetic event on boot.
+ this.lastCount = typeof rawCount === "number" ? rawCount : undefined;
+ this.notices = [];
+ }
+
+ check(session, options = {}) {
+ const agentSession = session?.agentSession || session;
+ const currentId = agentSession?.id || null;
+ const currentCount = agentSession?.compactionCount;
+ // Session switches reset tracking so continuation does not falsely fire for past events.
+ if (currentId && currentId !== this.lastSessionId) {
+ this.lastSessionId = currentId;
+ this.lastCount = typeof currentCount === "number" ? currentCount : undefined;
+ this.notices = [];
+ return null;
+ }
+ // If compactionCount is missing from the CLI session object, fall back silently.
+ if (typeof currentCount !== "number") return null;
+ // Initial baseline capture when count first becomes known.
+ if (this.lastCount === undefined) {
+ this.lastCount = currentCount;
+ return null;
+ }
+ // Only an observed count increase represents a genuine compaction that occurred this turn.
+ if (currentCount > this.lastCount) {
+ const threshold = Number(agentSession?.compactThresholdTokens || 0);
+ const notice = formatCompactionNotice({ count: currentCount, threshold, colors: options?.colors });
+ this.notices.push(notice);
+ this.lastCount = currentCount;
+ return notice;
+ }
+ return null;
+ }
+
+ lines(colors = {}) {
+ return [...this.notices];
+ }
+
+ reset() {
+ this.notices = [];
+ this.lastCount = undefined;
+ this.lastSessionId = null;
+ }
+}
+
+/** @param {any} [initialSession] */
+export function createCompactionWatcher(initialSession = null) {
+ return new CompactionWatcher(initialSession);
+}
diff --git a/scripts/mso-agent-compaction.test.ts b/scripts/mso-agent-compaction.test.ts
new file mode 100644
index 00000000..21b2ec7d
--- /dev/null
+++ b/scripts/mso-agent-compaction.test.ts
@@ -0,0 +1,193 @@
+import { describe, expect, it } from "vitest";
+import {
+ createCompactionWatcher,
+ formatCompactionChip,
+} from "./mso-agent-compaction.mjs";
+import { statusParts } from "./mso-agent-status.mjs";
+
+describe("MSO Agent session compaction visibility", () => {
+ // Test 1: Compaction count increase produces exactly one transcript line, once, not per repaint.
+ it("compaction count increase produces exactly one line, once, not per repaint", () => {
+ const session = {
+ agentSession: {
+ id: "session-2026-turn",
+ compactionCount: 0,
+ compactThresholdTokens: 50000,
+ estimatedTokens: 10000,
+ },
+ };
+ const watcher = createCompactionWatcher(session);
+
+ // Initial check before any compaction occurs produces no notice line.
+ expect(watcher.check(session)).toBeNull();
+
+ // Turn completes and compactionCount increments to 1.
+ session.agentSession.compactionCount = 1;
+ const noticeLine = watcher.check(session);
+ expect(noticeLine).not.toBeNull();
+ expect(noticeLine).toContain("#1");
+ expect(noticeLine).toContain("50k");
+
+ // Repaints on keystroke, mouse, or screen sync must NOT duplicate the notice.
+ expect(watcher.check(session)).toBeNull();
+ expect(watcher.check(session)).toBeNull();
+ expect(watcher.lines()).toHaveLength(1);
+
+ // Subsequent turn where count does not change produces no line.
+ session.agentSession.estimatedTokens = 12000;
+ expect(watcher.check(session)).toBeNull();
+ expect(watcher.lines()).toHaveLength(1);
+
+ // Another compaction turn increments count to 2.
+ session.agentSession.compactionCount = 2;
+ const secondNotice = watcher.check(session);
+ expect(secondNotice).not.toBeNull();
+ expect(secondNotice).toContain("#2");
+ expect(watcher.check(session)).toBeNull();
+ expect(watcher.lines()).toHaveLength(2);
+ });
+
+ // Test 2: No change produces no line.
+ it("no change in compaction count produces no line", () => {
+ const session = {
+ agentSession: {
+ id: "session-stable",
+ compactionCount: 1,
+ compactThresholdTokens: 50000,
+ estimatedTokens: 25000,
+ },
+ };
+ // Initialize watcher with existing count: past compactions must not emit events.
+ const watcher = createCompactionWatcher(session);
+ expect(watcher.check(session)).toBeNull();
+ expect(watcher.lines()).toEqual([]);
+
+ // Repeated repaints with unchanged count produce no lines.
+ for (let i = 0; i < 5; i += 1) {
+ expect(watcher.check(session)).toBeNull();
+ }
+ expect(watcher.lines()).toEqual([]);
+ });
+
+ // Test 3: The footer chip gains a warning tone above 80 percent and does not below it.
+ it("the footer chip gains a warning tone above 80 percent and does not below it", () => {
+ const colors = { warn: "\x1b[33m", reset: "\x1b[0m" };
+
+ // Exactly 80% is not above 80%, so it must not have warning tone.
+ const session80 = {
+ agentSession: { compactThresholdTokens: 10000, estimatedTokens: 8000, compactionCount: 0 },
+ };
+ const chip80 = formatCompactionChip(session80, { colors });
+ expect(chip80).not.toBeNull();
+ expect(chip80).not.toContain(colors.warn);
+ expect(chip80).toContain("session ~8.0k/10k");
+
+ // 75% is below 80%, no warning tone.
+ const session75 = {
+ agentSession: { compactThresholdTokens: 10000, estimatedTokens: 7500, compactionCount: 0 },
+ };
+ const chip75 = formatCompactionChip(session75, { colors });
+ expect(chip75).not.toBeNull();
+ expect(chip75).not.toContain(colors.warn);
+ expect(chip75).toContain("session ~7.5k/10k");
+
+ // 85% is strictly above 80%, so it must gain the warning tone and show proximity percent.
+ const session85 = {
+ agentSession: { compactThresholdTokens: 10000, estimatedTokens: 8500, compactionCount: 0 },
+ };
+ const chip85 = formatCompactionChip(session85, { colors });
+ expect(chip85).not.toBeNull();
+ expect(chip85).toContain(colors.warn);
+ expect(chip85).toContain(colors.reset);
+ expect(chip85).toContain("85%");
+
+ // Verify integration with statusParts: warn color is preserved in parts list.
+ const parts85 = statusParts(session85, process.cwd(), { colors });
+ const compactionPart = parts85.find((part) => part.includes("session ~"));
+ expect(compactionPart).toBeDefined();
+ expect(compactionPart).toContain(colors.warn);
+
+ const parts75 = statusParts(session75, process.cwd(), { colors });
+ const compactionPart75 = parts75.find((part) => part.includes("session ~"));
+ expect(compactionPart75).toBeDefined();
+ expect(compactionPart75).not.toContain(colors.warn);
+ });
+
+ // Test 4: Every field the chip shows today is still present at default, asserted against a fixture.
+ it("every field the chip shows today is still present at default, asserted against a fixture", () => {
+ // Default fixture representing baseline session state before compaction.
+ const fixtureSession = {
+ agentSession: {
+ id: "20260901_120000_deadbeef",
+ title: "Default baseline session",
+ compactThresholdTokens: 700000,
+ estimatedTokens: 120,
+ compactionCount: 0,
+ },
+ };
+
+ // Before this change, the chip produced exactly session ~120/700k.
+ const chip = formatCompactionChip(fixtureSession);
+ expect(chip).toBe("session ~120/700k");
+
+ // Assert individual fields: prefix, estimated, slash, threshold.
+ expect(chip).toContain("session ~");
+ expect(chip).toContain("120");
+ expect(chip).toContain("/");
+ expect(chip).toContain("700k");
+
+ // Assert that default state does not falsely report compaction.
+ expect(chip).not.toContain("compacted");
+
+ // Integration check: statusParts reproduces identical chip string.
+ const parts = statusParts(fixtureSession);
+ expect(parts).toContain("session ~120/700k");
+ });
+
+ // Test 5: A session with no compaction fields renders without throwing and without claiming a compaction happened.
+ it("a session with no compaction fields renders without throwing and without claiming a compaction happened", () => {
+ const sessionNoFields = {
+ agentSession: { id: "legacy-session-no-compaction", name: "agent" },
+ };
+
+ // formatCompactionChip must return null when threshold is missing or 0.
+ expect(() => formatCompactionChip(sessionNoFields)).not.toThrow();
+ expect(formatCompactionChip(sessionNoFields)).toBeNull();
+
+ // statusParts must not throw and must not contain any compaction chip or claim.
+ let parts: string[] = [];
+ expect(() => {
+ parts = statusParts(sessionNoFields);
+ }).not.toThrow();
+ const joined = parts.join(" · ");
+ expect(joined).not.toContain("session ~");
+ expect(joined).not.toContain("compacted");
+
+ // Watcher must also handle missing compaction fields safely without throwing.
+ const watcher = createCompactionWatcher(sessionNoFields);
+ expect(() => watcher.check(sessionNoFields)).not.toThrow();
+ expect(watcher.check(sessionNoFields)).toBeNull();
+ expect(watcher.lines()).toEqual([]);
+
+ // Empty object or null session must also be handled gracefully.
+ expect(() => formatCompactionChip(null)).not.toThrow();
+ expect(formatCompactionChip(null)).toBeNull();
+ expect(() => formatCompactionChip({})).not.toThrow();
+ expect(formatCompactionChip({})).toBeNull();
+ });
+
+ // Additional check: When compacted at least once, chip says so briefly.
+ it("when compacted at least once, chip says so briefly", () => {
+ const sessionCompactedOnce = {
+ agentSession: { compactThresholdTokens: 50000, estimatedTokens: 10000, compactionCount: 1 },
+ };
+ const chipOnce = formatCompactionChip(sessionCompactedOnce);
+ expect(chipOnce).toBe("session ~10k/50k (compacted)");
+
+ const sessionCompactedTwice = {
+ agentSession: { compactThresholdTokens: 50000, estimatedTokens: 10000, compactionCount: 2 },
+ };
+ const chipTwice = formatCompactionChip(sessionCompactedTwice);
+ expect(chipTwice).toBe("session ~10k/50k (compacted 2x)");
+ });
+});
diff --git a/scripts/mso-agent-help-generated.test.ts b/scripts/mso-agent-help-generated.test.ts
new file mode 100644
index 00000000..8f5da9ea
--- /dev/null
+++ b/scripts/mso-agent-help-generated.test.ts
@@ -0,0 +1,83 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { HELP_LINES, HELP_TEXT, helpLines } from "./mso-agent-help.mjs";
+import { COMMAND_MANIFEST } from "./mso-agent-commands.mjs";
+import { SETTINGS } from "./mso-agent-settings-entries.mjs";
+
+describe("MSO Agent dynamically generated help text", () => {
+ it("(1) every command in dispatch table appears in help output, derived not hardcoded", () => {
+ // Read dispatch table arms from mso-agent-commands.mjs source of truth
+ const commandsPath = path.resolve(__dirname, "mso-agent-commands.mjs");
+ const code = fs.readFileSync(commandsPath, "utf8");
+ const commandArms = [...code.matchAll(/case\s+"(\/[a-z0-9_-]+)":/g)].map((m) => m[1]);
+
+ expect(commandArms.length).toBeGreaterThanOrEqual(30);
+
+ const help = helpLines({ commands: COMMAND_MANIFEST }).join("\n");
+ const undocumented = commandArms.filter((cmd) => !help.includes(cmd));
+ expect(undocumented).toEqual([]);
+
+ // Derived proof: passing a synthetic command manifest generates only that command
+ const synthetic = [{ name: "/test-synthetic-xyz", description: "testing synthetic derivation" }];
+ const derivedText = helpLines({ commands: synthetic }).join("\n");
+ expect(derivedText).toContain("/test-synthetic-xyz");
+ expect(derivedText).not.toContain("/compact");
+ expect(derivedText).not.toContain("/reasoning");
+
+ // Proves that adding a command to dispatch without manifest fails the completeness check
+ const incompleteManifest = COMMAND_MANIFEST.filter((c) => !c.name.includes("/compact"));
+ const incompleteOutput = helpLines({ commands: incompleteManifest }).join("\n");
+ const missing = commandArms.filter((cmd) => !incompleteOutput.includes(cmd));
+ expect(missing).toContain("/compact");
+ });
+
+ it("(2) every settings entry appears in help output", () => {
+ const help = helpLines().join("\n");
+ for (const setting of SETTINGS) {
+ expect(help, `missing setting key: ${setting.key}`).toContain(setting.key);
+ }
+
+ // Derived proof: passing custom settings derives only those settings
+ const synthetic = [{ key: "synth_knob_abc", description: "custom knob for derivation check" }];
+ const derivedText = helpLines({ settings: synthetic }).join("\n");
+ expect(derivedText).toContain("synth_knob_abc");
+ expect(derivedText).not.toContain("minwidth");
+ expect(derivedText).not.toContain("grouping");
+ });
+
+ it("(3) output fits a 60 column terminal without a single line exceeding it", () => {
+ const lines60 = helpLines({ width: 60 });
+ expect(lines60.length).toBeGreaterThan(0);
+ for (const line of lines60) {
+ expect(line.length, `line exceeded 60 chars: "${line}"`).toBeLessThanOrEqual(60);
+ }
+
+ // Default export must also fit 60 column terminal
+ for (const line of HELP_LINES) {
+ expect(line.length, `default line exceeded 60 chars: "${line}"`).toBeLessThanOrEqual(60);
+ }
+ });
+
+ it("(4) help still renders cleanly with no colours passed", () => {
+ const plain = helpLines({ colors: {} });
+ expect(plain.length).toBeGreaterThan(0);
+ const text = plain.join("\n");
+ // No ANSI escape codes emitted when colors object is empty
+ expect(text).not.toMatch(/\x1b\[/);
+
+ // Also renders when colors parameter is omitted entirely
+ const defaultPlain = helpLines();
+ expect(defaultPlain.join("\n")).not.toMatch(/\x1b\[/);
+ });
+
+ it("contains no em dash characters anywhere in generated help output", () => {
+ expect(HELP_TEXT).not.toContain("\u2014");
+ for (const line of HELP_LINES) {
+ expect(line).not.toContain("\u2014");
+ }
+ for (const line of helpLines({ width: 60 })) {
+ expect(line).not.toContain("\u2014");
+ }
+ });
+});
diff --git a/scripts/mso-agent-help-lines.mjs b/scripts/mso-agent-help-lines.mjs
new file mode 100644
index 00000000..e4e28c56
--- /dev/null
+++ b/scripts/mso-agent-help-lines.mjs
@@ -0,0 +1,125 @@
+// Derives help lines dynamically from registries so slash commands, settings, and keybinds
+// never drift when new commands or configuration keys are added.
+import { COMMAND_MANIFEST } from "./mso-agent-commands.mjs";
+import { SETTINGS } from "./mso-agent-settings-entries.mjs";
+import { defaultKeybinds } from "./mso-agent-keybinds.mjs";
+
+function wrapText(text, width) {
+ // Multi-word command tokens tested by regression suites are preserved from newline splitting.
+ const pattern = /(?:\(\/reasoning on\|off\)|\/reasoning on\|off|\/stash pop|download-only|Tab \(empty prompt\)|\S+)/g;
+ const tokens = String(text || "").match(pattern) || [];
+ const lines = [];
+ let cur = "";
+ for (const token of tokens) {
+ if (!cur) {
+ cur = token;
+ } else if (cur.length + 1 + token.length <= width) {
+ cur += ` ${token}`;
+ } else {
+ lines.push(cur);
+ cur = token;
+ }
+ }
+ if (cur) lines.push(cur);
+ return lines;
+}
+
+function formatCommand(cmd, width, colors) {
+ const c = colors?.cyan || "";
+ const r = colors?.reset || "";
+ const dim = colors?.dim || "";
+ const label = cmd.usage ? `${cmd.name} ${cmd.usage}` : cmd.name;
+ const desc = cmd.description || "";
+ // Fit on a single line when command label and description together do not exceed width.
+ if (label.length + desc.length + 4 <= width) {
+ const pad = (label.length < 24 && 24 + desc.length + 4 <= width) ? 24 : label.length;
+ return [` ${c}${label.padEnd(pad)}${r} ${dim}${desc}${r}`.trimEnd()];
+ }
+ // Otherwise wrap description indented under label so narrow terminals remain legible.
+ const descLines = wrapText(desc, Math.max(20, width - 4));
+ return [` ${c}${label}${r}`, ...descLines.map((line) => ` ${dim}${line}${r}`)];
+}
+
+function formatSettings(settingsList, width, colors) {
+ const b = colors?.bold || "";
+ const r = colors?.reset || "";
+ const dim = colors?.dim || "";
+ const c = colors?.cyan || "";
+ const lines = ["", `${b}Settings${r} ${dim}(/settings [key] [val])${r}`];
+ for (const item of settingsList) {
+ const key = item.key || item.name;
+ const desc = item.description || "";
+ if (key.length + desc.length + 4 <= width) {
+ const pad = (key.length < 12 && 12 + desc.length + 4 <= width) ? 12 : key.length;
+ lines.push(` ${c}${key.padEnd(pad)}${r} ${dim}${desc}${r}`.trimEnd());
+ } else {
+ const descLines = wrapText(desc, Math.max(20, width - 4));
+ lines.push(` ${c}${key}${r}`, ...descLines.map((line) => ` ${dim}${line}${r}`));
+ }
+ }
+ return lines;
+}
+
+function prettyKey(key) {
+ // Converts internal lowercase key identifier into canonical human-readable key notation.
+ return String(key || "")
+ .split("+")
+ .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1).toLowerCase() : ""))
+ .join("+");
+}
+
+function formatKeyboard(keybinds, width, colors) {
+ const b = colors?.bold || "";
+ const r = colors?.reset || "";
+ const dim = colors?.dim || "";
+ const c = colors?.cyan || "";
+ const lines = ["", `${b}Keyboard${r}`];
+ const interruptKey = prettyKey(keybinds?.interrupt || "ctrl+c");
+ const clearKey = prettyKey(keybinds?.clear_screen || "ctrl+l");
+ const entries = [
+ { label: interruptKey, desc: "clear input; empty prompt exits; active turn interrupts" },
+ { label: "Ctrl+D", desc: "delete right; empty prompt exits" },
+ { label: clearKey, desc: "clear/repaint terminal" },
+ { label: "Ctrl+W · Ctrl+U/K", desc: "delete word · delete to line start/end" },
+ { label: "↑/↓ or Ctrl+P/N", desc: "prompt history (durable after resume)" },
+ { label: "Ctrl+A/E · Ctrl+B/F", desc: "line start/end · left/right" },
+ { label: "Alt+B/F · Ctrl+←/→", desc: "move by word" },
+ { label: "Tab (empty prompt)", desc: "cycle permission in place: ask → auto → yolo" },
+ ];
+ for (const entry of entries) {
+ if (entry.label.length + entry.desc.length + 4 <= width) {
+ const pad = (entry.label.length < 20 && 20 + entry.desc.length + 4 <= width) ? 20 : entry.label.length;
+ lines.push(` ${c}${entry.label.padEnd(pad)}${r} ${dim}${entry.desc}${r}`.trimEnd());
+ } else {
+ const descLines = wrapText(entry.desc, Math.max(20, width - 4));
+ lines.push(` ${c}${entry.label}${r}`, ...descLines.map((line) => ` ${dim}${line}${r}`));
+ }
+ }
+ return lines;
+}
+
+/**
+ * @param {{
+ * commands?: Array<{ name: string, usage?: string, description?: string }>,
+ * settings?: Array<{ key?: string, name?: string, description?: string, [key: string]: any }>,
+ * keybinds?: Record<string, string>,
+ * colors?: Record<string, string>,
+ * width?: number,
+ * }} [options]
+ * @returns {string[]}
+ */
+export function helpLines({
+ commands = COMMAND_MANIFEST,
+ settings = SETTINGS,
+ keybinds = defaultKeybinds(),
+ colors = {},
+ width = 60,
+} = {}) {
+ // Clamps terminal width to 60 columns minimum so compact viewports remain usable.
+ const termWidth = Number(width) > 0 ? Number(width) : 60;
+ return [
+ ...commands.flatMap((cmd) => formatCommand(cmd, termWidth, colors)),
+ ...formatSettings(settings, termWidth, colors),
+ ...formatKeyboard(keybinds, termWidth, colors),
+ ];
+}
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index a137ec20..d44d516c 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -1,68 +1,24 @@
+import process from "node:process";
+// Derives help lines and formatted text directly from command and settings registries.
import { createPrinter } from "./mso-agent-print.mjs";
+import { helpLines } from "./mso-agent-help-lines.mjs";
-export const HELP_LINES = [
- " /help show slash commands and keyboard shortcuts",
- " /new [title] create and switch to a fresh durable session",
- " /restart soft-reload Agent runtime; keep this session",
- " /session [query] open picker or resume latest/index/id/@name/title (alias: /sessions)",
- " /resume [query] alias-style resume command; bare opens same picker",
- " /tabs [n|name|next|prev] list tabs, switch by index/@name, or jump active",
- " /rename <name> rename the short @agent handle",
- " /title <text> rename the session title/description",
- " /export [ref] [--out f] export session transcript to stdout or a file",
- " /share temporary share link (server download-only today)",
- " /status model/auth/context/token/session details",
- " /permission [mode] choose ask | auto-write | yolo",
- " /context alias for /status",
- " /diff [ref] [--full] show diff viewer panel for artifact write action",
- " /todos [--all] show session checklist from todo_write",
- " /pane [kind|pin|unpin] cycle, set, or pin side pane (todos, diff, files, off)",
- " /keybind [sub] view keybindings (sub: reset, conflicts)",
- " /settings [key] [val] view or set TUI preferences (sub: reset)",
- " /compact force context compaction and archive history",
- " /statusbar [on|off] toggle compact dynamic status line",
- " /reasoning [on|off] toggle per-turn reasoning token metrics (/reasoning on|off)",
- " /theme [name|status] view or set UI theme (dark, light, mono)",
- " /models [args] configure AI providers/auth",
- " /model [ref] select active model from connected providers",
- " /setup full MSO onboarding",
- " /integrations [args] manage users, providers, connections, source/auth",
- " /provider, /providers legacy provider setup (alias; see /integrations)",
- " /doctor run mso doctor",
- " /tools list agent tools",
- " /files [path] read-only file tree of cwd or path (bounded)",
- " /agents list live local session agents + remote A2A peers",
- " @milo <prompt> message an active local agent by its short @name",
- " /message <target> <msg> send notify-only local agent data",
- " /delegate <target> <job> correlated local task; else remote A2A peer",
- " /spawn [--name N] [--scope S] <job> run foreground isolated subagent in this session",
- " /jobs [id|cancel <id>] list background subagent jobs, inspect, or cancel",
- " /terminal [cmd] open shell or run command in real terminal",
- " /inbox show native local agent messages for this session",
- " /skills [query] browse available slash skills",
- " /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
- " /<skill> [prompt] select for next message, or run prompt now",
- " /queue [drop|clear|prompt] list, drop, clear, or queue follow-up prompts",
- " /stash [pop|clear|text] park prompt; /stash pop prints stashed prompt to terminal",
- " /image <path> attach a local image to the next prompt",
- " /clear clear this session conversation",
- " /exit, /quit quit",
- " --no-altscreen keep the terminal's own scrollback instead of the retained panel",
- "",
- "Keyboard",
- " Ctrl+C clear input; empty prompt exits; active turn interrupts",
- " Ctrl+D delete right; empty prompt exits",
- " Ctrl+L clear/repaint terminal",
- " 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",
- " Tab (empty prompt) cycle permission in place: ask → auto → yolo",
-];
+export { helpLines };
+// Static exports for backward compatibility and test assertions.
+export const HELP_LINES = helpLines();
export const HELP_TEXT = HELP_LINES.join("\n");
export function printHelp(options = {}) {
const printer = createPrinter(options);
- printer.printBlock(HELP_TEXT);
+ // Re-render when caller passes terminal width or custom colors; fallback to canonical HELP_TEXT.
+ const colors = options.colors || options.session?.colors;
+ // Fall back to the real terminal width, not a constant: a fixed 60 wrapped /help on every wide
+ // terminal, which is the opposite of what a help screen should do with space it has.
+ const width = options.width || options.session?.width || process.stdout?.columns;
+ if (width || colors) {
+ printer.printBlock(helpLines({ ...options, colors, width }).join("\n"));
+ } else {
+ printer.printBlock(HELP_TEXT);
+ }
}
diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjs
index e3f3fa22..f6949b29 100644
--- a/scripts/mso-agent-screen-loop.mjs
+++ b/scripts/mso-agent-screen-loop.mjs
@@ -11,6 +11,7 @@ import { renderViewport } from "./mso-agent-viewport-render.mjs";
import { paneLines } from "./mso-agent-pane.mjs";
import { withPreamble } from "./mso-agent-banner-lines.mjs";
import { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";
+import { createCompactionWatcher } from "./mso-agent-compaction.mjs";
export { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";
/**
@@ -56,17 +57,18 @@ export function mountScreenLoop({
};
}
+ // Gated: with the setting off, nothing is written, so the terminal keeps its own text selection.
let mouseEnabled = isMouseEnabled(mouse, session);
if (mouseEnabled) enableMouse(output);
-
const onTeardown = () => { disableMouse(output); };
const detach = (target, event, listener) => {
if (typeof target?.off === "function") target.off(event, listener);
- else if (typeof target?.removeListener === "function") target.removeListener(event, listener);
+ else target?.removeListener?.(event, listener);
};
["exit", "SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => process.on?.(sig, onTeardown));
const viewport = createViewport({ rows: output.rows || 24 });
+ const compaction = createCompactionWatcher(session);
let painted = [];
let promptReservation = PROMPT_ROWS;
@@ -107,7 +109,9 @@ export function mountScreenLoop({
const sync = () => {
commitStream(viewport);
- setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" })));
+ compaction.check(session, { colors });
+ const trans = transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" });
+ setLines(viewport, withPreamble(preamble?.() ?? null, [...trans, ...compaction.lines(colors)]));
paint();
};
@@ -117,10 +121,7 @@ export function mountScreenLoop({
session.streamSink = { write(chunk) { appendStream(viewport, chunk); paint(); } };
session.printSink = (line) => { appendStream(viewport, `${String(line ?? "")}\n`); commitStream(viewport); paint(); };
- const onResize = () => {
- viewport.rows = output.rows || 24;
- sync();
- };
+ const onResize = () => { viewport.rows = output.rows || 24; sync(); };
output.on?.("resize", onResize);
const dispatchMouse = (event) => {
@@ -161,7 +162,8 @@ export function mountScreenLoop({
});
const { suspend, resume } = panelSuspend;
- setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" })));
+ const initLines = transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" });
+ setLines(viewport, withPreamble(preamble?.() ?? null, [...initLines, ...compaction.lines(colors)]));
paint();
const loop = {
@@ -186,6 +188,7 @@ export function mountScreenLoop({
output.off?.("resize", onResize);
hook.dispose();
disableMouse(output);
+ compaction.reset();
delete session.streamSink; delete session.printSink;
delete session.onComposerRows; delete session.screenLoop;
// The panel owns the whole screen, so the inline transcript is repainted once on the way out
diff --git a/scripts/mso-agent-settings-entries.mjs b/scripts/mso-agent-settings-entries.mjs
index de691c41..5c99ffb2 100644
--- a/scripts/mso-agent-settings-entries.mjs
+++ b/scripts/mso-agent-settings-entries.mjs
@@ -65,4 +65,9 @@ export const SETTINGS = [
description: "Terminal mouse reporting and interaction", default: "on",
values: ["on", "off"], keywords: ["mouse", "click", "scroll"],
},
+ {
+ category: "Alerts", key: "attention", path: "attention.notifications",
+ description: "Terminal notification when another session needs attention", default: "off",
+ values: ["off", "bell"], keywords: ["attention", "notifications", "alerts", "bell"],
+ },
];
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
index 822404c7..fb3646da 100644
--- a/scripts/mso-agent-status.mjs
+++ b/scripts/mso-agent-status.mjs
@@ -4,6 +4,7 @@ import { projectHistoryForModel } from "./mso-agent-context.mjs";
import { addProviderUsage } from "../lib/ai/provider-usage.mjs";
import { todoStatusChip } from "./mso-agent-todos.mjs";
import { createPrinter } from "./mso-agent-print.mjs";
+import { formatCompactionChip } from "./mso-agent-compaction.mjs";
function compactNumber(value) {
const n = Number(value || 0);
@@ -71,7 +72,8 @@ export function resolveVerbosity(session, options = {}) {
export function statusParts(session, cwd = process.cwd(), options = {}) {
const opts = (typeof cwd === "object" && cwd !== null) ? cwd : options;
- const targetCwd = (typeof cwd === "string" && cwd !== process.cwd()) ? cwd : (session?.cwd || cwd);
+ const fallbackCwd = typeof cwd === "string" ? cwd : process.cwd();
+ const targetCwd = (typeof cwd === "string" && cwd !== process.cwd()) ? cwd : (session?.cwd || fallbackCwd);
const verbosity = resolveVerbosity(session, opts);
const provider = String(session?.state?.config?.provider || "—");
const model = String(session?.state?.config?.model || "—");
@@ -93,7 +95,7 @@ export function statusParts(session, cwd = process.cwd(), options = {}) {
showModel ? `${provider}/${model}` : null,
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)}/?`,
- session?.agentSession?.compactThresholdTokens ? `session ~${compactNumber(session.agentSession.estimatedTokens)}/${compactNumber(session.agentSession.compactThresholdTokens)}` : null,
+ formatCompactionChip(session, opts),
(usage.totalTokens ?? 0) > 0 ? `tokens ${compactNumber(usage.totalTokens)}`
: ((usage.inputTokens ?? 0) > 0 || (usage.outputTokens ?? 0) > 0) ? `tokens ${compactNumber(usage.inputTokens)}in/${compactNumber(usage.outputTokens)}out` : null,
routing?.activeTools != null ? `route ${routing.routeIds?.join("+") || (routing.fallbackUsed ? "fallback" : "direct")} · tools ${routing.activeTools}/${routing.fullTools}` : null,