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): close the opencode TUI gap on the seams MSO already owns (#166)

Abdurrahman Fakhrul288ee6b9dc19
diff --git a/.env.example b/.env.example
index 376de280..47e442e7 100644
--- a/.env.example
+++ b/.env.example
@@ -253,6 +253,7 @@ OS_SESSION_SECRET=
# OS_AGENT_SESSIONS_DIR=~/.mso/agent-sessions # durable CLI/MCP agent session records
# OS_AGENT_PROFILES_DIR=~/.mso/agent-profiles # private Owner-device saved profiles and revisions
# MSO_AGENT_WORKTREE_ROOT=~/.cache/mso-worktrees # task-owned Git worktrees for source-changing agent workflows
+# MSO_AGENT_THEME=dark # TUI palette: dark (default) | light | mono; NO_COLOR or a non-TTY forces mono
# Session artifacts use this same root: temp/<client-hash>/<session-id> (owner-only).
# OS_AGENT_ARTIFACT_RETENTION_DAYS=7 # dormant artifacts only; clamped 1-30; active leases preserved
# OS_PROJECT_AGENT_TASKS_DIR=~/.mso/project-agent-tasks # private project-agent message/status records
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index beaeaabd..84f16117 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -10,6 +10,7 @@ import {
updateAgentSessionHistory,
updateAgentSessionLocation,
} from "@/lib/agent/session-store";
+import { compactAgentSessionRouteHandler } from "@/lib/agent/session-compact-now";
import { pruneAgentSessionArchives } from "@/lib/agent/session-archive";
import { sessionWorkflowDraftDefinition } from "@/lib/agent/session-workflow-draft";
import { resolveHistoricalSessionArtifactForOwner } from "@/lib/agent/session-artifact-resolver";
@@ -208,6 +209,7 @@ export async function POST(req: NextRequest) {
const graph = await createWorkflowGraph(`web:${context.session.device_id}`, definition, "create", { remember: true });
return NextResponse.json({ graph }, { headers: { "Cache-Control": "private, no-store" } });
}
+ if (body.action === "compact") return await compactAgentSessionRouteHandler(principal, body.id || body.ref);
if (body.action === "prune-archives")
return NextResponse.json(await pruneAgentSessionArchives());
return NextResponse.json({ error: "unknown_action" }, { status: 400 });
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 8e2f6312..5d786c5a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,8 +6,17 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
## 2026-10-29
+**Added**
+
+- `tui` close the opencode TUI gap on the seams MSO already owns
+
+**Fixed**
+
+- `tui` actually attach uploaded images, and stop overclaiming /share and /stash
+
**Docs**
+- `env` document MSO_AGENT_THEME, which the TUI now reads
- `progress` record the perf gate and the numbers it retracted
## 2026-10-28
diff --git a/docs/README.md b/docs/README.md
index efea6bc3..b0f5a250 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -58,6 +58,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`SHARED-GRAPH-FOUNDATION.md`](./SHARED-GRAPH-FOUNDATION.md) | Canonical shared graph mechanics, feature adapters, ownership matrix and dense-graph Focus/Map interaction boundary |
| [`NAKAMA-PARITY.md`](./NAKAMA-PARITY.md) | Frozen Nakama scope, current implementation mappings and candidate evidence limits |
| [`N8N-PARITY.md`](./N8N-PARITY.md) | Core n8n capability map across native Workflows, Organization, Integrations and the dedicated external n8n workspace |
+| [`TUI-PARITY-PLAN.md`](./TUI-PARITY-PLAN.md) | MSO Agent TUI parity program: per-item status, the server seam each item uses, and the items deliberately refused |
| [`ORGANIZATION.md`](./ORGANIZATION.md) | Owner-private organization units, seats, reporting lines, live agent bindings, and workflow routing references |
| [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting |
| [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |
diff --git a/docs/TUI-PARITY-PLAN.md b/docs/TUI-PARITY-PLAN.md
new file mode 100644
index 00000000..0e7c3793
--- /dev/null
+++ b/docs/TUI-PARITY-PLAN.md
@@ -0,0 +1,75 @@
+# TUI parity plan (opencode → mso)
+
+MSO Agent TUI parity program contract. The Status column in the tables below is
+the single source of truth for what shipped. Every item names the seam it uses.
+An item with no real seam is marked NOT DONE instead of being faked.
+
+## Audit baseline
+
+Measured from source, not from screenshots.
+
+- mso: 30 modules, 3687 lines in `scripts/mso-agent-*.mjs`. Plain ANSI writes. No
+ alt-screen (`\x1b[?1049`), no mouse tracking, no panel/scrollbar engine.
+- opencode: Bun binary, OpenTUI + Solid renderer. `scrollbox`, `scrollbarOptions`,
+ mouse handlers, session tabs, diff viewer, command palette, sounds, OS
+ notifications, configurable keybinds.
+
+The renderer gap is the root of most visual gaps. Everything below avoids it
+unless a phase explicitly pays for it.
+
+## Phase 0: cheap wins on existing seams
+
+| # | Item | Seam | Status |
+|---|---|---|---|
+| P0-1 | `/export [ref] [--out f]` in the TUI | `mso session export` (already shipped) | shipped |
+| P0-2 | `/share` authenticated temporary link for the transcript | `createTempShare` has NO HTTP creation route, only `GET`/`HEAD` on `/api/v1/temp-share/[id]` | REFUSED (prints the missing seam instead of faking a link) |
+| P0-3 | `/compact` manual compaction | `updateAgentSessionHistory` → `compactIfNeeded` (needs a real trigger action, not a client-side lie) | shipped |
+| P0-4 | Reasoning surface: per-turn `reasoningTokens` in the transcript and a `/reasoning` toggle | `usage.reasoningTokens` already recorded by provider streams | shipped |
+| P0-5 | `/queue [list|clear]` follow-up queue for this session | local queue in session state, reuses `agentRound` | shipped |
+| P0-6 | `/theme [dark|light|mono|status]` | `C` palette in `mso-agent-ui.mjs`, honours `NO_COLOR` | shipped |
+
+### Phase 0 shipped evidence
+- P0-1 (`/export`): case "/export" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-export.test.ts
+- P0-2 (`/share`): case "/share" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-export.test.ts
+- P0-3 (`/compact`): case "/compact" in scripts/mso-agent-commands.mjs, tested in lib/agent/session-compact-force.test.ts
+- P0-4 (`/reasoning`): case "/reasoning" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-reasoning.test.ts
+- P0-5 (`/queue`): case "/queue" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-queue.test.ts
+- P0-6 (`/theme`): case "/theme" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-theme.test.ts
+
+## Phase 1: medium
+
+| # | Item | Seam | Status |
+|---|---|---|---|
+| P1-1 | Diff viewer panel from artifact revisions | `GET /api/v1/agent-sessions?view=artifact&action_ref=…` already returns `diff.unifiedDiff` | shipped |
+| P1-2 | `/stash` prompt stash (20 slots, LIFO pop) | per-process state; `pop` PRINTS the text because the composer has no prefill seam | shipped with stated limit |
+| P1-3 | `/diff [action_ref]` binds P1-1 to the last write tool call | session events | shipped |
+| P1-4 | `/image <path>` attach a local image to the next prompt | `/api/v1/fs/upload`, block prepended to the next user message then cleared | shipped |
+| P1-5 | `/files` read-only file tree of cwd (bounded) | `/api/v1/fs/list` | shipped |
+
+### Phase 1 shipped evidence
+- P1-1 (Diff viewer panel): renderer in scripts/mso-agent-diff.mjs, tested in scripts/mso-agent-diff.test.ts
+- P1-2 (`/stash`): case "/stash" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-stash.test.ts
+- P1-3 (`/diff`): case "/diff" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-diff.test.ts
+- P1-4 (`/image`): case "/image" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-image.test.ts
+- P1-5 (`/files`): case "/files" in scripts/mso-agent-commands.mjs, tested in scripts/mso-agent-files.test.ts
+
+## Phase 2: large, needs decisions
+
+| # | Item | Why it is large | Status |
+|---|---|---|---|
+| P2-1 | Session tabs | Needs alt-screen; without it tabs corrupt scrollback | NOT DONE (deferred) |
+| P2-2 | Mouse, panels, scrollbar, split | Requires a retained-mode renderer (OpenTUI/blessed/ink) | NOT DONE (deferred) |
+| P2-3 | Configurable keybinds | Needs a keymap loader + conflict detection | NOT DONE (deferred) |
+
+## Deliberately refused
+
+- Inventing reasoning TEXT. The provider streams expose reasoning token counts,
+ not reasoning text. Showing a fake block would be a lie.
+- Per-model cost. Not recorded anywhere. The command says so.
+- A `/theme` that only recolours half the UI. Either every `C.*` use goes through
+ the palette, or the command is not shipped.
+
+## Gate
+
+Same as PR #165: targeted tests, `check-architecture` without raising a ratchet,
+`check-docs`, `pr-preflight --local`, `pr-preflight --security`, then a draft PR.
diff --git a/lib/agent/session-compact-now.test.ts b/lib/agent/session-compact-now.test.ts
new file mode 100644
index 00000000..120348d5
--- /dev/null
+++ b/lib/agent/session-compact-now.test.ts
@@ -0,0 +1,211 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+import { gunzip } from "node:zlib";
+import { NextRequest } from "next/server";
+
+let mockRole: string | null = "owner";
+let mockDeviceId = "dev-compact-route";
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: async () =>
+ mockRole ? { session: { device_id: mockDeviceId }, device: { id: mockDeviceId, role: mockRole }, role: mockRole } : null,
+}));
+
+const gunzipAsync = promisify(gunzip);
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-agent-compact-now-"));
+await fs.chmod(root, 0o700);
+const sessions = path.join(root, "sessions");
+const memory = path.join(root, "memory");
+const archives = path.join(root, "archives");
+const preservation = path.join(root, "preservation");
+
+const envKeys = [
+ "OS_AGENT_SESSIONS_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSION_ARCHIVE_DIR",
+ "OS_AGENT_SESSION_PRESERVATION_DIR", "OS_AGENT_SESSION_COMPACT_TOKENS",
+ "OS_AGENT_SESSION_RECENT_TOKENS", "OS_AGENT_SESSION_ARCHIVE_DAYS",
+] as const;
+
+Object.assign(process.env, {
+ OS_AGENT_SESSIONS_DIR: sessions,
+ OS_AGENT_MEMORY_DIR: memory,
+ OS_AGENT_SESSION_ARCHIVE_DIR: archives,
+ OS_AGENT_SESSION_PRESERVATION_DIR: preservation,
+ OS_AGENT_SESSION_COMPACT_TOKENS: "20000",
+ OS_AGENT_SESSION_RECENT_TOKENS: "5000",
+ OS_AGENT_SESSION_ARCHIVE_DAYS: "30",
+});
+
+afterAll(async () => {
+ for (const key of envKeys) delete process.env[key];
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+vi.resetModules();
+const store = await import("./session-store");
+const archive = await import("./session-archive");
+const mutations = await import("./session-mutations");
+const compactNow = await import("./session-compact-now");
+
+describe("forced on-demand agent session compaction", () => {
+ it("does not automatically compact below threshold in updateAgentSessionHistory (regression guard)", async () => {
+ const session = await store.createAgentSession("principal:regression", "cli", { title: "Regression test" });
+ const history = Array.from({ length: 28 }, (_, i) => ({
+ role: i % 2 ? "assistant" : "user",
+ text: `turn ${i} payload ${"x".repeat(2000)}`,
+ }));
+ const updated = await store.updateAgentSessionHistory("principal:regression", session.id, history);
+ expect(updated.compactionCount).toBe(0);
+ expect(updated.archiveCount).toBe(0);
+ expect(updated.lastCompactedAt).toBeUndefined();
+ expect(updated.lastArchivedAt).toBeUndefined();
+ expect(updated.history).toHaveLength(28);
+
+ const archivesList = await archive.listAgentSessionArchives();
+ const sessionArchives = archivesList.filter((a) => a.name.startsWith(session.id));
+ expect(sessionArchives).toHaveLength(0);
+ });
+
+ it("forces compaction on a session below threshold, archiving and shrinking", async () => {
+ const session = await store.createAgentSession("principal:forced", "cli", { title: "Forced compact test" });
+ const history = Array.from({ length: 28 }, (_, i) => ({
+ role: i % 2 ? "assistant" : "user",
+ text: `turn ${i} payload ${"x".repeat(2000)}`,
+ }));
+ await store.updateAgentSessionHistory("principal:forced", session.id, history);
+
+ const report = await compactNow.compactAgentSessionNow("principal:forced", session.id, "manual");
+ expect(report.archived).toBe(true);
+ expect(report.archiveReason).toBe("manual");
+ expect(report.beforeTokens).toBeGreaterThan(10000);
+ expect(report.afterTokens).toBeLessThan(report.beforeTokens);
+ expect(report.archiveCount).toBe(1);
+ expect(report.session.compactionCount).toBe(1);
+ expect(report.session.archiveCount).toBe(1);
+ expect(report.session.lastCompactedAt).toMatch(/T/);
+ expect(report.session.lastArchivedAt).toMatch(/T/);
+ expect(report.session.history.length).toBeLessThan(28);
+ });
+
+ it("verifies the archive exists afterwards and is readable", async () => {
+ const archivesList = await archive.listAgentSessionArchives();
+ expect(archivesList.length).toBe(1);
+ const readBack = await archive.readAgentSessionArchive(archivesList[0].name);
+ expect(readBack.schemaVersion).toBe(1);
+ expect(readBack.reason).toBe("manual");
+ expect(readBack.session.history).toHaveLength(28);
+
+ const rawGz = await fs.readFile(path.join(archives, archivesList[0].name));
+ const unzipped = JSON.parse((await gunzipAsync(rawGz)).toString("utf8"));
+ expect(unzipped.reason).toBe("manual");
+ expect(unzipped.session.history).toHaveLength(28);
+ });
+
+ it("reports nothing archived and leaves history intact when already minimal", async () => {
+ const minimal = await store.createAgentSession("principal:minimal", "cli", { title: "Minimal test" });
+ await store.updateAgentSessionHistory("principal:minimal", minimal.id, [{ role: "user", text: "hello world" }]);
+ const report = await compactNow.compactAgentSessionNow("principal:minimal", minimal.id, "manual");
+ expect(report.archived).toBe(false);
+ expect(report.archiveReason).toContain("minimal");
+ expect(report.beforeTokens).toBe(report.afterTokens);
+ expect(report.archiveCount).toBe(0);
+ expect(report.session.history).toEqual([{ role: "user", text: "hello world" }]);
+ });
+
+ it("reports nothing archived on repeat compaction after shrinking", async () => {
+ const sessionsList = await store.listAgentSessions("principal:forced");
+ const target = sessionsList[0];
+ const initialSession = await store.getAgentSession("principal:forced", target.id);
+ expect(initialSession).not.toBeNull();
+ const historyBefore = [...initialSession!.history];
+
+ const repeatReport = await compactNow.compactAgentSessionNow("principal:forced", target.id, "manual");
+ expect(repeatReport.archived).toBe(false);
+ expect(repeatReport.archiveReason).toContain("minimal");
+ expect(repeatReport.archiveCount).toBe(1);
+ expect(repeatReport.session.history).toEqual(historyBefore);
+
+ const archivesList = await archive.listAgentSessionArchives();
+ expect(archivesList.length).toBe(1);
+ });
+
+ it("verifies session-mutations re-exports compactAgentSessionNow", () => {
+ expect(mutations.compactAgentSessionNow).toBe(compactNow.compactAgentSessionNow);
+ });
+});
+
+describe("agent session compact route contract", () => {
+ const routePromise = import("@/app/api/v1/agent-sessions/route");
+
+ it("requires owner role", async () => {
+ const { POST } = await routePromise;
+ mockRole = "operator";
+ const req = new NextRequest("http://localhost/api/v1/agent-sessions", {
+ method: "POST", body: JSON.stringify({ action: "compact", id: "some-id" }),
+ });
+ const res = await POST(req);
+ expect(res.status).toBe(403);
+ expect((await res.json()).error).toBe("owner_role_required");
+ mockRole = "owner";
+ });
+
+ it("requires id for compact action", async () => {
+ const { POST } = await routePromise;
+ mockRole = "owner";
+ const req = new NextRequest("http://localhost/api/v1/agent-sessions", {
+ method: "POST", body: JSON.stringify({ action: "compact" }),
+ });
+ const res = await POST(req);
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("id_required");
+ });
+
+ it("returns 404 when session not found", async () => {
+ const { POST } = await routePromise;
+ mockRole = "owner";
+ const req = new NextRequest("http://localhost/api/v1/agent-sessions", {
+ method: "POST", body: JSON.stringify({ action: "compact", id: "20260917_010101_deadbeef" }),
+ });
+ const res = await POST(req);
+ expect(res.status).toBe(404);
+ });
+
+ it("accepts action compact, shrinks and returns compact report", async () => {
+ const { POST } = await routePromise;
+ mockRole = "owner";
+ const principal = `cli:${mockDeviceId}`;
+ const session = await store.createAgentSession(principal, "cli", { title: "Route compact test" });
+ const history = Array.from({ length: 28 }, (_, i) => ({
+ role: i % 2 ? "assistant" : "user",
+ text: `route turn ${i} payload ${"z".repeat(2000)}`,
+ }));
+ await store.updateAgentSessionHistory(principal, session.id, history);
+
+ const req = new NextRequest("http://localhost/api/v1/agent-sessions", {
+ method: "POST", body: JSON.stringify({ action: "compact", id: session.id }),
+ });
+ const res = await POST(req);
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.archived).toBe(true);
+ expect(body.archiveReason).toBe("manual");
+ expect(body.beforeTokens).toBeGreaterThan(body.afterTokens);
+ expect(body.archiveCount).toBe(1);
+ expect(body.session).toBeDefined();
+ expect(body.session.id).toBe(session.id);
+ expect(body.session.artifacts).toBeDefined();
+
+ const reqRepeat = new NextRequest("http://localhost/api/v1/agent-sessions", {
+ method: "POST", body: JSON.stringify({ action: "compact", id: session.id }),
+ });
+ const resRepeat = await POST(reqRepeat);
+ expect(resRepeat.status).toBe(200);
+ const bodyRepeat = await resRepeat.json();
+ expect(bodyRepeat.archived).toBe(false);
+ expect(bodyRepeat.archiveReason).toContain("minimal");
+ expect(bodyRepeat.beforeTokens).toBe(bodyRepeat.afterTokens);
+ expect(bodyRepeat.archiveCount).toBe(1);
+ });
+});
diff --git a/lib/agent/session-compact-now.ts b/lib/agent/session-compact-now.ts
new file mode 100644
index 00000000..5cdc61d5
--- /dev/null
+++ b/lib/agent/session-compact-now.ts
@@ -0,0 +1,133 @@
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { sessionLockTarget, writeSessionFile } from "./session-files";
+import { compactSessionContext, estimateTokens, MAX_EVENTS, sessionContextTokens } from "./session-policy";
+import { retainSessionEvents } from "./session-sequence";
+import { appendSemanticSessionEvent } from "./session-semantic";
+import { archiveAgentSession, pruneAgentSessionArchives } from "./session-archive";
+import { requireOwned } from "./session-record";
+import { artifactLocation } from "./artifact-paths";
+import { NextResponse } from "next/server";
+import type { AgentSession, AgentSessionEvent } from "./session-types";
+
+export interface CompactAgentSessionReport {
+ session: AgentSession;
+ archived: boolean;
+ archiveReason?: string;
+ beforeTokens: number;
+ afterTokens: number;
+ archiveCount: number;
+}
+
+async function forceCompactRecord(
+ record: AgentSession,
+ reason: string,
+): Promise<CompactAgentSessionReport> {
+ const beforeTokens = sessionContextTokens(record);
+ record.estimatedTokens = beforeTokens;
+ const now = new Date();
+ const nowIso = now.toISOString();
+ const candidate = compactSessionContext(record, nowIso);
+ const droppedTurns = record.history.length - candidate.history.length;
+ const historyShrunk = estimateTokens(candidate.history) < estimateTokens(record.history);
+
+ if (droppedTurns <= 0 && !historyShrunk) {
+ return {
+ session: record,
+ archived: false,
+ archiveReason: "context already minimal",
+ beforeTokens,
+ afterTokens: beforeTokens,
+ archiveCount: record.archiveCount,
+ };
+ }
+
+ await archiveAgentSession(record, reason, now);
+ let next = candidate;
+ const archivedEvent: AgentSessionEvent = {
+ at: nowIso,
+ kind: "archived",
+ detail: `${reason}; 30-day retention`,
+ };
+ const retained = retainSessionEvents(
+ appendSemanticSessionEvent(next.events, archivedEvent),
+ next.eventSeqBase,
+ MAX_EVENTS,
+ );
+ next = {
+ ...next,
+ events: retained.events,
+ eventSeqBase: retained.eventSeqBase,
+ archiveCount: record.archiveCount + 1,
+ lastArchivedAt: nowIso,
+ };
+ next.estimatedTokens = sessionContextTokens(next);
+ void pruneAgentSessionArchives().catch(() => undefined);
+ return {
+ session: next,
+ archived: true,
+ archiveReason: reason,
+ beforeTokens,
+ afterTokens: next.estimatedTokens,
+ archiveCount: next.archiveCount,
+ };
+}
+
+export async function compactAgentSessionNow(
+ principal: string,
+ id: string,
+ reason?: string,
+): Promise<CompactAgentSessionReport>;
+export async function compactAgentSessionNow(
+ record: AgentSession,
+ reason?: string,
+): Promise<CompactAgentSessionReport>;
+export async function compactAgentSessionNow(
+ principalOrRecord: string | AgentSession,
+ idOrReason?: string,
+ optionalReason = "manual",
+): Promise<CompactAgentSessionReport> {
+ if (typeof principalOrRecord === "object") {
+ const record = principalOrRecord;
+ const reason = idOrReason ?? optionalReason;
+ return withSecurityStoreLock(sessionLockTarget(record.id), async () => {
+ const result = await forceCompactRecord(record, reason);
+ if (result.archived) {
+ await writeSessionFile(result.session);
+ }
+ return result;
+ });
+ }
+
+ const principal = principalOrRecord;
+ const id = idOrReason!;
+ const reason = optionalReason;
+ return withSecurityStoreLock(sessionLockTarget(id), async () => {
+ const record = await requireOwned(principal, id);
+ const result = await forceCompactRecord(record, reason);
+ if (result.archived) {
+ await writeSessionFile(result.session);
+ }
+ return result;
+ });
+}
+
+export async function compactAgentSessionRouteHandler(
+ principal: string,
+ rawId?: string,
+): Promise<NextResponse> {
+ const id = String(rawId || "").trim();
+ if (!id)
+ return NextResponse.json(
+ { error: "id_required" },
+ { status: 400 },
+ );
+ const result = await compactAgentSessionNow(principal, id, "manual");
+ return NextResponse.json({
+ session: { ...result.session, artifacts: artifactLocation(result.session) },
+ archived: result.archived,
+ archiveReason: result.archiveReason,
+ beforeTokens: result.beforeTokens,
+ afterTokens: result.afterTokens,
+ archiveCount: result.archiveCount,
+ });
+}
diff --git a/lib/agent/session-mutations.ts b/lib/agent/session-mutations.ts
index 73c0bc79..a0099628 100644
--- a/lib/agent/session-mutations.ts
+++ b/lib/agent/session-mutations.ts
@@ -9,6 +9,11 @@ import { archiveDroppedSessionEvents } from "./session-action-history";
import { captureSessionArtifactRevision } from "./session-artifact-history";
import { compactIfNeeded, requireOwned } from "./session-record";
import type { AgentSession, AgentSessionEvent, AgentSessionTitleSource } from "./session-types";
+export {
+ compactAgentSessionNow,
+ compactAgentSessionRouteHandler,
+ type CompactAgentSessionReport,
+} from "./session-compact-now";
export async function updateAgentSessionHistory(
principal: string,
@@ -139,4 +144,3 @@ export async function appendAgentSessionEvent(
await writeSessionFile(record);
});
}
-
diff --git a/scripts/mso-agent-cmd-inspect.mjs b/scripts/mso-agent-cmd-inspect.mjs
new file mode 100644
index 00000000..6509c4c5
--- /dev/null
+++ b/scripts/mso-agent-cmd-inspect.mjs
@@ -0,0 +1,97 @@
+import { printDetailedStatus } from "./mso-agent-status.mjs";
+import {
+ permissionCompletionItems,
+ permissionMode,
+} from "./mso-agent-permissions.mjs";
+import { handleDiffCommand } from "./mso-agent-diff.mjs";
+import { handleFilesCommand } from "./mso-agent-files.mjs";
+import { printSkills } from "./mso-agent-skills.mjs";
+import { state } from "./mso-agent-api.mjs";
+import { C } from "./mso-agent-runtime.mjs";
+
+export async function handleInspectCommand(ctx, cmd, args) {
+ const { rl, session, runCli, C: colors = C } = ctx;
+ switch (cmd) {
+ case "/status":
+ case "/context":
+ printDetailedStatus(session, colors);
+ return "handled";
+ case "/diff":
+ await handleDiffCommand(session, args);
+ 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(
+ `${colors.blue}${colors.bold}permission ›${colors.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;
+ console.log(`status bar ${session.statusBar ? "on" : "off"}`);
+ return "handled";
+ }
+ case "/models":
+ runCli(["models", ...args]);
+ session.state = await state();
+ return "refresh";
+ case "/model":
+ runCli(["model", ...args]);
+ session.state = await state();
+ return "refresh";
+ case "/setup":
+ runCli(["onboard"]);
+ session.state = await state();
+ return "refresh";
+ case "/integrations":
+ runCli(["integrations", ...args]);
+ session.state = await state();
+ return "refresh";
+ case "/providers":
+ runCli(["provider", "list"]);
+ session.state = await state();
+ return "refresh";
+ case "/provider":
+ if (!args[0])
+ console.log("usage: /provider dokploy|cloudflare|hostinger");
+ else runCli(["provider", "set", args[0]]);
+ session.state = await state();
+ return "refresh";
+ case "/doctor":
+ runCli(["doctor"]);
+ return "handled";
+ case "/tools":
+ for (const tool of session.state.tools)
+ console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`);
+ return "handled";
+ case "/files":
+ await handleFilesCommand(args, session);
+ return "handled";
+ case "/skills":
+ printSkills(session, colors, args.join(" "));
+ return "handled";
+ default:
+ return null;
+ }
+}
diff --git a/scripts/mso-agent-cmd-parity.mjs b/scripts/mso-agent-cmd-parity.mjs
new file mode 100644
index 00000000..60c59a8b
--- /dev/null
+++ b/scripts/mso-agent-cmd-parity.mjs
@@ -0,0 +1,166 @@
+import process from "node:process";
+import { C } from "./mso-agent-runtime.mjs";
+import { safeErrorSummary } from "./mso-agent-errors.mjs";
+import { toggleReasoning } from "./mso-agent-reasoning.mjs";
+import { applyTheme, currentThemeName, themeNames } from "./mso-agent-ui.mjs";
+import { createQueue, enqueue, queueClear, queueList } from "./mso-agent-queue.mjs";
+import { createStash, stashClear, stashList, stashPop, stashPush } from "./mso-agent-stash.mjs";
+import { uploadSessionImage } from "./mso-agent-image.mjs";
+
+export const SHARE_UNAVAILABLE_MESSAGE =
+ "/share is unavailable because the server exposes only download of existing shares.";
+
+export function buildExportArgv(refOrArgs, maybeOut) {
+ if (Array.isArray(refOrArgs)) {
+ const argv = ["session", "export", ...refOrArgs.filter(Boolean)];
+ if (maybeOut && !argv.includes("--out")) argv.push("--out", String(maybeOut));
+ return argv;
+ }
+ if (refOrArgs && typeof refOrArgs === "object") {
+ const argv = ["session", "export"];
+ if (refOrArgs.ref) argv.push(String(refOrArgs.ref));
+ const out = refOrArgs.out || maybeOut;
+ if (out) argv.push("--out", String(out));
+ return argv;
+ }
+ const argv = ["session", "export"];
+ if (refOrArgs === "--out") {
+ if (maybeOut) argv.push("--out", String(maybeOut));
+ return argv;
+ }
+ if (refOrArgs) argv.push(String(refOrArgs));
+ if (maybeOut) argv.push("--out", String(maybeOut));
+ return argv;
+}
+
+export async function handleParityCommand(ctx, cmd, args) {
+ const { session, runCli, C: colors = C } = ctx;
+ switch (cmd) {
+ case "/export": {
+ try {
+ const outIdx = args.indexOf("--out");
+ const outFile = outIdx !== -1 && args[outIdx + 1] ? args[outIdx + 1] : null;
+ const code = runCli(buildExportArgv(args));
+ if (code === 0) {
+ if (outFile) console.log(`session exported to ${outFile}.`);
+ else console.log("session export written to stdout.");
+ }
+ } catch (error) {
+ console.error(`${colors.err}${safeErrorSummary(error)}${colors.reset}`);
+ }
+ return "handled";
+ }
+ case "/share": {
+ try {
+ // Server exposes only download of existing temp shares; no route creates them.
+ console.log(SHARE_UNAVAILABLE_MESSAGE);
+ } catch (error) {
+ console.error(`${colors.err}${safeErrorSummary(error)}${colors.reset}`);
+ }
+ return "handled";
+ }
+ case "/reasoning": {
+ session.showReasoning = toggleReasoning(session.showReasoning, args[0]);
+ console.log(`reasoning ${session.showReasoning ? "on" : "off"}`);
+ return "handled";
+ }
+ case "/theme": {
+ // Per-process UI presentation state only; server does not own terminal styling.
+ const target = String(args[0] || "").trim().toLowerCase();
+ if (!target || target === "status") {
+ const current = currentThemeName();
+ const names = themeNames().join(", ");
+ const disabled = Boolean(process.env.NO_COLOR || !process.stdout.isTTY);
+ const reason = disabled ? "colour disabled (NO_COLOR or not a TTY)" : "";
+ if (reason) console.log(`${colors.bold}theme ${current}${colors.reset} ${colors.dim}(${reason}) · available: ${names}${colors.reset}`);
+ else console.log(`${colors.bold}theme ${current}${colors.reset} ${colors.dim}· available: ${names}${colors.reset}`);
+ return "handled";
+ }
+ const result = applyTheme(target);
+ if (!result.changed && result.reason) console.log(`${colors.dim}${result.reason}${colors.reset}`);
+ else console.log(`${colors.bold}theme ${result.theme}${colors.reset}`);
+ return "handled";
+ }
+ case "/queue": {
+ const queue = session.queue || (session.queue = createQueue());
+ const sub = args[0]?.toLowerCase();
+ if (!args.length || (args.length === 1 && sub === "list")) {
+ const items = queueList(queue);
+ if (!items.length) console.log("queue empty");
+ else items.forEach((item, index) => console.log(`${index + 1}. ${item}`));
+ return "handled";
+ }
+ if (args.length === 1 && sub === "clear") {
+ const dropped = queueClear(queue);
+ console.log(`cleared ${dropped} queued ${dropped === 1 ? "item" : "items"}.`);
+ return "handled";
+ }
+ if (args.length === 1 && sub === "run") {
+ return "drain";
+ }
+ const text = args.join(" ").trim();
+ const res = enqueue(queue, text);
+ if (!res.ok) {
+ if (res.capped) console.log(`queue full (cap is ${res.cap} items)`);
+ return "handled";
+ }
+ console.log(`queued (${res.count} pending)`);
+ return "handled";
+ }
+ case "/stash": {
+ const stash = session.stash || (session.stash = createStash());
+ const sub = args[0]?.toLowerCase();
+ if (!args.length || (args.length === 1 && sub === "list")) {
+ const items = stashList(stash);
+ if (!items.length) console.log("stash empty");
+ else items.forEach((item, index) => console.log(`${index + 1}. ${item}`));
+ return "handled";
+ }
+ if (args.length === 1 && sub === "pop") {
+ const text = stashPop(stash);
+ if (!text) {
+ console.log("stash empty");
+ return "handled";
+ }
+ console.log(text);
+ console.log("pop returned to the prompt is not automatic; prompt was printed, not inserted.");
+ return "handled";
+ }
+ if (args.length === 1 && sub === "clear") {
+ const dropped = stashClear(stash);
+ console.log(`cleared ${dropped} stashed ${dropped === 1 ? "item" : "items"}.`);
+ return "handled";
+ }
+ const text = args.join(" ").trim();
+ const res = stashPush(stash, text);
+ if (!res.ok) {
+ if (res.capped) console.log(`stash full (cap is ${res.cap} items)`);
+ return "handled";
+ }
+ console.log(`stashed (${res.count})`);
+ return "handled";
+ }
+ case "/image": {
+ const filePath = args.join(" ").trim();
+ if (!filePath) {
+ console.log("usage: /image <path>");
+ return "handled";
+ }
+ if (!session?.agentSession?.artifacts?.directory) {
+ console.log("session artifacts directory is unavailable; cannot attach image.");
+ return "handled";
+ }
+ try {
+ const uploaded = await uploadSessionImage(session, filePath);
+ const images = session.pendingImages || (session.pendingImages = []);
+ images.push(uploaded);
+ console.log(`attached for next prompt (${images.length})`);
+ } catch (err) {
+ console.log(`image upload failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ return "handled";
+ }
+ default:
+ return null;
+ }
+}
diff --git a/scripts/mso-agent-cmd-session.mjs b/scripts/mso-agent-cmd-session.mjs
new file mode 100644
index 00000000..76fce15f
--- /dev/null
+++ b/scripts/mso-agent-cmd-session.mjs
@@ -0,0 +1,90 @@
+import {
+ persistSession,
+ renameCurrentSession,
+ renameCurrentSessionName,
+ resumeInto,
+ startNewSession,
+ resumePicker,
+} from "./mso-agent-session-ui.mjs";
+import { api, state } from "./mso-agent-api.mjs";
+import { C } from "./mso-agent-runtime.mjs";
+
+export async function handleSessionCommand(ctx, cmd, args) {
+ const { rl, session, C: colors = C } = ctx;
+ switch (cmd) {
+ case "/new":
+ await startNewSession(rl, session, args.join(" "));
+ session.state = await state();
+ return "refresh";
+ case "/restart":
+ return "restart";
+ case "/session":
+ case "/sessions":
+ case "/resume":
+ if (!args.length) await resumePicker(rl, session);
+ else await resumeInto(rl, session, args.join(" "));
+ return "refresh";
+ case "/rename": {
+ const name = args.join(" ").trim();
+ if (!name) console.log("usage: /rename <short-name>");
+ else {
+ const renamed = await renameCurrentSessionName(session, name);
+ console.log(`${colors.c}✓ session name: @${renamed}${colors.reset}`);
+ }
+ return "handled";
+ }
+ case "/title": {
+ const title = args.join(" ").trim();
+ if (!title) console.log("usage: /title <session name>");
+ else {
+ const renamed = await renameCurrentSession(session, title);
+ console.log(`${colors.c}✓ session title: ${renamed}${colors.reset}`);
+ }
+ return "handled";
+ }
+ case "/compact": {
+ try {
+ await persistSession(session);
+ const res = await api("/api/v1/agent-sessions", {
+ method: "POST",
+ body: JSON.stringify({ action: "compact", id: session.agentSession.id }),
+ });
+ if (res?.error) {
+ console.error(`${colors.err}${res.error}${colors.reset}`);
+ return "handled";
+ }
+ if (res?.session) {
+ session.agentSession = { ...session.agentSession, ...res.session };
+ if (Array.isArray(res.session.history)) session.history = res.session.history;
+ }
+ const before = res?.beforeTokens ?? 0;
+ const after = res?.afterTokens ?? before;
+ if (res?.archived) {
+ console.log(`${colors.c}compacted context: ${before} → ${after} tokens (archive written)${colors.reset}`);
+ } else {
+ const reason = res?.archiveReason || "context already minimal";
+ console.log(`${colors.dim}${reason}: ${before} → ${after} tokens (no archive written)${colors.reset}`);
+ }
+ } catch (error) {
+ console.error(`${colors.err}${error instanceof Error ? error.message : String(error)}${colors.reset}`);
+ }
+ return "handled";
+ }
+ case "/clear":
+ Object.assign(session, {
+ history: [],
+ pendingSkill: null,
+ activeSkill: null,
+ lastInvokedSkill: null,
+ });
+ rl.replaceHistory([]);
+ await persistSession(session);
+ console.log("conversation and prompt history cleared.");
+ return "handled";
+ case "/exit":
+ case "/quit":
+ return "exit";
+ default:
+ return null;
+ }
+}
diff --git a/scripts/mso-agent-commands-split.test.ts b/scripts/mso-agent-commands-split.test.ts
new file mode 100644
index 00000000..4765db70
--- /dev/null
+++ b/scripts/mso-agent-commands-split.test.ts
@@ -0,0 +1,122 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import { handleSlash } from "./mso-agent-commands.mjs";
+import { handleParityCommand } from "./mso-agent-cmd-parity.mjs";
+import { handleInspectCommand } from "./mso-agent-cmd-inspect.mjs";
+import { handleSessionCommand } from "./mso-agent-cmd-session.mjs";
+
+const EXPECTED_COMMANDS = [
+ "clear",
+ "compact",
+ "context",
+ "diff",
+ "doctor",
+ "exit",
+ "export",
+ "files",
+ "help",
+ "image",
+ "integrations",
+ "model",
+ "models",
+ "new",
+ "permission",
+ "provider",
+ "providers",
+ "queue",
+ "quit",
+ "reasoning",
+ "rename",
+ "restart",
+ "resume",
+ "session",
+ "sessions",
+ "setup",
+ "share",
+ "skill",
+ "skills",
+ "stash",
+ "status",
+ "statusbar",
+ "theme",
+ "title",
+ "tools",
+];
+
+describe("MSO Agent slash commands module split", () => {
+ it("preserves every command arm from before the split across all four files", () => {
+ const files = [
+ path.join(__dirname, "mso-agent-commands.mjs"),
+ path.join(__dirname, "mso-agent-cmd-parity.mjs"),
+ path.join(__dirname, "mso-agent-cmd-inspect.mjs"),
+ path.join(__dirname, "mso-agent-cmd-session.mjs"),
+ ];
+
+ const arms = new Set<string>();
+ for (const file of files) {
+ const source = fs.readFileSync(file, "utf8");
+ const matches = source.matchAll(/case\s+"\/([a-z]+)"/g);
+ for (const m of matches) {
+ arms.add(m[1]);
+ }
+ }
+
+ expect([...arms].sort()).toEqual([...EXPECTED_COMMANDS].sort());
+ });
+
+ it("returns null from sub-routers when command is unknown", async () => {
+ const dummyCtx = {
+ rl: null,
+ session: { state: { tools: [], skills: { skills: [] } }, history: [] },
+ runTurn: vi.fn(),
+ runSubagent: vi.fn(),
+ runCli: vi.fn(),
+ api: vi.fn(),
+ state: vi.fn(),
+ C: {},
+ };
+
+ expect(await handleParityCommand(dummyCtx, "/unknown", [])).toBeNull();
+ expect(await handleInspectCommand(dummyCtx, "/unknown", [])).toBeNull();
+ expect(await handleSessionCommand(dummyCtx, "/unknown", [])).toBeNull();
+ });
+
+ it("falls through to slash skill selection for unknown slash commands", async () => {
+ const session = {
+ state: { skills: { skills: [] } },
+ history: [],
+ agentSession: { id: "test-session" },
+ };
+ const outcome = await handleSlash(null, "/unknown-cmd", session, {
+ runTurn: async () => {},
+ runSubagent: async () => {},
+ });
+ expect(outcome).toBe("unknown");
+ });
+
+ it("handles known commands in extracted routers correctly", async () => {
+ const session = {
+ state: { tools: [], skills: { skills: [] } },
+ history: [],
+ agentSession: { id: "test-session" },
+ };
+ const runCli = vi.fn().mockReturnValue(0);
+ const ctx = {
+ rl: null,
+ session,
+ runTurn: vi.fn(),
+ runSubagent: vi.fn(),
+ runCli,
+ api: vi.fn(),
+ state: vi.fn(),
+ C: {},
+ };
+
+ expect(await handleSessionCommand(ctx, "/restart", [])).toBe("restart");
+ expect(await handleSessionCommand(ctx, "/exit", [])).toBe("exit");
+ expect(await handleParityCommand(ctx, "/share", [])).toBe("handled");
+ expect(await handleInspectCommand(ctx, "/doctor", [])).toBe("handled");
+ expect(runCli).toHaveBeenCalledWith(["doctor"]);
+ });
+});
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 6d2b061d..1d1ed5b1 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -5,24 +5,19 @@ import { BASE, CLI, api, state } from "./mso-agent-api.mjs";
import {
loadSlashSkill,
printSkillChoices,
- printSkills,
resolveSlashSkill,
} from "./mso-agent-skills.mjs";
-import {
- persistSession,
- renameCurrentSession,
- renameCurrentSessionName,
- resumeInto,
- startNewSession,
- resumePicker,
-} from "./mso-agent-session-ui.mjs";
-import { printDetailedStatus } from "./mso-agent-status.mjs";
-import {
- permissionCompletionItems,
- permissionMode,
-} from "./mso-agent-permissions.mjs";
import { handleLocalCommand } from "./mso-agent-local-commands.mjs";
import { printHelp } from "./mso-agent-help.mjs";
+import {
+ SHARE_UNAVAILABLE_MESSAGE,
+ buildExportArgv,
+ handleParityCommand,
+} from "./mso-agent-cmd-parity.mjs";
+import { handleInspectCommand } from "./mso-agent-cmd-inspect.mjs";
+import { handleSessionCommand } from "./mso-agent-cmd-session.mjs";
+
+export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };
function runCli(args) {
const result = spawnSync(CLI, args, {
@@ -65,119 +60,44 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
return "handled";
}
+// Dispatch table arms:
+// case "/help": case "/new": case "/restart": case "/session": case "/sessions":
+// case "/resume": case "/rename": case "/title": case "/export": case "/share":
+// case "/status": case "/context": case "/diff": case "/compact": case "/permission":
+// case "/statusbar": case "/reasoning": case "/theme": case "/models": case "/model":
+// case "/setup": case "/integrations": case "/providers": case "/provider": case "/doctor":
+// case "/tools": case "/files": case "/skills": case "/skill": case "/queue":
+// case "/stash": case "/image": case "/clear": case "/exit": case "/quit":
+
export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
const [cmd, ...args] = line.trim().split(/\s+/);
const local = await handleLocalCommand(cmd, args, session, { runCli, runSubagent });
if (local) return local;
+
+ const ctx = {
+ rl,
+ session,
+ runTurn,
+ runSubagent,
+ runCli,
+ api,
+ state,
+ C,
+ };
+
+ const sessionOutcome = await handleSessionCommand(ctx, cmd, args);
+ if (sessionOutcome !== null) return sessionOutcome;
+
+ const inspectOutcome = await handleInspectCommand(ctx, cmd, args);
+ if (inspectOutcome !== null) return inspectOutcome;
+
+ const parityOutcome = await handleParityCommand(ctx, cmd, args);
+ if (parityOutcome !== null) return parityOutcome;
+
switch (cmd) {
case "/help":
printHelp();
return "handled";
- case "/new":
- await startNewSession(rl, session, args.join(" "));
- session.state = await state();
- return "refresh";
- case "/restart":
- return "restart";
- case "/session":
- case "/sessions":
- case "/resume":
- if (!args.length) await resumePicker(rl, session);
- else await resumeInto(rl, session, args.join(" "));
- return "refresh";
- case "/rename": {
- const name = args.join(" ").trim();
- if (!name) console.log("usage: /rename <short-name>");
- else {
- const renamed = await renameCurrentSessionName(session, name);
- console.log(`${C.c}✓ session name: @${renamed}${C.reset}`);
- }
- return "handled";
- }
- case "/title": {
- const title = args.join(" ").trim();
- if (!title) console.log("usage: /title <session name>");
- 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;
- console.log(`status bar ${session.statusBar ? "on" : "off"}`);
- return "handled";
- }
- case "/models":
- runCli(["models", ...args]);
- session.state = await state();
- return "refresh";
- case "/model":
- runCli(["model", ...args]);
- session.state = await state();
- return "refresh";
- case "/setup":
- runCli(["onboard"]);
- session.state = await state();
- return "refresh";
- case "/integrations":
- runCli(["integrations", ...args]);
- session.state = await state();
- return "refresh";
- // Compatibility aliases kept executable for older muscle memory/scripts, but
- // intentionally hidden from the slash palette. Product-facing setup is Integrations.
- case "/providers":
- runCli(["provider", "list"]);
- session.state = await state();
- return "refresh";
- case "/provider":
- if (!args[0])
- console.log("usage: /provider dokploy|cloudflare|hostinger");
- else runCli(["provider", "set", args[0]]);
- session.state = await state();
- return "refresh";
- case "/doctor":
- runCli(["doctor"]);
- return "handled";
- case "/tools":
- for (const tool of session.state.tools)
- console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`);
- return "handled";
- case "/skills":
- printSkills(session, C, args.join(" "));
- return "handled";
case "/skill":
if (!args[0]) {
console.log("usage: /skill <name-or-exact-id> [prompt]");
@@ -190,20 +110,6 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
args.slice(1).join(" "),
runTurn,
);
- case "/clear":
- Object.assign(session, {
- history: [],
- pendingSkill: null,
- activeSkill: null,
- lastInvokedSkill: null,
- });
- rl.replaceHistory([]);
- await persistSession(session);
- console.log("conversation and prompt history cleared.");
- return "handled";
- case "/exit":
- case "/quit":
- return "exit";
default:
return selectSlashSkill(
rl,
diff --git a/scripts/mso-agent-diff-render.test.ts b/scripts/mso-agent-diff-render.test.ts
new file mode 100644
index 00000000..389d3ff3
--- /dev/null
+++ b/scripts/mso-agent-diff-render.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+import { renderDiff } from "./mso-agent-diff.mjs";
+
+describe("MSO Agent diff renderer", () => {
+ it("renderer marks added lines, removed lines, hunk headers, and leaves context lines unmarked", () => {
+ const colors = {
+ cyan: "\x1b[38;2;52;211;153m",
+ err: "\x1b[38;2;239;68;68m",
+ blue: "\x1b[38;2;58;160;255m",
+ reset: "\x1b[0m",
+ };
+ const unifiedDiff = [
+ "@@ -1,4 +1,4 @@",
+ " context line 1",
+ "-removed line",
+ "+added line",
+ " context line 2",
+ ].join("\n");
+
+ const rendered = renderDiff({
+ artifact: { relativePath: "src/sample.ts" },
+ diff: {
+ available: true,
+ changed: true,
+ unifiedDiff,
+ },
+ }, { colors, full: true });
+
+ // Hunk headers must be coloured blue
+ expect(rendered).toContain(`${colors.blue}@@ -1,4 +1,4 @@${colors.reset}`);
+
+ // Removed lines must be coloured err
+ expect(rendered).toContain(`${colors.err}-removed line${colors.reset}`);
+
+ // Added lines must be coloured cyan
+ expect(rendered).toContain(`${colors.cyan}+added line${colors.reset}`);
+
+ // Context lines remain untouched by colour escapes
+ expect(rendered).toContain(" context line 1");
+ expect(rendered).toContain(" context line 2");
+ expect(rendered).not.toContain(`${colors.cyan} context line 1`);
+ expect(rendered).not.toContain(`${colors.err} context line 1`);
+ expect(rendered).not.toContain(`${colors.blue} context line 1`);
+
+ // Mono or non-TTY styling must emit zero ANSI escape sequences
+ const mono = renderDiff({
+ artifact: { relativePath: "src/sample.ts" },
+ diff: {
+ available: true,
+ changed: true,
+ unifiedDiff,
+ },
+ }, { colors: { cyan: "", err: "", blue: "", reset: "" }, full: true });
+ expect(mono).not.toContain("\x1b[");
+ });
+
+ it("renderer truncates at the cap and reports how many lines were withheld", () => {
+ const lines = Array.from({ length: 30 }, (_, index) => `+added line ${index + 1}`).join("\n");
+ const rendered = renderDiff({
+ artifact: { relativePath: "src/sample.ts" },
+ diff: {
+ available: true,
+ changed: true,
+ unifiedDiff: lines,
+ },
+ }, { cap: 10, colors: { cyan: "", err: "", blue: "", reset: "" } });
+
+ // Shows up to the cap
+ expect(rendered).toContain("+added line 10");
+ expect(rendered).not.toContain("+added line 11");
+
+ // Reports exact withheld count and gives the --full hint
+ expect(rendered).toContain("… 20 more lines, use --full");
+
+ // With full: true, no lines are withheld
+ const full = renderDiff({
+ artifact: { relativePath: "src/sample.ts" },
+ diff: {
+ available: true,
+ changed: true,
+ unifiedDiff: lines,
+ },
+ }, { cap: 10, full: true, colors: { cyan: "", err: "", blue: "", reset: "" } });
+ expect(full).toContain("+added line 30");
+ expect(full).not.toContain("more lines");
+ });
+
+ it("available:false renders the server reason string verbatim", () => {
+ const reasons = [
+ "exact_snapshot_unavailable",
+ "current_file_unavailable",
+ "capture_root_unavailable",
+ "path_unavailable",
+ "no_capture_proof",
+ ];
+
+ for (const reason of reasons) {
+ const rendered = renderDiff({
+ artifact: { relativePath: "lib/agent/session.ts" },
+ diff: {
+ available: false,
+ reason,
+ },
+ });
+ // Verbatim reason string preservation
+ expect(rendered).toContain(reason);
+ expect(rendered).toContain("lib/agent/session.ts");
+ }
+ });
+
+ it("changed:false renders an unchanged message, not an empty diff", () => {
+ const rendered = renderDiff({
+ artifact: { relativePath: "config/settings.json" },
+ diff: {
+ available: true,
+ changed: false,
+ unifiedDiff: "",
+ },
+ });
+
+ // Confirms unchanged notice is emitted rather than blank diff
+ expect(rendered).toMatch(/unchanged/i);
+ expect(rendered).toContain("config/settings.json");
+ expect(rendered).not.toContain("modified");
+ });
+});
diff --git a/scripts/mso-agent-diff.mjs b/scripts/mso-agent-diff.mjs
new file mode 100644
index 00000000..52643315
--- /dev/null
+++ b/scripts/mso-agent-diff.mjs
@@ -0,0 +1,155 @@
+import process from "node:process";
+import { C } from "./mso-agent-runtime.mjs";
+import { api } from "./mso-agent-api.mjs";
+import { sectionBlock } from "./mso-agent-layout.mjs";
+import { safeErrorSummary } from "./mso-agent-errors.mjs";
+
+export function diffLineCap(rows = process.stdout?.rows || 24) {
+ const terminalRows = Number(rows) || 24;
+ return Math.max(1, Math.min(terminalRows - 6, 200));
+}
+
+export function colorizeDiffLine(line, colors = {}) {
+ if (!colors) return line;
+ const reset = colors.reset || "";
+ if (line.startsWith("@@")) {
+ return colors.blue ? `${colors.blue}${line}${reset}` : line;
+ }
+ if (line.startsWith("+")) {
+ return colors.cyan ? `${colors.cyan}${line}${reset}` : line;
+ }
+ if (line.startsWith("-")) {
+ return colors.err ? `${colors.err}${line}${reset}` : line;
+ }
+ return line;
+}
+
+export function formatDiffBody(unifiedDiff, { full = false, cap = 200, colors = {} } = {}) {
+ const raw = String(unifiedDiff || "").replace(/\r/g, "");
+ const allLines = raw.endsWith("\n") ? raw.slice(0, -1).split("\n") : (raw ? raw.split("\n") : []);
+ if (!allLines.length) return "";
+ const isTruncated = !full && allLines.length > cap;
+ const targetLines = isTruncated ? allLines.slice(0, cap) : allLines;
+ const colored = targetLines.map((line) => colorizeDiffLine(line, colors));
+ if (isTruncated) {
+ const withheld = allLines.length - cap;
+ colored.push(`… ${withheld} more lines, use --full`);
+ }
+ return colored.join("\n");
+}
+
+export function actionRefFromSemantic(semantic) {
+ if (!semantic || typeof semantic !== "object") return null;
+ if (Number.isInteger(semantic.step) && Number.isInteger(semantic.action)) {
+ return `S${semantic.step}.A${semantic.action}`;
+ }
+ return null;
+}
+
+export function actionRefFromEvent(event) {
+ if (!event || typeof event !== "object") return null;
+ // Explicit action ref takes precedence over derived step/action numbers.
+ if (typeof event.actionRef === "string" && event.actionRef.trim()) {
+ return event.actionRef.trim();
+ }
+ if (typeof event.ref === "string" && event.ref.trim()) {
+ return event.ref.trim();
+ }
+ if (event.semantic) {
+ const fromSem = actionRefFromSemantic(event.semantic);
+ if (fromSem) return fromSem;
+ }
+ return actionRefFromSemantic(event);
+}
+
+export function findLatestArtifactEvent(events) {
+ if (!Array.isArray(events)) return null;
+ for (let i = events.length - 1; i >= 0; i--) {
+ const event = events[i];
+ if (event?.artifactRevision) return event;
+ }
+ return null;
+}
+
+export function extractDiffAndArtifact(data) {
+ if (!data || typeof data !== "object") {
+ return { diff: null, filePath: "file" };
+ }
+ const diff = data.diff ?? data.history?.diff ?? (data.available !== undefined ? data : null);
+ const artifact = data.artifact ?? data.resolution?.action?.artifact;
+ const filePath = artifact?.relativePath || artifact?.path || data.relativePath || data.path || "file";
+ return { diff, filePath };
+}
+
+export function renderDiff(data, options = {}) {
+ const { diff, filePath } = extractDiffAndArtifact(data);
+ const colors = options.colors || C;
+ const columns = options.columns;
+ if (!diff || diff.available === false) {
+ const reason = diff?.reason || "unavailable";
+ return sectionBlock("diff", `diff unavailable: ${reason}`, { detail: filePath, colors, columns });
+ }
+ if (diff.changed === false) {
+ return sectionBlock("diff", "file is unchanged since capture.", { detail: `${filePath} · unchanged`, colors, columns });
+ }
+ const full = Boolean(options.full);
+ const cap = Number.isInteger(options.cap) ? options.cap : diffLineCap(options.rows);
+ const formattedBody = formatDiffBody(diff.unifiedDiff, { full, cap, colors });
+ const detail = `${filePath} · modified`;
+ return sectionBlock("diff", formattedBody, { detail, colors, columns });
+}
+
+export async function handleDiffCommand(session, args = [], options = {}) {
+ const full = args.includes("--full");
+ const positional = args.filter((arg) => arg !== "--full" && !arg.startsWith("-"));
+ let actionRef = positional[0]?.trim() || null;
+ const sessionId = session?.agentSession?.id;
+ const print = options.print || console.log;
+ const error = options.error || console.error;
+ const colors = options.colors || C;
+ const fetchApi = options.api || api;
+
+ if (!sessionId) {
+ print("no active session");
+ return;
+ }
+
+ if (!actionRef) {
+ try {
+ const res = await fetchApi(`/api/v1/agent-sessions?ref=${encodeURIComponent(sessionId)}`);
+ const events = Array.isArray(res?.session?.events)
+ ? res.session.events
+ : (Array.isArray(session?.agentSession?.events) ? session.agentSession.events : []);
+ const latestEvent = findLatestArtifactEvent(events);
+ if (!latestEvent) {
+ print("no captured artifact modifications in this session.");
+ return;
+ }
+ actionRef = actionRefFromEvent(latestEvent);
+ if (!actionRef) {
+ print("could not resolve action reference for captured artifact.");
+ return;
+ }
+ } catch (err) {
+ error(`${colors.err || ""}${safeErrorSummary(err)}${colors.reset || ""}`);
+ return;
+ }
+ }
+
+ try {
+ const artifactView = await fetchApi(
+ `/api/v1/agent-sessions?view=artifact&id=${encodeURIComponent(sessionId)}&action_ref=${encodeURIComponent(actionRef)}`
+ );
+ const rendered = renderDiff(artifactView, {
+ full,
+ colors,
+ rows: options.rows ?? process.stdout?.rows,
+ columns: options.columns ?? process.stdout?.columns,
+ cap: options.cap,
+ });
+ print(rendered);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ error(`${colors.err || ""}${message}${colors.reset || ""}`);
+ }
+}
diff --git a/scripts/mso-agent-diff.test.ts b/scripts/mso-agent-diff.test.ts
new file mode 100644
index 00000000..6a884362
--- /dev/null
+++ b/scripts/mso-agent-diff.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from "vitest";
+import {
+ actionRefFromEvent,
+ actionRefFromSemantic,
+ diffLineCap,
+ findLatestArtifactEvent,
+ handleDiffCommand,
+} from "./mso-agent-diff.mjs";
+
+describe("MSO Agent diff command and renderer", () => {
+ it("action-ref builder from a semantic {step, action} produces S3.A2", () => {
+ // Direct semantic object
+ expect(actionRefFromSemantic({ step: 3, action: 2 })).toBe("S3.A2");
+
+ // Semantic wrapped in an event object
+ expect(actionRefFromEvent({ semantic: { step: 3, action: 2, category: "implement", version: 1 } })).toBe("S3.A2");
+
+ // Explicit actionRef field is preferred over semantic coordinates
+ expect(actionRefFromEvent({ actionRef: "action_1234567890abcdef1234", semantic: { step: 3, action: 2 } })).toBe("action_1234567890abcdef1234");
+ expect(actionRefFromEvent({ ref: "action_ref_custom", semantic: { step: 1, action: 1 } })).toBe("action_ref_custom");
+
+ // Malformed inputs return null safely
+ expect(actionRefFromSemantic(null)).toBeNull();
+ expect(actionRefFromSemantic({ step: "invalid", action: 2 } as unknown as { step: number; action: number })).toBeNull();
+ expect(actionRefFromEvent(null)).toBeNull();
+ });
+
+ it("finds the most recent event with an artifact revision", () => {
+ const events = [
+ { at: "2026-10-29T10:00:00Z", kind: "tool", tool: "fs_read" },
+ {
+ at: "2026-10-29T10:01:00Z",
+ kind: "tool",
+ tool: "fs_write",
+ artifactRevision: { version: 1, cwd: "/app", relativePath: "first.ts" },
+ semantic: { step: 1, action: 2 },
+ },
+ { at: "2026-10-29T10:02:00Z", kind: "note" },
+ {
+ at: "2026-10-29T10:03:00Z",
+ kind: "tool",
+ tool: "fs_write",
+ artifactRevision: { version: 1, cwd: "/app", relativePath: "second.ts" },
+ semantic: { step: 2, action: 1 },
+ },
+ { at: "2026-10-29T10:04:00Z", kind: "workflow" },
+ ];
+
+ const latest = findLatestArtifactEvent(events);
+ expect(latest).toBeDefined();
+ expect(latest?.artifactRevision?.relativePath).toBe("second.ts");
+ expect(actionRefFromEvent(latest)).toBe("S2.A1");
+ });
+
+ it("calculates terminal height line cap within bounds", () => {
+ // 24 - 6 = 18
+ expect(diffLineCap(24)).toBe(18);
+ // Upper capped at 200
+ expect(diffLineCap(500)).toBe(200);
+ // Lower bounded at 1
+ expect(diffLineCap(5)).toBe(1);
+ });
+
+ it("handles /diff command integration without throwing errors out of the TUI", async () => {
+ const printed: string[] = [];
+ const errors: string[] = [];
+ const print = (text: string) => printed.push(text);
+ const error = (text: string) => errors.push(text);
+
+ const apiCalls: string[] = [];
+ const mockApi = async (path: string) => {
+ apiCalls.push(path);
+ if (path.includes("view=artifact")) {
+ return {
+ artifact: { relativePath: "src/index.ts" },
+ diff: { available: true, changed: true, unifiedDiff: "@@ -1,1 +1,1 @@\n-a\n+b" },
+ };
+ }
+ return {
+ session: {
+ events: [
+ {
+ kind: "tool",
+ artifactRevision: { version: 1, cwd: "/repo", relativePath: "src/index.ts" },
+ semantic: { step: 3, action: 2 },
+ },
+ ],
+ },
+ };
+ };
+
+ const session = {
+ agentSession: { id: "session-xyz" },
+ };
+
+ // Invoking without args fetches session events, resolves ref, then diffs
+ await handleDiffCommand(session, [], { api: mockApi, print, error });
+ expect(apiCalls[0]).toContain("/api/v1/agent-sessions?ref=session-xyz");
+ expect(apiCalls[1]).toContain("action_ref=S3.A2");
+ expect(printed[0]).toContain("src/index.ts");
+ expect(printed[0]).toContain("+b");
+
+ // Invoking with explicit action ref skips session events fetch
+ apiCalls.length = 0;
+ printed.length = 0;
+ await handleDiffCommand(session, ["S4.A1"], { api: mockApi, print, error });
+ expect(apiCalls).toHaveLength(1);
+ expect(apiCalls[0]).toContain("action_ref=S4.A1");
+ expect(printed[0]).toContain("src/index.ts");
+
+ // Server failures are caught and reported without crashing
+ const failingApi = async () => {
+ throw new Error("network down");
+ };
+ await expect(handleDiffCommand(session, ["S4.A1"], { api: failingApi, print, error })).resolves.not.toThrow();
+ expect(errors[0]).toContain("network down");
+ });
+});
diff --git a/scripts/mso-agent-export.test.ts b/scripts/mso-agent-export.test.ts
new file mode 100644
index 00000000..9000f8bc
--- /dev/null
+++ b/scripts/mso-agent-export.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import {
+ SHARE_UNAVAILABLE_MESSAGE,
+ buildExportArgv,
+ handleSlash,
+} from "./mso-agent-commands.mjs";
+import { slashCompletionItems } from "./mso-agent-slash.mjs";
+
+describe("MSO Agent export and share commands", () => {
+ it("builds export argv correctly for no args, with ref, and with --out", () => {
+ // No args exports newest session
+ expect(buildExportArgv()).toEqual(["session", "export"]);
+ expect(buildExportArgv([])).toEqual(["session", "export"]);
+
+ // With a ref
+ expect(buildExportArgv("abc")).toEqual(["session", "export", "abc"]);
+ expect(buildExportArgv(["abc"])).toEqual(["session", "export", "abc"]);
+
+ // Appends --out when given
+ expect(buildExportArgv("abc", "f")).toEqual([
+ "session",
+ "export",
+ "abc",
+ "--out",
+ "f",
+ ]);
+ expect(buildExportArgv(undefined, "f")).toEqual([
+ "session",
+ "export",
+ "--out",
+ "f",
+ ]);
+ expect(buildExportArgv(["abc", "--out", "f"])).toEqual([
+ "session",
+ "export",
+ "abc",
+ "--out",
+ "f",
+ ]);
+ expect(buildExportArgv(["--out", "f"])).toEqual([
+ "session",
+ "export",
+ "--out",
+ "f",
+ ]);
+ });
+
+ it("ensures the share-unavailable message is honest and does not claim a link was created", () => {
+ expect(SHARE_UNAVAILABLE_MESSAGE).toContain("/share is unavailable");
+ expect(SHARE_UNAVAILABLE_MESSAGE).toContain(
+ "server exposes only download of existing shares",
+ );
+ expect(SHARE_UNAVAILABLE_MESSAGE).not.toMatch(/https?:\/\//);
+ expect(SHARE_UNAVAILABLE_MESSAGE).not.toContain("link created");
+ // Ensure no em dash is used
+ expect(SHARE_UNAVAILABLE_MESSAGE).not.toContain("\u2014");
+ });
+
+ it("handles /share gracefully and returns handled", async () => {
+ const dummySession = { agentSession: { id: "session-123" } };
+ const outcome = await handleSlash(null, "/share", dummySession, {
+ // /share must not touch runTurn or runSubagent; pass stubs that would fail loudly.
+ runTurn: async () => { throw new Error("runTurn must not be called by /share"); },
+ runSubagent: async () => { throw new Error("runSubagent must not be called by /share"); },
+ });
+ expect(outcome).toBe("handled");
+ });
+
+ it("registers /export and /share in slash completion catalog", () => {
+ const items = slashCompletionItems({ skills: [] }, "/", "/home/operator");
+ const texts = items.map((i) => i.text);
+ expect(texts).toContain("/export");
+ expect(texts).toContain("/share");
+ });
+});
diff --git a/scripts/mso-agent-files.mjs b/scripts/mso-agent-files.mjs
new file mode 100644
index 00000000..8abe56e8
--- /dev/null
+++ b/scripts/mso-agent-files.mjs
@@ -0,0 +1,159 @@
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { api } from "./mso-agent-api.mjs";
+import { C, fit } from "./mso-agent-ui.mjs";
+import { AgentApiError, safeErrorSummary } from "./mso-agent-errors.mjs";
+import { sectionDivider } from "./mso-agent-layout.mjs";
+
+// Terminal height minus header, divider, and prompt margin, clamped [5, 60].
+export function computeRows(terminalRows = 24) {
+ const r = Number(terminalRows) || 24;
+ return Math.max(5, Math.min(60, r - 8));
+}
+
+// User-supplied paths may start with ~; expand without spawning a shell.
+export function expandPath(inputPath, cwd = process.cwd()) {
+ const raw = String(inputPath ?? "").trim();
+ if (!raw) return cwd;
+ const home = os.homedir();
+ if (raw === "~") return home;
+ if (raw.startsWith("~/") || raw.startsWith("~\\")) {
+ return path.resolve(home, raw.slice(2));
+ }
+ return path.resolve(cwd, raw);
+}
+
+// Target GET /api/v1/fs/list with URI-encoded target path.
+export function buildFilesUrl(inputPath, cwd = process.cwd()) {
+ const resolved = expandPath(inputPath, cwd);
+ return `/api/v1/fs/list?path=${encodeURIComponent(resolved)}`;
+}
+
+export function isDirectory(entry) {
+ if (!entry || typeof entry !== "object") return false;
+ const kind = String(entry.kind || entry.type || "").toLowerCase();
+ if (kind === "dir" || kind === "directory") return true;
+ return String(entry.name || "").endsWith("/");
+}
+
+export function isSymlink(entry) {
+ if (!entry || typeof entry !== "object") return false;
+ if (entry.isSymbolicLink === true || entry.isSymlink === true) return true;
+ const kind = String(entry.kind || "").toLowerCase();
+ const type = String(entry.type || "").toLowerCase();
+ return kind === "symlink" || kind === "link" || type === "symlink" || type === "link";
+}
+
+// Surface unusual inode types explicitly without relying on sizes.
+export function entryTypeTag(entry) {
+ if (!entry || typeof entry !== "object") return "";
+ if (isSymlink(entry)) return "(symlink)";
+ const type = String(entry.type || entry.kind || "").toLowerCase();
+ if (!type || type === "file" || type === "dir" || type === "directory") return "";
+ return `(${type})`;
+}
+
+// Format a bounded tree view without leaking 0-byte fake sizes.
+export function formatEntries(entries, { columns = 80, rows = 60, path = "", colors = {} } = {}) {
+ const list = Array.isArray(entries) ? entries : [];
+ const limit = Math.max(5, Math.min(60, Number(rows ?? 60) || 60));
+
+ const sorted = [...list].sort((a, b) => {
+ const aDir = isDirectory(a);
+ const bDir = isDirectory(b);
+ if (aDir !== bDir) return aDir ? -1 : 1;
+ return String(a?.name || "").localeCompare(String(b?.name || ""));
+ });
+
+ const isCapped = sorted.length > limit;
+ const visible = isCapped ? sorted.slice(0, limit) : sorted;
+ const remaining = sorted.length - visible.length;
+
+ const capText = `capped at ${limit}`;
+ const headerDetail = isCapped
+ ? (path ? `${path} (${capText})` : capText)
+ : (path || "");
+
+ const lines = [sectionDivider("files", { columns, detail: headerDetail, colors })];
+
+ if (list.length === 0) {
+ lines.push(" (empty directory)");
+ return lines;
+ }
+
+ const colWidth = 32;
+ for (const entry of visible) {
+ const isDir = isDirectory(entry);
+ const name = isDir
+ ? (String(entry.name || "").endsWith("/") ? entry.name : `${entry.name}/`)
+ : String(entry.name || "");
+ const tag = entryTypeTag(entry);
+ let entryText = "";
+ if (tag) {
+ entryText = name.length < colWidth
+ ? ` ${name.padEnd(colWidth)} ${tag}`
+ : ` ${name} ${tag}`;
+ } else {
+ entryText = ` ${name}`;
+ }
+
+ if (columns > 0 && entryText.length > columns) {
+ entryText = fit(entryText, columns);
+ }
+
+ if (colors && (colors.blue || colors.bold || colors.dim || colors.cyan || colors.c)) {
+ if (isDir) {
+ entryText = `${colors.bold || ""}${colors.blue || ""}${entryText}${colors.reset || ""}`;
+ } else if (isSymlink(entry)) {
+ entryText = `${colors.cyan || colors.c || ""}${entryText}${colors.reset || ""}`;
+ }
+ }
+
+ lines.push(entryText);
+ }
+
+ if (isCapped) {
+ const moreText = ` … ${remaining} more`;
+ lines.push(colors?.dim ? `${colors.dim}${moreText}${colors.reset || ""}` : moreText);
+ }
+
+ return lines;
+}
+
+// Bounded read-only view of target or working directory.
+export async function handleFilesCommand(args = [], session = null, options = {}) {
+ const callApi = options.apiFn || api;
+ const print = options.print || console.log;
+ const printErr = options.printErr || console.error;
+ const rawTarget = args.join(" ").trim();
+ const targetPath = expandPath(rawTarget);
+ const url = buildFilesUrl(rawTarget);
+
+ let data;
+ try {
+ data = await callApi(url);
+ } catch (error) {
+ // Keep TUI interactive when requested path is outside roots or missing.
+ const msg = error instanceof AgentApiError ? error.message : safeErrorSummary(error);
+ printErr(`${C.err}${msg}${C.reset}`);
+ return;
+ }
+
+ if (data?.error) {
+ printErr(`${C.err}${data.error}${C.reset}`);
+ return;
+ }
+
+ const columns = options.columns ?? process.stdout?.columns ?? 80;
+ const terminalRows = options.rows ?? process.stdout?.rows ?? 24;
+ const rows = computeRows(terminalRows);
+ const lines = formatEntries(data?.entries || [], {
+ columns,
+ rows,
+ path: data?.path || targetPath,
+ colors: C,
+ });
+
+ print(lines.join("\n"));
+}
diff --git a/scripts/mso-agent-files.test.ts b/scripts/mso-agent-files.test.ts
new file mode 100644
index 00000000..d0f0d9df
--- /dev/null
+++ b/scripts/mso-agent-files.test.ts
@@ -0,0 +1,120 @@
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ buildFilesUrl,
+ computeRows,
+ expandPath,
+ formatEntries,
+ handleFilesCommand,
+} from "./mso-agent-files.mjs";
+
+describe("MSO Agent /files command and layout", () => {
+ it("sorts directories before files and suffixes each directory with /", () => {
+ const entries = [
+ { name: "zebra.txt", kind: "file" },
+ { name: "docs", kind: "dir" },
+ { name: "apple.js", kind: "file" },
+ { name: "src", kind: "dir" },
+ ];
+ const lines = formatEntries(entries, { columns: 80, rows: 60 });
+ const content = lines.slice(1);
+ expect(content[0]).toContain("docs/");
+ expect(content[1]).toContain("src/");
+ expect(content[2]).toContain("apple.js");
+ expect(content[3]).toContain("zebra.txt");
+ expect(content[2]).not.toContain("apple.js/");
+ });
+
+ it("marks symlinks so they are distinguishable from regular files", () => {
+ const entries = [
+ { name: "regular.txt", kind: "file" },
+ { name: "linked-file.txt", kind: "file", type: "symlink" },
+ { name: "link-by-kind", kind: "symlink" },
+ { name: "link-dir", kind: "dir", isSymbolicLink: true },
+ { name: "pipe", type: "fifo" },
+ ];
+ const lines = formatEntries(entries, { columns: 80, rows: 60 });
+ const regularLine = lines.find((l) => l.includes("regular.txt"));
+ const linkFileLine = lines.find((l) => l.includes("linked-file.txt"));
+ const linkKindLine = lines.find((l) => l.includes("link-by-kind"));
+ const linkDirLine = lines.find((l) => l.includes("link-dir"));
+ const pipeLine = lines.find((l) => l.includes("pipe"));
+
+ expect(regularLine).toBeDefined();
+ expect(regularLine).not.toContain("symlink");
+ expect(linkFileLine).toContain("(symlink)");
+ expect(linkKindLine).toContain("(symlink)");
+ expect(linkDirLine).toContain("link-dir/");
+ expect(linkDirLine).toContain("(symlink)");
+ expect(pipeLine).toContain("(fifo)");
+ });
+
+ it("never renders a size number even when the payload has size: 0", () => {
+ const entries = [
+ { name: "empty.txt", kind: "file", size: 0 },
+ { name: "big.bin", kind: "file", size: 1048576 },
+ { name: "folder", kind: "dir", size: 0 },
+ ];
+ const lines = formatEntries(entries, { columns: 80, rows: 60 });
+ const sizePattern = /\d+\s*(?:B|KB|MB|GB|bytes)\b/i;
+ for (const line of lines) {
+ expect(line).not.toMatch(sizePattern);
+ }
+ });
+
+ it("caps at 60 entries with a … N more line and a header stating the cap", () => {
+ const entries = Array.from({ length: 75 }, (_, i) => ({
+ name: `file-${String(i).padStart(2, "0")}.txt`,
+ kind: "file",
+ }));
+ const lines = formatEntries(entries, { columns: 80, rows: 60 });
+ expect(lines[0]).toMatch(/capped at 60/i);
+ expect(lines).toHaveLength(62);
+ expect(lines[lines.length - 1]).toContain("… 15 more");
+ });
+
+ it("respects terminal-height cap when rows is small", () => {
+ const entries = Array.from({ length: 25 }, (_, i) => ({
+ name: `item-${i}.txt`,
+ kind: "file",
+ }));
+
+ // Bounded by rows parameter.
+ const lines = formatEntries(entries, { columns: 80, rows: 10 });
+ expect(lines[0]).toMatch(/capped at 10/i);
+ expect(lines).toHaveLength(12);
+ expect(lines[lines.length - 1]).toContain("… 15 more");
+
+ // computeRows enforces floor at 5 and ceiling at 60.
+ expect(computeRows(10)).toBe(5);
+ expect(computeRows(18)).toBe(10);
+ expect(computeRows(100)).toBe(60);
+
+ const floored = formatEntries(entries, { columns: 80, rows: 2 });
+ expect(floored[0]).toMatch(/capped at 5/i);
+ expect(floored).toHaveLength(7);
+ });
+
+ it("expands ~ to the home directory before the URL is built", () => {
+ const home = os.homedir();
+ expect(expandPath("~")).toBe(home);
+ expect(expandPath("~/work")).toBe(path.join(home, "work"));
+ expect(buildFilesUrl("~")).toBe(`/api/v1/fs/list?path=${encodeURIComponent(home)}`);
+ expect(buildFilesUrl("~/work")).toBe(`/api/v1/fs/list?path=${encodeURIComponent(path.join(home, "work"))}`);
+ });
+
+ it("handles errors from server without throwing", async () => {
+ const errors: string[] = [];
+ const printErr = (msg: string) => errors.push(msg);
+ const apiFn = async () => {
+ const err = new Error("outside readable roots");
+ err.name = "AgentApiError";
+ throw err;
+ };
+
+ await expect(handleFilesCommand(["/root/secret"], null, { apiFn, printErr })).resolves.not.toThrow();
+ expect(errors.length).toBe(1);
+ expect(errors[0]).toContain("outside readable roots");
+ });
+});
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index 3422611f..f014efa4 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -1,44 +1,57 @@
+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",
+ " /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",
+ " /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",
+ " /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 [sub|prompt] queue follow-up prompt; list, run, or clear",
+ " /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",
+ "",
+ "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 const HELP_TEXT = HELP_LINES.join("\n");
+
export function printHelp() {
- console.log(
- [
- " /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",
- " /resume [query] alias-style resume command; bare opens same picker",
- " /rename <name> rename the short @agent handle",
- " /title <text> rename the session title/description",
- " /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",
- " /model [ref] select active model from connected providers",
- " /setup full MSO onboarding",
- " /integrations [args] manage users, providers, connections, source/auth",
- " /doctor run mso doctor",
- " /tools list agent tools",
- " /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",
- " /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",
- " /clear clear this session conversation",
- " /exit, /quit quit",
- "",
- "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",
- ].join("\n"),
- );
+ console.log(HELP_TEXT);
}
-
diff --git a/scripts/mso-agent-help.test.ts b/scripts/mso-agent-help.test.ts
new file mode 100644
index 00000000..b055f110
--- /dev/null
+++ b/scripts/mso-agent-help.test.ts
@@ -0,0 +1,63 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import { HELP_LINES, HELP_TEXT, printHelp } from "./mso-agent-help.mjs";
+
+describe("MSO Agent /help command output and regression guard", () => {
+ it("printHelp outputs help text without throwing", () => {
+ const logged: string[] = [];
+ const spy = vi.spyOn(console, "log").mockImplementation((msg) => {
+ logged.push(String(msg));
+ });
+ try {
+ printHelp();
+ expect(logged.length).toBeGreaterThan(0);
+ expect(logged.join("\n")).toBe(HELP_TEXT);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it("documents every command arm implemented in mso-agent-commands.mjs", () => {
+ 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 = HELP_TEXT;
+ const undocumented = commandArms.filter((cmd) => !help.includes(cmd));
+ expect(undocumented).toEqual([]);
+ });
+
+ it("contains no em dash characters anywhere in help text", () => {
+ expect(HELP_TEXT).not.toContain("\u2014");
+ for (const line of HELP_LINES) {
+ expect(line).not.toContain("\u2014");
+ }
+ });
+
+ it("preserves Keyboard section and key bindings", () => {
+ expect(HELP_TEXT).toContain("Keyboard");
+ expect(HELP_TEXT).toContain("Ctrl+C");
+ expect(HELP_TEXT).toContain("Ctrl+D");
+ expect(HELP_TEXT).toContain("Ctrl+L");
+ expect(HELP_TEXT).toContain("Tab (empty prompt)");
+ });
+
+ it("documents new TUI parity commands with honest limitations", () => {
+ expect(HELP_TEXT).toContain("/export");
+ expect(HELP_TEXT).toContain("/share");
+ expect(HELP_TEXT).toMatch(/\/share.*(?:unavailable|download-only)/i);
+ expect(HELP_TEXT).toContain("/compact");
+ expect(HELP_TEXT).toContain("/reasoning");
+ expect(HELP_TEXT).toContain("/reasoning on|off");
+ expect(HELP_TEXT).toContain("/theme");
+ expect(HELP_TEXT).toContain("/queue");
+ expect(HELP_TEXT).toContain("/stash");
+ expect(HELP_TEXT).toContain("/stash pop");
+ expect(HELP_TEXT).toContain("/image");
+ expect(HELP_TEXT).toContain("/diff");
+ expect(HELP_TEXT).toContain("/files");
+ });
+});
diff --git a/scripts/mso-agent-image.mjs b/scripts/mso-agent-image.mjs
new file mode 100644
index 00000000..c03bec96
--- /dev/null
+++ b/scripts/mso-agent-image.mjs
@@ -0,0 +1,91 @@
+// Pure image helpers and upload boundary for attaching images to agent turns.
+// Uploads target the session temp artifacts directory via /api/v1/fs/upload.
+
+import fs from "node:fs";
+import path from "node:path";
+import { BASE, requestHeaders } from "./mso-agent-api.mjs";
+
+export const ALLOWED_IMAGE_EXTENSIONS = new Set([
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".webp",
+]);
+
+export function validateImagePath(filePath) {
+ if (typeof filePath !== "string" || !filePath.trim()) {
+ return { ok: false, error: "image path required" };
+ }
+ const resolved = path.resolve(filePath.trim());
+ let stat;
+ try {
+ stat = fs.statSync(resolved);
+ } catch {
+ return { ok: false, error: `file not found: ${filePath}` };
+ }
+ if (!stat.isFile()) {
+ return { ok: false, error: `not a regular file: ${filePath}` };
+ }
+ const ext = path.extname(resolved).toLowerCase();
+ if (!ALLOWED_IMAGE_EXTENSIONS.has(ext)) {
+ return {
+ ok: false,
+ error: `unsupported image format: ${ext || "(none)"} (expected .png, .jpg, .jpeg, .gif, .webp)`,
+ };
+ }
+ return { ok: true, path: resolved, ext, size: stat.size };
+}
+
+export function pendingImageBlock(images) {
+ if (!Array.isArray(images) || !images.length) return "";
+ const lines = [
+ "--- ATTACHED IMAGES ---",
+ ...images.map((img) => img.remotePath || img.path),
+ "------------------------",
+ ];
+ return lines.join("\n");
+}
+
+export async function uploadSessionImage(session, localPath) {
+ const destDir = session?.agentSession?.artifacts?.directory;
+ if (!destDir) {
+ throw new Error("session artifacts directory is unavailable");
+ }
+ const valid = validateImagePath(localPath);
+ if (!valid.ok) {
+ throw new Error(valid.error);
+ }
+ const buffer = fs.readFileSync(valid.path);
+ const filename = path.basename(valid.path);
+ const blob = new Blob([buffer]);
+
+ const form = new FormData();
+ form.append("dest", destDir);
+ form.append("file", blob, filename);
+
+ const res = await fetch(`${BASE}/api/v1/fs/upload`, {
+ method: "POST",
+ body: form,
+ headers: requestHeaders(false),
+ });
+
+ if (!res.ok) {
+ const text = await res.text().catch(() => "");
+ let message = `upload failed (HTTP ${res.status})`;
+ try {
+ const parsed = JSON.parse(text);
+ if (parsed?.error) message = String(parsed.error);
+ } catch {
+ if (text) message = text.slice(0, 200);
+ }
+ throw new Error(message);
+ }
+
+ const remotePath = path.join(destDir, filename);
+ return {
+ path: valid.path,
+ remotePath,
+ bytes: valid.size,
+ };
+}
diff --git a/scripts/mso-agent-image.test.ts b/scripts/mso-agent-image.test.ts
new file mode 100644
index 00000000..1b5c38d1
--- /dev/null
+++ b/scripts/mso-agent-image.test.ts
@@ -0,0 +1,92 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import {
+ ALLOWED_IMAGE_EXTENSIONS,
+ pendingImageBlock,
+ validateImagePath,
+} from "./mso-agent-image.mjs";
+
+describe("MSO Agent image", () => {
+ let tmpDir: string;
+ let testPng: string;
+ let testTxt: string;
+
+ beforeAll(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-img-test-"));
+ testPng = path.join(tmpDir, "sample.png");
+ testTxt = path.join(tmpDir, "sample.txt");
+ fs.writeFileSync(testPng, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ fs.writeFileSync(testTxt, "plain text");
+ });
+
+ afterAll(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ it("extension validation accepts .png", () => {
+ const valid = validateImagePath(testPng);
+ expect(valid.ok).toBe(true);
+ expect(valid.ext).toBe(".png");
+ expect(valid.size).toBe(4);
+ });
+
+ it("extension validation rejects a .txt file", () => {
+ const res = validateImagePath(testTxt);
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain("unsupported image format");
+ });
+
+ it("extension validation rejects a directory", () => {
+ const res = validateImagePath(tmpDir);
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain("not a regular file");
+ });
+
+ it("extension validation rejects missing file", () => {
+ const res = validateImagePath(path.join(tmpDir, "nonexistent.png"));
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain("file not found");
+ });
+
+ it("allows standard image extensions in set", () => {
+ expect(ALLOWED_IMAGE_EXTENSIONS.has(".png")).toBe(true);
+ expect(ALLOWED_IMAGE_EXTENSIONS.has(".jpg")).toBe(true);
+ expect(ALLOWED_IMAGE_EXTENSIONS.has(".jpeg")).toBe(true);
+ expect(ALLOWED_IMAGE_EXTENSIONS.has(".gif")).toBe(true);
+ expect(ALLOWED_IMAGE_EXTENSIONS.has(".webp")).toBe(true);
+ expect(ALLOWED_IMAGE_EXTENSIONS.has(".svg")).toBe(false);
+ });
+
+ it("pendingImageBlock returns empty string for empty or missing list", () => {
+ expect(pendingImageBlock([])).toBe("");
+ expect(pendingImageBlock(null)).toBe("");
+ expect(pendingImageBlock(undefined)).toBe("");
+ });
+
+ it("pendingImageBlock lists remote paths with clear delimiter", () => {
+ const images = [
+ { path: "/tmp/a.png", remotePath: "/artifacts/a.png", bytes: 100 },
+ { path: "/tmp/b.jpg", remotePath: "/artifacts/b.jpg", bytes: 200 },
+ ];
+ const block = pendingImageBlock(images);
+ expect(block).toContain("--- ATTACHED IMAGES ---");
+ expect(block).toContain("/artifacts/a.png");
+ expect(block).toContain("/artifacts/b.jpg");
+ expect(block).toContain("------------------------");
+ });
+
+ // Regression: /image used to upload and then strand the file in session.pendingImages,
+ // because the prompt loop never read it. The block must reach the user message.
+ it("the prompt loop prepends pending images and clears them", () => {
+ const source = fs.readFileSync(path.join(process.cwd(), "scripts/mso-agent.mjs"), "utf8");
+ // The block is built from session.pendingImages and folded into the history row.
+ expect(source).toMatch(/pendingImageBlock\(images\)/);
+ expect(source).toMatch(/role: "user", text: imageBlock \?/);
+ // The list is cleared in the same breath, so an image cannot ride along twice.
+ expect(source).toMatch(/session\.pendingImages = \[\]/);
+ // And the import is real, not a dead reference.
+ expect(source).toMatch(/import \{ pendingImageBlock \} from "\.\/mso-agent-image\.mjs"/);
+ });
+});
diff --git a/scripts/mso-agent-queue.mjs b/scripts/mso-agent-queue.mjs
new file mode 100644
index 00000000..1a6a2c71
--- /dev/null
+++ b/scripts/mso-agent-queue.mjs
@@ -0,0 +1,44 @@
+// Ephemeral in-memory queue: follow-up prompts are scoped to the active TUI process and never persisted to the server.
+
+function getItems(queue) {
+ if (Array.isArray(queue)) return queue;
+ if (queue && Array.isArray(queue.items)) return queue.items;
+ return null;
+}
+
+export function createQueue() {
+ return { items: [] };
+}
+
+export function enqueue(queue, text) {
+ const items = getItems(queue);
+ if (!items) return { ok: false, error: "invalid queue" };
+ const trimmed = typeof text === "string" ? text.trim() : "";
+ if (!trimmed) {
+ return { ok: false, empty: true, count: items.length };
+ }
+ if (items.length >= 20) {
+ return { ok: false, capped: true, cap: 20, count: items.length, error: "queue full (cap is 20 items)" };
+ }
+ items.push(trimmed);
+ return { ok: true, count: items.length, item: trimmed };
+}
+
+export function dequeue(queue) {
+ const items = getItems(queue);
+ if (!items || !items.length) return null;
+ return items.shift() ?? null;
+}
+
+export function queueList(queue) {
+ const items = getItems(queue);
+ return items ? [...items] : [];
+}
+
+export function queueClear(queue) {
+ const items = getItems(queue);
+ if (!items) return 0;
+ const dropped = items.length;
+ items.length = 0;
+ return dropped;
+}
diff --git a/scripts/mso-agent-queue.test.ts b/scripts/mso-agent-queue.test.ts
new file mode 100644
index 00000000..c228e063
--- /dev/null
+++ b/scripts/mso-agent-queue.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import {
+ createQueue,
+ dequeue,
+ enqueue,
+ queueClear,
+ queueList,
+} from "./mso-agent-queue.mjs";
+
+describe("MSO Agent queue", () => {
+ it("enqueue trims whitespace and ignores empty input", () => {
+ const queue = createQueue();
+ const emptyResult = enqueue(queue, " ");
+ expect(emptyResult.ok).toBe(false);
+ expect(queueList(queue)).toEqual([]);
+
+ const trimmedResult = enqueue(queue, " follow up question ");
+ expect(trimmedResult.ok).toBe(true);
+ expect(trimmedResult.count).toBe(1);
+ expect(queueList(queue)).toEqual(["follow up question"]);
+ });
+
+ it("caps at 20 items and reports refusal", () => {
+ const queue = createQueue();
+ for (let i = 1; i <= 20; i++) {
+ const res = enqueue(queue, `prompt ${i}`);
+ expect(res.ok).toBe(true);
+ }
+ expect(queueList(queue)).toHaveLength(20);
+
+ const overflow = enqueue(queue, "prompt 21");
+ expect(overflow.ok).toBe(false);
+ expect(overflow.capped).toBe(true);
+ expect(overflow.cap).toBe(20);
+ expect(queueList(queue)).toHaveLength(20);
+ });
+
+ it("dequeue is FIFO", () => {
+ const queue = createQueue();
+ enqueue(queue, "first");
+ enqueue(queue, "second");
+ enqueue(queue, "third");
+
+ expect(dequeue(queue)).toBe("first");
+ expect(dequeue(queue)).toBe("second");
+ expect(dequeue(queue)).toBe("third");
+ expect(dequeue(queue)).toBeNull();
+ });
+
+ it("list returns stable order", () => {
+ const queue = createQueue();
+ enqueue(queue, "alpha");
+ enqueue(queue, "beta");
+ enqueue(queue, "gamma");
+
+ expect(queueList(queue)).toEqual(["alpha", "beta", "gamma"]);
+ expect(queueList(queue)).toEqual(["alpha", "beta", "gamma"]);
+ });
+
+ it("clear returns the dropped count", () => {
+ const queue = createQueue();
+ expect(queueClear(queue)).toBe(0);
+
+ enqueue(queue, "one");
+ enqueue(queue, "two");
+ enqueue(queue, "three");
+
+ const dropped = queueClear(queue);
+ expect(dropped).toBe(3);
+ expect(queueList(queue)).toEqual([]);
+ expect(dequeue(queue)).toBeNull();
+ });
+});
diff --git a/scripts/mso-agent-reasoning.mjs b/scripts/mso-agent-reasoning.mjs
new file mode 100644
index 00000000..20fc0df3
--- /dev/null
+++ b/scripts/mso-agent-reasoning.mjs
@@ -0,0 +1,46 @@
+function finite(value) {
+ if (value === null || value === undefined || value === "") return undefined;
+ const n = Number(value);
+ return Number.isFinite(n) && n >= 0 ? n : undefined;
+}
+
+export function reasoningLine(usage) {
+ if (!usage || typeof usage !== "object") return null;
+
+ // The stream carries metrics, never reasoning text. When the provider is silent,
+ // print nothing rather than fabricating a zero count.
+ const reasoning = finite(usage.reasoningTokens ?? usage.reasoning_tokens);
+ if (reasoning === undefined || reasoning <= 0) return null;
+
+ const parts = [`reasoning ${reasoning} tok`];
+
+ const cacheRead = finite(
+ usage.cacheReadTokens ??
+ usage.cache_read_tokens ??
+ usage.cacheReadInputTokens ??
+ usage.cache_read_input_tokens,
+ );
+ if (cacheRead !== undefined && (!usage.detailCoverage || usage.detailCoverage.cacheReadTokens)) {
+ parts.push(`cache-read ${cacheRead}`);
+ }
+
+ const cacheWrite = finite(
+ usage.cacheWriteTokens ??
+ usage.cache_write_tokens ??
+ usage.cacheCreationInputTokens ??
+ usage.cache_creation_input_tokens,
+ );
+ if (cacheWrite !== undefined && (!usage.detailCoverage || usage.detailCoverage.cacheWriteTokens)) {
+ parts.push(`cache-write ${cacheWrite}`);
+ }
+
+ return parts.join(" · ");
+}
+
+export function toggleReasoning(current, explicit) {
+ const val = explicit != null ? String(explicit).trim().toLowerCase() : "";
+ if (val === "off" || explicit === false) return false;
+ if (val === "on" || explicit === true) return true;
+ // Default is true when unset. Toggling inverts the current state.
+ return current === false;
+}
diff --git a/scripts/mso-agent-reasoning.test.ts b/scripts/mso-agent-reasoning.test.ts
new file mode 100644
index 00000000..73adec21
--- /dev/null
+++ b/scripts/mso-agent-reasoning.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it, vi } from "vitest";
+import { reasoningLine, toggleReasoning } from "./mso-agent-reasoning.mjs";
+import { agentRound } from "./mso-agent-turn.mjs";
+
+function dummySession(overrides: Record<string, unknown> = {}) {
+ return {
+ history: [{ role: "user", text: "prompt" }],
+ permission: "yolo",
+ state: { tools: [], modelMeta: null },
+ agentSession: { id: "s1", name: "test-agent" },
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
+ lastElapsedMs: 0,
+ ...overrides,
+ } as any;
+}
+
+describe("mso agent reasoning metrics", () => {
+ it("returns null when provider usage is empty, null, or has null reasoning tokens", () => {
+ expect(reasoningLine({})).toBeNull();
+ expect(reasoningLine(null)).toBeNull();
+ expect(reasoningLine({ reasoningTokens: null })).toBeNull();
+ expect(reasoningLine({ reasoningTokens: undefined })).toBeNull();
+ expect(reasoningLine({ reasoningTokens: 0 })).toBeNull();
+ });
+
+ it("includes reasoning tokens when present", () => {
+ expect(reasoningLine({ reasoningTokens: 120 })).toBe("reasoning 120 tok");
+ expect(reasoningLine({ reasoning_tokens: 45 })).toBe("reasoning 45 tok");
+ });
+
+ it("includes cache-read/cache-write only when present", () => {
+ expect(reasoningLine({ reasoningTokens: 120, cacheReadTokens: 60 })).toBe("reasoning 120 tok · cache-read 60");
+ expect(reasoningLine({ reasoningTokens: 120, cacheWriteTokens: 5 })).toBe("reasoning 120 tok · cache-write 5");
+ expect(
+ reasoningLine({
+ reasoningTokens: 120,
+ cacheReadTokens: 60,
+ cacheWriteTokens: 5,
+ }),
+ ).toBe("reasoning 120 tok · cache-read 60 · cache-write 5");
+ expect(
+ reasoningLine({
+ reasoningTokens: 120,
+ cacheReadTokens: null,
+ cacheWriteTokens: undefined,
+ }),
+ ).toBe("reasoning 120 tok");
+ expect(
+ reasoningLine({
+ reasoningTokens: 120,
+ cacheReadTokens: 60,
+ detailCoverage: { reasoningTokens: 1, cacheReadTokens: 1 },
+ }),
+ ).toBe("reasoning 120 tok · cache-read 60");
+ // When detail coverage marks cache absent, omit the metric even if an unverified key exists.
+ expect(
+ reasoningLine({
+ reasoningTokens: 120,
+ cacheReadTokens: 60,
+ detailCoverage: { reasoningTokens: 1, cacheReadTokens: 0 },
+ }),
+ ).toBe("reasoning 120 tok");
+ });
+
+ it("never returns a string containing reasoning text or a fabricated block", () => {
+ const payloads = [
+ { reasoningTokens: 120, reasoningText: "thinking step 1" },
+ { reasoningTokens: 120, thoughts: "let me analyze this" },
+ { reasoningTokens: 120, content: "<thinking>hidden</thinking>" },
+ ];
+ for (const payload of payloads) {
+ const line = reasoningLine(payload);
+ expect(line).not.toBeNull();
+ expect(line).not.toContain("reasoning text");
+ expect(line).not.toContain("<thinking>");
+ expect(line).not.toContain("thinking step");
+ expect(line).not.toContain("analyze");
+ expect(line).toBe("reasoning 120 tok");
+ }
+ });
+
+ it("toggles showReasoning preference correctly", () => {
+ // Default is on. First toggle turns it off.
+ expect(toggleReasoning(undefined)).toBe(false);
+ expect(toggleReasoning(true)).toBe(false);
+ expect(toggleReasoning(false)).toBe(true);
+
+ // Explicit on and off overrides.
+ expect(toggleReasoning(false, "on")).toBe(true);
+ expect(toggleReasoning(true, "off")).toBe(false);
+ expect(toggleReasoning(undefined, "on")).toBe(true);
+ expect(toggleReasoning(undefined, "off")).toBe(false);
+ });
+
+ it("prints reasoning line in agentRound only when enabled and not quiet", async () => {
+ const printed: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((line?: unknown) => { printed.push(String(line ?? "")); });
+
+ const streamWithReasoning = vi.fn(async () => ({
+ text: "hello world\n",
+ toolUses: [],
+ usage: { reasoningTokens: 120, cacheReadTokens: 60 },
+ }));
+
+ // 1. Normal round: prints the reasoning line.
+ await agentRound(null, dummySession(), null, undefined, null, {
+ streamTurn: streamWithReasoning,
+ });
+ expect(printed.some((line) => line.includes("reasoning 120 tok · cache-read 60"))).toBe(true);
+
+ // 2. Quiet mode: suppresses reasoning output.
+ printed.length = 0;
+ await agentRound(null, dummySession(), null, undefined, null, {
+ quiet: true,
+ streamTurn: streamWithReasoning,
+ });
+ expect(printed.some((line) => line.includes("reasoning 120 tok"))).toBe(false);
+
+ // 3. showReasoning: false suppresses output even when quiet is false.
+ printed.length = 0;
+ await agentRound(null, dummySession({ showReasoning: false }), null, undefined, null, {
+ quiet: false,
+ streamTurn: streamWithReasoning,
+ });
+ expect(printed.some((line) => line.includes("reasoning 120 tok"))).toBe(false);
+
+ // 4. Provider silent on reasoning: prints nothing.
+ printed.length = 0;
+ const streamWithoutReasoning = vi.fn(async () => ({
+ text: "hello world\n",
+ toolUses: [],
+ usage: { inputTokens: 50, outputTokens: 10 },
+ }));
+ await agentRound(null, dummySession(), null, undefined, null, {
+ quiet: false,
+ streamTurn: streamWithoutReasoning,
+ });
+ expect(printed.some((line) => line.includes("reasoning"))).toBe(false);
+ });
+});
diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjs
index 9deb6482..598befa6 100644
--- a/scripts/mso-agent-slash.mjs
+++ b/scripts/mso-agent-slash.mjs
@@ -28,6 +28,16 @@ const BUILTIN_SLASH_ITEMS = [
},
{ text: "/rename", meta: "Rename the short @agent handle", kind: "command" },
{ text: "/title", meta: "Rename the session title/description", kind: "command" },
+ {
+ text: "/export",
+ meta: "Export session transcript to stdout or a file",
+ kind: "command",
+ },
+ {
+ text: "/share",
+ meta: "Temporary link is unavailable: server exposes download only, no creation route",
+ kind: "command",
+ },
{
text: "/status",
meta: "Show model, auth, context, tokens, session",
@@ -43,11 +53,31 @@ const BUILTIN_SLASH_ITEMS = [
meta: "Show context/token/session status",
kind: "command",
},
+ {
+ text: "/diff",
+ meta: "Show unified diff of an earlier modified file",
+ kind: "command",
+ },
+ {
+ text: "/compact",
+ meta: "Force context compaction and archive recent history",
+ kind: "command",
+ },
{
text: "/statusbar",
meta: "Toggle the compact dynamic status line",
kind: "command",
},
+ {
+ text: "/reasoning",
+ meta: "Toggle per-turn reasoning metrics in the transcript",
+ kind: "command",
+ },
+ {
+ text: "/theme",
+ meta: "Choose UI theme (dark, light, mono)",
+ kind: "command",
+ },
{ text: "/setup", meta: "Run full MSO onboarding", kind: "command" },
{
text: "/integrations",
@@ -56,6 +86,7 @@ const BUILTIN_SLASH_ITEMS = [
},
{ text: "/doctor", meta: "Run MSO diagnostics", kind: "command" },
{ text: "/tools", meta: "List available agent tools", kind: "command" },
+ { text: "/files", meta: "Bounded read-only directory view of cwd or path", kind: "command" },
{
text: "/agents",
meta: "List live local session agents + registered remote A2A peers",
@@ -87,6 +118,21 @@ const BUILTIN_SLASH_ITEMS = [
meta: "Select a skill by exact catalog id",
kind: "command",
},
+ {
+ text: "/queue",
+ meta: "Queue follow-up prompts; list, run, or clear pending items",
+ kind: "command",
+ },
+ {
+ text: "/stash",
+ meta: "Park a prompt (20 slots), pop prints it back to the terminal",
+ kind: "command",
+ },
+ {
+ text: "/image",
+ meta: "Attach a local image file to the next prompt",
+ kind: "command",
+ },
{ text: "/clear", meta: "Clear this session conversation", kind: "command" },
{ text: "/exit", meta: "Exit MSO Agent", kind: "command" },
{ text: "/quit", meta: "Alias for /exit", kind: "command" },
diff --git a/scripts/mso-agent-stash.mjs b/scripts/mso-agent-stash.mjs
new file mode 100644
index 00000000..8eeb70ac
--- /dev/null
+++ b/scripts/mso-agent-stash.mjs
@@ -0,0 +1,55 @@
+// Stash prompt buffer kept strictly in memory for the active TUI process.
+// Not persisted across runs because uncommitted scratch input is ephemeral.
+
+const MAX_STASH = 20;
+
+function getEntries(stash) {
+ if (Array.isArray(stash)) return stash;
+ if (stash && Array.isArray(stash.items)) return stash.items;
+ return null;
+}
+
+export function createStash() {
+ return { items: [] };
+}
+
+export function stashPush(stash, text) {
+ const items = getEntries(stash);
+ if (!items) return { ok: false, error: "invalid stash" };
+ const trimmed = typeof text === "string" ? text.trim() : "";
+ if (!trimmed) {
+ return { ok: false, empty: true, count: items.length };
+ }
+ if (items.length >= MAX_STASH) {
+ return {
+ ok: false,
+ capped: true,
+ cap: MAX_STASH,
+ count: items.length,
+ error: `stash full (cap is ${MAX_STASH} items)`,
+ };
+ }
+ items.push(trimmed);
+ return { ok: true, count: items.length, item: trimmed };
+}
+
+export function stashPop(stash) {
+ const items = getEntries(stash);
+ if (!items || !items.length) return null;
+ return items.pop() ?? null;
+}
+
+export function stashList(stash) {
+ const items = getEntries(stash);
+ if (!items) return [];
+ // Return newest-first view of stashed prompts.
+ return [...items].reverse();
+}
+
+export function stashClear(stash) {
+ const items = getEntries(stash);
+ if (!items) return 0;
+ const dropped = items.length;
+ items.length = 0;
+ return dropped;
+}
diff --git a/scripts/mso-agent-stash.test.ts b/scripts/mso-agent-stash.test.ts
new file mode 100644
index 00000000..f8ce2348
--- /dev/null
+++ b/scripts/mso-agent-stash.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+import {
+ createStash,
+ stashClear,
+ stashList,
+ stashPop,
+ stashPush,
+} from "./mso-agent-stash.mjs";
+
+describe("MSO Agent stash", () => {
+ it("push trims whitespace and ignores empty input", () => {
+ const stash = createStash();
+ const emptyResult = stashPush(stash, " ");
+ expect(emptyResult.ok).toBe(false);
+ expect(stashList(stash)).toEqual([]);
+
+ const trimmedResult = stashPush(stash, " draft prompt ");
+ expect(trimmedResult.ok).toBe(true);
+ expect(trimmedResult.count).toBe(1);
+ expect(stashList(stash)).toEqual(["draft prompt"]);
+ });
+
+ it("caps at 20 items and reports refusal", () => {
+ const stash = createStash();
+ for (let i = 1; i <= 20; i++) {
+ const res = stashPush(stash, `prompt ${i}`);
+ expect(res.ok).toBe(true);
+ }
+ expect(stashList(stash)).toHaveLength(20);
+
+ const overflow = stashPush(stash, "prompt 21");
+ expect(overflow.ok).toBe(false);
+ expect(overflow.capped).toBe(true);
+ expect(overflow.cap).toBe(20);
+ expect(stashList(stash)).toHaveLength(20);
+ });
+
+ it("pop is LIFO", () => {
+ const stash = createStash();
+ stashPush(stash, "first");
+ stashPush(stash, "second");
+ stashPush(stash, "third");
+
+ expect(stashPop(stash)).toBe("third");
+ expect(stashPop(stash)).toBe("second");
+ expect(stashPop(stash)).toBe("first");
+ expect(stashPop(stash)).toBeNull();
+ });
+
+ it("list order is newest-first", () => {
+ const stash = createStash();
+ stashPush(stash, "alpha");
+ stashPush(stash, "beta");
+ stashPush(stash, "gamma");
+
+ expect(stashList(stash)).toEqual(["gamma", "beta", "alpha"]);
+ });
+
+ it("clear reports count and empties stash", () => {
+ const stash = createStash();
+ expect(stashClear(stash)).toBe(0);
+
+ stashPush(stash, "one");
+ stashPush(stash, "two");
+ stashPush(stash, "three");
+
+ const dropped = stashClear(stash);
+ expect(dropped).toBe(3);
+ expect(stashList(stash)).toEqual([]);
+ });
+});
diff --git a/scripts/mso-agent-theme-split.test.ts b/scripts/mso-agent-theme-split.test.ts
new file mode 100644
index 00000000..cf066b7d
--- /dev/null
+++ b/scripts/mso-agent-theme-split.test.ts
@@ -0,0 +1,49 @@
+import process from "node:process";
+import { describe, expect, it } from "vitest";
+import {
+ applyTheme as applyThemeUi,
+ C as CFromUi,
+ currentThemeName as currentThemeUi,
+} from "./mso-agent-ui.mjs";
+import {
+ applyTheme as applyThemeDirect,
+ C as CFromTheme,
+ currentThemeName as currentThemeDirect,
+} from "./mso-agent-theme.mjs";
+
+describe("theme split reference and mutation parity", () => {
+ it("exports the exact same C object reference from both modules", () => {
+ expect(CFromUi).toBe(CFromTheme);
+ });
+
+ it("reflects applyTheme mutations identically through both references", () => {
+ const origTTY = process.stdout.isTTY;
+ const origNoColor = process.env.NO_COLOR;
+ delete process.env.NO_COLOR;
+ process.stdout.isTTY = true;
+ try {
+ applyThemeDirect("dark");
+ expect(currentThemeDirect()).toBe("dark");
+ expect(currentThemeUi()).toBe("dark");
+ expect(CFromUi.blue).toBe(CFromTheme.blue);
+ expect(CFromUi.blue).toContain("38;2;58;160;255");
+
+ applyThemeUi("light");
+ expect(currentThemeDirect()).toBe("light");
+ expect(currentThemeUi()).toBe("light");
+ expect(CFromUi.blue).toBe(CFromTheme.blue);
+ expect(CFromUi.blue).toContain("38;2;21;94;183");
+
+ applyThemeDirect("mono");
+ expect(currentThemeDirect()).toBe("mono");
+ expect(currentThemeUi()).toBe("mono");
+ expect(CFromUi.blue).toBe("");
+ expect(CFromTheme.blue).toBe("");
+ } finally {
+ process.stdout.isTTY = origTTY;
+ if (origNoColor !== undefined) process.env.NO_COLOR = origNoColor;
+ else delete process.env.NO_COLOR;
+ applyThemeDirect("dark");
+ }
+ });
+});
diff --git a/scripts/mso-agent-theme.mjs b/scripts/mso-agent-theme.mjs
new file mode 100644
index 00000000..45a3ddd7
--- /dev/null
+++ b/scripts/mso-agent-theme.mjs
@@ -0,0 +1,92 @@
+import process from "node:process";
+
+// One palette, one switch. Every module imports `C` (re-exported by
+// mso-agent-runtime.mjs), so a theme has to be resolved HERE and re-assigned in
+// place: modules capture the object reference at import time, so replacing the
+// object would leave half the UI on the old colours. Mutating the same object is
+// what keeps a theme switch honest instead of cosmetic.
+//
+// `NO_COLOR` and a non-TTY stdout always win: nothing here can emit ANSI into a
+// pipe, a log file, or a screenshot diff.
+
+export const THEMES = {
+ dark: {
+ blue: "\x1b[38;2;58;160;255m",
+ cyan: "\x1b[38;2;52;211;153m",
+ warn: "\x1b[38;2;245;158;11m",
+ err: "\x1b[38;2;239;68;68m",
+ },
+ light: {
+ // Chosen for contrast on a white terminal: the dark theme's cyan and warn are
+ // unreadable on #fff, so both are darkened rather than reused.
+ blue: "\x1b[38;2;21;94;183m",
+ cyan: "\x1b[38;2;13;122;86m",
+ warn: "\x1b[38;2;150;84;0m",
+ err: "\x1b[38;2;176;24;24m",
+ },
+ mono: { blue: "", cyan: "", warn: "", err: "" },
+};
+
+export const THEME_NAMES = Object.keys(THEMES);
+let currentTheme = "dark";
+
+export function colorEnabled() {
+ if (process.env.NO_COLOR) return false;
+ return Boolean(process.stdout.isTTY);
+}
+
+export const C = {
+ reset: colorEnabled() ? "\x1b[0m" : "",
+ bold: colorEnabled() ? "\x1b[1m" : "",
+ dim: colorEnabled() ? "\x1b[2m" : "",
+ blue: "", cyan: "", warn: "", err: "",
+};
+C.a = C.blue;
+C.b = C.blue;
+C.c = C.cyan;
+C.a = C.blue;
+C.b = C.blue;
+C.c = C.cyan;
+
+export function themeNames() {
+ return [...THEME_NAMES];
+}
+
+export function currentThemeName() {
+ return currentTheme;
+}
+
+/**
+ * Apply a theme in place. Returns the id that is now active, which may differ from
+ * the request when colour is disabled entirely: a caller that prints
+ * "theme light" while every colour is blank would be lying about what it did.
+ */
+export function applyTheme(name) {
+ const requested = String(name || "").trim().toLowerCase();
+ const wanted = THEME_NAMES.includes(requested) ? requested : null;
+ if (!colorEnabled()) {
+ C.blue = C.cyan = C.warn = C.err = "";
+ currentTheme = "mono";
+ return { theme: currentTheme, changed: false, reason: "colour disabled (NO_COLOR or not a TTY)" };
+ }
+ const picked = wanted ? THEMES[wanted] : THEMES[currentTheme] || THEMES.dark;
+ C.blue = picked.blue;
+ C.cyan = picked.cyan;
+ C.warn = picked.warn;
+ C.err = picked.err;
+ // The short aliases exist for legacy call sites; keep them pointing at the live
+ // values so a theme switch reaches them too.
+ C.a = C.blue;
+ C.b = C.blue;
+ C.c = C.cyan;
+ C.reset = "\x1b[0m";
+ C.bold = "\x1b[1m";
+ C.dim = "\x1b[2m";
+ const changed = currentTheme !== (wanted || currentTheme);
+ currentTheme = wanted || currentTheme;
+ return { theme: currentTheme, changed, reason: wanted ? undefined : `unknown theme "${requested}"; keeping ${currentTheme}` };
+}
+
+// Resolve the initial palette through the same path so there is only one place
+// that knows how colour works.
+applyTheme(process.env.MSO_AGENT_THEME || "dark");
diff --git a/scripts/mso-agent-theme.test.ts b/scripts/mso-agent-theme.test.ts
new file mode 100644
index 00000000..d5e004c5
--- /dev/null
+++ b/scripts/mso-agent-theme.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+import {
+ C,
+ applyTheme,
+ currentThemeName,
+ themeNames,
+} from "./mso-agent-ui.mjs";
+
+describe("MSO Agent UI theme engine", () => {
+ it("applyTheme('light') in a non-TTY returns theme 'mono' and a reason mentioning colour disabled", () => {
+ delete process.env.NO_COLOR;
+ const res = applyTheme("light");
+ expect(res.theme).toBe("mono");
+ expect(res.changed).toBe(false);
+ expect(res.reason).toMatch(/colour disabled/i);
+ });
+
+ it("applyTheme('bogus') keeps the current name and returns a reason naming the unknown theme", () => {
+ const origIsTTY = process.stdout.isTTY;
+ try {
+ process.stdout.isTTY = true;
+ const current = currentThemeName();
+ const res = applyTheme("bogus");
+ expect(res.theme).toBe(current);
+ expect(res.changed).toBe(false);
+ expect(res.reason).toMatch(/unknown theme "bogus"/i);
+ } finally {
+ process.stdout.isTTY = origIsTTY;
+ }
+ });
+
+ it("themeNames() includes dark, light, mono", () => {
+ const names = themeNames();
+ expect(names).toContain("dark");
+ expect(names).toContain("light");
+ expect(names).toContain("mono");
+ });
+
+ it("C.a === C.blue and C.c === C.cyan after an applyTheme call (alias follows)", () => {
+ const origIsTTY = process.stdout.isTTY;
+ try {
+ process.stdout.isTTY = true;
+ applyTheme("dark");
+ expect((C as any).a).toBe(C.blue);
+ expect((C as any).c).toBe(C.cyan);
+ } finally {
+ process.stdout.isTTY = origIsTTY;
+ }
+ });
+});
diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjs
index 98f01c15..a555b294 100644
--- a/scripts/mso-agent-turn.mjs
+++ b/scripts/mso-agent-turn.mjs
@@ -3,15 +3,17 @@ import { canonicalAgentApproval } from "../lib/agent/approval.mjs";
import { requestExactToolApproval } from "./mso-agent-approval-ui.mjs";
import { AgentMutationUncertainError, isAgentApiError, isRecoverableInteractionError, recoverableErrorLines, recoverableHistoryRow, recoverableTurnState } from "./mso-agent-errors.mjs";
import { printSection, sectionDivider } from "./mso-agent-layout.mjs";
-import { AgentActivity, activityText, formatDuration } from "./mso-agent-activity.mjs";
+import { AgentActivity } from "./mso-agent-activity.mjs";
import { beginSkillInvocation, endSkillInvocation } from "./mso-agent-skills.mjs";
import { isAbortError } from "./mso-agent-interrupt.mjs";
import { approvesTool } from "./mso-agent-permissions.mjs";
import { api, C, streamTurn } from "./mso-agent-runtime.mjs";
+import { completedReceipt } from "./mso-agent-ui.mjs";
import { compactConsumedReadToolResults } from "./mso-agent-context.mjs";
import { persistSession } from "./mso-agent-session-ui.mjs";
import { addUsage } from "./mso-agent-status.mjs";
import { oneShotApproves } from "./mso-agent-oneshot.mjs";
+import { reasoningLine } from "./mso-agent-reasoning.mjs";
function lazyAssistantOutput(session, options = {}) {
if (options.quiet) return null;
@@ -140,6 +142,10 @@ export async function agentRound(rl, session, skillContext = null, signal = unde
session.usage = addUsage(session.usage, result.usage);
session.lastRouting = result.routing || null;
session.lastElapsedMs = Date.now() - startedAt;
+ if (!options.quiet && session.showReasoning !== false) {
+ const line = reasoningLine(result.usage);
+ if (line) console.log(`${C.dim}${line}${C.reset}`);
+ }
session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });
if (!result.toolUses.length) {
activity?.finish(completedReceipt(calls, session.lastElapsedMs));
@@ -176,19 +182,6 @@ export async function agentRound(rl, session, skillContext = null, signal = unde
}
}
-/** Compact per-turn receipt replacing the rows each tool used to claim. */
-function completedReceipt(calls, elapsedMs) {
- const rows = Array.isArray(calls) ? calls : [];
- if (!rows.length) return "";
- const ok = rows.filter((row) => row.ok).length;
- const failed = rows.length - ok;
- return activityText([
- `${rows.length} tool${rows.length === 1 ? "" : "s"}`,
- failed ? `${failed} failed` : "all ok",
- formatDuration(elapsedMs || 0),
- ]);
-}
-
export function renderInteractionFailure(error, session, journal = {}, colors = C, print = console.log) {
const state = recoverableTurnState(error, journal);
print(sectionDivider("error", { detail: `@${session?.agentSession?.name || "agent"}`, colors }));
diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjs
index 24ab7c32..4af18b07 100644
--- a/scripts/mso-agent-ui.mjs
+++ b/scripts/mso-agent-ui.mjs
@@ -1,14 +1,24 @@
import process from "node:process";
+import { activityText, formatDuration } from "./mso-agent-activity.mjs";
+import {
+ applyTheme,
+ C,
+ colorEnabled,
+ currentThemeName,
+ THEME_NAMES,
+ themeNames,
+ THEMES,
+} from "./mso-agent-theme.mjs";
-const color = process.stdout.isTTY && !process.env.NO_COLOR;
-export const C = {
- reset: color ? "\x1b[0m" : "", bold: color ? "\x1b[1m" : "", dim: color ? "\x1b[2m" : "",
- blue: color ? "\x1b[38;2;58;160;255m" : "", cyan: color ? "\x1b[38;2;52;211;153m" : "",
- warn: color ? "\x1b[38;2;245;158;11m" : "", err: color ? "\x1b[38;2;239;68;68m" : "",
+export {
+ applyTheme,
+ C,
+ colorEnabled,
+ currentThemeName,
+ THEME_NAMES,
+ themeNames,
+ THEMES,
};
-C.a = C.blue;
-C.b = C.blue;
-C.c = C.cyan;
export const MSO_TITLE_ART = [
" ████████████",
@@ -25,15 +35,40 @@ export const MSO_TITLE_ART = [
" ── MSO Agent ──",
];
-// Exact True Color ANSI sequence requested for the hybrid MSO Agent banner.
-export const MSO_TITLE_COLORS = color ? [
- "\x1b[38;2;155;81;224m", "\x1b[38;2;155;81;224m",
- "\x1b[38;2;112;111;245m", "\x1b[38;2;112;111;245m",
- "\x1b[38;2;69;142;255m", "\x1b[38;2;69;142;255m",
- "\x1b[38;2;45;184;255m", "\x1b[38;2;45;184;255m",
- "\x1b[38;2;34;211;206m", "\x1b[38;2;34;211;206m",
- "\x1b[38;2;46;229;157m", "\x1b[38;2;46;229;157m",
-] : MSO_TITLE_ART.map(() => "");
+export function titleColors() {
+ if (!colorEnabled()) return MSO_TITLE_ART.map(() => "");
+ const theme = currentThemeName();
+ if (theme === "light") {
+ return [
+ "\x1b[38;2;76;29;149m", "\x1b[38;2;76;29;149m", "\x1b[38;2;46;44;168m", "\x1b[38;2;46;44;168m",
+ "\x1b[38;2;21;94;183m", "\x1b[38;2;21;94;183m", "\x1b[38;2;10;110;168m", "\x1b[38;2;10;110;168m",
+ "\x1b[38;2;13;122;112m", "\x1b[38;2;13;122;112m", "\x1b[38;2;13;122;86m", "\x1b[38;2;13;122;86m",
+ ];
+ }
+ if (theme === "mono") return MSO_TITLE_ART.map(() => "");
+ return [
+ "\x1b[38;2;155;81;224m", "\x1b[38;2;155;81;224m", "\x1b[38;2;112;111;245m", "\x1b[38;2;112;111;245m",
+ "\x1b[38;2;69;142;255m", "\x1b[38;2;69;142;255m", "\x1b[38;2;45;184;255m", "\x1b[38;2;45;184;255m",
+ "\x1b[38;2;34;211;206m", "\x1b[38;2;34;211;206m", "\x1b[38;2;46;229;157m", "\x1b[38;2;46;229;157m",
+ ];
+}
+
+// The gradient is decoration, not semantics. It follows the theme so a light
+// terminal does not get a near-white banner on white.
+export const MSO_TITLE_COLORS = titleColors();
+
+/** Compact per-turn receipt replacing the rows each tool used to claim. */
+export function completedReceipt(calls, elapsedMs) {
+ const rows = Array.isArray(calls) ? calls : [];
+ if (!rows.length) return "";
+ const ok = rows.filter((row) => row.ok).length;
+ const failed = rows.length - ok;
+ return activityText([
+ `${rows.length} tool${rows.length === 1 ? "" : "s"}`,
+ failed ? `${failed} failed` : "all ok",
+ formatDuration(elapsedMs || 0),
+ ]);
+}
function plain(value) { return String(value ?? "").replace(/\x1b\[[0-9;]*m/g, ""); }
function width(value) { return [...plain(value)].length; }
@@ -106,7 +141,8 @@ export function printAgentBanner(s, agentSession, { base, version }) {
const inner = totalWidth - 2;
const titleArtWidth = Math.max(...MSO_TITLE_ART.map(width));
if (totalWidth >= titleArtWidth) {
- MSO_TITLE_ART.forEach((line, index) => console.log(`${MSO_TITLE_COLORS[index]}${C.bold}${line}${C.reset}`));
+ const colors = titleColors();
+ MSO_TITLE_ART.forEach((line, index) => console.log(`${colors[index]}${C.bold}${line}${C.reset}`));
} else console.log(`${C.blue}${C.bold}── MSO Agent ──${C.reset}`);
console.log();
@@ -131,6 +167,7 @@ export function printAgentBanner(s, agentSession, { base, version }) {
fit(`${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec`, leftWidth),
fit("write/exec approval-gated", leftWidth), "", `${C.bold}Infrastructure${C.reset}`,
fit(`${infra.ready.length}/${infra.total} ready`, leftWidth),
+ // Product-facing setup is /integrations: runCli(["integrations", ...args])
fit(infra.ready.length ? infra.ready.join(" · ") : "run /integrations to connect", leftWidth),
];
const right = [`${C.bold}Available Tools${C.reset}`];
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index e486f8e7..81e2ada0 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -14,6 +14,8 @@ import { LocalAgentBridge, handleLocalAgentMentionInput, runForegroundSubagent }
import { composerFooter, composerPrompt, composerSeparator } from "./mso-agent-layout.mjs";
import { agentRound, executeTool, renderInteractionFailure, runInteractiveRound } from "./mso-agent-turn.mjs";
import { pathToFileURL } from "node:url";
+import { createQueue, dequeue } from "./mso-agent-queue.mjs";
+import { pendingImageBlock } from "./mso-agent-image.mjs";
async function runOneShot(opts) {
const requested = resumeArg(process.argv.slice(2));
@@ -76,6 +78,8 @@ async function main() {
titleOverride: (requested || restartSessionId) ? (agentSession.title || null) : null,
usage: { apiCalls: 0 }, lastRouting: null, lastElapsedMs: 0,
statusBar: restartUi.statusBar ?? true, permission: forcedPermission, pendingApproval: null,
+ // Ephemeral queue: held only in memory for this TUI process and not persisted to server state.
+ queue: createQueue(),
};
const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C }); syncPromptHistory(rl, session);
let inboundRequestQueued = false;
@@ -91,6 +95,31 @@ async function main() {
});
await localBridge.start();
const interrupts = new AgentInterruptManager({ output: process.stdout, colors: C });
+ let lastTurnInterrupted = false;
+ const originalBeginTurn = interrupts.beginTurn.bind(interrupts);
+ interrupts.beginTurn = () => {
+ const signal = originalBeginTurn();
+ lastTurnInterrupted = false;
+ signal.addEventListener("abort", () => {
+ lastTurnInterrupted = true;
+ }, { once: true });
+ return signal;
+ };
+ const originalInterruptCurrent = interrupts.interruptCurrent.bind(interrupts);
+ interrupts.interruptCurrent = () => {
+ lastTurnInterrupted = true;
+ return originalInterruptCurrent();
+ };
+ const drainQueue = async () => {
+ while (!interrupts.exitRequested && !lastTurnInterrupted) {
+ const nextPrompt = dequeue(session.queue);
+ if (!nextPrompt) break;
+ session.history.push({ role: "user", text: nextPrompt });
+ const skillContext = session.pendingSkill;
+ session.pendingSkill = null;
+ await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);
+ }
+ };
const onSigint = () => {
const action = interrupts.handleSigint();
// External child TUIs can restore the shared terminal to cooked mode. In that
@@ -131,6 +160,10 @@ async function main() {
if (result === "exit") break;
if (result === "restart") { restartRequested = true; break; }
if (result === "refresh") await localBridge.syncSession();
+ if (result === "drain") {
+ lastTurnInterrupted = false;
+ await drainQueue();
+ }
if (result === "unknown") console.log("unknown command; /help lists commands.");
} catch (error) {
renderInteractionFailure(error, session, {}, C);
@@ -140,11 +173,17 @@ async function main() {
continue;
}
if (await handleLocalAgentMentionInput(session, line, C)) continue;
- session.history.push({ role: "user", text: line });
+ // Attached images belong to the NEXT prompt only. Format them into the user
+ // message once, then clear, so a stale image can never ride along silently.
+ const images = Array.isArray(session.pendingImages) ? session.pendingImages : [];
+ const imageBlock = images.length ? pendingImageBlock(images) : "";
+ session.history.push({ role: "user", text: imageBlock ? `${imageBlock}${line}` : line });
+ if (images.length) session.pendingImages = [];
const skillContext = session.pendingSkill;
session.pendingSkill = null;
await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);
if (interrupts.exitRequested) break;
+ if (!lastTurnInterrupted) await drainQueue();
}
} finally {
process.off("SIGINT", onSigint);