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(agent): align model and session terminal UX

Rahman54a2665bccef
diff --git a/README.md b/README.md
index 8a0c9da9..38d20f8b 100644
--- a/README.md
+++ b/README.md
@@ -73,7 +73,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
**Extend** — Alfa AI, modular slices, and custom apps.
-- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` now opens the interactive setup/operations agent; `mso model` connects or changes its provider first.
+- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
@@ -195,7 +195,9 @@ On the normal Ubuntu/WSL PATH (which includes `/usr/local/bin`) these work immed
```bash
mso # interactive MSO setup/operations agent
mso -h
-mso model # connect/change the AI provider used by MSO Agent / Alfa
+mso models # configure AI provider/API/OAuth connections (does not switch model)
+mso model # select the active model from connected providers
+mso --continue # resume the latest durable MSO Agent session
mso doctor
mso onboard # run/re-run guided setup; starts the built loopback runtime on WSL when needed
mso provider list # Dokploy/Cloudflare/Hostinger status (secrets masked)
@@ -324,7 +326,10 @@ covers anything without one.
```bash
mso # interactive setup/operations agent with MSO ASCII terminal UI
mso -h # grouped command list; `mso <command> --help` per command
-mso model # connect/change AI provider before/while using the agent
+mso models # configure AI provider/API/OAuth connections
+mso model # select/switch the active model
+mso --continue # resume the latest MSO Agent session
+mso --resume "session title" # resume by index/id/short id/title query
mso doctor # includes HTTPS/login-origin diagnosis
mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
mso onboard # guided AI/app/infrastructure/skill setup
diff --git a/app/api/assistant/route.ts b/app/api/assistant/route.ts
index 894012a8..7c92e6d3 100644
--- a/app/api/assistant/route.ts
+++ b/app/api/assistant/route.ts
@@ -14,6 +14,7 @@ import { streamOpenAI } from "@/lib/ai/openai-stream";
import { safeProviderFetch } from "@/lib/host/ssrf";
import { ensureFreshCodex } from "@/lib/ai/oauth/codex";
import { streamCodex } from "@/lib/ai/codex-stream";
+import { anthropicDonePayload } from "@/lib/ai/usage";
import { recall } from "@/lib/ai/memory";
import { rateLimited } from "@/lib/host/rate-limit";
import { IS_DEMO } from "@/lib/demo";
@@ -202,8 +203,7 @@ export async function POST(req: Request) {
if (cfg.tokenSaver === "caveman") sys += "\n\n" + CAVEMAN;
else if (cfg.tokenSaver === "ponytail") sys += "\n\n" + PONYTAIL;
const encoder = new TextEncoder();
- const sse = (event: string, data: unknown) =>
- encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ const sse = (event: string, data: unknown) => encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
const tools = Array.isArray(body.tools) && body.tools.length ? body.tools : undefined;
// One upstream Anthropic stream per request. Hoisted so the stream's cancel()
@@ -248,7 +248,7 @@ export async function POST(req: Request) {
(b: Anthropic.ContentBlock): b is Anthropic.ToolUseBlock => b.type === "tool_use",
);
for (const u of uses) emit("tool_use", { id: u.id, name: u.name, input: u.input });
- emit("done", { stopReason: final.stop_reason });
+ emit("done", anthropicDonePayload(final));
}
} else if (resolved) {
// openai-protocol: the adapter POSTs {baseUrl}/chat/completions
diff --git a/app/api/config/route.test.ts b/app/api/config/route.test.ts
new file mode 100644
index 00000000..a9615a7e
--- /dev/null
+++ b/app/api/config/route.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const writeConfig = vi.fn();
+const setKey = vi.fn();
+const deleteKey = vi.fn();
+const upsertCustomProvider = vi.fn();
+const removeCustomProvider = vi.fn();
+const removeOAuthBundle = vi.fn();
+const readConfig = vi.fn();
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: vi.fn(async () => true) }));
+vi.mock("@/lib/config/store", () => ({
+ DEFAULT_MODEL: "default-model",
+ DEFAULT_PROVIDER: "anthropic",
+ readConfig: (...args: unknown[]) => readConfig(...args),
+ writeConfig: (...args: unknown[]) => writeConfig(...args),
+ hostCredentialStore: () => ({
+ getKey: vi.fn(async () => ""),
+ setKey: (...args: unknown[]) => setKey(...args),
+ deleteKey: (...args: unknown[]) => deleteKey(...args),
+ }),
+ isBuiltinProvider: (id: string) => ["anthropic", "openai", "openrouter", "google", "groq", "xai", "deepseek", "mistral"].includes(id),
+ slugifyProvider: (value: string) => value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
+ upsertCustomProvider: (...args: unknown[]) => upsertCustomProvider(...args),
+ removeCustomProvider: (...args: unknown[]) => removeCustomProvider(...args),
+ removeOAuthBundle: (...args: unknown[]) => removeOAuthBundle(...args),
+}));
+vi.mock("@/lib/models/defaults", () => ({ defaultModelFor: (p: string) => `${p}-default` }));
+vi.mock("@/lib/host/ssrf", () => ({
+ resolveSafeProviderEndpoint: vi.fn(async (url: string) => ({ url: new URL(url) })),
+}));
+
+const request = (body: unknown) => new Request("http://localhost/api/config", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+}) as never;
+
+describe("/api/config provider-auth vs model-selection contract", () => {
+ beforeEach(() => {
+ writeConfig.mockReset().mockResolvedValue(undefined);
+ setKey.mockReset().mockResolvedValue(undefined);
+ deleteKey.mockReset().mockResolvedValue(undefined);
+ upsertCustomProvider.mockReset().mockResolvedValue(undefined);
+ removeCustomProvider.mockReset().mockResolvedValue(undefined);
+ removeOAuthBundle.mockReset().mockResolvedValue(undefined);
+ readConfig.mockReset().mockResolvedValue({ provider: "anthropic", model: "claude-active", keys: {}, customProviders: {}, oauthTokens: {} });
+ });
+
+ it("stores a built-in provider key with select:false without changing the active provider/model", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(request({ provider: "openrouter", apiKey: "secret", select: false }));
+ expect(res.status).toBe(200);
+ expect(setKey).toHaveBeenCalledWith(undefined, "openrouter", "secret");
+ expect(writeConfig).not.toHaveBeenCalled();
+ });
+
+ it("keeps legacy/default POST behavior selecting provider+model when select is omitted", async () => {
+ const { POST } = await import("./route");
+ await POST(request({ provider: "openrouter", model: "openai/gpt-4o" }));
+ expect(writeConfig).toHaveBeenCalledWith({ provider: "openrouter", model: "openai/gpt-4o" });
+ });
+
+ it("adds a custom provider with select:false without switching the active model", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(request({
+ customProvider: { name: "My Hub", baseURL: "https://ai.example.com/v1", apiKey: "secret", protocol: "openai", models: ["m1"] },
+ select: false,
+ }));
+ expect(res.status).toBe(200);
+ expect(upsertCustomProvider).toHaveBeenCalledWith("my-hub", expect.objectContaining({ models: ["m1"] }));
+ expect(setKey).toHaveBeenCalledWith(undefined, "my-hub", "secret");
+ expect(writeConfig).not.toHaveBeenCalled();
+ expect(await res.json()).toMatchObject({ slug: "my-hub", selected: false });
+ });
+});
diff --git a/app/api/config/route.ts b/app/api/config/route.ts
index f374b52b..703f95a6 100644
--- a/app/api/config/route.ts
+++ b/app/api/config/route.ts
@@ -74,6 +74,9 @@ export async function POST(req: NextRequest) {
provider?: string;
customProvider?: CustomBody;
tokenSaver?: string;
+ // Provider credential management can be separated from active model selection.
+ // Existing callers default to select=true; CLI `mso models add` sends false.
+ select?: boolean;
};
try {
body = await req.json();
@@ -111,16 +114,22 @@ export async function POST(req: NextRequest) {
...(models.length ? { models } : {}),
});
await hostCredentialStore().setKey(undefined, slug, c.apiKey.trim());
- // Select the new provider (+ its first model) so the assistant uses it now.
- await writeConfig({ provider: slug, ...(models[0] ? { model: models[0] } : {}) });
- return NextResponse.json({ ok: true, slug });
+ // Preserve legacy Settings behavior unless the caller explicitly asks to only
+ // configure credentials. This is what lets `mso models` manage auth while
+ // `mso model` remains the only model-selection UX.
+ if (body.select !== false) {
+ await writeConfig({ provider: slug, ...(models[0] ? { model: models[0] } : {}) });
+ }
+ return NextResponse.json({ ok: true, slug, selected: body.select !== false });
}
// ── Set a built-in provider / model / key ──────────────────────────────────
const provider = (body.provider || DEFAULT_PROVIDER).trim();
- const patch: { model?: string; provider?: string } = { provider };
- if (typeof body.model === "string" && body.model.trim()) patch.model = body.model.trim();
- await writeConfig(patch);
+ if (body.select !== false) {
+ const patch: { model?: string; provider?: string } = { provider };
+ if (typeof body.model === "string" && body.model.trim()) patch.model = body.model.trim();
+ await writeConfig(patch);
+ }
// Key routes through the per-provider store. Empty string clears it (incl. the
// legacy anthropicApiKey alias) so a cleared key doesn't linger.
diff --git a/app/api/models/test/route.test.ts b/app/api/models/test/route.test.ts
new file mode 100644
index 00000000..9b131081
--- /dev/null
+++ b/app/api/models/test/route.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const resolveModelRef = vi.fn();
+const readOAuthBundle = vi.fn();
+const writeOAuthBundle = vi.fn();
+const codexModels = vi.fn();
+const ensureFreshCodex = vi.fn();
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: vi.fn(async () => true) }));
+vi.mock("@/lib/config/store", () => ({
+ resolveModelRef: (...args: unknown[]) => resolveModelRef(...args),
+ readOAuthBundle: (...args: unknown[]) => readOAuthBundle(...args),
+ writeOAuthBundle: (...args: unknown[]) => writeOAuthBundle(...args),
+ hostCredentialStore: vi.fn(() => ({})),
+ selectedCustomConn: vi.fn(async () => null),
+}));
+vi.mock("@/lib/ai/oauth/codex", () => ({
+ codexModels: (...args: unknown[]) => codexModels(...args),
+ ensureFreshCodex: (...args: unknown[]) => ensureFreshCodex(...args),
+}));
+vi.mock("@/lib/models", () => ({ resolveModel: vi.fn() }));
+vi.mock("@/lib/host/ssrf", () => ({ safeProviderFetch: vi.fn() }));
+
+describe("/api/models/test OpenAI Codex OAuth", () => {
+ beforeEach(() => {
+ resolveModelRef.mockReset().mockResolvedValue("openai-codex/gpt-5.6-sol");
+ const bundle = { kind: "oauth", access: "x", expires: Date.now() + 999999 };
+ readOAuthBundle.mockReset().mockResolvedValue(bundle);
+ ensureFreshCodex.mockReset().mockResolvedValue(bundle);
+ codexModels.mockReset().mockResolvedValue(["gpt-5.6-sol", "gpt-5.6-terra"]);
+ writeOAuthBundle.mockReset().mockResolvedValue(undefined);
+ });
+
+ it("validates the selected subscription model via the account model list", async () => {
+ const { POST } = await import("./route");
+ const res = await POST();
+ expect(await res.json()).toEqual({ ok: true, provider: "openai-codex", model: "gpt-5.6-sol" });
+ expect(codexModels).toHaveBeenCalled();
+ });
+
+ it("reports a selected model that the account does not expose", async () => {
+ codexModels.mockResolvedValueOnce(["gpt-5.6-terra"]);
+ const { POST } = await import("./route");
+ const res = await POST();
+ expect(await res.json()).toMatchObject({ ok: false, error: expect.stringContaining("not available") });
+ });
+});
diff --git a/app/api/models/test/route.ts b/app/api/models/test/route.ts
index e042219d..a7bcf46e 100644
--- a/app/api/models/test/route.ts
+++ b/app/api/models/test/route.ts
@@ -1,9 +1,10 @@
import { NextResponse } from "next/server";
import Anthropic from "@anthropic-ai/sdk";
import { requireSession } from "@/lib/auth/require-session";
-import { resolveModelRef, hostCredentialStore, selectedCustomConn } from "@/lib/config/store";
+import { resolveModelRef, hostCredentialStore, selectedCustomConn, readOAuthBundle, writeOAuthBundle } from "@/lib/config/store";
import { resolveModel } from "@/lib/models";
import { safeProviderFetch } from "@/lib/host/ssrf";
+import { codexModels, ensureFreshCodex } from "@/lib/ai/oauth/codex";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -14,12 +15,30 @@ export const dynamic = "force-dynamic";
export async function POST() {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ const selectedRef = await resolveModelRef();
+ if (selectedRef.startsWith("openai-codex/")) {
+ const selectedModel = selectedRef.slice("openai-codex/".length);
+ try {
+ const stored = await readOAuthBundle("openai-codex");
+ if (!stored) return NextResponse.json({ ok: false, error: "OpenAI ChatGPT OAuth is not connected" });
+ const fresh = await ensureFreshCodex(stored);
+ if (fresh !== stored) await writeOAuthBundle("openai-codex", fresh);
+ const models = await codexModels(fresh);
+ if (!models.includes(selectedModel)) {
+ return NextResponse.json({ ok: false, error: `model ${selectedModel} is not available for this ChatGPT account` });
+ }
+ return NextResponse.json({ ok: true, provider: "openai-codex", model: selectedModel });
+ } catch (e) {
+ return NextResponse.json({ ok: false, error: (e as Error).message });
+ }
+ }
+
let resolved;
let customProvider = false;
try {
const custom = await selectedCustomConn();
customProvider = Boolean(custom);
- resolved = await resolveModel(await resolveModelRef(), {
+ resolved = await resolveModel(selectedRef, {
store: hostCredentialStore(),
baseUrl: custom?.baseUrl,
protocol: custom?.protocol,
diff --git a/app/api/oauth/[provider]/route.test.ts b/app/api/oauth/[provider]/route.test.ts
new file mode 100644
index 00000000..4a9b3aac
--- /dev/null
+++ b/app/api/oauth/[provider]/route.test.ts
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const writeConfig = vi.fn();
+const writeOAuthBundle = vi.fn();
+const clearFlow = vi.fn();
+const getFlow = vi.fn();
+const codexPoll = vi.fn();
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: vi.fn(async () => true) }));
+vi.mock("@/lib/config/store", () => ({
+ writeConfig: (...args: unknown[]) => writeConfig(...args),
+ writeOAuthBundle: (...args: unknown[]) => writeOAuthBundle(...args),
+}));
+vi.mock("@/lib/ai/oauth/codex", () => ({
+ CODEX: { verificationUrl: "https://example.com/device" },
+ codexStart: vi.fn(async () => ({ deviceAuthId: "dev-auth", userCode: "ABCD", intervalMs: 3000 })),
+ codexPoll: (...args: unknown[]) => codexPoll(...args),
+ codexModels: vi.fn(async () => ["gpt-account-model"]),
+}));
+vi.mock("@/lib/ai/oauth/flow-state", () => ({
+ setFlow: vi.fn(),
+ getFlow: (...args: unknown[]) => getFlow(...args),
+ clearFlow: (...args: unknown[]) => clearFlow(...args),
+}));
+
+const request = (body: unknown) => new Request("http://localhost/api/oauth/openai", {
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
+}) as never;
+const ctx = { params: Promise.resolve({ provider: "openai" }) };
+
+describe("OpenAI Codex OAuth selection semantics", () => {
+ beforeEach(() => {
+ writeConfig.mockReset().mockResolvedValue(undefined);
+ writeOAuthBundle.mockReset().mockResolvedValue(undefined);
+ clearFlow.mockReset();
+ getFlow.mockReset().mockReturnValue({ deviceAuthId: "dev-auth", userCode: "ABCD" });
+ codexPoll.mockReset().mockResolvedValue({ bundle: { access: "token" } });
+ });
+
+ it("stores OAuth credentials but preserves active model when select:false", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(request({ action: "poll", select: false }), ctx);
+ expect(res.status).toBe(200);
+ expect(writeOAuthBundle).toHaveBeenCalled();
+ expect(writeConfig).not.toHaveBeenCalled();
+ expect(await res.json()).toMatchObject({ slug: "openai-codex", selected: false, model: "gpt-account-model" });
+ });
+
+ it("keeps existing callers selecting the OAuth provider when select is omitted", async () => {
+ const { POST } = await import("./route");
+ await POST(request({ action: "poll" }), ctx);
+ expect(writeConfig).toHaveBeenCalledWith({ provider: "openai-codex", model: "gpt-account-model" });
+ });
+});
diff --git a/app/api/oauth/[provider]/route.ts b/app/api/oauth/[provider]/route.ts
index 2fb1b853..67ec9ddb 100644
--- a/app/api/oauth/[provider]/route.ts
+++ b/app/api/oauth/[provider]/route.ts
@@ -10,11 +10,12 @@ export const dynamic = "force-dynamic";
// OAuth "sign in with…" for subscription providers. POST { action:"start"|"poll" }.
// Only OpenAI (Codex device-code) is wired today; others return not-supported.
// Session-gated; the token bundle lands in the 0600 host config file, and on
-// success the provider is selected so the assistant uses it immediately.
+// success the provider is selected by default so existing Settings behavior stays compatible;
+// callers may send select:false when they are only adding provider credentials.
export async function POST(req: NextRequest, ctx: { params: Promise<{ provider: string }> }) {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { provider } = await ctx.params;
- let body: { action?: string };
+ let body: { action?: string; select?: boolean };
try {
body = await req.json();
} catch {
@@ -45,8 +46,8 @@ export async function POST(req: NextRequest, ctx: { params: Promise<{ provider:
// by the backend, so writing it here just made the first request after a
// successful sign-in fail.
const model = models[0] ?? "";
- await writeConfig({ provider: SLUG, model });
- return NextResponse.json({ ok: true, slug: SLUG, model });
+ if (body.select !== false) await writeConfig({ provider: SLUG, model });
+ return NextResponse.json({ ok: true, slug: SLUG, model, selected: body.select !== false });
}
default:
return NextResponse.json({ error: "bad_action" }, { status: 400 });
diff --git a/bin/mso b/bin/mso
index d9a7040e..3f6a866e 100755
--- a/bin/mso
+++ b/bin/mso
@@ -42,9 +42,9 @@
# status Public service status (no session needed)
# health Is this CLI's session valid?
# doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
-# agent Interactive MSO setup/ops agent (bare `mso` opens this)
+# agent [--continue|--resume <query>] Interactive MSO Agent; resume durable sessions
# chat Alias for agent
-# model Connect or change the AI provider used by MSO Agent / Alfa
+# model [ref] Select active model from a connected provider
# onboard [-y] Guided setup: AI, apps, infrastructure, skills
# setup Alias for onboard
# provider * Infrastructure credentials: list | set | rm | doctor
@@ -65,9 +65,9 @@
# threads * Conversation history: list | show | rm
# agent-sessions * Durable MSO Agent sessions: list | show | create
# memory * Assistant memories: list | add | rm
-# config * BYOK provider + model/style: show | set | key | style | rm
+# config * Advanced raw AI config compatibility surface
# prefs * UI preferences: show | set
-# models * Model catalog: list | test
+# models * Configure AI providers/auth; inspect model catalog
# skills * Discover host skills + curated market: available/install/remove
# changelog What shipped, newest first (same text Settings → About shows)
# mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all
@@ -126,18 +126,20 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.5.4"
+VERSION="1.5.5"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
# Global options are parsed BEFORE the env file is sourced, because --env chooses
# which file that is.
-BASE_OVERRIDE=""; ENV_OVERRIDE=""
+BASE_OVERRIDE=""; ENV_OVERRIDE=""; AGENT_START_ARGS=()
while [ $# -gt 0 ]; do
case "$1" in
--base) [ -n "${2-}" ] || die "--base needs a url"; BASE_OVERRIDE="$2"; shift 2 ;;
--env) [ -n "${2-}" ] || die "--env needs a file"; ENV_OVERRIDE="$2"; shift 2 ;;
+ --continue|-c) AGENT_START_ARGS+=("--continue"); shift ;;
+ --resume|-r) [ -n "${2-}" ] || die "$1 needs a session query"; AGENT_START_ARGS+=("--resume" "$2"); shift 2 ;;
--) shift; break ;;
*) break ;;
esac
@@ -670,6 +672,8 @@ U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
U_doctor="doctor [--fix]"
U_provider="provider list|show <id>|set <dokploy|cloudflare|hostinger>|rm <id>|doctor [id]|projects|zones"
+U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
+U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>]"
U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
@@ -681,7 +685,7 @@ U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"
U_memory="memory list|add <text>|rm <id>"
U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"
U_prefs="prefs show|set <json>"
-U_models="models list|test"
+U_models="models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]"
U_skills="skills list|read <id>|search <query…>|available|info <id>|install <id…> [-y] [--force]|remove <id…> [-y]"
U_mcp="mcp list|activity [n]|revoke <id>|revoke all"
U_oauth="oauth <provider> start|poll OAuth currently: openai (ChatGPT Codex)"
@@ -703,6 +707,7 @@ if [ $# -ge 2 ]; then
fi
cmd="${1:-agent}"; maybe_update_notice "$cmd"; shift || true
+if [ "$cmd" = agent ] || [ "$cmd" = chat ]; then set -- "${AGENT_START_ARGS[@]}" "$@"; fi
case "$cmd" in
version|--version|-V|-v)
app_version="$(jq -r '.version // "unknown"' "$ROOT/package.json" 2>/dev/null || printf unknown)"
@@ -865,7 +870,7 @@ case "$cmd" in
exit $(( fails > 0 ? 1 : 0 )) ;;
agent|chat) run_agent "$@" ;;
- model) run_model_setup ;;
+ model) run_model_setup "$@" ;;
setup) run_onboard "${1-}" ;;
onboard) run_onboard "${1-}" ;;
provider|providers) run_provider "$@" ;;
@@ -971,12 +976,7 @@ case "$cmd" in
set) jpost "/api/prefs" "$(json_arg "${2:?json, e.g. '{\"tweaks\":{\"theme\":\"dark\"}}'}")" ;;
*) die "usage: mso $U_prefs" ;;
esac ;;
- models)
- case "${1:-list}" in
- list) jget "/api/models" ;;
- test) jpost "/api/models/test" ;;
- *) die "usage: mso $U_models" ;;
- esac ;;
+ models) run_models "$@" ;;
skills)
case "${1:-list}" in
list) jget "/api/skills" ;;
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index f73b50fc..a9a5dad5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `agent` align model and session terminal UX
- `install` make upgrades agent-friendly
- `agent` add interactive slash palette
- `agent` add project-aware slash skills
diff --git a/docs/CLI.md b/docs/CLI.md
index 0682987d..84c829bf 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -82,9 +82,9 @@ Commands:
status Public service status (no session needed)
health Is this CLI's session valid?
doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
- agent Interactive MSO setup/ops agent (bare `mso` opens this)
+ agent [--continue|--resume <query>] Interactive MSO Agent; resume durable sessions
chat Alias for agent
- model Connect or change the AI provider used by MSO Agent / Alfa
+ model [ref] Select active model from a connected provider
onboard [-y] Guided setup: AI, apps, infrastructure, skills
setup Alias for onboard
provider * Infrastructure credentials: list | set | rm | doctor
@@ -105,9 +105,9 @@ Commands:
threads * Conversation history: list | show | rm
agent-sessions * Durable MSO Agent sessions: list | show | create
memory * Assistant memories: list | add | rm
- config * BYOK provider + model/style: show | set | key | style | rm
+ config * Advanced raw AI config compatibility surface
prefs * UI preferences: show | set
- models * Model catalog: list | test
+ models * Configure AI providers/auth; inspect model catalog
skills * Discover host skills + curated market: available/install/remove
changelog What shipped, newest first (same text Settings → About shows)
mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all
diff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.md
index c216b05a..7b87e7cd 100644
--- a/docs/INFRASTRUCTURE-PROVIDERS.md
+++ b/docs/INFRASTRUCTURE-PROVIDERS.md
@@ -17,7 +17,12 @@ Bare `mso` is the interactive setup/operations agent:
```bash
mso # launch MSO Agent
mso agent # explicit alias
-mso model # connect/change the AI provider
+mso --continue # resume latest durable Agent session
+mso --resume <query> # resume by index/id/short-id/title
+mso models # configure AI provider/API/OAuth connections
+mso models add openai-codex # connect ChatGPT subscription OAuth without switching model
+mso model # choose active model from connected providers
+mso model list # list models selectable from the active provider
mso setup # guided setup (alias of `mso onboard`)
mso provider list # masked infrastructure status
mso provider set dokploy # hidden terminal prompts
@@ -28,9 +33,11 @@ mso provider projects # Dokploy projects
mso provider zones # Cloudflare zones
```
-When no AI provider is connected, `mso` runs the same interactive provider flow as
-`mso model` before the agent starts. The current model connection choices are OpenAI
-ChatGPT/Codex device OAuth plus the built-in API-key providers documented in
+AI provider authentication and model selection are intentionally separate. `mso models` owns
+credentials/authentication and does **not** switch the active model; `mso model` owns selection.
+When no AI provider is connected, bare `mso` opens the provider manager first and then the model
+picker. If credentials already exist but the selection is unusable, only the model picker runs.
+The connection choices are OpenAI ChatGPT/Codex device OAuth plus the built-in API-key providers documented in
[`INSTALL.md`](./INSTALL.md).
The terminal UI intentionally follows the useful *shape* of mature agent CLIs such as
@@ -40,10 +47,20 @@ interactive prompt — but uses original MSO ASCII artwork and MSO's own tool/ru
Agent slash commands are:
```text
-/model /setup /providers /provider <id> /doctor
-/tools /skills /clear /exit
+/models /model /status /context /statusbar /title
+/session /sessions /resume /setup /providers /provider <id>
+/doctor /tools /skills /clear /exit
```
+The prompt status line is dynamic: active `provider/model`, approximate current context (`ctx ~…`)
+with a catalog context-window denominator when available, provider-reported token usage when the
+upstream exposes it, turn count, last-turn duration, durable session id and working directory.
+`/status` expands the same information. Context without tokenizer/provider metadata is deliberately
+labeled approximate rather than presented as an exact token count. `/sessions` lists durable sessions;
+`/resume` opens a picker or accepts `latest`, a list index, exact/short id, exact title or unique title
+substring. The CLI equivalents are `mso --continue` and `mso --resume <query>`. Session discovery
+remains scoped to the authenticated principal; resume never bypasses principal/session isolation.
+
## 2. One tool catalog, two transports
`scripts/mso-agent.mjs` does not invent a second host-tool implementation. It asks the
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index ade8f51e..a2e13b8f 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -129,6 +129,13 @@ is an API-key integration here, not OAuth. The OpenAI OAuth path is the ChatGPT
Codex backend; it is separate from OpenAI Platform API keys and separate again from MSO's
ChatGPT MCP OAuth.
+After onboarding, use the two AI commands deliberately: `mso models` manages provider/API/OAuth
+connections without changing the active model; `mso model` selects a model from providers that are
+already connected. `mso models test` validates the currently selected connection (including the
+ChatGPT/Codex subscription path), while `mso model list [provider]` shows selectable model IDs.
+Agent sessions are durable: `mso --continue` resumes the latest CLI session and
+`mso --resume <index|id|title>` resolves a prior session without weakening principal isolation.
+
Hermes/OpenClaw installation is optional and uses each app's existing managed-job installer.
Their model/provider configuration belongs to those applications and is not implicitly
filled from Alfa's credential. Selected app installs stream their job transcript until a
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index d36ac0f7..16c5a7dc 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,16 @@
Running log of what shipped each phase. Newest at top.
+## 2026-09-01 — Agent model/session UX parity + dynamic status — SHIPPED
+
+MSO Agent 1.5.5 aligns the useful interaction contract of mature agent harnesses without copying their branding/runtime. The startup banner now uses the owner-specified 12-line Hybrid MSO geometry and exact six-stop True Color gradient (purple/indigo → blue → cyan → teal/emerald). AI configuration is split into two explicit surfaces: `mso models` manages provider API keys/OAuth/custom-provider connections **without switching the active model**, while `mso model` validates and selects only models available through connected providers. Exact `/model` now wins over the `/models` prefix in the slash palette; OpenRouter-style model IDs containing `/` are resolved against the current provider before being interpreted as a provider/model ref.
+
+The terminal now carries a compact dynamic status line with active provider/model, approximate context consumption (explicit `~`, plus catalog context window when known), provider-reported token usage when available, turn count, last-turn latency, durable session id and working directory. `/status`/`/context` expand the same state and `/statusbar` toggles it. Session UX supports `/title`, numbered `/sessions`, `/resume` picker, `latest`, index, exact/short id, exact title or unique fuzzy title; startup equivalents are `mso --continue` and `mso --resume <query>`. Resume stays bounded to sessions visible to the authenticated principal. Anthropic and ChatGPT/Codex streaming now propagate provider usage into the terminal status when upstream data exists; OpenAI-compatible streams consume usage opportunistically and otherwise keep the clearly-labeled estimate.
+
+The same audit caught two real regressions before release: `/api/models/test` could not validate the `openai-codex` subscription provider because it incorrectly entered the generic API-key resolver, and Enter on exact `/model` could apply the highlighted longer `/models` completion. Both paths now have dedicated regression tests. Provider-auth APIs accept `select:false` for CLI connection management while keeping legacy Settings callers selecting by default, so existing browser behavior remains compatible.
+
+Verification for this milestone passed **262 test files / 1,939 tests** (1 expected fail, 7 skipped), typecheck, documentation consistency, cycle checks and high/critical dependency audit. PTY smoke covers exact 12-row banner/color output, wide/narrow terminal behavior, zero-newline arrow navigation, `/model` vs `/models`, `/status`, durable title, resume by title and `--continue`.
+
## 2026-09-01 — Version identity and update messaging DX — SHIPPED
MSO's two legitimate version domains are now explicit instead of looking like drift. The app/package
diff --git a/lib/ai/codex-stream.ts b/lib/ai/codex-stream.ts
index 82fc1acd..c4150867 100644
--- a/lib/ai/codex-stream.ts
+++ b/lib/ai/codex-stream.ts
@@ -159,6 +159,7 @@ export async function streamCodex(opts: {
const dec = new TextDecoder();
let buf = "";
let sawToolCall = false;
+ let usage: { inputTokens?: number; outputTokens?: number; totalTokens?: number } | null = null;
const seen = new Set<string>();
while (true) {
@@ -176,7 +177,10 @@ export async function streamCodex(opts: {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (!data || data === "[DONE]") continue;
- let ev: { type?: string; delta?: string; item?: ResponsesItem; response?: { output?: ResponsesItem[] } };
+ let ev: {
+ type?: string; delta?: string; item?: ResponsesItem;
+ response?: { output?: ResponsesItem[]; usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number } };
+ };
try {
ev = JSON.parse(data);
} catch {
@@ -192,6 +196,13 @@ export async function streamCodex(opts: {
if (ev.type === "response.output_item.done" && ev.item) {
if (emitCall(ev.item, seen, realName, emit)) sawToolCall = true;
} else if (ev.type === "response.completed") {
+ if (ev.response?.usage) {
+ usage = {
+ inputTokens: ev.response.usage.input_tokens,
+ outputTokens: ev.response.usage.output_tokens,
+ totalTokens: ev.response.usage.total_tokens,
+ };
+ }
for (const item of ev.response?.output ?? []) {
if (emitCall(item, seen, realName, emit)) sawToolCall = true;
}
@@ -200,7 +211,7 @@ export async function streamCodex(opts: {
}
// The agent loop keys entirely off stopReason: reporting end_turn after a call
// would strand the tool result and end the run mid-task.
- emit("done", { stopReason: sawToolCall ? "tool_use" : "end_turn" });
+ emit("done", { stopReason: sawToolCall ? "tool_use" : "end_turn", ...(usage ? { usage } : {}) });
}
type ResponsesItem = {
diff --git a/lib/ai/openai-stream.ts b/lib/ai/openai-stream.ts
index 6eb9c896..1a4dcf6d 100644
--- a/lib/ai/openai-stream.ts
+++ b/lib/ai/openai-stream.ts
@@ -23,6 +23,7 @@ type OaOutMsg = {
};
type OaChunk = {
+ usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };
choices?: Array<{
delta?: {
content?: string | null;
@@ -109,6 +110,7 @@ export async function streamOpenAI(opts: {
// tool_call fragments arrive split across chunks; accumulate by index.
const calls = new Map<number, { id: string; name: string; args: string }>();
let finish: string | null = null;
+ let usage: { inputTokens?: number; outputTokens?: number; totalTokens?: number } | null = null;
reading: while (true) {
if (signal.aborted) { await reader.cancel().catch(() => {}); return; }
@@ -125,6 +127,13 @@ export async function streamOpenAI(opts: {
if (data === "[DONE]") break reading;
let chunk: OaChunk;
try { chunk = JSON.parse(data) as OaChunk; } catch { continue; }
+ if (chunk.usage) {
+ usage = {
+ inputTokens: chunk.usage.prompt_tokens,
+ outputTokens: chunk.usage.completion_tokens,
+ totalTokens: chunk.usage.total_tokens,
+ };
+ }
const choice = chunk.choices?.[0];
if (!choice) continue;
if (choice.delta?.content) emit("delta", choice.delta.content);
@@ -145,5 +154,5 @@ export async function streamOpenAI(opts: {
if (c.args) { try { input = JSON.parse(c.args); } catch { input = {}; } }
emit("tool_use", { id: c.id || `call_${c.name}`, name: c.name, input });
}
- emit("done", { stopReason: toStopReason(finish) });
+ emit("done", { stopReason: toStopReason(finish), ...(usage ? { usage } : {}) });
}
diff --git a/lib/ai/usage.ts b/lib/ai/usage.ts
new file mode 100644
index 00000000..d3baa67e
--- /dev/null
+++ b/lib/ai/usage.ts
@@ -0,0 +1,13 @@
+import type Anthropic from "@anthropic-ai/sdk";
+
+export function anthropicDonePayload(final: Anthropic.Message) {
+ return {
+ stopReason: final.stop_reason,
+ usage: {
+ inputTokens: final.usage.input_tokens,
+ outputTokens: final.usage.output_tokens,
+ cacheCreationInputTokens: final.usage.cache_creation_input_tokens ?? 0,
+ cacheReadInputTokens: final.usage.cache_read_input_tokens ?? 0,
+ },
+ };
+}
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 0cf8cbcf..1e1f5e4f 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -159,7 +159,11 @@ export class AgentComposer {
}
if (key.name === "tab" && items.length) return apply(items[selected]);
if (key.name === "return" || key.name === "enter") {
- if (items.length && items[selected]?.text && value !== items[selected].text) return apply(items[selected]);
+ // Exact input wins even when another prefix match is highlighted first
+ // (`/model` vs `/models`). Enter submits what the user actually typed;
+ // Tab is the explicit "apply highlighted completion" key.
+ if (items.some((item) => item?.text === value)) return finish(value);
+ if (items.length && items[selected]?.text) return apply(items[selected]);
return finish(value);
}
if (key.name === "up" && !items.length) return historyMove(-1);
diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.ts
index 32467b5e..ea6a0e3d 100644
--- a/scripts/mso-agent-composer.test.ts
+++ b/scripts/mso-agent-composer.test.ts
@@ -65,4 +65,20 @@ describe("MSO Agent interactive composer primitives", () => {
composer.close();
});
+ it("submits an exact slash command instead of a longer highlighted prefix", async () => {
+ class FakeInput extends EventEmitter {
+ isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; }
+ }
+ class FakeOutput { columns = 88; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }
+ const input = new FakeInput(); const output = new FakeOutput();
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors: { blue: "", bold: "", reset: "", dim: "" } });
+ const answer = composer.question("› ", { complete: (value: string) => value.startsWith("/model") ? [
+ { text: "/models", meta: "provider auth" }, { text: "/model", meta: "select model" },
+ ] : [] } as never);
+ for (const ch of "/model") input.emit("keypress", ch, { name: ch, sequence: ch });
+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(answer).resolves.toBe("/model");
+ composer.close();
+ });
+
});
diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.ts
index 0561be75..b6c919ce 100644
--- a/scripts/mso-agent-contract.test.ts
+++ b/scripts/mso-agent-contract.test.ts
@@ -2,26 +2,44 @@ import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
-const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.mjs"].map((name) => path.join(__dirname, name));
+const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.mjs", "mso-agent-slash.mjs", "mso-agent-status.mjs", "mso-agent-sessions.mjs"].map((name) => path.join(__dirname, name));
const src = files.map((file) => fs.readFileSync(file, "utf8")).join("\n");
describe("MSO terminal agent contract", () => {
- it("renders the final blue MSO Agent title art and setup/session shortcuts", () => {
- expect(src).toContain("████████╗ ███╗ ███╗███████╗ ██████╗ ");
- expect(src).toContain("██╔═╦═╦═╝████████████████╗ ████╗ ████║██╔════╝██╔═══██╗");
- expect(src).toContain("██║ > _ > ██║ ██║╚██╔╝██║╚════██║██║ ██║");
- expect(src).toContain("╚████████████████████████╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ");
- expect(src).toContain(" ── MSO Agent ──");
+ it("renders the exact hybrid MSO Agent title and keeps model/session UX discoverable", () => {
+ const banner = [
+ " ████████████",
+ " ██ ██",
+ " ██ ██ ██ ██ ██████████████████████",
+ " ██ ██ ███╗ ███╗███████╗ ██████╗ ",
+ " ██ ██ ████╗ ████║██╔════╝██╔═══██╗",
+ " ██ ██ ██ ██ ██╔████╔██║███████╗██║ ██║",
+ " ██ ██ ██ ██ ██║╚██╔╝██║╚════██║██║ ██║",
+ " ██ ██ ████████ ██ ██ ██║ ╚═╝ ██║███████║╚██████╔╝",
+ " ██ ██ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ",
+ " ██ ██",
+ " ████████████████████████████████████",
+ " ── MSO Agent ──",
+ ];
+ for (const line of banner) expect(src).toContain(line);
+ for (const rgb of [
+ "38;2;155;81;224", "38;2;112;111;245", "38;2;69;142;255",
+ "38;2;45;184;255", "38;2;34;211;206", "38;2;46;229;157",
+ ]) expect(src).toContain(rgb);
expect(src).toContain("MSO_TITLE_ART");
expect(src).toContain("MSO_TITLE_COLORS");
- expect(src).toContain("38;2;69;142;255");
- expect(src).toContain("38;2;46;229;157");
- expect(src).not.toContain("MSO_TITLE_GUTTER");
- expect(src).not.toContain("╭──┘ ╰────────╮");
- for (const command of ["/model", "/setup", "/providers", "/provider", "/doctor", "/tools", "/skills", "/skill", "/<skill>", "/session", "/sessions", "/resume", "/clear", "/exit"]) expect(src).toContain(command);
+ for (const command of [
+ "/models", "/model", "/status", "/context", "/statusbar", "/title",
+ "/session", "/sessions", "/resume", "/setup", "/providers", "/provider",
+ "/doctor", "/tools", "/skills", "/skill", "/<skill>", "/clear", "/exit",
+ ]) expect(src).toContain(command);
+ expect(src).toContain("Configure AI providers and authentication");
+ expect(src).toContain("Select the active model from connected providers");
expect(src).toContain("selected for the next message");
expect(src).toContain("AgentComposer");
expect(src).toContain("slashCompletionItems");
+ expect(src).toContain("renderStatusBar");
+ expect(src).toContain("resolveSessionQuery");
});
it("keeps infrastructure secrets out of model messages and binds write/exec approval to the exact full payload", () => {
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
index 21fc01b7..657dd8aa 100644
--- a/scripts/mso-agent-runtime.mjs
+++ b/scripts/mso-agent-runtime.mjs
@@ -38,11 +38,18 @@ export async function api(path, init = {}) {
}
export async function state() {
- const [config, toolsData, skills, infra] = await Promise.all([
- api("/api/config"), api("/api/v1/agent-tools"), api("/api/skills").catch(() => ({ skills: [] })), api("/api/v1/infra/providers").catch(() => ({ providers: [] })),
+ const config = await api("/api/config");
+ const provider = encodeURIComponent(String(config?.provider || ""));
+ const [toolsData, skills, infra, modelData] = await Promise.all([
+ api("/api/v1/agent-tools"),
+ api("/api/skills").catch(() => ({ skills: [] })),
+ api("/api/v1/infra/providers").catch(() => ({ providers: [] })),
+ provider ? api(`/api/models?provider=${provider}`).catch(() => ({ models: [] })) : Promise.resolve({ models: [] }),
]);
const tools = Array.isArray(toolsData?.tools) ? toolsData.tools : [];
- return { config, toolsData, tools, skills, infra };
+ const models = Array.isArray(modelData?.models) ? modelData.models : [];
+ const modelMeta = models.find((row) => String(row.id) === String(config?.model)) || null;
+ return { config, toolsData, tools, skills, infra, models, modelMeta };
}
export async function createCliSession(title = "MSO Agent session") {
@@ -110,7 +117,7 @@ export async function streamTurn(messages, tools, agentSession, skillContext = n
}
const reader = res.body.getReader();
const dec = new TextDecoder();
- let buf = "", text = "", stopReason = null;
+ let buf = "", text = "", stopReason = null, usage = null;
const toolUses = [];
while (true) {
const { done, value } = await reader.read();
@@ -127,10 +134,14 @@ export async function streamTurn(messages, tools, agentSession, skillContext = n
if (event === "delta") {
const chunk = JSON.parse(data); text += chunk; process.stdout.write(chunk);
} else if (event === "tool_use") toolUses.push(JSON.parse(data));
- else if (event === "done") stopReason = JSON.parse(data)?.stopReason ?? null;
+ else if (event === "done") {
+ const done = JSON.parse(data);
+ stopReason = done?.stopReason ?? null;
+ usage = done?.usage ?? null;
+ }
else if (event === "error") throw new Error(JSON.parse(data));
}
}
if (text && !text.endsWith("\n")) process.stdout.write("\n");
- return { text, toolUses, stopReason };
+ return { text, toolUses, stopReason, usage };
}
diff --git a/scripts/mso-agent-session-ui.mjs b/scripts/mso-agent-session-ui.mjs
new file mode 100644
index 00000000..ea844236
--- /dev/null
+++ b/scripts/mso-agent-session-ui.mjs
@@ -0,0 +1,81 @@
+import { C, createCliSession, listCliSessions, loadCliSession, saveCliSession } from "./mso-agent-runtime.mjs";
+import { resolveSessionQuery, sessionCompletionItems } from "./mso-agent-sessions.mjs";
+
+function autoTitle(history) {
+ const first = history.find((row) => row?.role === "user" && typeof row.text === "string" && row.text.trim());
+ return first ? String(first.text).replace(/[\r\n\t]+/g, " ").trim().slice(0, 100) : undefined;
+}
+
+export async function persistSession(session) {
+ const title = session.titleOverride || autoTitle(session.history);
+ const saved = await saveCliSession(session.agentSession, session.history, title);
+ session.agentSession = { ...session.agentSession, ...saved };
+}
+
+export function printSessions(rows) {
+ if (!rows.length) { console.log("No MSO Agent sessions yet."); return; }
+ console.log(`${C.bold}Recent MSO Agent sessions${C.reset}`);
+ rows.forEach((row, index) => {
+ const when = String(row.updatedAt || row.createdAt || "").replace("T", " ").slice(0, 19);
+ const title = String(row.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").slice(0, 48);
+ console.log(` ${String(index + 1).padStart(2)} ${C.blue}${row.id}${C.reset} ${C.dim}${when}${C.reset} ${String(row.historyTurns || 0).padStart(2)}t ${title}`);
+ });
+ console.log(`${C.dim}Resume: /resume latest | /resume 2 | /resume <id/title> · CLI: mso --continue / mso --resume <query>${C.reset}`);
+}
+
+async function resolveResume(query, rows = null) {
+ const sessions = rows || await listCliSessions(100);
+ const result = resolveSessionQuery(sessions, query);
+ if (result.session) return result.session;
+ if (result.ambiguous?.length) {
+ console.log(`${C.warn}resume query is ambiguous:${C.reset}`);
+ printSessions(result.ambiguous);
+ return null;
+ }
+ throw new Error(`no resumable MSO Agent session matches: ${query || "latest"}`);
+}
+
+export async function resumeInto(session, query, rows = null) {
+ const target = await resolveResume(query, rows);
+ if (!target) return false;
+ const loaded = await loadCliSession(target.id);
+ if (!loaded || loaded.source !== "cli") throw new Error("session is not a CLI MSO Agent session");
+ Object.assign(session, {
+ agentSession: loaded,
+ history: Array.isArray(loaded.history) ? loaded.history.slice(-48) : [],
+ pendingSkill: null,
+ titleOverride: loaded.title || null,
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
+ lastElapsedMs: 0,
+ });
+ console.log(`${C.c}resumed ${loaded.id}${C.reset} · ${loaded.title || "MSO Agent session"} · ${session.history.length} history rows`);
+ return true;
+}
+
+export async function resumePicker(rl, session) {
+ const rows = await listCliSessions(100);
+ if (!rows.length) { console.log("No MSO Agent sessions yet."); return; }
+ printSessions(rows.slice(0, 20));
+ const answer = await rl.question(`${C.blue}${C.bold}resume ›${C.reset} `, {
+ history: false,
+ complete: (value) => sessionCompletionItems(rows, value),
+ });
+ if (answer?.trim()) await resumeInto(session, answer.trim(), rows);
+}
+
+export function resumeArg(argv) {
+ if (argv.includes("--continue") || argv.includes("-c")) return "latest";
+ let index = argv.indexOf("--resume");
+ if (index < 0) index = argv.indexOf("-r");
+ if (index < 0) return null;
+ const value = argv[index + 1];
+ if (!value || value.startsWith("-")) throw new Error("--resume requires latest, an index, session id, or title query");
+ return value;
+}
+
+export async function startupSession(requested) {
+ if (!requested) return createCliSession();
+ const target = await resolveResume(requested, await listCliSessions(100));
+ if (!target) throw new Error(`cannot resume ambiguous session query: ${requested}`);
+ return loadCliSession(target.id);
+}
diff --git a/scripts/mso-agent-sessions.mjs b/scripts/mso-agent-sessions.mjs
new file mode 100644
index 00000000..f54a08f3
--- /dev/null
+++ b/scripts/mso-agent-sessions.mjs
@@ -0,0 +1,33 @@
+function clean(value) { return String(value ?? "").replace(/[\r\n\t]+/g, " ").trim(); }
+
+export function resolveSessionQuery(rows, query) {
+ const sessions = Array.isArray(rows) ? rows : [];
+ if (!sessions.length) return { session: null, ambiguous: [], reason: "empty" };
+ const raw = clean(query);
+ if (!raw || raw.toLowerCase() === "latest" || raw.toLowerCase() === "continue") return { session: sessions[0], ambiguous: [] };
+ if (/^\d+$/.test(raw)) {
+ const index = Number(raw) - 1;
+ return { session: sessions[index] || null, ambiguous: [], reason: sessions[index] ? undefined : "index" };
+ }
+ const lower = raw.toLowerCase();
+ const exactId = sessions.find((row) => String(row.id) === raw);
+ if (exactId) return { session: exactId, ambiguous: [] };
+ const idPrefix = sessions.filter((row) => String(row.id).toLowerCase().startsWith(lower) || String(row.id).toLowerCase().endsWith(lower));
+ if (idPrefix.length === 1) return { session: idPrefix[0], ambiguous: [] };
+ if (idPrefix.length > 1) return { session: null, ambiguous: idPrefix, reason: "ambiguous" };
+ const exactTitle = sessions.filter((row) => clean(row.title).toLowerCase() === lower);
+ if (exactTitle.length === 1) return { session: exactTitle[0], ambiguous: [] };
+ if (exactTitle.length > 1) return { session: null, ambiguous: exactTitle, reason: "ambiguous" };
+ const fuzzy = sessions.filter((row) => clean(row.title).toLowerCase().includes(lower));
+ if (fuzzy.length === 1) return { session: fuzzy[0], ambiguous: [] };
+ if (fuzzy.length > 1) return { session: null, ambiguous: fuzzy, reason: "ambiguous" };
+ return { session: null, ambiguous: [], reason: "not_found" };
+}
+
+export function sessionCompletionItems(rows, input) {
+ const q = clean(input).toLowerCase();
+ return (Array.isArray(rows) ? rows : []).map((row, index) => ({
+ text: row.id,
+ meta: `${index + 1} · ${row.source || "cli"} · ${row.historyTurns || 0} turns · ${clean(row.title || "MSO Agent session")}`,
+ })).filter((item) => !q || item.text.toLowerCase().includes(q) || item.meta.toLowerCase().includes(q)).slice(0, 20);
+}
diff --git a/scripts/mso-agent-sessions.test.ts b/scripts/mso-agent-sessions.test.ts
new file mode 100644
index 00000000..1a1eaa02
--- /dev/null
+++ b/scripts/mso-agent-sessions.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { resolveSessionQuery, sessionCompletionItems } from "./mso-agent-sessions.mjs";
+
+const rows = [
+ { id: "20260901_120000_aaaaaaaa", title: "Deploy Baton", source: "cli", historyTurns: 10 },
+ { id: "20260901_110000_bbbbbbbb", title: "Audit MSO", source: "cli", historyTurns: 4 },
+ { id: "20260901_100000_cccccccc", title: "Older Baton notes", source: "cli", historyTurns: 2 },
+];
+
+describe("MSO Agent session resolver", () => {
+ it("resumes latest, list index, exact id, short id and unique title", () => {
+ expect(resolveSessionQuery(rows, "latest").session?.id).toBe(rows[0].id);
+ expect(resolveSessionQuery(rows, "2").session?.id).toBe(rows[1].id);
+ expect(resolveSessionQuery(rows, rows[1].id).session?.id).toBe(rows[1].id);
+ expect(resolveSessionQuery(rows, "bbbbbbbb").session?.id).toBe(rows[1].id);
+ expect(resolveSessionQuery(rows, "Audit MSO").session?.id).toBe(rows[1].id);
+ });
+
+ it("refuses ambiguous fuzzy titles instead of guessing", () => {
+ const result = resolveSessionQuery(rows, "Baton");
+ expect(result.session).toBeNull();
+ expect(result.ambiguous).toHaveLength(2);
+ });
+
+ it("builds searchable session picker items", () => {
+ expect(sessionCompletionItems(rows, "audit")).toHaveLength(1);
+ expect(sessionCompletionItems(rows, "")[0].meta).toContain("10 turns");
+ });
+});
diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjs
index 600e07a0..9f9db6e3 100644
--- a/scripts/mso-agent-slash.mjs
+++ b/scripts/mso-agent-slash.mjs
@@ -3,10 +3,15 @@ import { currentSkillProject, resolveSlashSkill, slashSkillNames } from "./mso-a
export const BUILTIN_SLASH_ITEMS = [
{ text: "/help", meta: "Show commands and shortcuts", kind: "command" },
- { text: "/model", meta: "Connect or change the AI provider", kind: "command" },
+ { text: "/models", meta: "Configure AI providers and authentication", kind: "command" },
+ { text: "/model", meta: "Select the active model from connected providers", kind: "command" },
{ text: "/session", meta: "Show the current durable session id", kind: "command" },
{ text: "/sessions", meta: "List resumable MSO Agent sessions", kind: "command" },
- { text: "/resume", meta: "Resume an earlier session by id", kind: "command" },
+ { text: "/resume", meta: "Resume latest/index/id/title; no arg opens picker", kind: "command" },
+ { text: "/title", meta: "Rename the durable session", kind: "command" },
+ { text: "/status", meta: "Show model, auth, context, tokens, session", kind: "command" },
+ { text: "/context", meta: "Show context/token/session status", kind: "command" },
+ { text: "/statusbar", meta: "Toggle the compact dynamic status line", kind: "command" },
{ text: "/setup", meta: "Run full MSO onboarding", kind: "command" },
{ text: "/providers", meta: "Show infrastructure provider status", kind: "command" },
{ text: "/provider", meta: "Configure Dokploy, Cloudflare, or Hostinger", kind: "command" },
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
new file mode 100644
index 00000000..58859321
--- /dev/null
+++ b/scripts/mso-agent-status.mjs
@@ -0,0 +1,109 @@
+import os from "node:os";
+import path from "node:path";
+
+function compactNumber(value) {
+ const n = Number(value || 0);
+ if (!Number.isFinite(n) || n <= 0) return "0";
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}m`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}k`;
+ return String(Math.round(n));
+}
+
+export function estimateTokens(value) {
+ // Provider-neutral fallback. ~4 UTF-8 bytes/token is intentionally labeled with
+ // `~` in the UI; actual usage from a provider replaces cumulative estimates.
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? "");
+ return Math.max(0, Math.ceil(Buffer.byteLength(text, "utf8") / 4));
+}
+
+export function historyContextEstimate(history) {
+ return (Array.isArray(history) ? history : []).reduce((sum, row) => sum + estimateTokens(row), 0);
+}
+
+export function contextStatus(history, modelMeta) {
+ const used = historyContextEstimate(history);
+ const limit = Number(modelMeta?.context || 0);
+ return {
+ used,
+ limit: Number.isFinite(limit) && limit > 0 ? limit : null,
+ percent: limit > 0 ? Math.min(999, Math.round((used / limit) * 100)) : null,
+ };
+}
+
+export function addUsage(total, next) {
+ const base = total || { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
+ if (!next || typeof next !== "object") return base;
+ const input = Number(next.inputTokens ?? next.input_tokens ?? 0) || 0;
+ const output = Number(next.outputTokens ?? next.output_tokens ?? 0) || 0;
+ const explicit = Number(next.totalTokens ?? next.total_tokens ?? 0) || 0;
+ return {
+ inputTokens: base.inputTokens + input,
+ outputTokens: base.outputTokens + output,
+ totalTokens: base.totalTokens + (explicit || input + output),
+ };
+}
+
+function homeShort(cwd) {
+ const home = os.homedir();
+ if (cwd === home) return "~";
+ if (cwd.startsWith(`${home}${path.sep}`)) return `~/${path.relative(home, cwd)}`;
+ return cwd;
+}
+
+export function statusParts(session, cwd = process.cwd()) {
+ const provider = String(session?.state?.config?.provider || "—");
+ const model = String(session?.state?.config?.model || "—");
+ const ctx = contextStatus(session?.history, session?.state?.modelMeta);
+ const turns = (session?.history || []).filter((row) => row?.role === "user").length;
+ const shortSession = String(session?.agentSession?.id || "—").replace(/^\d{8}_\d{6}_/, "");
+ const usage = session?.usage || { totalTokens: 0 };
+ const elapsed = Number(session?.lastElapsedMs || 0);
+ return [
+ `${provider}/${model}`,
+ ctx.limit ? `ctx ~${compactNumber(ctx.used)}/${compactNumber(ctx.limit)} ${ctx.percent}%` : `ctx ~${compactNumber(ctx.used)}/?`,
+ usage.totalTokens > 0 ? `tokens ${compactNumber(usage.totalTokens)}` : null,
+ `turns ${turns}`,
+ elapsed > 0 ? `${(elapsed / 1000).toFixed(elapsed >= 10_000 ? 0 : 1)}s` : null,
+ `session ${shortSession}`,
+ homeShort(cwd),
+ ].filter(Boolean);
+}
+
+export function renderStatusBar(session, C, cwd = process.cwd()) {
+ return `${C.blue}${C.bold}◆${C.reset} ${statusParts(session, cwd).join(`${C.dim} · ${C.reset}`)}`;
+}
+
+export function detailedStatus(session, cwd = process.cwd()) {
+ const cfg = session?.state?.config || {};
+ const ctx = contextStatus(session?.history, session?.state?.modelMeta);
+ const usage = session?.usage || { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
+ const providerMeta = (cfg.providers || []).find((row) => row.id === cfg.provider);
+ return {
+ provider: cfg.provider || null,
+ providerAuth: providerMeta?.kind || (cfg.hasApiKey ? "key/env" : "unknown"),
+ model: cfg.model || null,
+ contextEstimatedTokens: ctx.used,
+ contextWindow: ctx.limit,
+ contextPercent: ctx.percent,
+ providerReportedUsage: usage,
+ turns: (session?.history || []).filter((row) => row?.role === "user").length,
+ session: session?.agentSession?.id || null,
+ title: session?.agentSession?.title || null,
+ cwd: homeShort(cwd),
+ };
+}
+
+export function printDetailedStatus(session, C, cwd = process.cwd()) {
+ const row = detailedStatus(session, cwd);
+ console.log(`${C.bold}MSO Agent status${C.reset}`);
+ console.log(` model ${row.provider}/${row.model}`);
+ console.log(` auth ${row.providerAuth}`);
+ console.log(` context ~${row.contextEstimatedTokens}${row.contextWindow ? ` / ${row.contextWindow} (${row.contextPercent}%)` : " / ?"}`);
+ if (row.providerReportedUsage.totalTokens > 0) {
+ console.log(` tokens ${row.providerReportedUsage.totalTokens} total · ${row.providerReportedUsage.inputTokens} in · ${row.providerReportedUsage.outputTokens} out`);
+ } else console.log(" tokens provider has not reported usage in this process; context remains estimated");
+ console.log(` turns ${row.turns}`);
+ console.log(` session ${row.session}`);
+ console.log(` title ${row.title || "MSO Agent session"}`);
+ console.log(` cwd ${row.cwd}`);
+}
diff --git a/scripts/mso-agent-status.test.ts b/scripts/mso-agent-status.test.ts
new file mode 100644
index 00000000..80676fe3
--- /dev/null
+++ b/scripts/mso-agent-status.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { addUsage, contextStatus, estimateTokens, statusParts } from "./mso-agent-status.mjs";
+
+describe("MSO Agent dynamic status", () => {
+ it("labels provider-neutral context as an estimate and uses catalog context window", () => {
+ expect(estimateTokens("abcd")).toBe(1);
+ const ctx = contextStatus([{ role: "user", text: "hello world" }], { context: 128000 });
+ expect(ctx.used).toBeGreaterThan(0);
+ expect(ctx.limit).toBe(128000);
+ expect(ctx.percent).toBeGreaterThanOrEqual(0);
+ });
+
+ it("accumulates provider-reported usage without losing fallback status", () => {
+ const usage = addUsage(addUsage(null, { inputTokens: 10, outputTokens: 4 }), { input_tokens: 6, output_tokens: 2 });
+ expect(usage).toEqual({ inputTokens: 16, outputTokens: 6, totalTokens: 22 });
+ const parts = statusParts({
+ state: { config: { provider: "openai-codex", model: "gpt-5.6-sol" }, modelMeta: { context: 128000 } },
+ history: [{ role: "user", text: "hello" }], usage, agentSession: { id: "20260901_120000_deadbeef" },
+ }, "/tmp");
+ expect(parts.join(" ")).toContain("openai-codex/gpt-5.6-sol");
+ expect(parts.join(" ")).toContain("tokens 22");
+ });
+});
diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjs
index 61f9499e..9189585c 100644
--- a/scripts/mso-agent-ui.mjs
+++ b/scripts/mso-agent-ui.mjs
@@ -11,24 +11,28 @@ C.b = C.blue;
C.c = C.cyan;
export const MSO_TITLE_ART = [
- "████████╗ ███╗ ███╗███████╗ ██████╗ ",
- "██╔═╦═╦═╝████████████████╗ ████╗ ████║██╔════╝██╔═══██╗",
- "██║ ╚═╩═╝ ██║ ██╔████╔██║███████╗██║ ██║",
- "██║ > _ > ██║ ██║╚██╔╝██║╚════██║██║ ██║",
- "██║ ██║ ██║ ╚═╝ ██║███████║╚██████╔╝",
- "╚████████████████████████╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ",
- " ── MSO Agent ── ",
+ " ████████████",
+ " ██ ██",
+ " ██ ██ ██ ██ ██████████████████████",
+ " ██ ██ ███╗ ███╗███████╗ ██████╗ ",
+ " ██ ██ ████╗ ████║██╔════╝██╔═══██╗",
+ " ██ ██ ██ ██ ██╔████╔██║███████╗██║ ██║",
+ " ██ ██ ██ ██ ██║╚██╔╝██║╚════██║██║ ██║",
+ " ██ ██ ████████ ██ ██ ██║ ╚═╝ ██║███████║╚██████╔╝",
+ " ██ ██ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ",
+ " ██ ██",
+ " ████████████████████████████████████",
+ " ── MSO Agent ──",
];
-// Blue → cyan → teal/emerald. No purple: the title should read as one cool MSO gradient.
+// Exact True Color ANSI sequence requested for the hybrid MSO Agent banner.
export const MSO_TITLE_COLORS = color ? [
- "\x1b[38;2;69;142;255m",
- "\x1b[38;2;58;160;255m",
- "\x1b[38;2;45;184;255m",
- "\x1b[38;2;34;211;238m",
- "\x1b[38;2;32;201;176m",
- "\x1b[38;2;46;229;157m",
- "\x1b[38;2;46;229;157m",
+ "\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(() => "");
function plain(value) { return String(value ?? "").replace(/\x1b\[[0-9;]*m/g, ""); }
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index ad53e990..47c5d91a 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -5,9 +5,10 @@ import { canonicalAgentApproval } from "../lib/agent/approval.mjs";
import { loadSlashSkill, printSkillChoices, printSkills, resolveSlashSkill } from "./mso-agent-skills.mjs";
import { AgentComposer } from "./mso-agent-composer.mjs";
import { slashCompletionItems } from "./mso-agent-slash.mjs";
+import { addUsage, printDetailedStatus, renderStatusBar } from "./mso-agent-status.mjs";
+import { persistSession, printSessions, resumeArg, resumeInto, resumePicker, startupSession } from "./mso-agent-session-ui.mjs";
import {
- BASE, CLI, C, api, createCliSession, listCliSessions, loadCliSession,
- printBanner, saveCliSession, state, streamTurn,
+ BASE, CLI, C, api, listCliSessions, printBanner, state, streamTurn,
} from "./mso-agent-runtime.mjs";
async function executeTool(rl, tool, call, agentSession) {
@@ -49,8 +50,11 @@ async function executeTool(rl, tool, call, agentSession) {
}
async function agentRound(rl, session, skillContext = null) {
+ const startedAt = Date.now();
for (let turn = 0; turn < 10; turn++) {
const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext);
+ session.usage = addUsage(session.usage, result.usage);
+ session.lastElapsedMs = Date.now() - startedAt;
session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });
if (!result.toolUses.length) return;
const results = [];
@@ -70,36 +74,6 @@ function runCli(args) {
return r.status ?? 1;
}
-function sessionTitle(history) {
- const first = history.find((row) => row?.role === "user" && typeof row.text === "string" && row.text.trim());
- return first ? String(first.text).replace(/[\r\n\t]+/g, " ").trim().slice(0, 100) : undefined;
-}
-
-async function persist(session) {
- const saved = await saveCliSession(session.agentSession, session.history, sessionTitle(session.history));
- session.agentSession = { ...session.agentSession, ...saved };
-}
-
-function printSessions(rows) {
- if (!rows.length) { console.log("No MSO Agent sessions yet."); return; }
- console.log(`${C.bold}Recent MSO Agent sessions${C.reset}`);
- for (const row of rows) {
- const when = String(row.updatedAt || row.createdAt || "").replace("T", " ").slice(0, 19);
- const title = String(row.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").slice(0, 54);
- console.log(` ${C.blue}${row.id}${C.reset} ${C.dim}${when}${C.reset} ${title}`);
- }
- console.log(`${C.dim}Resume with /resume <session-id> or mso agent --resume <session-id>${C.reset}`);
-}
-
-async function resumeInto(session, id) {
- const loaded = await loadCliSession(id);
- if (!loaded || loaded.source !== "cli") throw new Error("session is not a CLI MSO Agent session");
- session.agentSession = loaded;
- session.history = Array.isArray(loaded.history) ? loaded.history.slice(-48) : [];
- session.pendingSkill = null;
- console.log(`${C.c}resumed ${loaded.id}${C.reset} · ${loaded.title || "MSO Agent session"}`);
-}
-
async function selectSlashSkill(rl, session, requested, prompt = "") {
const resolved = resolveSlashSkill(session.state.skills, requested, process.cwd());
if (!resolved.skill) {
@@ -116,7 +90,7 @@ async function selectSlashSkill(rl, session, requested, prompt = "") {
session.history.push({ role: "user", text: prompt.trim() });
if (session.history.length > 48) session.history.splice(0, session.history.length - 48);
await agentRound(rl, session, loaded);
- await persist(session);
+ await persistSession(session);
return "handled";
}
@@ -127,8 +101,13 @@ async function slash(rl, line, session) {
console.log([
" /session show current durable MSO session id",
" /sessions list recent resumable sessions",
- " /resume <id> resume an earlier CLI MSO session",
- " /model connect/change AI provider",
+ " /resume [query] resume latest/index/id/title; no arg opens picker",
+ " /title <name> rename the durable session",
+ " /status model/auth/context/token/session details",
+ " /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",
" /providers infrastructure provider status",
" /provider <id> configure dokploy|cloudflare|hostinger",
@@ -143,12 +122,26 @@ async function slash(rl, line, session) {
case "/session":
console.log(`${C.blue}${session.agentSession.id}${C.reset} · ${session.agentSession.title || "MSO Agent session"}`); return "handled";
case "/sessions":
- printSessions(await listCliSessions(20)); return "handled";
+ printSessions(await listCliSessions(50)); return "handled";
case "/resume":
- if (!args[0]) console.log("usage: /resume <session-id>");
- else await resumeInto(session, args[0]);
+ if (!args.length) await resumePicker(rl, session);
+ else await resumeInto(session, args.join(" "));
+ return "refresh";
+ case "/title": {
+ const title = args.join(" ").trim();
+ if (!title) console.log("usage: /title <session name>");
+ else { session.titleOverride = title.slice(0, 120); await persistSession(session); console.log(`${C.c}✓ session title: ${session.titleOverride}${C.reset}`); }
return "handled";
- case "/model": runCli(["model"]); session.state = await state(); return "refresh";
+ }
+ case "/status": case "/context": printDetailedStatus(session, C); return "handled";
+ case "/statusbar": {
+ const v = String(args[0] || "").toLowerCase();
+ if (v === "off") session.statusBar = false; else if (v === "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 "/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";
@@ -156,20 +149,12 @@ async function slash(rl, line, session) {
case "/tools": for (const tool of session.state.tools) console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`); return "handled";
case "/skills": printSkills(session, C, args.join(" ")); return "handled";
case "/skill": if (!args[0]) { console.log("usage: /skill <name-or-exact-id> [prompt]"); return "handled"; } return selectSlashSkill(rl, session, args[0], args.slice(1).join(" "));
- case "/clear": session.history = []; session.pendingSkill = null; await persist(session); console.log("conversation cleared."); return "handled";
+ case "/clear": session.history = []; session.pendingSkill = null; await persistSession(session); console.log("conversation cleared."); return "handled";
case "/exit": return "exit";
default: return selectSlashSkill(rl, session, cmd.slice(1), args.join(" "));
}
}
-function resumeArg(argv) {
- const index = argv.indexOf("--resume");
- if (index < 0) return null;
- const value = argv[index + 1];
- if (!value || value.startsWith("-")) throw new Error("--resume requires an MSO session id");
- return value;
-}
-
async function main() {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
console.error("mso agent needs an interactive terminal. For one-shot automation use: mso ai <prompt>");
@@ -178,7 +163,7 @@ async function main() {
const requested = resumeArg(process.argv.slice(2));
const [s, agentSession] = await Promise.all([
state(),
- requested ? loadCliSession(requested) : createCliSession(),
+ startupSession(requested),
]);
if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");
printBanner(s, agentSession);
@@ -187,6 +172,10 @@ async function main() {
agentSession,
history: Array.isArray(agentSession.history) ? agentSession.history.slice(-48) : [],
pendingSkill: null,
+ titleOverride: requested ? (agentSession.title || null) : null,
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
+ lastElapsedMs: 0,
+ statusBar: true,
};
const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C });
const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd());
@@ -195,6 +184,7 @@ async function main() {
let line = "";
try {
console.log();
+ if (session.statusBar) console.log(renderStatusBar(session, C));
const answer = await rl.question(`${C.blue}${C.bold}›${C.reset} `, { complete: completeSlash });
if (answer === null) break;
line = answer.trim();
@@ -216,14 +206,15 @@ async function main() {
const skillContext = session.pendingSkill;
session.pendingSkill = null;
await agentRound(rl, session, skillContext);
- await persist(session);
+ await persistSession(session);
} catch (error) {
console.error(`${C.err}agent error: ${error instanceof Error ? error.message : String(error)}${C.reset}`);
- await persist(session).catch(() => undefined);
+ await persistSession(session).catch(() => undefined);
}
}
} finally {
- await persist(session).catch(() => undefined);
+ await persistSession(session).catch(() => undefined);
+ console.log(`${C.dim}session ${session.agentSession.id} · resume: mso --continue | mso --resume ${session.agentSession.id}${C.reset}`);
rl.close();
}
}
diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.sh
index f9de1ad5..c3f71c53 100755
--- a/scripts/mso-cli-agent.sh
+++ b/scripts/mso-cli-agent.sh
@@ -8,6 +8,19 @@ provider_key_body() {
node -e 'const fs=require("fs"); const a=fs.readFileSync(0).toString("utf8").split("\0"); process.stdout.write(JSON.stringify({provider:a[0]||"",apiKey:a[1]||""}));'
}
+provider_key_body_unselected() {
+ node -e 'const fs=require("fs"); const a=fs.readFileSync(0).toString("utf8").split("\0"); process.stdout.write(JSON.stringify({provider:a[0]||"",apiKey:a[1]||"",select:false}));'
+}
+
+custom_provider_body_unselected() {
+ node -e '
+const fs=require("fs");
+const a=fs.readFileSync(0).toString("utf8").split("\0");
+const models=(a[4]||"").split(/[\n,]+/).map(x=>x.trim()).filter(Boolean);
+process.stdout.write(JSON.stringify({customProvider:{name:a[0]||"",baseURL:a[1]||"",protocol:a[2]||"openai",apiKey:a[3]||"",...(models.length?{models}:{})},select:false}));
+'
+}
+
onboard_infra() {
local yes="$1" choice
if [ "$yes" = 1 ]; then
@@ -32,12 +45,209 @@ ai_config_ready() {
jq -e '. as $c | ($c.hasApiKey == true or any($c.providers[]?; .id == $c.provider and .kind == "oauth"))' >/dev/null 2>&1
}
+ai_model_config() { jget "/api/config"; }
+
+ai_provider_connected() {
+ local provider="$1" cfg="${2:-}"
+ [ -n "$cfg" ] || cfg=$(ai_model_config)
+ jq -e --arg p "$provider" '
+ (.provider == $p and .hasApiKey == true) or
+ any(.providers[]?; .id == $p and (.hasKey == true or .kind == "oauth" or .kind == "custom"))
+ ' <<<"$cfg" >/dev/null 2>&1
+}
+
+print_ai_providers() {
+ local cfg="$1"
+ echo "AI providers/auth"
+ printf ' active %s/%s\n' "$(jq -r '.provider // "—"' <<<"$cfg")" "$(jq -r '.model // "—"' <<<"$cfg")"
+ if ! jq -e '.providers | length > 0' <<<"$cfg" >/dev/null 2>&1; then
+ echo " · no stored provider credentials yet"
+ else
+ jq -r --arg active "$(jq -r '.provider // ""' <<<"$cfg")" '.providers[] | [if .id == $active then "●" else "✓" end, .id, .kind, (.masked // (if .hasKey then "configured" else "" end))] | @tsv' <<<"$cfg" |
+ while IFS=$'\t' read -r mark id kind auth; do printf ' %s %-18s %-8s %s\n' "$mark" "$id" "$kind" "$auth"; done
+ fi
+ if [ "$(jq -r '.hasApiKey // false' <<<"$cfg")" = true ] && ! jq -e --arg p "$(jq -r '.provider // ""' <<<"$cfg")" 'any(.providers[]?; .id==$p)' <<<"$cfg" >/dev/null 2>&1; then
+ echo " ● $(jq -r '.provider' <<<"$cfg") env credential (active)"
+ fi
+}
+
+ai_model_catalog() {
+ local provider="$1" cfg="${2:-}"
+ [ -n "$cfg" ] || cfg=$(ai_model_config)
+ local data
+ data=$(jget "/api/models?provider=$(enc "$provider")")
+ # Custom providers may declare their own IDs even though models.dev has no slug for them.
+ if ! jq -e '.models | length > 0' <<<"$data" >/dev/null 2>&1; then
+ jq -nc --arg p "$provider" --argjson c "$cfg" '{models:[($c.providers[]? | select(.id==$p) | .models[]?) | {provider:$p,id:.,ref:($p+"/"+.),name:.}]}'
+ else
+ printf '%s\n' "$data"
+ fi
+}
+
+print_model_catalog() {
+ local provider="$1" cfg="$2" data current
+ data=$(ai_model_catalog "$provider" "$cfg")
+ current="$(jq -r '.model // ""' <<<"$cfg")"
+ if ! jq -e '.models | length > 0' <<<"$data" >/dev/null 2>&1; then
+ echo "No discoverable models for $provider. Check provider auth/network or declare custom models."
+ return 1
+ fi
+ printf '%-2s %-34s %-10s %-8s %-8s %s\n' '' 'MODEL' 'CONTEXT' 'TOOLS' 'REASON' 'NAME'
+ jq -r --arg current "$current" '.models[] | [if .id==$current then "●" else " " end,.id,((.context // 0)|tostring),(if .tools then "yes" else "—" end),(if .reasoning then "yes" else "—" end),(.name // .id)] | @tsv' <<<"$data" |
+ while IFS=$'\t' read -r mark id context tools reasoning name; do
+ [ "$context" = 0 ] && context="—"
+ printf '%-2s %-34s %-10s %-8s %-8s %s\n' "$mark" "${id:0:34}" "$context" "$tools" "$reasoning" "${name:0:45}"
+ done
+}
+
+configure_oauth_provider() {
+ local provider="$1" response code url interval poll
+ [ "$provider" = "openai-codex" ] || die "OAuth provider not supported yet: $provider"
+ response=$(jpost "/api/oauth/openai" '{"action":"start","select":false}')
+ code=$(jq -r '.userCode // empty' <<<"$response"); url=$(jq -r '.verificationUrl // empty' <<<"$response"); interval=$(jq -r '.intervalMs // 5000' <<<"$response")
+ [ -n "$code" ] && [ -n "$url" ] || die "OpenAI OAuth did not return a device code"
+ echo "Open this URL in any browser: $url"
+ echo "Enter code: $code"
+ echo "Waiting for authorization (active model will NOT change)..."
+ while true; do
+ sleep "$(( interval / 1000 > 2 ? interval / 1000 : 3 ))"
+ poll=$(jpost "/api/oauth/openai" '{"action":"poll","select":false}')
+ if [ "$(jq -r '.ok // false' <<<"$poll")" = true ]; then
+ echo " ✓ connected $(jq -r '.slug' <<<"$poll"); model selection unchanged"
+ return
+ fi
+ [ "$(jq -r '.pending // false' <<<"$poll")" = true ] || die "OpenAI OAuth failed: $poll"
+ tty_print "."
+ done
+}
+
+configure_ai_provider() {
+ local provider="$1" key body name base protocol models
+ case "$provider" in
+ chatgpt|codex) provider=openai-codex ;;
+ esac
+ case "$provider" in
+ openai-codex) configure_oauth_provider "$provider"; return ;;
+ custom)
+ tty_ok || die "custom provider setup needs an interactive terminal"
+ tty_line "Provider name: " ""; name="$REPLY"; [ -n "$name" ] || die "provider name required"
+ tty_line "Base URL (https://.../v1): " ""; base="$REPLY"; [ -n "$base" ] || die "base URL required"
+ tty_line "Protocol [openai|anthropic] [openai]: " "openai"; protocol="$REPLY"
+ case "$protocol" in openai|anthropic) ;; *) die "protocol must be openai or anthropic" ;; esac
+ tty_line "Models (comma/newline IDs; optional): " ""; models="$REPLY"
+ tty_secret "API key: "; key="$REPLY"; [ -n "$key" ] || die "empty API key"
+ body=$(printf '%s\0%s\0%s\0%s\0%s' "$name" "$base" "$protocol" "$key" "$models" | custom_provider_body_unselected)
+ secret_post "/api/config" "$body" >/dev/null
+ unset key body REPLY
+ echo " ✓ custom provider configured; active model unchanged"
+ return ;;
+ anthropic|openai|openrouter|google|groq|xai|deepseek|mistral) ;;
+ *) die "provider must be: openai-codex anthropic openai openrouter google groq xai deepseek mistral custom" ;;
+ esac
+ tty_ok || die "provider setup needs an interactive terminal"
+ tty_secret "Paste $provider API key: "; key="$REPLY"; [ -n "$key" ] || die "empty API key"
+ body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body_unselected)
+ secret_post "/api/config" "$body" >/dev/null
+ unset key body REPLY
+ echo " ✓ $provider configured; active model unchanged"
+}
+
+select_model_ref() {
+ local requested="$1" cfg provider model candidate data
+ cfg=$(ai_model_config)
+ provider=$(jq -r '.provider // ""' <<<"$cfg"); model="$requested"
+ # Model IDs themselves may contain slashes (notably OpenRouter). Prefer an exact
+ # match in the current provider before treating the first segment as a provider.
+ if [ -n "$provider" ] && ai_provider_connected "$provider" "$cfg" && jq -e --arg id "$requested" 'any(.models[]?; .id==$id)' <<<"$(ai_model_catalog "$provider" "$cfg")" >/dev/null 2>&1; then
+ model="$requested"
+ else
+ candidate="${requested%%/*}"
+ if [ "$candidate" != "$requested" ] && ai_provider_connected "$candidate" "$cfg"; then
+ provider="$candidate"; model="${requested#*/}"
+ fi
+ fi
+ [ -n "$provider" ] || die "no provider selected; run: mso models add <provider>"
+ ai_provider_connected "$provider" "$cfg" || die "$provider is not connected; run: mso models add $provider"
+ data=$(ai_model_catalog "$provider" "$cfg")
+ if ! jq -e --arg id "$model" 'any(.models[]?; .id==$id)' <<<"$data" >/dev/null 2>&1; then
+ echo "model '$model' is not in the available catalog for $provider" >&2
+ print_model_catalog "$provider" "$cfg" >&2 || true
+ return 2
+ fi
+ jpost "/api/config" "$(jq -nc --arg p "$provider" --arg m "$model" '{provider:$p,model:$m}')" >/dev/null
+ echo " ✓ active model: $provider/$model"
+}
+
run_model_setup() {
- ensure_local_cli_device
- ensure_onboard_runtime
- jget "/api/auth/me" >/dev/null
- tty_ok || die "mso model needs an interactive terminal"
- onboard_ai 0
+ local sub="${1:-}" cfg provider data choice count selected
+ ensure_local_cli_device; ensure_onboard_runtime; jget "/api/auth/me" >/dev/null
+ cfg=$(ai_model_config)
+ case "$sub" in
+ current|show)
+ printf '%s/%s\n' "$(jq -r '.provider // "—"' <<<"$cfg")" "$(jq -r '.model // "—"' <<<"$cfg")"; return ;;
+ list)
+ provider="${2:-$(jq -r '.provider // ""' <<<"$cfg")}"; [ -n "$provider" ] || die "no active provider"
+ ai_provider_connected "$provider" "$cfg" || die "$provider is not connected; run: mso models add $provider"
+ print_model_catalog "$provider" "$cfg"; return ;;
+ set)
+ [ -n "${2-}" ] || die "usage: mso model set <provider> <model> | mso model set <provider/model>"
+ if [ -n "${3-}" ]; then select_model_ref "$2/$3"; else select_model_ref "$2"; fi
+ return ;;
+ '') ;;
+ *) select_model_ref "$sub"; return ;;
+ esac
+ tty_ok || die "mso model without a ref needs an interactive terminal; use: mso model list"
+ echo "Active model: $(jq -r '.provider+"/"+.model' <<<"$cfg")"
+ echo "Connected providers:"
+ mapfile -t providers < <({ jq -r '.providers[]?.id' <<<"$cfg"; if [ "$(jq -r '.hasApiKey // false' <<<"$cfg")" = true ]; then jq -r '.provider' <<<"$cfg"; fi; } | awk 'NF && !seen[$0]++')
+ [ "${#providers[@]}" -gt 0 ] || die "no AI provider connected; run: mso models"
+ for i in "${!providers[@]}"; do printf ' %d) %s%s\n' "$((i+1))" "${providers[$i]}" "$([ "${providers[$i]}" = "$(jq -r '.provider' <<<"$cfg")" ] && printf ' [active]' || true)"; done
+ tty_line "Provider [1]: " 1; choice="$REPLY"; [[ "$choice" =~ ^[0-9]+$ ]] || die "choose a provider number"
+ selected=$((choice-1)); [ "$selected" -ge 0 ] && [ "$selected" -lt "${#providers[@]}" ] || die "provider choice out of range"
+ provider="${providers[$selected]}"
+ data=$(ai_model_catalog "$provider" "$cfg"); count=$(jq '.models|length' <<<"$data")
+ [ "$count" -gt 0 ] || die "no discoverable models for $provider"
+ echo; print_model_catalog "$provider" "$cfg"
+ echo
+ mapfile -t model_ids < <(jq -r '.models[].id' <<<"$data")
+ for i in "${!model_ids[@]}"; do printf ' %d) %s\n' "$((i+1))" "${model_ids[$i]}"; done
+ tty_line "Model [1]: " 1; choice="$REPLY"; [[ "$choice" =~ ^[0-9]+$ ]] || die "choose a model number"
+ selected=$((choice-1)); [ "$selected" -ge 0 ] && [ "$selected" -lt "${#model_ids[@]}" ] || die "model choice out of range"
+ select_model_ref "$provider/${model_ids[$selected]}"
+}
+
+run_models() {
+ local sub="${1:-}" cfg provider choice
+ ensure_local_cli_device; ensure_onboard_runtime; jget "/api/auth/me" >/dev/null
+ cfg=$(ai_model_config)
+ case "$sub" in
+ status|list) print_ai_providers "$cfg" ;;
+ add|auth)
+ provider="${2-}"; [ -n "$provider" ] || die "usage: mso models $sub <provider>"
+ configure_ai_provider "$provider" ;;
+ rm|remove)
+ provider="${2-}"; [ -n "$provider" ] || die "usage: mso models rm <provider>"
+ jdel "/api/config?provider=$(enc "$provider")" >/dev/null; echo " ✓ removed AI provider: $provider" ;;
+ catalog)
+ provider="${2:-$(jq -r '.provider // ""' <<<"$cfg")}"; [ -n "$provider" ] || die "provider required"
+ print_model_catalog "$provider" "$cfg" ;;
+ test) jpost "/api/models/test" ;;
+ '')
+ tty_ok || { print_ai_providers "$cfg"; return; }
+ print_ai_providers "$cfg"; echo
+ echo " 0) Done"
+ echo " 1) Add/auth provider"
+ echo " 2) Remove provider"
+ echo " 3) Browse model catalog"
+ tty_line "Choose [0]: " 0; choice="$REPLY"
+ case "$choice" in
+ 1) tty_line "Provider [openai-codex|anthropic|openai|openrouter|google|groq|xai|deepseek|mistral|custom]: " "openai-codex"; configure_ai_provider "$REPLY" ;;
+ 2) tty_line "Provider id: " ""; [ -n "$REPLY" ] && run_models rm "$REPLY" ;;
+ 3) tty_line "Provider [$(jq -r '.provider // ""' <<<"$cfg")]: " "$(jq -r '.provider // ""' <<<"$cfg")"; print_model_catalog "$REPLY" "$cfg" ;;
+ *) : ;;
+ esac ;;
+ *) die "usage: mso models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]" ;;
+ esac
}
provider_metadata() { jget "/api/v1/infra/providers"; }
@@ -118,10 +328,18 @@ run_agent() {
jget "/api/auth/me" >/dev/null
cfg=$(jget "/api/config")
if ! printf '%s' "$cfg" | ai_config_ready; then
- echo "MSO Agent needs an AI provider first."
- onboard_ai 0
+ if jq -e '.providers | length > 0' <<<"$cfg" >/dev/null 2>&1; then
+ echo "MSO Agent has connected provider credentials, but the active model is not usable yet."
+ run_model_setup
+ else
+ echo "MSO Agent needs an AI provider/auth connection first."
+ run_models
+ cfg=$(jget "/api/config")
+ jq -e '.providers | length > 0' <<<"$cfg" >/dev/null 2>&1 || die "no AI provider connected; run: mso models add <provider>"
+ run_model_setup
+ fi
cfg=$(jget "/api/config")
- printf '%s' "$cfg" | ai_config_ready || die "no AI provider connected; run `mso model` when ready"
+ printf '%s' "$cfg" | ai_config_ready || die "active model is not usable; run: mso models list && mso model"
fi
MSO_AGENT_BASE="$B" MSO_AGENT_ORIGIN="$B" MSO_AGENT_JAR="$JAR" \
MSO_AGENT_CLI="$ROOT/bin/mso" MSO_AGENT_VERSION="$VERSION" \
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
new file mode 100644
index 00000000..4d68ebb1
--- /dev/null
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -0,0 +1,45 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const root = path.resolve(__dirname, "..");
+const cli = fs.readFileSync(path.join(root, "bin/mso"), "utf8");
+const agentCli = fs.readFileSync(path.join(__dirname, "mso-cli-agent.sh"), "utf8");
+const configRoute = fs.readFileSync(path.join(root, "app/api/config/route.ts"), "utf8");
+const oauthRoute = fs.readFileSync(path.join(root, "app/api/oauth/[provider]/route.ts"), "utf8");
+const slash = fs.readFileSync(path.join(__dirname, "mso-agent-slash.mjs"), "utf8");
+
+const all = [cli, agentCli, configRoute, oauthRoute, slash].join("\n");
+
+describe("MSO model/provider/session CLI contract", () => {
+ it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
+ expect(cli).toContain('VERSION="1.5.5"');
+ expect(cli).toContain("models * Configure AI providers/auth");
+ expect(cli).toContain("model [ref] Select active model");
+ expect(agentCli).toContain("run_models()");
+ expect(agentCli).toContain("run_model_setup()");
+ expect(agentCli).toContain("provider_key_body_unselected");
+ expect(agentCli).toContain("custom_provider_body_unselected");
+ expect(all).toContain("select:false");
+ expect(configRoute).toContain("body.select !== false");
+ expect(oauthRoute).toContain("body.select !== false");
+ expect(slash).toContain('text: "/models", meta: "Configure AI providers and authentication"');
+ expect(slash).toContain('text: "/model", meta: "Select the active model from connected providers"');
+ });
+
+ it("supports explicit and slash-containing model IDs without losing provider intent", () => {
+ expect(agentCli).toContain("Model IDs themselves may contain slashes");
+ expect(agentCli).toContain("mso model set <provider> <model>");
+ expect(agentCli).toContain("any(.models[]?; .id==$id)");
+ expect(agentCli).toContain('select_model_ref "$2/$3"');
+ });
+
+ it("makes durable session continuation a first-class CLI startup path", () => {
+ expect(cli).toContain("--continue|-c");
+ expect(cli).toContain("--resume|-r");
+ expect(cli).toContain('AGENT_START_ARGS+=("--continue")');
+ expect(cli).toContain('AGENT_START_ARGS+=("--resume" "$2")');
+ expect(slash).toContain('text: "/resume"');
+ expect(slash).toContain('text: "/status"');
+ });
+});