Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent): persist terminal and MCP sessions
Rahman9721687fad2d
diff --git a/.env.example b/.env.exampleindex d60a5471..6dd01acc 100644--- a/.env.example+++ b/.env.example@@ -201,8 +201,10 @@ OS_SESSION_SECRET=# OS_DEVICE_STORE=~/.mso/auth-devices.json # approved devices + live roles# OS_CONFIG_STORE=~/.mso/config.json # BYOK key + model# OS_PREFS_PATH=~/.mso/prefs.json # synced UI prefs (theme, layout)-# OS_MEMORY_STORE=~/.mso/memory.json # assistant long-term memory-# OS_THREADS_DIR=~/.mso/threads # assistant chat threads (one file each)+# OS_MEMORY_STORE=~/.mso/memory.json # Alfa assistant long-term memory+# OS_THREADS_DIR=~/.mso/threads # Alfa assistant chat threads (one file each)+# OS_AGENT_MEMORY_DIR=~/.mso/agent-memory # isolated MSO Agent USER.md/MEMORY.md stores+# OS_AGENT_SESSIONS_DIR=~/.mso/agent-sessions # durable CLI/MCP agent session records# Owner-private Dokploy/Cloudflare/Hostinger connection state. Defaults to the path# below; normally leave it there so the 0700 directory + 0600 file policy applies.# OS_INFRA_STORE=~/.mso/private/infra-providers.jsondiff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.tsnew file mode 100644index 00000000..f872fb48--- /dev/null+++ b/app/api/v1/agent-sessions/route.ts@@ -0,0 +1,58 @@+import { NextRequest, NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import {+ agentSessionSummary,+ createAgentSession,+ getAgentSession,+ listAgentSessions,+ updateAgentSessionHistory,+} from "@/lib/agent/session-store";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++async function ownerPrincipal(): Promise<string | null> {+ const context = await getSessionContext();+ return context?.role === "owner" ? `cli:${context.session.device_id}` : null;+}++export async function GET(req: NextRequest) {+ const principal = await ownerPrincipal();+ if (!principal) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });+ const id = req.nextUrl.searchParams.get("id")?.trim();+ if (id) {+ try {+ const session = await getAgentSession(principal, id);+ if (!session) return NextResponse.json({ error: "session_not_found" }, { status: 404 });+ return NextResponse.json({ session });+ } catch {+ return NextResponse.json({ error: "invalid_session_id" }, { status: 400 });+ }+ }+ const limit = Math.max(1, Math.min(100, Number(req.nextUrl.searchParams.get("limit")) || 30));+ return NextResponse.json({ sessions: await listAgentSessions(principal, limit) });+}++export async function POST(req: NextRequest) {+ const principal = await ownerPrincipal();+ if (!principal) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });+ let body: { action?: string; id?: string; title?: string; history?: unknown[] };+ try { body = await req.json(); } catch { return NextResponse.json({ error: "invalid_request" }, { status: 400 }); }++ try {+ if (body.action === "create") {+ const session = await createAgentSession(principal, "cli", { title: body.title });+ return NextResponse.json({ session });+ }+ if (body.action === "update") {+ if (!body.id || !Array.isArray(body.history)) return NextResponse.json({ error: "id_and_history_required" }, { status: 400 });+ const session = await updateAgentSessionHistory(principal, body.id, body.history, body.title);+ return NextResponse.json({ session: agentSessionSummary(session) });+ }+ return NextResponse.json({ error: "unknown_action" }, { status: 400 });+ } catch (error) {+ const message = error instanceof Error ? error.message : "agent session failed";+ if (message.includes("not found")) return NextResponse.json({ error: "session_not_found" }, { status: 404 });+ return NextResponse.json({ error: message.slice(0, 200) }, { status: 400 });+ }+}diff --git a/app/api/v1/agent-tools/route.test.ts b/app/api/v1/agent-tools/route.test.tsindex af451ac1..e40de336 100644--- a/app/api/v1/agent-tools/route.test.ts+++ b/app/api/v1/agent-tools/route.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { canonicalAgentApproval } from "@/lib/agent/approval.js";+import { canonicalAgentApproval } from "@/lib/agent/approval.mjs";const contextRef: { current: null | { role: string; session: { device_id: string } } } = {current: { role: "owner", session: { device_id: "dev-owner" } },@@ -9,6 +9,9 @@ const dispatchMock = vi.fn();vi.mock("@/lib/auth/require-session", () => ({getSessionContext: vi.fn(async () => contextRef.current),}));+vi.mock("@/lib/agent/session-store", () => ({+ getAgentSession: vi.fn(async (_principal: string, id: string) => ({ id, source: "cli" })),+}));vi.mock("@/lib/mcp/dispatch", () => ({dispatch: (...args: unknown[]) => dispatchMock(...args),}));@@ -74,7 +77,7 @@ describe("/api/v1/agent-tools", () => {it("refuses a mutation unless the terminal explicitly approved it", async () => {const { POST } = await import("./route");- const res = await POST(postReq({ name: "write_tool", input: { name: "x" } }));+ const res = await POST(postReq({ name: "write_tool", input: { name: "x" }, sessionId: "mso_test_session" }));expect(res.status).toBe(409);await expect(res.json()).resolves.toMatchObject({ error: "explicit_agent_approval_required", scope: "write" });expect(dispatchMock).not.toHaveBeenCalled();@@ -88,6 +91,7 @@ describe("/api/v1/agent-tools", () => {input: { name: "x", nested: { safe: false } },approved: true,approvalDigest: approved.digest,+ sessionId: "mso_test_session",}));expect(res.status).toBe(409);await expect(res.json()).resolves.toMatchObject({ error: "agent_approval_payload_mismatch", scope: "write" });@@ -99,13 +103,14 @@ describe("/api/v1/agent-tools", () => {const input = { name: "x" };const approvalDigest = canonicalAgentApproval("write_tool", input).digest;const { POST } = await import("./route");- const res = await POST(postReq({ name: "write_tool", input, approved: true, approvalDigest }));+ const res = await POST(postReq({ name: "write_tool", input, approved: true, approvalDigest, sessionId: "mso_test_session" }));expect(res.status).toBe(200);await expect(res.json()).resolves.toMatchObject({ ok: true, result: "done" });expect(dispatchMock).toHaveBeenCalledWith(expect.objectContaining({ method: "tools/call", params: { name: "write_tool", arguments: { name: "x" } } }),"exec","cli:dev-owner",+ { principal: "cli:dev-owner", sessionId: "mso_test_session" },);});});diff --git a/app/api/v1/agent-tools/route.ts b/app/api/v1/agent-tools/route.tsindex 1a20b19f..8019e348 100644--- a/app/api/v1/agent-tools/route.ts+++ b/app/api/v1/agent-tools/route.ts@@ -1,5 +1,6 @@import { NextRequest, NextResponse } from "next/server";-import { matchesAgentApproval } from "@/lib/agent/approval.js";+import { matchesAgentApproval } from "@/lib/agent/approval.mjs";+import { getAgentSession } from "@/lib/agent/session-store";import { getSessionContext } from "@/lib/auth/require-session";import { dispatch } from "@/lib/mcp/dispatch";import { maxScope, allows } from "@/lib/mcp/scope";@@ -30,11 +31,20 @@ export async function GET() {export async function POST(req: NextRequest) {const context = await ownerContext();if (!context) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });- let body: { name?: string; input?: Record<string, unknown>; approved?: boolean; approvalDigest?: string };+ let body: { name?: string; input?: Record<string, unknown>; approved?: boolean; approvalDigest?: string; sessionId?: string };try { body = await req.json(); } catch { return NextResponse.json({ error: "invalid_request" }, { status: 400 }); }const name = String(body.name ?? "");const tool = TOOLS.find((entry) => entry.name === name);if (!tool) return NextResponse.json({ error: `unknown tool: ${name}` }, { status: 404 });+ const principal = `cli:${context.session.device_id}`;+ const sessionId = String(body.sessionId ?? "").trim();+ if (!sessionId) return NextResponse.json({ error: "agent_session_required" }, { status: 400 });+ let agentSession;+ try { agentSession = await getAgentSession(principal, sessionId); }+ catch { return NextResponse.json({ error: "invalid_agent_session" }, { status: 400 }); }+ if (!agentSession || agentSession.source !== "cli") {+ return NextResponse.json({ error: "agent_session_not_found" }, { status: 404 });+ }const scope = maxScope();if (!allows(scope, tool.scope)) return NextResponse.json({ error: `deployment scope ${scope} does not allow ${tool.scope}` }, { status: 403 });if (tool.scope !== "read") {@@ -43,7 +53,12 @@ export async function POST(req: NextRequest) {return NextResponse.json({ error: "agent_approval_payload_mismatch", tool: name, scope: tool.scope }, { status: 409 });}}- const rpc = await dispatch({ id: "cli-call", method: "tools/call", params: { name, arguments: body.input ?? {} } }, scope, `cli:${context.session.device_id}`);+ const rpc = await dispatch(+ { id: "cli-call", method: "tools/call", params: { name, arguments: body.input ?? {} } },+ scope,+ principal,+ { principal, sessionId },+ );const result = (rpc.result ?? {}) as { content?: Array<{ type?: string; text?: string }>; isError?: boolean };if ((rpc as { error?: unknown }).error) return NextResponse.json(rpc, { status: 400 });const text = (result.content ?? []).filter((row) => row.type === "text").map((row) => row.text ?? "").join("\n");diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex aaa95b30..21ce7bbe 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -8,6 +8,8 @@ const mocks = vi.hoisted(() => ({rateLimited: vi.fn(() => false),rateLimitedUntrusted: vi.fn(() => false),mcpRequestOriginAllowed: vi.fn(() => true),+ createAgentSession: vi.fn(),+ getAgentSession: vi.fn(),}));vi.mock("@/lib/mcp/store", () => ({@@ -39,11 +41,15 @@ vi.mock("@/lib/host", () => ({}));vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}) }));+vi.mock("@/lib/agent/session-store", () => ({+ createAgentSession: mocks.createAgentSession,+ getAgentSession: mocks.getAgentSession,+}));function request(body: BodyInit, headers: Record<string, string> = {}) {return new Request("https://mso.example.test/mcp", {method: "POST",- headers: { authorization: "Bearer live-token", "content-type": "application/json", ...headers },+ headers: { authorization: "Bearer live-token", "content-type": "application/json", "Mcp-Session-Id": "mso_test_session", ...headers },body,// Required by Node when a ReadableStream is supplied; harmless for string bodies.duplex: "half",@@ -59,6 +65,8 @@ describe("/mcp request boundary", () => {mocks.rateLimited.mockClear().mockReturnValue(false);mocks.rateLimitedUntrusted.mockClear().mockReturnValue(false);mocks.mcpRequestOriginAllowed.mockClear().mockReturnValue(true);+ mocks.createAgentSession.mockReset().mockResolvedValue({ id: "mso_initialized", source: "mcp" });+ mocks.getAgentSession.mockReset().mockImplementation(async (_principal: string, id: string) => ({ id, source: "mcp" }));});afterEach(() => vi.unstubAllEnvs());@@ -124,7 +132,7 @@ describe("/mcp request boundary", () => {});it("clamps a previously issued token to the deployment ceiling on every call", async () => {- const token = { hash: "c".repeat(64), scope: "exec" as const };+ const token = { hash: "c".repeat(64), scope: "exec" as const, clientId: "client-clamp", label: "Clamp test" };mocks.validateToken.mockResolvedValueOnce(token);mocks.clampScope.mockReturnValueOnce("read");const { POST } = await import("./route");@@ -132,11 +140,16 @@ describe("/mcp request boundary", () => {const res = await POST(request(JSON.stringify(body)));expect(res.status).toBe(200);expect(mocks.clampScope).toHaveBeenCalledWith("exec");- expect(mocks.dispatch).toHaveBeenCalledWith(body, "read", `mcp:${token.hash.slice(0, 16)}`);+ expect(mocks.dispatch).toHaveBeenCalledWith(+ body,+ "read",+ `mcp:${token.hash.slice(0, 16)}`,+ { principal: `mcp-client:${token.clientId}`, sessionId: "mso_test_session" },+ );});it("applies the 50,000-call daily token limit", async () => {- const token = { hash: "d".repeat(64), scope: "read" as const };+ const token = { hash: "d".repeat(64), scope: "read" as const, clientId: "client-daily", label: "Daily test" };mocks.validateToken.mockResolvedValueOnce(token);const { POST } = await import("./route");await POST(request(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })));diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex 4b5a2c53..d37ffa02 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -1,10 +1,11 @@-import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED } from "@/lib/mcp/dispatch";+import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED, type RpcRequest } from "@/lib/mcp/dispatch";import { validateToken, touchToken } from "@/lib/mcp/store";import { clampScope, mcpEnabled } from "@/lib/mcp/scope";import { publicOrigin, clientIp, mcpRequestOriginAllowed } from "@/lib/mcp/origin";import { rateLimited, rateLimitedUntrusted } from "@/lib/host";import { TOOLS } from "@/lib/mcp/tools";import { toolsetInfo } from "@/lib/mcp/toolset";+import { createAgentSession, getAgentSession } from "@/lib/agent/session-store";// The MCP endpoint. Deliberately at /mcp and NOT under /api: proxy.ts blocks// mutating /api that cannot prove same-origin, and an MCP client is by definition@@ -16,6 +17,7 @@ export const dynamic = "force-dynamic";const CALLS_PER_MIN = 120;const CALLS_PER_DAY = 50_000;const PREAUTH_PER_MIN = 240;+const MCP_SESSION_HEADER = "Mcp-Session-Id";export const MAX_MCP_BODY_BYTES = 2 * 1024 * 1024;class BodyTooLarge extends Error {}@@ -50,6 +52,46 @@ async function parseBoundedJson(req: Request): Promise<unknown> {}}+async function resolveAgentSession(+ req: Request,+ body: RpcRequest,+ principal: string,+ label: string,+): Promise<{ sessionId: string } | { response: Response }> {+ try {+ if (body.method === "initialize") {+ const session = await createAgentSession(principal, "mcp", { title: `ChatGPT/MCP · ${label || "MSO"}` });+ return { sessionId: session.id };+ }+ const sessionId = (req.headers.get(MCP_SESSION_HEADER) ?? "").trim();+ if (!sessionId) {+ return {+ response: Response.json(+ { jsonrpc: "2.0", id: body.id ?? null, error: { code: -32600, message: "missing MCP session id; initialize the connection again" } },+ { status: 400, headers: { "Cache-Control": "no-store" } },+ ),+ };+ }+ const session = await getAgentSession(principal, sessionId);+ if (!session || session.source !== "mcp") {+ return {+ response: Response.json(+ { jsonrpc: "2.0", id: body.id ?? null, error: { code: -32600, message: "unknown MCP session id for this client" } },+ { status: 404, headers: { "Cache-Control": "no-store" } },+ ),+ };+ }+ return { sessionId };+ } catch {+ return {+ response: Response.json(+ { jsonrpc: "2.0", id: body.id ?? null, error: { code: -32603, message: "could not establish MSO agent session" } },+ { status: 500, headers: { "Cache-Control": "no-store" } },+ ),+ };+ }+}+export async function POST(req: Request) {const origin = publicOrigin(req);const challenge = `Bearer realm="mso", resource_metadata="${origin}/.well-known/oauth-protected-resource"`;@@ -78,8 +120,6 @@ export async function POST(req: Request) {if (rateLimited(`mcp:tok:${token.hash}`, CALLS_PER_MIN, 60_000)) {return Response.json(rpcError(null, RATE_LIMITED, "rate limited — retry in 60s"), { status: 429, headers: { "Retry-After": "60" } });}- // Per-minute alone still allows ~172k calls/day from one runaway agent, on an- // endpoint whose top scope is a shell. The daily cap is the backstop.if (rateLimited(`mcp:day:${token.hash}`, CALLS_PER_DAY, 86_400_000)) {return Response.json(rpcError(null, RATE_LIMITED, "daily call limit reached for this token"), { status: 429, headers: { "Retry-After": "3600" } });}@@ -97,15 +137,22 @@ export async function POST(req: Request) {return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }, { status: 400 });}+ const rpc = body as RpcRequest;+ const principal = `mcp-client:${token.clientId}`;+ const resolved = await resolveAgentSession(req, rpc, principal, token.label);+ if ("response" in resolved) return resolved.response;+ const sessionHeaders = { "Cache-Control": "no-store", [MCP_SESSION_HEADER]: resolved.sessionId };+// Ack EVERY authenticated notification, not just notifications/initialized — a// client that sends notifications/cancelled hangs waiting for a response otherwise.- if (isNotification(body)) return new Response(null, { status: 202 });+ if (isNotification(body)) return new Response(null, { status: 202, headers: sessionHeaders });void touchToken(token.hash).catch(() => {});- // Same 16-char id the Settings table and `mso mcp list` show, so an audit line- // maps straight back to the token you would revoke.- const result = await dispatch(body as Parameters<typeof dispatch>[0], effectiveScope, `mcp:${token.hash.slice(0, 16)}`);- return Response.json(result, { status: 200, headers: { "Cache-Control": "no-store" } });+ // Audit actor remains token-specific, while agent principal is client-specific so+ // a refreshed bearer can resume the same client's sessions without weakening audit identity.+ const actor = `mcp:${token.hash.slice(0, 16)}`;+ const result = await dispatch(rpc, effectiveScope, actor, { principal, sessionId: resolved.sessionId });+ return Response.json(result, { status: 200, headers: sessionHeaders });}// Some clients probe with GET before POSTing. Answer with what this is, never@@ -119,6 +166,7 @@ export async function GET(req: Request) {name: "mso MCP",transport: "streamable-http (JSON-RPC over POST)",auth: "Bearer <mcp token> — obtain via OAuth 2.1 + PKCE",+ sessions: "durable Mcp-Session-Id; use agent_sessions_list / agent_session_resume across ChatGPT conversations",authorization_servers: [publicOrigin(req)],toolset: toolsetInfo(TOOLS),});diff --git a/bin/mso b/bin/msoindex 1452e2cd..54857ae2 100755--- a/bin/mso+++ b/bin/mso@@ -63,6 +63,7 @@# AI + state# ai <prompt…> One turn with the assistant# 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# prefs * UI preferences: show | set@@ -676,6 +677,7 @@ U_service="service status|start|stop|restart|logs [n]"U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"U_update="update [--rebuild] | status | log"U_threads="threads list|show <id>|save <json>|rm <id>"+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>"@@ -858,7 +860,7 @@ case "$cmd" in[ "$fails" -eq 0 ] && echo "all good." || echo "$fails check(s) failed."exit $(( fails > 0 ? 1 : 0 )) ;;- agent|chat) run_agent ;;+ agent|chat) run_agent "$@" ;;model) run_model_setup ;;setup) run_onboard "${1-}" ;;onboard) run_onboard "${1-}" ;;@@ -928,6 +930,13 @@ case "$cmd" inrm) jdel "/api/threads?id=$(enc "${2:?id}")" ;;*) die "usage: mso $U_threads" ;;esac ;;+ agent-sessions)+ case "${1:-list}" in+ list) jget "/api/v1/agent-sessions${2:+?limit=$(enc "$2")}" ;;+ show) jget "/api/v1/agent-sessions?id=$(enc "${2:?id}")" ;;+ create) jpost "/api/v1/agent-sessions" "$(jq -n --arg title "${2:-MSO Agent session}" '{action:"create",title:$title}')" ;;+ *) die "usage: mso $U_agent_sessions" ;;+ esac ;;memory)case "${1:-list}" inlist) jget "/api/memory" ;;diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex d160321b..1c83df16 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,8 +8,14 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `agent` persist terminal and MCP sessions+- `mcp` render live workflow progress in ChatGPT- `cli` add MSO folder ASCII icon+**Fixed**++- `mcp` preserve app-only workflow status schema+## 2026-08-31**Added**diff --git a/docs/CLI.md b/docs/CLI.mdindex 4dd1f8ca..0682987d 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -103,6 +103,7 @@ Commands:AI + stateai <prompt…> One turn with the assistantthreads * Conversation history: list | show | rm+ agent-sessions * Durable MSO Agent sessions: list | show | creatememory * Assistant memories: list | add | rmconfig * BYOK provider + model/style: show | set | key | style | rmprefs * UI preferences: show | setdiff --git a/lib/agent/approval.js b/lib/agent/approval.mjssimilarity index 100%rename from lib/agent/approval.jsrename to lib/agent/approval.mjsdiff --git a/lib/agent/approval.test.ts b/lib/agent/approval.test.tsindex 42e30206..b1552944 100644--- a/lib/agent/approval.test.ts+++ b/lib/agent/approval.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { canonicalAgentApproval, matchesAgentApproval, MAX_AGENT_APPROVAL_BYTES } from "./approval.js";+import { canonicalAgentApproval, matchesAgentApproval, MAX_AGENT_APPROVAL_BYTES } from "./approval.mjs";describe("agent approval binding", () => {it("renders every nested field losslessly in a stable canonical order", () => {diff --git a/lib/agent/memory-store.ts b/lib/agent/memory-store.tsnew file mode 100644index 00000000..436ec8d1--- /dev/null+++ b/lib/agent/memory-store.ts@@ -0,0 +1,136 @@+import { createHash, randomUUID } from "node:crypto";+import { constants as fsConstants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";++export type AgentMemoryDocument = "USER.md" | "MEMORY.md";+export interface AgentMemorySnapshot {+ capturedAt: string;+ user: string;+ memory: string;+}++const ROOT = path.resolve(process.env.OS_AGENT_MEMORY_DIR || path.join(os.homedir(), ".mso", "agent-memory"));+const MAX_DOC_BYTES = 64 * 1024;+const KEY_RE = /^[^\r\n]{1,80}$/;++function principalKey(principal: string): string {+ if (!principal || principal.length > 512) throw new Error("invalid agent memory principal");+ return createHash("sha256").update(principal).digest("hex").slice(0, 32);+}++function dirFor(principal: string): string {+ return path.join(ROOT, principalKey(principal));+}++function fileFor(principal: string, document: AgentMemoryDocument): string {+ if (document !== "USER.md" && document !== "MEMORY.md") throw new Error("invalid memory document");+ return path.join(dirFor(principal), document);+}++async function readDocument(principal: string, document: AgentMemoryDocument): Promise<string> {+ const file = fileFor(principal, document);+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;+ try {+ handle = await fs.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);+ const stat = await handle.stat();+ if (!stat.isFile()) throw new Error("agent memory must be a regular file");+ if (stat.size > MAX_DOC_BYTES) throw new Error("agent memory document is too large");+ if ((stat.mode & 0o077) !== 0) throw new Error("agent memory permissions are too broad; expected 0600");+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("agent memory is not owned by the MSO user");+ return await handle.readFile("utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";+ throw error;+ } finally {+ await handle?.close().catch(() => undefined);+ }+}++async function writeDocument(principal: string, document: AgentMemoryDocument, content: string): Promise<void> {+ if (Buffer.byteLength(content, "utf8") > MAX_DOC_BYTES) throw new Error("agent memory document exceeds 64 KiB");+ const file = fileFor(principal, document);+ const dir = path.dirname(file);+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });+ await fs.chmod(ROOT, 0o700).catch(() => undefined);+ await fs.chmod(dir, 0o700).catch(() => undefined);+ const tmp = `${file}.${randomUUID()}.tmp`;+ await fs.writeFile(tmp, content, { encoding: "utf8", mode: 0o600, flag: "wx" });+ await fs.chmod(tmp, 0o600);+ await fs.rename(tmp, file);+ await fs.chmod(file, 0o600);+}++function cleanKey(key: string): string {+ const normalized = key.trim();+ if (!KEY_RE.test(normalized) || normalized.startsWith("#")) throw new Error("memory key must be one line, 1-80 characters");+ return normalized;+}++function cleanValue(value: string): string {+ const normalized = value.trim();+ if (!normalized || Buffer.byteLength(normalized, "utf8") > 8 * 1024) throw new Error("memory value must be 1-8192 bytes");+ return normalized;+}++function replaceSection(source: string, key: string, value: string | null): string {+ const lines = source.replace(/\r\n/g, "\n").split("\n");+ const heading = `## ${key}`;+ const start = lines.findIndex((line) => line === heading);+ let next = lines.length;+ if (start >= 0) {+ for (let i = start + 1; i < lines.length; i++) {+ if (lines[i].startsWith("## ")) { next = i; break; }+ }+ lines.splice(start, next - start);+ }+ if (value !== null) {+ while (lines.length && !lines.at(-1)?.trim()) lines.pop();+ if (lines.length) lines.push("");+ lines.push(heading, value, "");+ }+ return lines.join("\n").trim() ? `${lines.join("\n").trim()}\n` : "";+}++export async function snapshotAgentMemory(principal: string): Promise<AgentMemorySnapshot> {+ const [user, memory] = await Promise.all([+ readDocument(principal, "USER.md"),+ readDocument(principal, "MEMORY.md"),+ ]);+ return { capturedAt: new Date().toISOString(), user, memory };+}++export async function readAgentMemory(principal: string): Promise<AgentMemorySnapshot> {+ return snapshotAgentMemory(principal);+}++export async function rememberAgentMemory(+ principal: string,+ document: AgentMemoryDocument,+ key: string,+ value: string,+): Promise<AgentMemorySnapshot> {+ const safeKey = cleanKey(key);+ const safeValue = cleanValue(value);+ const file = fileFor(principal, document);+ await withSecurityStoreLock(file, async () => {+ const current = await readDocument(principal, document);+ await writeDocument(principal, document, replaceSection(current, safeKey, safeValue));+ });+ return snapshotAgentMemory(principal);+}++export async function forgetAgentMemory(+ principal: string,+ document: AgentMemoryDocument,+ key: string,+): Promise<AgentMemorySnapshot> {+ const safeKey = cleanKey(key);+ const file = fileFor(principal, document);+ await withSecurityStoreLock(file, async () => {+ const current = await readDocument(principal, document);+ await writeDocument(principal, document, replaceSection(current, safeKey, null));+ });+ return snapshotAgentMemory(principal);+}diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.tsnew file mode 100644index 00000000..62513447--- /dev/null+++ b/lib/agent/session-store.ts@@ -0,0 +1,227 @@+import { createHash, randomBytes, randomUUID } from "node:crypto";+import { constants as fsConstants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { snapshotAgentMemory } from "./memory-store";++import type {+ AgentSession, AgentSessionEvent, AgentSessionResumePacket, AgentSessionSource, AgentSessionSummary,+} from "./session-types";+export type { AgentSession, AgentSessionEvent, AgentSessionResumePacket, AgentSessionSource, AgentSessionSummary } from "./session-types";++const ROOT = path.resolve(process.env.OS_AGENT_SESSIONS_DIR || path.join(os.homedir(), ".mso", "agent-sessions"));+const LOCK_TARGET = path.join(ROOT, ".sessions");+const SESSION_ID = /^\d{8}_\d{6}_[a-f0-9]{8}$/;+const MAX_SESSION_BYTES = 512 * 1024;+const MAX_EVENTS = 200;+const MAX_HISTORY = 48;+const MAX_LIST = 200;++function principalHash(principal: string): string {+ if (!principal || principal.length > 512) throw new Error("invalid agent session principal");+ return createHash("sha256").update(principal).digest("hex");+}++function fileFor(id: string): string {+ if (!SESSION_ID.test(id)) throw new Error("invalid agent session id");+ const candidate = path.resolve(ROOT, `${id}.json`);+ const relative = path.relative(ROOT, candidate);+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error("invalid agent session id");+ return candidate;+}++function sessionId(now = new Date()): string {+ const iso = now.toISOString();+ const date = iso.slice(0, 10).replaceAll("-", "");+ const time = iso.slice(11, 19).replaceAll(":", "");+ return `${date}_${time}_${randomBytes(4).toString("hex")}`;+}++function safeTitle(value: string | undefined): string {+ const text = String(value ?? "MSO Agent session").replace(/[\r\n\t]+/g, " ").trim();+ return (text || "MSO Agent session").slice(0, 120);+}++function safeDetail(value: string | undefined): string | undefined {+ const text = String(value ?? "").replace(/[\r\n\t]+/g, " ").trim();+ return text ? text.slice(0, 500) : undefined;+}++function normalizeRecord(raw: AgentSession): AgentSession {+ return {+ ...raw,+ title: safeTitle(raw.title),+ history: Array.isArray(raw.history) ? raw.history.slice(-MAX_HISTORY) : [],+ events: Array.isArray(raw.events) ? raw.events.slice(-MAX_EVENTS) : [],+ };+}++async function readFile(id: string): Promise<AgentSession | null> {+ const file = fileFor(id);+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;+ try {+ handle = await fs.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);+ const stat = await handle.stat();+ if (!stat.isFile()) throw new Error("agent session must be a regular file");+ if (stat.size <= 0 || stat.size > MAX_SESSION_BYTES) throw new Error("agent session has an invalid size");+ if ((stat.mode & 0o077) !== 0) throw new Error("agent session permissions are too broad; expected 0600");+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("agent session is not owned by the MSO user");+ const raw = JSON.parse(await handle.readFile("utf8")) as AgentSession;+ if (!raw || raw.id !== id || !raw.principalHash || !raw.source) throw new Error("agent session has an invalid shape");+ return normalizeRecord(raw);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw error;+ } finally {+ await handle?.close().catch(() => undefined);+ }+}++async function writeFile(record: AgentSession): Promise<void> {+ await fs.mkdir(ROOT, { recursive: true, mode: 0o700 });+ await fs.chmod(ROOT, 0o700).catch(() => undefined);+ const file = fileFor(record.id);+ const normalized = normalizeRecord(record);+ const body = JSON.stringify(normalized, null, 2);+ if (Buffer.byteLength(body, "utf8") > MAX_SESSION_BYTES) throw new Error("agent session exceeds 512 KiB");+ const tmp = `${file}.${randomUUID()}.tmp`;+ await fs.writeFile(tmp, body, { encoding: "utf8", mode: 0o600, flag: "wx" });+ await fs.chmod(tmp, 0o600);+ await fs.rename(tmp, file);+ await fs.chmod(file, 0o600);+}++function summary(record: AgentSession): AgentSessionSummary {+ return {+ id: record.id,+ source: record.source,+ title: record.title,+ createdAt: record.createdAt,+ updatedAt: record.updatedAt,+ ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),+ eventCount: record.events.length,+ historyTurns: record.history.length,+ };+}++async function requireOwned(principal: string, id: string): Promise<AgentSession> {+ const record = await readFile(id);+ if (!record || record.principalHash !== principalHash(principal)) throw new Error("agent session not found for this client");+ return record;+}++export async function createAgentSession(+ principal: string,+ source: AgentSessionSource,+ options: { title?: string; resumedFrom?: string } = {},+): Promise<AgentSession> {+ const id = sessionId();+ const now = new Date().toISOString();+ const memorySnapshot = await snapshotAgentMemory(principal);+ const record: AgentSession = {+ id,+ principalHash: principalHash(principal),+ source,+ title: safeTitle(options.title),+ createdAt: now,+ updatedAt: now,+ ...(options.resumedFrom ? { resumedFrom: options.resumedFrom } : {}),+ memorySnapshot,+ history: [],+ events: [{ at: now, kind: "created", detail: options.resumedFrom ? `resumed from ${options.resumedFrom}` : undefined }],+ };+ await withSecurityStoreLock(LOCK_TARGET, async () => writeFile(record));+ return record;+}++export async function getAgentSession(principal: string, id: string): Promise<AgentSession | null> {+ const record = await readFile(id);+ if (!record || record.principalHash !== principalHash(principal)) return null;+ return record;+}++export async function listAgentSessions(principal: string, limit = 30): Promise<AgentSessionSummary[]> {+ const wanted = Math.max(1, Math.min(MAX_LIST, Math.trunc(limit) || 30));+ let names: string[];+ try { names = await fs.readdir(ROOT); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw error;+ }+ const owner = principalHash(principal);+ const out: AgentSessionSummary[] = [];+ for (const name of names) {+ if (!name.endsWith(".json")) continue;+ const id = name.slice(0, -5);+ if (!SESSION_ID.test(id)) continue;+ try {+ const record = await readFile(id);+ if (record?.principalHash === owner) out.push(summary(record));+ } catch {+ // A corrupt/unowned row must never make another session visible or take the list endpoint down.+ }+ }+ return out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, wanted);+}++export async function updateAgentSessionHistory(+ principal: string,+ id: string,+ history: unknown[],+ title?: string,+): Promise<AgentSession> {+ return withSecurityStoreLock(LOCK_TARGET, async () => {+ const record = await requireOwned(principal, id);+ record.history = Array.isArray(history) ? history.slice(-MAX_HISTORY) : [];+ if (title) record.title = safeTitle(title);+ record.updatedAt = new Date().toISOString();+ await writeFile(record);+ return record;+ });+}++export async function appendAgentSessionEvent(+ principal: string,+ id: string,+ event: Omit<AgentSessionEvent, "at"> & { at?: string },+): Promise<void> {+ await withSecurityStoreLock(LOCK_TARGET, async () => {+ const record = await requireOwned(principal, id);+ const row: AgentSessionEvent = {+ at: event.at ?? new Date().toISOString(),+ kind: event.kind,+ ...(event.tool ? { tool: event.tool.slice(0, 120) } : {}),+ ...(event.state ? { state: event.state.slice(0, 40) } : {}),+ ...(event.workflowId ? { workflowId: event.workflowId.slice(0, 80) } : {}),+ ...(safeDetail(event.detail) ? { detail: safeDetail(event.detail) } : {}),+ };+ record.events = [...record.events, row].slice(-MAX_EVENTS);+ record.updatedAt = row.at;+ await writeFile(record);+ });+}++export async function resumeAgentSession(+ principal: string,+ targetId: string,+ currentId?: string,+): Promise<AgentSessionResumePacket> {+ const target = await requireOwned(principal, targetId);+ if (currentId && currentId !== targetId) {+ await withSecurityStoreLock(LOCK_TARGET, async () => {+ const current = await requireOwned(principal, currentId);+ current.resumedFrom = targetId;+ current.memorySnapshot = target.memorySnapshot;+ const now = new Date().toISOString();+ const resumedEvent: AgentSessionEvent = { at: now, kind: "resumed", detail: `resumed ${targetId}` };+ current.events = [...current.events, resumedEvent].slice(-MAX_EVENTS);+ current.updatedAt = now;+ await writeFile(current);+ });+ }+ return { session: summary(target), memorySnapshot: target.memorySnapshot, recentEvents: target.events.slice(-40) };+}++export function agentSessionSummary(record: AgentSession): AgentSessionSummary {+ return summary(record);+}diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.tsnew file mode 100644index 00000000..fc28e543--- /dev/null+++ b/lib/agent/session-types.ts@@ -0,0 +1,42 @@+import type { AgentMemorySnapshot } from "./memory-store";++export type AgentSessionSource = "cli" | "mcp" | "alfa";++export interface AgentSessionEvent {+ at: string;+ kind: "created" | "resumed" | "tool" | "workflow" | "note";+ tool?: string;+ state?: string;+ workflowId?: string;+ detail?: string;+}++export interface AgentSession {+ id: string;+ principalHash: string;+ source: AgentSessionSource;+ title: string;+ createdAt: string;+ updatedAt: string;+ resumedFrom?: string;+ memorySnapshot: AgentMemorySnapshot;+ history: unknown[];+ events: AgentSessionEvent[];+}++export interface AgentSessionSummary {+ id: string;+ source: AgentSessionSource;+ title: string;+ createdAt: string;+ updatedAt: string;+ resumedFrom?: string;+ eventCount: number;+ historyTurns: number;+}++export interface AgentSessionResumePacket {+ session: AgentSessionSummary;+ memorySnapshot: AgentMemorySnapshot;+ recentEvents: AgentSessionEvent[];+}diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsindex bda1bcb9..b581a308 100644--- a/lib/config/env-example.test.ts+++ b/lib/config/env-example.test.ts@@ -50,7 +50,7 @@ const NOT_A_KNOB: Record<string, string> = {};function usedEnvNames(): string[] {- const files = execSync("git ls-files '*.ts' '*.tsx' '*.mjs'", { cwd: ROOT, encoding: "utf8" })+ const files = execSync("git ls-files --cached --others --exclude-standard '*.ts' '*.tsx' '*.mjs'", { cwd: ROOT, encoding: "utf8" }).split("\n").filter(Boolean)// A test may stub anything, so .test files do not count as "the app reads it".diff --git a/lib/host/audit.ts b/lib/host/audit.tsindex 21156177..4a13e000 100644--- a/lib/host/audit.ts+++ b/lib/host/audit.ts@@ -33,6 +33,8 @@ export type AuditAction =| "workflow.start"| "workflow.cancel"| "workflow.finish"+ | "agent.session"+ | "agent.memory"/** An MCP token asked for a tool above its scope. Not an error — it is the* signal that matters: a `read` connector repeatedly reaching for `exec_run`* is what a prompt-injected model looks like from the outside. */diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.tsindex 831a7f9d..920f212f 100644--- a/lib/mcp/dispatch.ts+++ b/lib/mcp/dispatch.ts@@ -1,4 +1,5 @@import { audit, rateLimited } from "@/lib/host";+import { appendAgentSessionEvent } from "@/lib/agent/session-store";import { activeWorkflowForActor, recordWorkflowStep, type ActiveWorkflow } from "@/lib/skills/memory";import { activityTarget, newActivityId, recordMcpActivity } from "./activity";import { allows, type Scope } from "./scope";@@ -18,6 +19,44 @@ const PROTOCOL = "2024-11-05";export const UNAUTHORIZED = -32001;export const RATE_LIMITED = -32029;+export interface McpAgentContext {+ principal?: string;+ sessionId?: string;+}++function sessionDetail(name: string, args: Record<string, unknown>, target?: string): string | undefined {+ if (name === "workflow_start") {+ const intent = typeof args.intent === "string" ? args.intent.slice(0, 320) : "";+ const project = typeof args.project === "string" ? args.project.slice(0, 120) : "";+ return [intent, project ? `project=${project}` : ""].filter(Boolean).join(" · ") || undefined;+ }+ if (name === "workflow_finish") {+ return typeof args.summary === "string" ? args.summary.slice(0, 400) : target;+ }+ if (name === "workflow_cancel") {+ return typeof args.reason === "string" ? args.reason.slice(0, 300) : target;+ }+ return target || undefined;+}++async function recordAgentEvent(+ context: McpAgentContext | undefined,+ tool: string,+ state: string,+ args: Record<string, unknown>,+ workflowId?: string,+ target?: string,+): Promise<void> {+ if (!context?.principal || !context.sessionId) return;+ await appendAgentSessionEvent(context.principal, context.sessionId, {+ kind: tool.startsWith("workflow_") ? "workflow" : "tool",+ tool,+ state,+ workflowId,+ detail: sessionDetail(tool, args, target),+ }).catch(() => undefined);+}+const ok = (id: RpcRequest["id"], result: unknown) => ({ jsonrpc: "2.0", id: id ?? null, result });const fail = (id: RpcRequest["id"], code: number, message: string) =>({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });@@ -41,7 +80,7 @@ function instructions(scope: Scope): string {const startup = scope === "read"? "This token is read-only: use skills_search for capability discovery, then bounded read tools. Verify the answer without attempting workflow memory writes.": "For any task needing two or more operational calls, call workflow_start directly as the ONE startup call; it already searches trusted skills and recipes, resolves the project, and reports the current toolset. Multiple workflows may run in parallel on one token. Use workflow_finish or workflow_cancel with the exact id, and pass that workflow_id on every operational call in its run; omit it for standalone work. Verify before workflow_finish.";- return `${startup} Prefer bounded tools for one or two direct operations. At exec scope, use one narrow exec_run batch for short repository-wide search/git checks; use exec_job_start + exec_job_status for tests/builds that may exceed 30 seconds. Show concise progress using badges such as [Skills], [Files], [Terminal], [Git], [Build], [Verify], and [Screenshot]; never expose private chain-of-thought.`;+ return `${startup} Every MCP connection has a durable MSO session id. Use agent_session_current when the user asks for it; use agent_sessions_list + agent_session_resume to recover safe MSO operational context from an earlier ChatGPT conversation. Session resume does not expose ChatGPT hidden transcripts. Persistent USER.md/MEMORY.md are client-scoped and frozen into each new session. Prefer bounded tools for one or two direct operations. At exec scope, use one narrow exec_run batch for short repository-wide search/git checks; use exec_job_start + exec_job_status for tests/builds that may exceed 30 seconds. Show concise progress using badges such as [Skills], [Files], [Terminal], [Git], [Build], [Verify], and [Screenshot]; never expose private chain-of-thought.`;}function flowFields(workflow: ActiveWorkflow | null | undefined) {@@ -75,7 +114,7 @@ function structuredResult(toolName: string, result: unknown) {: { content };}-export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Promise<Record<string, unknown>> {+export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, agentContext?: McpAgentContext): Promise<Record<string, unknown>> {const id = req.id ?? null;switch (req.method) {case "initialize": {@@ -85,7 +124,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pcapabilities: { tools: { listChanged: false }, resources: { listChanged: false } },serverInfo: { name: "mso", version: MCP_SERVER_VERSION },instructions: instructions(scope),- _meta: { toolset },+ _meta: { toolset, ...(agentContext?.sessionId ? { agentSessionId: agentContext.sessionId } : {}) },});}case "notifications/initialized":@@ -125,6 +164,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pif (!workflowProbe) {void recordMcpActivity({ id: deniedId, actor, tool: name, state: "denied", scope, ...initialFlow, target, detail: `scope ${scope} < ${tool.scope}` });await recordWorkflowStep(actor, activeWorkflow?.id, { id: deniedId, tool: name, state: "denied", target, args, ts: new Date().toISOString() });+ await recordAgentEvent(agentContext, name, "denied", args, activeWorkflow?.id, target);}return ok(id, {content: [{ type: "text", text: `error: this token holds scope "${scope}"; ${name} needs "${tool.scope}". Mint a new token in mso Settings → MCP.` }],@@ -139,6 +179,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pconst target = activityTarget(args);const message = "workflow_id was not found for this MCP client";void recordMcpActivity({ id: mismatchId, actor, tool: name, state: "failed", scope, target, detail: message });+ await recordAgentEvent(agentContext, name, "failed", args, undefined, target);return ok(id, {content: [{ type: "text", text: `error: ${message}. Use the exact id returned by workflow_start, or omit workflow_id for a standalone call.` }],isError: true,@@ -153,6 +194,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pif (!workflowProbe) {void recordMcpActivity({ id: limitedId, actor, tool: name, state: "rate_limited", scope, ...initialFlow, target, detail: "rate limited" });await recordWorkflowStep(actor, activeWorkflow?.id, { id: limitedId, tool: name, state: "rate_limited", target, args, ts: new Date().toISOString() });+ await recordAgentEvent(agentContext, name, "rate_limited", args, activeWorkflow?.id, target);}return ok(id, {content: [{ type: "text", text: `error: ${name} is rate limited (${tool.limit.max} per ${Math.round(tool.limit.windowMs / 1000)}s). Wait and retry.` }],@@ -168,7 +210,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pconst target = activityTarget(args);if (!workflowProbe) void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });try {- const result = await tool.run(args, { actor, scope, workflowId: activeWorkflow?.id });+ const result = await tool.run(args, { actor, principal: agentContext?.principal, sessionId: agentContext?.sessionId, scope, workflowId: activeWorkflow?.id });if (trail) {const outcome = trail.outcome?.(result);void audit({ action: outcome?.action ?? trail.action, actor, target: auditTarget, ok: outcome?.ok ?? true, detail: outcome?.detail, meta: { via: "mcp", scope } });@@ -178,6 +220,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pif (!workflowProbe) {void recordMcpActivity({ id: activityId, actor, tool: name, state: "completed", scope, ...flowFields(completedWorkflow), target, durationMs });await recordWorkflowStep(actor, completedWorkflow?.id, { id: activityId, tool: name, state: "completed", target, args, durationMs, ts: new Date().toISOString() });+ await recordAgentEvent(agentContext, name, "completed", args, completedWorkflow?.id, target);}if (isMcpDirectResult(result)) return ok(id, { content: result.content, ...(result.isError ? { isError: true } : {}) });return ok(id, structuredResult(name, result));@@ -188,6 +231,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Pif (!workflowProbe) {void recordMcpActivity({ id: activityId, actor, tool: name, state: "failed", scope, ...initialFlow, target, durationMs, detail: message.slice(0, 220) });await recordWorkflowStep(actor, activeWorkflow?.id, { id: activityId, tool: name, state: "failed", target, args, durationMs, ts: new Date().toISOString() });+ await recordAgentEvent(agentContext, name, "failed", args, activeWorkflow?.id, target);}return ok(id, { content: [{ type: "text", text: "error: " + message.slice(0, 500) }], isError: true });}diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex 4a8f3646..a63c7f4b 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -42,6 +42,13 @@ const MCP_ONLY: Record<string, string> = {"workflow.status": "app-only MCP Apps bridge used by the ChatGPT progress component; Alfa already owns its in-shell run state and must not poll the external workflow store","workflow.cancel": "same actor-scoped boundary; external runs need explicit recovery from an interrupted task","workflow.finish": "same actor-scoped learning loop; Alfa recipes can use the session route later without weakening MCP scope semantics",+ "agent.session.current": "external MCP clients need a stable durable MSO session id they can quote from a later ChatGPT conversation; in-shell Alfa already owns its conversation identity",+ "agent.sessions.list": "external MCP clients need explicit cross-conversation session discovery; Alfa's in-app thread UI already provides its own conversation list",+ "agent.session.resume": "external MCP clients must reconstruct only the safe MSO resume packet across ChatGPT conversations; Alfa can reopen its own persisted in-app thread directly",+ "agent.session.note": "durable operational notes belong to the MCP client's isolated MSO session store; Alfa has a separate owner-scoped conversation/memory store",+ "agent.memory.read": "MCP clients use isolated USER.md/MEMORY.md-style agent memory snapshots; Alfa intentionally keeps its existing owner recall instead of sharing external-client memory",+ "agent.memory.remember": "same isolated MCP memory store; sharing it with Alfa would collapse two trust/ownership boundaries",+ "agent.memory.forget": "same isolated MCP memory store; deletion remains scoped to the external MCP client principal","exec.job.start": "external MCP requests have a hard request-time budget and need a bounded resumable shell job; in-shell Alfa can keep using its interactive Terminal/approved exec.run surfaces","exec.job.status": "status exists only to resume an MCP async exec job; Alfa has no corresponding external request timeout to recover from","exec.job.cancel": "cancellation is paired with the MCP-only async exec lifecycle and remains actor/workflow-bound",diff --git a/lib/mcp/tool-context.ts b/lib/mcp/tool-context.tsnew file mode 100644index 00000000..37fc4073--- /dev/null+++ b/lib/mcp/tool-context.ts@@ -0,0 +1,19 @@+import type { McpTool } from "./tool-kit";++const WORKFLOW_CONTEXT_EXEMPT = new Set([+ "skills_search", "workflow_start", "workflow_status", "workflow_cancel", "workflow_finish",+]);++export const withWorkflowContext = (tool: McpTool): McpTool => WORKFLOW_CONTEXT_EXEMPT.has(tool.name) ? tool : ({+ ...tool,+ inputSchema: {+ ...tool.inputSchema,+ properties: {+ ...tool.inputSchema.properties,+ workflow_id: {+ type: "string",+ description: "Exact id returned by workflow_start. Include it on every operational step in that run; omit it for a standalone call.",+ },+ },+ },+});diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.tsindex 7fd0f71f..ee57f6ce 100644--- a/lib/mcp/tool-kit.ts+++ b/lib/mcp/tool-kit.ts@@ -28,6 +28,11 @@ export function isMcpDirectResult(value: unknown): value is McpDirectResult {export interface McpRunContext {actor?: string;+ /** Stable principal for persistent agent session/memory ownership. Unlike the+ * token-scoped audit actor, this may survive an OAuth token refresh. */+ principal?: string;+ /** Durable Streamable HTTP / terminal-agent session id, when available. */+ sessionId?: string;scope: Scope;workflowId?: string;}@@ -59,23 +64,10 @@ export interface McpTool {targetArg?: string;/** Derive the outcome from the RESULT, for a handler that reports failure by* returning rather than throwing. Without it the dispatcher can only record- * "did not throw", which is a lie for anything that has an exit code.- * Only exec_run needs this — `setCamoufoxEnabled` throws, and the fs helpers- * throw, so the catch branch already records those correctly. Deliberately- * NOT a generic result→outcome mapper: one call site is not a pattern. */+ * "did not throw", which is a lie for anything that has an exit code. */outcome?: (result: unknown) => { ok: boolean; action?: AuditAction; detail?: string };};- /** Per-OPERATION rate limit, mirroring the one its /api/v1 route already applies.- *- * The token bucket in app/mcp/route.ts is per TOKEN (120/min, 50,000/day) and says- * nothing about which tool was called, so an MCP client got the same allowance- * for `apps_power` as for `fs_list` — while the browser and the CLI hit- * `managed-app:<id>` at 12/min going through the route. That is a 10x gap on a- * daemon restart, available to a WRITE-scope token that holds no shell.- *- * `keyArg` puts the bucket on the same key the route uses, so MCP and the UI- * share it rather than getting one each. Numbers here must MATCH the route's,- * never undercut them — the route is the authority. */+ /** Per-operation rate limit, mirroring the one its /api/v1 route already applies. */limit?: { max: number; windowMs: number; keyArg?: string; key: string };}diff --git a/lib/mcp/tools-agent.ts b/lib/mcp/tools-agent.tsnew file mode 100644index 00000000..53a1219c--- /dev/null+++ b/lib/mcp/tools-agent.ts@@ -0,0 +1,107 @@+import { forgetAgentMemory, readAgentMemory, rememberAgentMemory, type AgentMemoryDocument } from "@/lib/agent/memory-store";+import { appendAgentSessionEvent, getAgentSession, listAgentSessions, resumeAgentSession } from "@/lib/agent/session-store";+import { type McpTool, S, str } from "./tool-kit";++function principal(context: { principal?: string }): string {+ if (!context.principal) throw new Error("agent session principal is unavailable");+ return context.principal;+}++function document(a: Record<string, unknown>): AgentMemoryDocument {+ const value = str(a, "document");+ if (value !== "USER.md" && value !== "MEMORY.md") throw new Error("document must be USER.md or MEMORY.md");+ return value;+}++export const AGENT_TOOLS: McpTool[] = [+ {+ name: "agent_session_current",+ description:+ "Return this MCP conversation's durable MSO session id and summary. Use the id when the user wants to refer back to this MSO session from a later ChatGPT conversation.",+ scope: "read",+ annotations: { readOnlyHint: true, idempotentHint: true },+ inputSchema: S({}),+ run: async (_a, context) => {+ if (!context.sessionId) throw new Error("this MCP client did not establish an MSO session");+ const session = await getAgentSession(principal(context), context.sessionId);+ if (!session) throw new Error("current MSO session is no longer available");+ return {+ id: session.id,+ source: session.source,+ title: session.title,+ createdAt: session.createdAt,+ updatedAt: session.updatedAt,+ resumedFrom: session.resumedFrom,+ };+ },+ },+ {+ name: "agent_sessions_list",+ description:+ "List durable MSO sessions owned by this MCP client, newest first. Use this when the user asks to find, recall, continue, or resume an earlier MSO session.",+ scope: "read",+ annotations: { readOnlyHint: true, idempotentHint: true },+ inputSchema: S({ limit: { type: "number", description: "How many sessions to return (1-100, default 20)." } }),+ run: (a, context) => listAgentSessions(principal(context), Math.max(1, Math.min(100, Number(a.limit) || 20))),+ },+ {+ name: "agent_session_resume",+ description:+ "Read the safe resume packet for one prior MSO session owned by this MCP client: session metadata, its frozen memory snapshot, and recent operational events. This resumes MSO operational context; it cannot recover ChatGPT's hidden conversation transcript.",+ scope: "read",+ annotations: { readOnlyHint: true, idempotentHint: true },+ inputSchema: S({ session_id: { type: "string", description: "Exact MSO session id returned by agent_session_current or agent_sessions_list." } }, ["session_id"]),+ run: (a, context) => resumeAgentSession(principal(context), str(a, "session_id"), context.sessionId),+ },+ {+ name: "agent_session_note",+ description:+ "Attach one concise durable note to the current MSO session so a later resume has the important operational context. Do not store passwords, API keys, tokens, cookies, or other secrets.",+ scope: "write",+ limit: { key: "workflow.memory", max: 30, windowMs: 60_000 },+ audit: { action: "agent.session", targetArg: "note" },+ inputSchema: S({ note: { type: "string", description: "Concise non-secret note, max 500 characters." } }, ["note"]),+ run: async (a, context) => {+ if (!context.sessionId) throw new Error("this MCP client did not establish an MSO session");+ const note = str(a, "note").trim();+ if (note.length > 500) throw new Error("session note must be 500 characters or fewer");+ await appendAgentSessionEvent(principal(context), context.sessionId, { kind: "note", detail: note });+ return { ok: true, sessionId: context.sessionId };+ },+ },+ {+ name: "agent_memory_read",+ description:+ "Read this MCP client's persistent USER.md and MEMORY.md agent memory. Sessions capture a frozen snapshot at creation, matching Hermes-style stable per-session context.",+ scope: "read",+ annotations: { readOnlyHint: true, idempotentHint: true },+ inputSchema: S({}),+ run: (_a, context) => readAgentMemory(principal(context)),+ },+ {+ name: "agent_memory_remember",+ description:+ "Create or replace one keyed entry in this MCP client's persistent USER.md or MEMORY.md. USER.md is for stable user preferences/profile; MEMORY.md is for learned environment/project conventions. Never store secrets.",+ scope: "write",+ limit: { key: "workflow.memory", max: 30, windowMs: 60_000 },+ audit: { action: "agent.memory", targetArg: "key" },+ inputSchema: S({+ document: { type: "string", enum: ["USER.md", "MEMORY.md"] },+ key: { type: "string", description: "Stable one-line entry key, 1-80 characters." },+ value: { type: "string", description: "Non-secret memory value." },+ }, ["document", "key", "value"]),+ run: (a, context) => rememberAgentMemory(principal(context), document(a), str(a, "key"), str(a, "value")),+ },+ {+ name: "agent_memory_forget",+ description: "Remove one keyed entry from this MCP client's persistent USER.md or MEMORY.md.",+ scope: "write",+ limit: { key: "workflow.memory", max: 30, windowMs: 60_000 },+ audit: { action: "agent.memory", targetArg: "key" },+ inputSchema: S({+ document: { type: "string", enum: ["USER.md", "MEMORY.md"] },+ key: { type: "string" },+ }, ["document", "key"]),+ run: (a, context) => forgetAgentMemory(principal(context), document(a), str(a, "key")),+ },+];diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 0e587cbd..0d9dddd8 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -6,6 +6,8 @@ import { DISCOVERY_TOOLS } from "./tools-discovery";import { LEARNING_TOOLS } from "./tools-learning";import { POWER_TOOLS } from "./tools-power";import { INFRA_TOOLS } from "./tools-infra";+import { AGENT_TOOLS } from "./tools-agent";+import { withWorkflowContext } from "./tool-context";// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,// not the tool, writes the trail, because these call lib/host directly and so@@ -212,26 +214,4 @@ const MUTATE_TOOLS: McpTool[] = [},];-const WORKFLOW_CONTEXT_EXEMPT = new Set([- "skills_search",- "workflow_start",- "workflow_status",- "workflow_cancel",- "workflow_finish",-]);-const withWorkflowContext = (tool: McpTool): McpTool => WORKFLOW_CONTEXT_EXEMPT.has(tool.name) ? tool : ({- ...tool,- inputSchema: {- ...tool.inputSchema,- properties: {- ...tool.inputSchema.properties,- workflow_id: {- type: "string",- description:- "Exact id returned by workflow_start. Include it on every operational step in that run; omit it for a standalone call.",- },- },- },-});--export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));+export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.tsindex ef767c89..742e35a5 100644--- a/scripts/mso-agent-contract.test.ts+++ b/scripts/mso-agent-contract.test.ts@@ -2,16 +2,18 @@ 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"].map((name) => path.join(__dirname, name));+const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.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 MSO folder-terminal icon, wordmark, and setup shortcuts", () => {- expect(src).toContain("╭──┘ ╰────────╮");- expect(src).toContain("│ >_ │");- expect(src).toContain("███╗ ███╗ ███████╗ ██████╗");- expect(src).toContain("process.stdout.columns < 72");- for (const command of ["/model", "/setup", "/providers", "/provider", "/doctor", "/tools", "/skills", "/clear", "/exit"]) expect(src).toContain(command);+ 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("── MSO Agent ──");+ expect(src).toContain("MSO_TITLE_ART");+ expect(src).not.toContain("╭──┘ ╰────────╮");+ for (const command of ["/model", "/setup", "/providers", "/provider", "/doctor", "/tools", "/skills", "/session", "/sessions", "/resume", "/clear", "/exit"]) expect(src).toContain(command);});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.mjsindex 96d31a7f..5651cb54 100644--- a/scripts/mso-agent-runtime.mjs+++ b/scripts/mso-agent-runtime.mjs@@ -1,17 +1,13 @@import fs from "node:fs";import process from "node:process";+import { C, fit, MSO_TITLE_ART, printAgentBanner } from "./mso-agent-ui.mjs";+export { C, MSO_TITLE_ART } from "./mso-agent-ui.mjs";export const BASE = String(process.env.MSO_AGENT_BASE || "http://127.0.0.1:4005").replace(/\/$/, "");const ORIGIN = String(process.env.MSO_AGENT_ORIGIN || BASE);const JAR = String(process.env.MSO_AGENT_JAR || "");export const CLI = String(process.env.MSO_AGENT_CLI || "mso");const VERSION = String(process.env.MSO_AGENT_VERSION || "");-const color = process.stdout.isTTY && !process.env.NO_COLOR;-export const C = {- reset: color ? "\x1b[0m" : "", bold: color ? "\x1b[1m" : "", dim: color ? "\x1b[2m" : "",- a: color ? "\x1b[38;2;124;92;255m" : "", b: color ? "\x1b[38;2;58;160;255m" : "", c: color ? "\x1b[38;2;52;211;153m" : "",- warn: color ? "\x1b[38;2;245;158;11m" : "", err: color ? "\x1b[38;2;239;68;68m" : "",-};function cookieHeader() {if (!JAR) return "";@@ -41,39 +37,6 @@ export async function api(path, init = {}) {return body;}-function logo() {- const icon = [- " ╭──────╮ ",- "╭──┘ ╰────────╮ ",- "│ │ ",- "│ >_ │ ",- "│ │ ",- "╰──────────────────╯ ",- ];- const wordmark = [- "███╗ ███╗ ███████╗ ██████╗ ",- "████╗ ████║ ██╔════╝ ██╔═══██╗",- "██╔████╔██║ ███████╗ ██║ ██║",- "██║╚██╔╝██║ ╚════██║ ██║ ██║",- "██║ ╚═╝ ██║ ███████║ ╚██████╔╝",- "╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ",- ];- const narrow = Number(process.stdout.columns || 0) > 0 && process.stdout.columns < 72;- const lines = narrow ? [...icon, "", ...wordmark] : wordmark.map((line, i) => `${icon[i]} ${line}`);- return lines.map((line, i) => {- if (!line) return line;- const phase = narrow ? i % 6 : i;- return `${phase < 2 ? C.a : phase < 4 ? C.b : C.c}${C.bold}${line}${C.reset}`;- }).join("\n");-}--function countSkills(data) { return Array.isArray(data?.skills) ? data.skills.length : 0; }-function summarizeInfra(data) {- const rows = Array.isArray(data?.providers) ? data.providers : [];- const ready = rows.filter((row) => row.configured).map((row) => row.id);- return { ready, total: rows.length };-}-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: [] })),@@ -82,53 +45,59 @@ export async function state() {return { config, toolsData, tools, skills, infra };}-function compactNames(rows, max = 7) {- const names = rows.map((row) => String(row.id ?? row.name ?? "")).filter(Boolean);- return `${names.slice(0, max).join(", ")}${names.length > max ? `, +${names.length - max} more` : ""}` || "none";+export async function createCliSession(title = "MSO Agent session") {+ const out = await api("/api/v1/agent-sessions", { method: "POST", body: JSON.stringify({ action: "create", title }) });+ return out.session;+}+export async function loadCliSession(id) {+ const out = await api(`/api/v1/agent-sessions?id=${encodeURIComponent(id)}`);+ return out.session;+}+export async function listCliSessions(limit = 20) {+ const out = await api(`/api/v1/agent-sessions?limit=${Math.max(1, Math.min(100, Number(limit) || 20))}`);+ return Array.isArray(out.sessions) ? out.sessions : [];+}+export async function saveCliSession(session, history, title) {+ const out = await api("/api/v1/agent-sessions", {+ method: "POST",+ body: JSON.stringify({ action: "update", id: session.id, history, ...(title ? { title } : {}) }),+ });+ return out.session;}-export function printBanner(s) {- const byScope = { read: 0, write: 0, exec: 0 };- for (const tool of s.tools) byScope[tool.scope] = (byScope[tool.scope] || 0) + 1;- const infra = summarizeInfra(s.infra);- const readTools = s.tools.filter((tool) => tool.scope === "read");- const gatedTools = s.tools.filter((tool) => tool.scope !== "read");- const skills = Array.isArray(s.skills?.skills) ? s.skills.skills : [];- console.log(logo());- console.log();- console.log(`${C.bold}╭─ MSO Agent${C.reset} ${C.dim}${VERSION ? `v${VERSION} · ` : ""}${BASE}${C.reset}`);- console.log(`│ model ${C.a}${s.config?.provider ?? "—"}/${s.config?.model ?? "—"}${C.reset}`);- console.log(`│ capabilities ${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec ${C.dim}(write/exec approval-gated)${C.reset}`);- console.log(`├─ ${C.bold}Available Tools${C.reset}`);- console.log(`│ read ${compactNames(readTools)}`);- console.log(`│ approval ${compactNames(gatedTools, 6)}`);- console.log(`├─ ${C.bold}Available Skills${C.reset}`);- console.log(`│ ${countSkills(s.skills)} loaded ${compactNames(skills, 8)}`);- console.log(`├─ ${C.bold}Infrastructure${C.reset}`);- console.log(`│ ${infra.ready.length}/${infra.total} ready ${infra.ready.length ? infra.ready.join(", ") : "run /providers to connect Dokploy/Cloudflare/Hostinger"}`);- console.log(`╰─ ${C.dim}Ask MSO to inspect, configure, deploy, or debug this server. /help shows commands.${C.reset}`);+export function printBanner(s, agentSession) {+ return printAgentBanner(s, agentSession, { base: BASE, version: VERSION });}-const SYSTEM = [- "You are MSO Agent, the interactive terminal setup and operations agent for Manef Shell OS on the user's own server.",- "Use the provided tools to do real work instead of only describing commands. Prefer bounded tools over exec_run.",- "For setup, first inspect infrastructure with infra_providers_list and live-check configured providers with infra_provider_doctor.",- "Dokploy, Cloudflare, and Hostinger credentials are entered interactively with `mso provider set <id>` and are never exposed to you; never ask the user to paste API tokens into chat or shell commands.",- "Use dokploy_* and cloudflare_*/hostinger_* tools after the user has configured those providers. Cloudflare DNS must remain per-record and DNS-only unless the user explicitly asks for proxying.",- "If multiple operational calls are needed, use workflow_start, pass its workflow_id to later calls, verify, then workflow_finish. If the task is abandoned, workflow_cancel.",- "Write and exec tools may be denied by the user's approval prompt. Never retry a denied call unchanged.",- "Be concise. Explain only decisions the user needs to make or concrete results/errors.",-].join(" ");+function sessionSystem(agentSession) {+ const snapshot = agentSession?.memorySnapshot || {};+ const user = fit(snapshot.user || "", 12000);+ const memory = fit(snapshot.memory || "", 12000);+ return [+ "You are MSO Agent, the interactive terminal setup and operations agent for Manef Shell OS on the user's own server.",+ agentSession?.id ? `Current durable MSO session id: ${agentSession.id}.` : "",+ "Use the provided tools to do real work instead of only describing commands. Prefer bounded tools over exec_run.",+ "For setup, first inspect infrastructure with infra_providers_list and live-check configured providers with infra_provider_doctor.",+ "Dokploy, Cloudflare, and Hostinger credentials are entered interactively with `mso provider set <id>` and are never exposed to you; never ask the user to paste API tokens into chat or shell commands.",+ "Use dokploy_* and cloudflare_*/hostinger_* tools after the user has configured those providers. Cloudflare DNS must remain per-record and DNS-only unless the user explicitly asks for proxying.",+ "If multiple operational calls are needed, use workflow_start, pass its workflow_id to later calls, verify, then workflow_finish. If the task is abandoned, workflow_cancel.",+ "Write and exec tools may be denied by the user's approval prompt. Never retry a denied call unchanged.",+ "USER.md and MEMORY.md below are a frozen snapshot captured when this MSO session started. Do not silently live-refresh them during this session. Never store secrets in agent memory.",+ user ? `\n<USER.md>\n${user}\n</USER.md>` : "",+ memory ? `\n<MEMORY.md>\n${memory}\n</MEMORY.md>` : "",+ "Be concise. Explain only decisions the user needs to make or concrete results/errors.",+ ].filter(Boolean).join(" ");+}function toolForModel(tool) {return { name: tool.name, description: tool.description, input_schema: tool.inputSchema || { type: "object", properties: {} } };}-export async function streamTurn(messages, tools) {+export async function streamTurn(messages, tools, agentSession) {const res = await fetch(`${BASE}/api/assistant`, {method: "POST",headers: { origin: ORIGIN, cookie: cookieHeader(), "content-type": "application/json" },- body: JSON.stringify({ messages, tools: tools.map(toolForModel), system: SYSTEM }),+ body: JSON.stringify({ messages, tools: tools.map(toolForModel), system: sessionSystem(agentSession) }),});if (!res.ok || !res.body) {let body = {}; try { body = await res.json(); } catch {}diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjsnew file mode 100644index 00000000..85021c00--- /dev/null+++ b/scripts/mso-agent-ui.mjs@@ -0,0 +1,145 @@+import process from "node:process";++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" : "",+};+C.a = C.blue;+C.b = C.blue;+C.c = C.cyan;++export const MSO_TITLE_ART = [+ "████████████",+ " ██ ██",+ " ██ ██ ██ ██ ██████████████████████",+ " ██ ██ ███╗ ███╗███████╗ ██████╗ ",+ " ██ ██ ████╗ ████║██╔════╝██╔═══██╗",+ " ██ ██ ██ ██ ██╔████╔██║███████╗██║ ██║",+ " ██ ██ ██ ██ ██║╚██╔╝██║╚════██║██║ ██║",+ " ██ ██ ████████ ██ ██ ██║ ╚═╝ ██║███████║╚██████╔╝",+ " ██ ██ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ",+ " ██ ██",+ " ████████████████████████████████████",+ " ── MSO Agent ──",+];++function plain(value) { return String(value ?? "").replace(/\x1b\[[0-9;]*m/g, ""); }+function width(value) { return [...plain(value)].length; }+export function fit(value, max) {+ const source = plain(value).replace(/[\r\n\t]+/g, " ");+ if (max <= 0) return "";+ if ([...source].length <= max) return source;+ if (max <= 1) return "…".slice(0, max);+ return [...source].slice(0, max - 1).join("") + "…";+}+function pad(value, max) {+ const clean = fit(value, max);+ return clean + " ".repeat(Math.max(0, max - width(clean)));+}+function rule(char, n) { return char.repeat(Math.max(0, n)); }+function terminalWidth() {+ const cols = Number(process.stdout.columns || 104);+ return Math.max(72, Math.min(118, cols - 2));+}+function countSkills(data) { return Array.isArray(data?.skills) ? data.skills.length : 0; }+function summarizeInfra(data) {+ const rows = Array.isArray(data?.providers) ? data.providers : [];+ const ready = rows.filter((row) => row.configured).map((row) => String(row.id));+ return { ready, total: rows.length };+}+function toolCategory(name) {+ if (/^fs_/.test(name)) return "files";+ if (/^(sys_|apps_|browser_)/.test(name)) return "system";+ if (/^(project|projects)_/.test(name)) return "projects";+ if (/^(workflow_|skills_|agent_)/.test(name)) return "agent";+ if (/^(dokploy_|cloudflare_|hostinger_|infra_)/.test(name)) return "infra";+ return "other";+}+function groupedToolLines(tools, maxLines = 5) {+ const order = ["files", "system", "projects", "agent", "infra", "other"];+ const groups = new Map(order.map((key) => [key, []]));+ for (const tool of tools) groups.get(toolCategory(String(tool.name)))?.push(String(tool.name));+ return order.filter((key) => groups.get(key)?.length).slice(0, maxLines).map((key) => ({+ label: key, value: groups.get(key).join(", "),+ }));+}+function groupedSkillLines(skills, maxLines = 5) {+ const rows = Array.isArray(skills) ? skills : [];+ const groups = new Map();+ for (const skill of rows) {+ const label = String(skill.category || skill.source || "skills").replace(/^mso[:/ -]?/i, "") || "skills";+ if (!groups.has(label)) groups.set(label, []);+ const name = String(skill.id || skill.name || "");+ if (name) groups.get(label).push(name);+ }+ return [...groups.entries()].slice(0, maxLines).map(([label, names]) => ({ label, value: names.join(", ") }));+}+function kv(label, value, widthLimit) {+ const labelWidth = Math.min(13, Math.max(8, widthLimit > 36 ? 12 : 9));+ return `${pad(label, labelWidth)} ${fit(value, Math.max(0, widthLimit - labelWidth - 1))}`;+}+function panelLine(left, right, leftWidth, rightWidth, gap = 3) {+ return `│ ${pad(left, leftWidth)}${" ".repeat(gap)}${pad(right, rightWidth)} │`;+}+function panelSingle(text, inner) { return `│ ${pad(text, inner)} │`; }+function panelTitle(title, inner) {+ const label = ` ${title} `;+ const remaining = Math.max(0, inner - width(label));+ const before = Math.floor(remaining / 2);+ return `┌${rule("─", before)}${label}${rule("─", remaining - before)}┐`;+}++export function printAgentBanner(s, agentSession, { base, version }) {+ const totalWidth = terminalWidth();+ const inner = totalWidth - 2;+ const titleArtWidth = Math.max(...MSO_TITLE_ART.map(width));+ if (totalWidth >= titleArtWidth) {+ for (const line of MSO_TITLE_ART) console.log(`${C.blue}${C.bold}${line}${C.reset}`);+ } else console.log(`${C.blue}${C.bold}── MSO Agent ──${C.reset}`);+ console.log();++ const byScope = { read: 0, write: 0, exec: 0 };+ for (const tool of s.tools) byScope[tool.scope] = (byScope[tool.scope] || 0) + 1;+ const infra = summarizeInfra(s.infra);+ const tools = groupedToolLines(s.tools, 5);+ const skills = groupedSkillLines(s.skills?.skills, 5);+ const model = `${s.config?.provider ?? "—"}/${s.config?.model ?? "—"}`;+ const sessionId = agentSession?.id || "—";+ const title = `MSO Agent${version ? ` v${version}` : ""} · ${sessionId}`;++ console.log(panelTitle(title, inner));+ if (totalWidth >= 94) {+ const gap = 4;+ const leftWidth = Math.max(30, Math.floor((inner - gap) * 0.37));+ const rightWidth = inner - gap - leftWidth;+ const left = [+ `${C.bold}Runtime${C.reset}`, kv("model", model, leftWidth), kv("session", sessionId, leftWidth),+ kv("endpoint", base, leftWidth), "", `${C.bold}Capabilities${C.reset}`,+ fit(`${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec`, leftWidth),+ fit("write/exec approval-gated", leftWidth), "", `${C.bold}Infrastructure${C.reset}`,+ fit(`${infra.ready.length}/${infra.total} ready`, leftWidth),+ fit(infra.ready.length ? infra.ready.join(" · ") : "run /providers to connect", leftWidth),+ ];+ const right = [`${C.bold}Available Tools${C.reset}`];+ for (const row of tools) right.push(kv(row.label, row.value, rightWidth));+ right.push("", `${C.bold}Available Skills${C.reset}`);+ for (const row of skills) right.push(kv(row.label, row.value, rightWidth));+ const rows = Math.max(left.length, right.length);+ for (let i = 0; i < rows; i++) console.log(panelLine(left[i] || "", right[i] || "", leftWidth, rightWidth, gap));+ } else {+ const lines = [+ `${C.bold}Runtime${C.reset}`, kv("model", model, inner), kv("session", sessionId, inner), kv("endpoint", base, inner), "",+ `${C.bold}Available Tools${C.reset}`, ...tools.map((row) => kv(row.label, row.value, inner)), "",+ `${C.bold}Available Skills${C.reset}`, ...skills.map((row) => kv(row.label, row.value, inner)), "",+ `${C.bold}Capabilities${C.reset}`, `${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec · write/exec approval-gated`,+ `${C.bold}Infrastructure${C.reset}`, `${infra.ready.length}/${infra.total} ready · ${infra.ready.length ? infra.ready.join(" · ") : "run /providers to connect"}`,+ ];+ for (const line of lines) console.log(panelSingle(line, inner));+ }+ console.log(`└${rule("─", inner)}┘`);+ console.log(`${C.dim}${s.tools.length} tools · ${countSkills(s.skills)} skills · /sessions · /help for commands${C.reset}`);+ console.log();+ console.log(`${C.bold}Welcome to MSO Agent!${C.reset} Type your message or /help for commands.`);+}diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex dc6e502a..876d1d92 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -2,10 +2,13 @@import { spawnSync } from "node:child_process";import readline from "node:readline/promises";import process from "node:process";-import { canonicalAgentApproval } from "../lib/agent/approval.js";-import { BASE, CLI, C, api, printBanner, state, streamTurn } from "./mso-agent-runtime.mjs";+import { canonicalAgentApproval } from "../lib/agent/approval.mjs";+import {+ BASE, CLI, C, api, createCliSession, listCliSessions, loadCliSession,+ printBanner, saveCliSession, state, streamTurn,+} from "./mso-agent-runtime.mjs";-async function executeTool(rl, tool, call) {+async function executeTool(rl, tool, call, agentSession) {if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };let approved = tool.scope === "read";let approval = null;@@ -30,6 +33,7 @@ async function executeTool(rl, tool, call) {body: JSON.stringify({name: tool.name,input,+ sessionId: agentSession.id,...(tool.scope === "read" ? {} : { approved: true, approvalDigest: approval.digest }),}),});@@ -42,18 +46,18 @@ async function executeTool(rl, tool, call) {}}-async function agentRound(rl, history, tools) {+async function agentRound(rl, session) {for (let turn = 0; turn < 10; turn++) {- const result = await streamTurn(history, tools);- history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });+ const result = await streamTurn(session.history, session.state.tools, session.agentSession);+ session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });if (!result.toolUses.length) return;const results = [];for (const call of result.toolUses) {- const tool = tools.find((row) => row.name === call.name);- const outcome = await executeTool(rl, tool, call);+ const tool = session.state.tools.find((row) => row.name === call.name);+ const outcome = await executeTool(rl, tool, call, session.agentSession);results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });}- history.push({ role: "tool", results });+ session.history.push({ role: "tool", results });}console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);}@@ -64,11 +68,61 @@ function runCli(args) {return r.status ?? 1;}-async function slash(line, rl, session) {+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) : [];+ console.log(`${C.c}resumed ${loaded.id}${C.reset} · ${loaded.title || "MSO Agent session"}`);+}++async function slash(line, session) {const [cmd, ...args] = line.trim().split(/\s+/);switch (cmd) {case "/help":- console.log(" /model connect/change AI provider\n /setup full MSO onboarding\n /providers infrastructure provider status\n /provider <id> configure dokploy|cloudflare|hostinger\n /doctor run mso doctor\n /tools list agent tools\n /skills list available skills\n /clear clear this conversation\n /exit quit"); return "handled";+ 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",+ " /setup full MSO onboarding",+ " /providers infrastructure provider status",+ " /provider <id> configure dokploy|cloudflare|hostinger",+ " /doctor run mso doctor",+ " /tools list agent tools",+ " /skills list available skills",+ " /clear clear this session conversation",+ " /exit quit",+ ].join("\n")); return "handled";+ case "/session":+ console.log(`${C.blue}${session.agentSession.id}${C.reset} · ${session.agentSession.title || "MSO Agent session"}`); return "handled";+ case "/sessions":+ printSessions(await listCliSessions(20)); return "handled";+ case "/resume":+ if (!args[0]) console.log("usage: /resume <session-id>");+ else await resumeInto(session, args[0]);+ return "handled";case "/model": runCli(["model"]); 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";@@ -76,40 +130,69 @@ async function slash(line, rl, session) {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": for (const skill of session.state.skills?.skills ?? []) console.log(` ${skill.id}${skill.description ? ` — ${skill.description}` : ""}`); return "handled";- case "/clear": session.history.length = 0; console.log("conversation cleared."); return "handled";+ case "/clear": session.history = []; await persist(session); console.log("conversation cleared."); return "handled";case "/exit": return "exit";default: return "unknown";}}+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>");process.exit(2);}- let s = await state();- printBanner(s);+ const requested = resumeArg(process.argv.slice(2));+ const [s, agentSession] = await Promise.all([+ state(),+ requested ? loadCliSession(requested) : createCliSession(),+ ]);+ if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");+ printBanner(s, agentSession);const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true, historySize: 100 });- const session = { state: s, history: [] };+ const session = {+ state: s,+ agentSession,+ history: Array.isArray(agentSession.history) ? agentSession.history.slice(-48) : [],+ };process.on("SIGINT", () => { console.log("\nUse /exit to quit."); });try {while (true) {let line = "";- try { line = (await rl.question(`\n${C.a}${C.bold}›${C.reset} `)).trim(); }+ try { line = (await rl.question(`\n${C.blue}${C.bold}›${C.reset} `)).trim(); }catch { break; }if (!line) continue;if (line.startsWith("/")) {- const result = await slash(line, rl, session);- if (result === "exit") break;- if (result === "unknown") console.log("unknown command; /help lists commands.");+ try {+ const result = await slash(line, session);+ if (result === "exit") break;+ if (result === "unknown") console.log("unknown command; /help lists commands.");+ } catch (error) {+ console.error(`${C.err}${error instanceof Error ? error.message : String(error)}${C.reset}`);+ }continue;}session.history.push({ role: "user", text: line });- if (session.history.length > 36) session.history.splice(0, session.history.length - 36);- try { await agentRound(rl, session.history, session.state.tools); }- catch (error) { console.error(`${C.err}agent error: ${error instanceof Error ? error.message : String(error)}${C.reset}`); }+ if (session.history.length > 48) session.history.splice(0, session.history.length - 48);+ try {+ await agentRound(rl, session);+ await persist(session);+ } catch (error) {+ console.error(`${C.err}agent error: ${error instanceof Error ? error.message : String(error)}${C.reset}`);+ await persist(session).catch(() => undefined);+ }}- } finally { rl.close(); }+ } finally {+ await persist(session).catch(() => undefined);+ rl.close();+ }}main().catch((error) => { console.error(`${C.err}mso agent: ${error instanceof Error ? error.message : String(error)}${C.reset}`); process.exit(1); });diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.shindex 1ba7583d..f9de1ad5 100755--- a/scripts/mso-cli-agent.sh+++ b/scripts/mso-cli-agent.sh@@ -125,5 +125,5 @@ run_agent() {fiMSO_AGENT_BASE="$B" MSO_AGENT_ORIGIN="$B" MSO_AGENT_JAR="$JAR" \MSO_AGENT_CLI="$ROOT/bin/mso" MSO_AGENT_VERSION="$VERSION" \- node "$ROOT/scripts/mso-agent.mjs"+ node "$ROOT/scripts/mso-agent.mjs" "$@"}diff --git a/scripts/mso-gateway-boundaries.test.ts b/scripts/mso-gateway-boundaries.test.tsindex 0b4c4089..45053436 100644--- a/scripts/mso-gateway-boundaries.test.ts+++ b/scripts/mso-gateway-boundaries.test.ts@@ -53,7 +53,7 @@ esacexpect(out.status).not.toBe(0);expect(out.stderr).toContain("public endpoint did not return the MSO health contract");expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(false);- }, 15_000);+ }, 25_000);it("refuses local runtime starts while an offline update holds the checkout exclusion", async () => {const f = fixture(), base = path.join(f.dir, "runtime-exclusion");