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(mcp): ship cognitive runtime p0

Rahman539c1d50e61c
diff --git a/.env.example b/.env.example
index 6dd01acc..95ef32dd 100644
--- a/.env.example
+++ b/.env.example
@@ -205,6 +205,13 @@ OS_SESSION_SECRET=
# 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
+# Session context is estimated provider-neutrally and compacted when it reaches this
+# threshold. Raw/older context is first written as a SANITIZED gzip backup; secrets
+# are recursively redacted before archival. Defaults: 700k threshold, 140k recent.
+# OS_AGENT_SESSION_COMPACT_TOKENS=700000
+# OS_AGENT_SESSION_RECENT_TOKENS=140000
+# OS_AGENT_SESSION_ARCHIVE_DIR=~/.mso/agent-session-archive
+# OS_AGENT_SESSION_ARCHIVE_DAYS=30
# 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.json
diff --git a/AGENTS.md b/AGENTS.md
index 99d7d2e0..9eedca57 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -69,6 +69,20 @@ external mappings, skill trust/routing, and client action refresh are one releas
Do not declare an MCP change complete until that full contract is verified.
+## Cognitive-runtime work
+
+- The LLM provider is replaceable. Do not solve MSO agent quality by hard-coding one vendor's hidden
+ reasoning/session behavior when the same invariant can live in the provider-neutral harness.
+- Preserve the three identity boundaries: authenticated client principal → durable conversation session →
+ exact workflow/job. Active work is session-scoped; verified recipes may be client-scoped.
+- Public MCP remains capability-complete. MSO-owned model harnesses may defer/select schemas, compact
+ history, or bound tool output only when capability recall and permissions remain unchanged.
+- Any context/tool optimization must run `bun run bench:cognitive`; smaller prompts are not a win if
+ required-tool recall, deterministic behavior, verification, or security regresses.
+- Competitor claims require comparable measurements. A Hermes prompt-size win is not an overall Hermes
+ win; do not claim OpenClaw superiority until an equivalent task/quality benchmark exists.
+- The current contract and P1 boundaries live in `docs/COGNITIVE-RUNTIME.md`.
+
## Comparison and privileged operations
- `docs/comparison-data.json` is the comparison SSOT. Generate README/`docs/COMPARISON.md` with
diff --git a/README.md b/README.md
index c12ceb13..d1f09cb2 100644
--- a/README.md
+++ b/README.md
@@ -76,6 +76,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **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).
+- **Keep agents efficient independently of the model provider** — the MCP-first [Cognitive Runtime](./docs/COGNITIVE-RUNTIME.md) isolates conversations from OAuth identity, budgets model context/tool output, selects a compact per-turn capability set without weakening scopes, compacts durable sessions with sanitized 30-day backup archives, and learns only verified workflow recipes. `bun run bench:cognitive` guards routing recall and context footprint.
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
@@ -497,6 +498,7 @@ Not currently supported:
| [docs/CLI.md](./docs/CLI.md) | Generated `mso` command-line reference |
| [docs/DEVELOPMENT.md](./docs/DEVELOPMENT.md) | Local dev, gates and exact release flow |
| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Current AppShell/host/MCP/managed-app architecture |
+| [docs/COGNITIVE-RUNTIME.md](./docs/COGNITIVE-RUNTIME.md) | Provider-neutral agent session/context/tool-routing architecture and benchmark contract |
| [docs/COMPARISON.md](./docs/COMPARISON.md) | Generated comparison methodology, evidence and per-cell notes |
| [docs/COMPETITIVE-ROADMAP.md](./docs/COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate boundaries and next measurable investments |
| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, update, backup/restore and origins |
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index f872fb48..ff85ecd5 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -1,12 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
-import {
- agentSessionSummary,
- createAgentSession,
- getAgentSession,
- listAgentSessions,
- updateAgentSessionHistory,
-} from "@/lib/agent/session-store";
+import { createAgentSession, renameAgentSession, updateAgentSessionHistory } from "@/lib/agent/session-store";
+import { pruneAgentSessionArchives } from "@/lib/agent/session-archive";
+import { ownerSessionSummaries, resolveAgentSessionOwnerRef, resumeAgentSessionForOwner } from "@/lib/agent/session-query";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -16,43 +12,47 @@ async function ownerPrincipal(): Promise<string | null> {
return context?.role === "owner" ? `cli:${context.session.device_id}` : null;
}
+function error(error: unknown): NextResponse {
+ const message = error instanceof Error ? error.message : "agent session failed";
+ const status = message.includes("not_found") || message.includes("not found") ? 404 : message.includes("ambiguous") ? 409 : 400;
+ return NextResponse.json({ error: message.slice(0, 240) }, { status });
+}
+
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 ref = (req.nextUrl.searchParams.get("ref") || req.nextUrl.searchParams.get("id") || "").trim();
+ if (ref) {
+ try { return NextResponse.json({ session: await resolveAgentSessionOwnerRef(ref) }); }
+ catch (e) { return error(e); }
}
- const limit = Math.max(1, Math.min(100, Number(req.nextUrl.searchParams.get("limit")) || 30));
- return NextResponse.json({ sessions: await listAgentSessions(principal, limit) });
+ const limit = Math.max(1, Math.min(200, Number(req.nextUrl.searchParams.get("limit")) || 30));
+ return NextResponse.json({ sessions: await ownerSessionSummaries(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[] };
+ let body: { action?: string; id?: string; ref?: 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 });
+ return NextResponse.json({ session: await createAgentSession(principal, "cli", { title: body.title, titleSource: body.title ? "manual" : "default" }) });
}
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({ session: await updateAgentSessionHistory(principal, body.id, body.history, body.title, "auto") });
}
+ if (body.action === "resume") {
+ const ref = String(body.ref || body.id || "").trim();
+ if (!ref) return NextResponse.json({ error: "session_reference_required" }, { status: 400 });
+ return NextResponse.json({ session: await resumeAgentSessionForOwner(principal, ref) });
+ }
+ if (body.action === "rename") {
+ if (!body.id || !body.title) return NextResponse.json({ error: "id_and_title_required" }, { status: 400 });
+ return NextResponse.json({ session: await renameAgentSession(principal, body.id, body.title) });
+ }
+ if (body.action === "prune-archives") return NextResponse.json(await pruneAgentSessionArchives());
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 });
- }
+ } catch (e) { return error(e); }
}
diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.ts
index 21ce7bbe..dd1d2412 100644
--- a/app/mcp/route.test.ts
+++ b/app/mcp/route.test.ts
@@ -8,8 +8,7 @@ const mocks = vi.hoisted(() => ({
rateLimited: vi.fn(() => false),
rateLimitedUntrusted: vi.fn(() => false),
mcpRequestOriginAllowed: vi.fn(() => true),
- createAgentSession: vi.fn(),
- getAgentSession: vi.fn(),
+ findOrCreateAgentSessionForConversation: vi.fn(),
}));
vi.mock("@/lib/mcp/store", () => ({
@@ -42,8 +41,7 @@ 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,
+ findOrCreateAgentSessionForConversation: mocks.findOrCreateAgentSessionForConversation,
}));
function request(body: BodyInit, headers: Record<string, string> = {}) {
@@ -65,8 +63,7 @@ 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" }));
+ mocks.findOrCreateAgentSessionForConversation.mockReset().mockResolvedValue({ id: "20260901_100000_aabbccdd", source: "mcp" });
});
afterEach(() => vi.unstubAllEnvs());
@@ -144,10 +141,30 @@ describe("/mcp request boundary", () => {
body,
"read",
`mcp:${token.hash.slice(0, 16)}`,
- { principal: `mcp-client:${token.clientId}`, sessionId: "mso_test_session" },
+ undefined,
);
});
+ it("binds tools/call to a hashed ChatGPT conversation session without forwarding the raw conversation id", async () => {
+ const token = { hash: "e".repeat(64), scope: "read" as const, clientId: "client-session", label: "Session test" };
+ mocks.validateToken.mockResolvedValue(token);
+ const { POST } = await import("./route");
+ const rawConversation = "chatgpt-conversation-raw-secret-id";
+ const body = { jsonrpc: "2.0", id: 7, method: "tools/call", params: {
+ name: "sys_stats", arguments: {}, _meta: { "openai/session": rawConversation },
+ } };
+ const res = await POST(request(JSON.stringify(body), { "Mcp-Session-Id": "transport-rotated" }));
+ expect(res.status).toBe(200);
+ expect(mocks.findOrCreateAgentSessionForConversation).toHaveBeenCalledTimes(1);
+ const [principal, hash] = mocks.findOrCreateAgentSessionForConversation.mock.calls[0];
+ expect(principal).toBe(`mcp-client:${token.clientId}`);
+ expect(hash).toMatch(/^[a-f0-9]{64}$/);
+ expect(hash).not.toContain(rawConversation);
+ expect(mocks.dispatch).toHaveBeenCalledWith(body, "read", `mcp:${token.hash.slice(0, 16)}`, {
+ principal: `mcp-client:${token.clientId}`, sessionId: "20260901_100000_aabbccdd",
+ });
+ });
+
it("applies the 50,000-call daily token limit", async () => {
const token = { hash: "d".repeat(64), scope: "read" as const, clientId: "client-daily", label: "Daily test" };
mocks.validateToken.mockResolvedValueOnce(token);
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index d37ffa02..223ef114 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -5,21 +5,15 @@ import { publicOrigin, clientIp, mcpRequestOriginAllowed } from "@/lib/mcp/origi
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";
+import { mcpSessionHeaders, resolveMcpSession } from "@/lib/mcp/session-context";
-// 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
-// cross-origin. The CSRF gate is not what protects this route — the bearer is, and
-// a bearer is not something a browser attaches on its own the way a cookie is.
export const runtime = "nodejs";
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 {}
async function parseBoundedJson(req: Request): Promise<unknown> {
@@ -28,95 +22,37 @@ async function parseBoundedJson(req: Request): Promise<unknown> {
const length = Number(rawLength);
if (Number.isFinite(length) && length > MAX_MCP_BODY_BYTES) throw new BodyTooLarge();
}
-
if (!req.body) return JSON.parse("");
- const reader = req.body.getReader();
- const decoder = new TextDecoder();
- let total = 0;
- let text = "";
+ const reader = req.body.getReader(), decoder = new TextDecoder();
+ let total = 0, text = "";
try {
while (true) {
- const { done, value } = await reader.read();
- if (done) break;
+ const { done, value } = await reader.read(); if (done) break;
total += value.byteLength;
if (total > MAX_MCP_BODY_BYTES) {
- await reader.cancel("MCP request body too large").catch(() => {});
- throw new BodyTooLarge();
+ await reader.cancel("MCP request body too large").catch(() => {}); throw new BodyTooLarge();
}
text += decoder.decode(value, { stream: true });
}
- text += decoder.decode();
- return JSON.parse(text);
- } finally {
- reader.releaseLock();
- }
-}
-
-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" } },
- ),
- };
- }
+ text += decoder.decode(); return JSON.parse(text);
+ } finally { reader.releaseLock(); }
}
export async function POST(req: Request) {
const origin = publicOrigin(req);
const challenge = `Bearer realm="mso", resource_metadata="${origin}/.well-known/oauth-protected-resource"`;
- const unauthorized = (msg: string) =>
- Response.json(rpcError(null, UNAUTHORIZED, msg), { status: 401, headers: { "WWW-Authenticate": challenge } });
-
+ const unauthorized = (msg: string) => Response.json(rpcError(null, UNAUTHORIZED, msg), { status: 401, headers: { "WWW-Authenticate": challenge } });
if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
- if (!mcpRequestOriginAllowed(req)) {
- return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });
- }
-
- // Pre-auth flood guard: an invalid token still costs a sha256 + a file read.
+ if (!mcpRequestOriginAllowed(req)) return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });
if (rateLimitedUntrusted(`mcp:ip:${clientIp(req)}`, PREAUTH_PER_MIN, 60_000)) {
return Response.json(rpcError(null, RATE_LIMITED, "rate limited"), { status: 429, headers: { "Retry-After": "60" } });
}
const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
if (!bearer) return unauthorized("missing bearer token");
-
- // Authenticate before reading any caller-controlled body. A rejected bearer must
- // cost only the bounded token lookup, never a multi-megabyte JSON allocation.
const token = await validateToken(bearer);
if (!token) return unauthorized("invalid, revoked or expired MCP token");
const effectiveScope = clampScope(token.scope);
-
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" } });
}
@@ -125,49 +61,33 @@ export async function POST(req: Request) {
}
let body: unknown;
- try {
- body = await parseBoundedJson(req);
- } catch (error) {
- if (error instanceof BodyTooLarge) {
- return Response.json(
- { jsonrpc: "2.0", id: null, error: { code: -32600, message: "request body too large" } },
- { status: 413, headers: { "Cache-Control": "no-store" } },
- );
- }
+ try { body = await parseBoundedJson(req); }
+ catch (error) {
+ if (error instanceof BodyTooLarge) return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "request body too large" } }, { status: 413, headers: { "Cache-Control": "no-store" } });
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);
+ const principal = token.clientId ? `mcp-client:${token.clientId}` : `mcp-token:${token.hash}`;
+ const resolved = await resolveMcpSession(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, headers: sessionHeaders });
+ const headers = mcpSessionHeaders(resolved.responseSessionId);
+ if (isNotification(body)) return new Response(null, { status: 202, headers });
void touchToken(token.hash).catch(() => {});
- // 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 });
+ const agentContext = resolved.agentSessionId ? { principal, sessionId: resolved.agentSessionId } : undefined;
+ const result = await dispatch(rpc, effectiveScope, actor, agentContext);
+ return Response.json(result, { status: 200, headers });
}
-// Some clients probe with GET before POSTing. Answer with what this is, never
-// with anything that needs the token.
export async function GET(req: Request) {
if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
- if (!mcpRequestOriginAllowed(req)) {
- return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });
- }
+ if (!mcpRequestOriginAllowed(req)) return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });
return Response.json({
- name: "mso MCP",
- transport: "streamable-http (JSON-RPC over POST)",
+ 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),
+ sessions: "ChatGPT conversations bind through hashed _meta[openai/session]; Mcp-Session-Id is legacy transport compatibility only",
+ authorization_servers: [publicOrigin(req)], toolset: toolsetInfo(TOOLS),
});
}
diff --git a/bin/mso b/bin/mso
index ad306f66..43be39ef 100755
--- a/bin/mso
+++ b/bin/mso
@@ -126,7 +126,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.5.8"
+VERSION="1.6.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index da1cf3ef..e61d2a77 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -158,7 +158,7 @@ park a visible Approve/Deny card. The complete semantic contract is
**MCP** is for external clients such as ChatGPT, Claude.ai and Cursor. Its catalog lives in
`lib/mcp/`; access is controlled by the OAuth token scope rather than Alfa approval cards.
-At the current toolset it exposes 31 tools: 16 read, 10 write and 5 exec. Project-specific
+At the current toolset it exposes 47 transport tools: 46 model/operator tools (24 read, 17 write, 5 exec) plus the app-only `workflow_status` progress bridge. Project-specific
function names remain data behind `project_capabilities` / `project_function_call`, so one
project cannot dynamically rewrite the global MCP tool prefix.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index dde9018c..a24fd81a 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**
+- `mcp` ship cognitive runtime p0
- `agent` add interrupt-safe terminal controls
- `agent` add arrow picker and skill states
- `agent` align model and session terminal UX
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index 8040bfb8..7084e806 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -12,10 +12,10 @@
> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>
> and <https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex>.
-<!-- mcp-toolset: server=1.6.0 version=2026.08.31.1 tools=38 read=20 write=13 exec=5 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.1 tools=46 read=24 write=17 exec=5 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.08.31.1**: **38 tools**
-(20 read, 13 write, 5 exec). Use `GET /mcp` or Settings → MCP as the live authority if
+MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.1**: **47 transport tools** total; **46 model/operator tools**
+(24 read, 17 write, 5 exec) plus app-only `workflow_status` for the progress widget. Use `GET /mcp` or Settings → MCP as the live authority if
this document and a deployed instance ever disagree.
## 1. What this connection does
@@ -141,51 +141,58 @@ A token sees a scope prefix; there is no per-project or per-agent hidden tool fi
`tools/list` filters the catalog and `tools/call` independently re-checks the required
scope.
-### `read` — 20 tools
+### `read` — 24 model/operator tools
+- `agent_memory_read`
+- `agent_session_current`
+- `agent_session_resume`
+- `agent_sessions_list`
+- `apps_list`
+- `apps_logs`
+- `browser_status`
+- `cloudflare_zones_list`
+- `dokploy_projects_list`
+- `exec_job_status`
- `fs_list`
- `fs_read`
- `fs_search`
- `fs_usage`
-- `sys_stats`
-- `sys_processes`
-- `apps_list`
-- `apps_logs`
-- `browser_status`
-- `projects_list`
+- `infra_provider_doctor`
+- `infra_providers_list`
- `project_capabilities`
+- `projects_list`
+- `screen_capture`
- `skills_list`
- `skills_read`
- `skills_search`
-- `screen_capture`
-- `exec_job_status`
-- `infra_providers_list`
-- `infra_provider_doctor`
-- `dokploy_projects_list`
-- `cloudflare_zones_list`
-
-### `write` — read + 13 tools
+- `sys_processes`
+- `sys_stats`
+### `write` — read + 17 tools
-- `fs_write`
-- `fs_upload_file`
-- `fs_mkdir`
-- `fs_move`
+- `agent_memory_forget`
+- `agent_memory_remember`
+- `agent_session_note`
+- `agent_session_rename`
+- `apps_power`
+- `cloudflare_dns_upsert`
+- `dokploy_project_ensure`
- `fs_copy`
- `fs_delete`
-- `apps_power`
-- `workflow_start`
+- `fs_mkdir`
+- `fs_move`
+- `fs_upload_file`
+- `fs_write`
+- `hostinger_dns_upsert`
- `workflow_cancel`
- `workflow_finish`
-- `dokploy_project_ensure`
-- `cloudflare_dns_upsert`
-- `hostinger_dns_upsert`
+- `workflow_start`
### `exec` — write + 5 tools
-- `exec_run`
-- `exec_job_start`
-- `exec_job_cancel`
- `browser_power`
+- `exec_job_cancel`
+- `exec_job_start`
+- `exec_run`
- `project_function_call`
`exec_run` is full host shell power as the MSO service user. The command filter is an
@@ -214,9 +221,9 @@ Settings → MCP:
```text
server: 1.6.0
-toolset: 2026.08.31.1
+toolset: 2026.09.02.1
hash: <live schema hash>
-count: 31
+count: 46 model/operator tools (+ 1 app-only bridge)
```
Use this sequence after an MSO MCP change:
@@ -238,7 +245,31 @@ workspace **Refresh** / action-control flow to pull new or changed definitions.
are not automatically enabled. Always follow the current workspace UI if OpenAI changes
this behaviour.
-## 7. Multi-step work and `workflow_id`
+## 7. Conversation identity, durable context, and `workflow_id`
+
+ChatGPT conversation state is not the OAuth token and is not the HTTP transport session.
+For `tools/call`, MSO reads the host-provided `_meta["openai/session"]` when present, derives
+a privacy-safe SHA-256 correlation value with the stable MCP client principal, and stores only
+that digest. The raw opaque ChatGPT conversation id is never persisted or written to audit.
+`Mcp-Session-Id` remains a compatibility fallback for older/generic clients; transport-id
+rotation does not split a ChatGPT conversation when `openai/session` is available.
+
+Each conversation receives its own durable MSO Agent session and therefore its own active
+workflow/job ownership boundary. Learned successful recipes remain client-principal scoped, so
+conversation B may benefit from a verified recipe learned in conversation A without being able
+to finish/cancel A's live workflow. `agent_session_current`, `agent_sessions_list`,
+`agent_session_resume`, `agent_session_note`, and `agent_session_rename` expose only safe MSO
+operational context; they cannot recover ChatGPT's hidden transcript. Persistent `USER.md` /
+`MEMORY.md` are frozen into each new session.
+
+Durable session context has a provider-neutral estimated-token counter. The default compaction
+threshold is **700,000 tokens**; compaction preserves a structured summary plus about **140,000
+recent tokens**, and first writes a recursively redacted gzip backup. Archives default to
+**30-day retention** and are pruned both after archival and at MSO boot. The CLI can continue a
+ChatGPT/MCP session via `mso --resume <id-or-title>`; continuation is copy-on-resume rather than
+two surfaces mutating one session file.
+
+### Multi-step work and `workflow_id`
For a task needing several operational calls, ChatGPT should call `workflow_start` once.
The returned exact `workflow_id` is then included on later operational calls. Missing id =
diff --git a/docs/COGNITIVE-RUNTIME.md b/docs/COGNITIVE-RUNTIME.md
new file mode 100644
index 00000000..12e35420
--- /dev/null
+++ b/docs/COGNITIVE-RUNTIME.md
@@ -0,0 +1,168 @@
+# MSO Cognitive Runtime
+
+MSO treats the LLM as a replaceable reasoning engine. The durable product advantage lives in the
+**provider-neutral harness** around it: conversation identity, context budgeting, memory, tool discovery,
+permissions, verification, learned workflows, and reproducible evaluation.
+
+This document is the current contract for the MCP-first P0 runtime. Provider-specific features may be
+used when available, but correctness must not depend on OpenAI-, Anthropic-, Google-, Qwen-, GLM-,
+DeepSeek-, or other vendor-specific hidden state.
+
+## Invariants
+
+1. **Authentication is not conversation state.** OAuth/client identity owns durable user state and learned
+ recipes; one ChatGPT conversation owns one active MSO session/workflow namespace.
+2. **Transport is not application state.** `Mcp-Session-Id` is compatibility transport state. When ChatGPT
+ supplies `_meta["openai/session"]`, MSO hashes it with the stable client principal and never persists the
+ raw opaque conversation id.
+3. **Capabilities never bypass scopes.** Routing, programmatic selection, learned recipes, Skills, and
+ project functions may reduce what is shown to a model; they never elevate `read → write → exec`.
+4. **Context is a budget, not a transcript dump.** Large history/tool output must be projected, compacted,
+ or retrieved just in time. A bigger context window is headroom, not a reason to fill it.
+5. **Experience is reusable only after proof.** `workflow_finish(success=true)` follows independent
+ verification. The learned recipe is redacted, client-scoped, and does not grant access to another
+ conversation's active workflow.
+6. **Optimization is benchmark-gated.** A smaller prompt is not a win if tool recall or task success drops.
+
+## Identity and workflow hierarchy
+
+```text
+OAuth / MCP client principal
+│
+├─ conversation A → durable MSO session A → workflow A1 / jobs A1
+├─ conversation B → durable MSO session B → workflow B1 / jobs B1
+└─ learned verified recipes shared at the client-principal boundary
+```
+
+The audit actor remains token-specific for forensics. Active workflows and asynchronous job handles use a
+session owner derived from `principal + durable session id`; recipes use the stable principal. Therefore a
+second conversation can learn from a successful route without being able to status/finish/cancel the first
+conversation's live run.
+
+## Context lifecycle
+
+MSO keeps **durable session context** separate from the **model-active context** sent on one turn.
+
+- Durable session estimate defaults to a **700,000 token** compaction threshold.
+- Before compaction, MSO writes a recursively redacted gzip archive with owner-only permissions.
+- Compaction retains a structured summary plus approximately **140,000 recent tokens** by default.
+- Archive retention defaults to **30 days** and is enforced after archival and at MSO boot.
+- CLI continuation is copy-on-resume across surfaces, so ChatGPT/MCP and a terminal do not mutate one
+ session file concurrently.
+- The model receives recent history up to roughly 55% of its advertised context window, capped at 120k
+ history tokens, leaving headroom for system policy, memory, selected Skills/tools, reasoning, and output.
+- Assistant tool-use + matching tool-result rows are projected as one group so context trimming cannot
+ leave an invalid orphaned tool turn.
+
+Environment overrides are documented in `.env.example`:
+`OS_AGENT_SESSION_COMPACT_TOKENS`, `OS_AGENT_SESSION_RECENT_TOKENS`,
+`OS_AGENT_SESSION_ARCHIVE_DIR`, and `OS_AGENT_SESSION_ARCHIVE_DAYS`.
+
+## Deferred capability selection
+
+The external MCP server keeps a stable, complete scope-filtered catalog for standards interoperability.
+MSO's own terminal model harness uses a provider-neutral **per-turn capability router** instead of sending
+all schemas on every call.
+
+The router always retains a small control/discovery core (workflow lifecycle, `skills_search`, project and
+session discovery), scores the current request plus recent evidence, preserves recently used tools, and
+adds required companions such as `exec_job_status`/`exec_job_cancel` when a long job is selected.
+The normal target is at most 14 selected schemas before mandatory companions.
+
+If a missing capability is needed, `skills_search` searches the unified catalog of tools, Skills, and
+learned recipes. A tool named by discovery/tool output becomes eligible on the next round. The full local
+catalog still performs invocation validation, so hiding a schema from one turn neither deletes the tool nor
+changes its permission.
+
+## Tool-result budget
+
+Generic MCP text fallbacks are bounded before they enter model context:
+
+- default: **32 KiB**;
+- `exec_run`: 48 KiB;
+- file/job outputs that legitimately need more headroom: 64 KiB;
+- hard policy ceiling: 128 KiB.
+
+Oversized results return a parseable `msoTruncated` envelope containing original byte count, bounded
+preview, and a narrowing hint. Explicit MCP Apps structured projections remain separate. The correct
+recovery is a narrower read/search/grep/tail, not silently increasing the context flood.
+
+## Memory planes in P0
+
+P0 intentionally keeps two proven memory layers rather than inventing one universal store:
+
+- **Agent memory** (`USER.md` / `MEMORY.md`) — stable client-principal facts, frozen into each new session.
+- **Experience memory** — successful/failed workflow trajectories, redacted replayable step shape,
+ semantic embedding, success rate, fastest/average duration, and last-use evidence.
+
+The next memory revision may introduce typed semantic/episodic/procedural records with provenance,
+confidence, temporal validity, supersession, and conflict resolution. That is P1/P2 work and must beat the
+P0 retrieval/evaluation baseline before becoming the default.
+
+## Benchmark contract
+
+Run:
+
+```bash
+bun run bench:cognitive
+bun scripts/bench-cognitive-runtime.mjs --json
+```
+
+The P0 benchmark is deterministic and provider-neutral. Its checked scenarios cover application logs,
+server health, safe file editing, long/short execution, project functions, Cloudflare/Hostinger/Dokploy,
+browser/screenshots, memory, session resume, and Skills.
+
+Release gates require:
+
+- **100% required-tool recall** on the checked scenarios;
+- deterministic selection for identical input;
+- lower active schema bytes than the full MSO catalog;
+- when Hermes' installed CLI exposes `hermes prompt-size`, lower active tool-schema bytes than that exact
+ comparable metric.
+
+The benchmark reports OpenClaw's installed version but **does not declare an OpenClaw win** from schema
+footprint because the installed OpenClaw CLI currently exposes no directly equivalent offline prompt-size
+probe. Overall product superiority also cannot be inferred from a prompt-size result. Future comparison
+must add equivalent task-success, tool-error, token-per-success, latency-per-success, and policy-compliance
+scenarios before making that claim.
+
+## Current P0 baseline
+
+On the development host at implementation time:
+
+| Metric | MSO P0 | Hermes local baseline |
+|---|---:|---:|
+| Full MSO transport catalog | 47 tools | — |
+| Full MSO schema bytes | 31,212 | — |
+| Average MSO active tools / turn | 14.6 | — |
+| Average active schema bytes / turn | 11,074 | 44,758 tool-schema bytes |
+| MSO schema reduction vs full catalog | 64.5% | — |
+| Required-tool routing recall | 100% | not the same benchmark |
+| Deterministic routing | yes | not the same benchmark |
+
+These numbers are a reproducible **harness-footprint baseline**, not an overall quality leaderboard. Re-run
+the benchmark after catalog/router changes; do not copy the numbers into marketing claims without a fresh
+measurement and comparable evaluation.
+
+## P1 direction
+
+P1 should build on these invariants rather than replace them:
+
+1. typed memory records with provenance, confidence, sensitivity, temporal validity, and supersession;
+2. retrieval evaluation before adding graph complexity;
+3. Tool/Skill quality telemetry (success, latency, cost, invalid arguments, retries, rollback);
+4. an eval-gated **Tool Forge** that may propose project functions/Skills from repeated verified workflows,
+ but cannot promote generated code directly to trusted execution;
+5. optional programmatic read-only orchestration for bulk filtering/aggregation, still constrained by the
+ caller's scope and normal host guards;
+6. task-success benchmarks shared with Hermes/OpenClaw where equivalent non-interactive contracts exist.
+
+## Security notes
+
+- Session archives are private backups, not secret vaults; recursive redaction happens before compression.
+- Persistent memory is data, never an instruction or permission source.
+- A discovered Skill or recipe cannot grant a tool the caller's token does not already permit.
+- Untrusted Skills keep their instructions withheld until promoted through the existing trust process.
+- `exec_run` remains full service-user shell power at `exec` scope; cognitive routing is not a sandbox.
+- Never expose raw ChatGPT conversation ids, tokens, credentials, hidden chain-of-thought, or unrestricted
+ tool output in memory/recipes/archives.
diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
index 7af3018a..1197337a 100644
--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md
+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
@@ -4,10 +4,10 @@
> can evolve independently, so do not claim its mapping count is current without checking
> that repository at the time of the change.
-<!-- mcp-toolset: server=1.6.0 version=2026.08.31.1 tools=38 read=20 write=13 exec=5 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.1 tools=46 read=24 write=17 exec=5 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.08.31.1**: **38 tools**
-(20 read, 13 write, 5 exec). `GET /mcp` exposes the live names, version/hash and scoped
+MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.1**: **47 tools**
+(25 read, 17 write, 5 exec). `GET /mcp` exposes the live names, version/hash and scoped
manifest and is the machine-readable parity source.
## Why this contract matters
@@ -33,22 +33,28 @@ Before changing an MCP tool name:
## Current MSO catalog
-### Read (20)
+### Read (24 model/operator)
-`fs_list`, `fs_read`, `fs_search`, `fs_usage`, `sys_stats`, `sys_processes`,
-`apps_list`, `apps_logs`, `browser_status`, `projects_list`, `project_capabilities`,
-`skills_list`, `skills_read`, `skills_search`, `screen_capture`, `exec_job_status`,
-`infra_providers_list`, `infra_provider_doctor`, `dokploy_projects_list`, `cloudflare_zones_list`.
+`agent_memory_read`, `agent_session_current`, `agent_session_resume`, `agent_sessions_list`,
+`apps_list`, `apps_logs`, `browser_status`, `cloudflare_zones_list`, `dokploy_projects_list`,
+`exec_job_status`, `fs_list`, `fs_read`, `fs_search`, `fs_usage`, `infra_provider_doctor`,
+`infra_providers_list`, `project_capabilities`, `projects_list`, `screen_capture`, `skills_list`,
+`skills_read`, `skills_search`, `sys_processes`, `sys_stats`.
-### Write (13 beyond read)
+### Write (17 beyond read)
-`fs_write`, `fs_upload_file`, `fs_mkdir`, `fs_move`, `fs_copy`, `fs_delete`,
-`apps_power`, `workflow_start`, `workflow_cancel`, `workflow_finish`,
-`dokploy_project_ensure`, `cloudflare_dns_upsert`, `hostinger_dns_upsert`.
+`agent_memory_forget`, `agent_memory_remember`, `agent_session_note`, `agent_session_rename`,
+`apps_power`, `cloudflare_dns_upsert`, `dokploy_project_ensure`, `fs_copy`, `fs_delete`,
+`fs_mkdir`, `fs_move`, `fs_upload_file`, `fs_write`, `hostinger_dns_upsert`,
+`workflow_cancel`, `workflow_finish`, `workflow_start`.
### Exec (5 beyond write)
-`exec_run`, `browser_power`, `project_function_call`, `exec_job_start`, `exec_job_cancel`.
+`browser_power`, `exec_job_cancel`, `exec_job_start`, `exec_run`, `project_function_call`.
+
+### App-only bridge (1)
+
+`workflow_status` is exposed for the MCP Apps progress widget and is not part of the model/operator action catalog.
## Scope and workflow compatibility
diff --git a/docs/MCP.md b/docs/MCP.md
index 53ed3fd2..92c593e4 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -75,8 +75,8 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe
| Scope | Tools |
|---|---|
-| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` `exec_job_status` `infra_providers_list` `infra_provider_doctor` `dokploy_projects_list` `cloudflare_zones_list` |
-| `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` `dokploy_project_ensure` `cloudflare_dns_upsert` `hostinger_dns_upsert` |
+| `read` | `agent_memory_read` `agent_session_current` `agent_session_resume` `agent_sessions_list` `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` `exec_job_status` `infra_providers_list` `infra_provider_doctor` `dokploy_projects_list` `cloudflare_zones_list` |
+| `write` | + `agent_memory_forget` `agent_memory_remember` `agent_session_note` `agent_session_rename` `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` `dokploy_project_ensure` `cloudflare_dns_upsert` `hostinger_dns_upsert` |
| `exec` | + `project_function_call` `exec_run` `exec_job_start` `exec_job_cancel` `browser_power` |
Alfa — the in-app assistant — overlaps the same host capabilities under dot.case names,
@@ -124,12 +124,13 @@ The catalog has a stable server version plus a schema-derived toolset signature.
Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.
-<!-- mcp-toolset: server=1.6.0 version=2026.08.31.1 tools=38 read=20 write=13 exec=5 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.1 tools=46 read=24 write=17 exec=5 -->
-Current catalog: **31 tools** (16 read, 10 write, 5 exec), server `1.6.0` / toolset
-`2026.08.28.1`. `project_capabilities` and `project_function_call` add one stable
-project-automation seam without creating a dynamic MCP tool catalog; existing tool names
-remain unchanged.
+Current transport catalog: **47 tools**, server `1.6.0` / toolset `2026.09.02.1`.
+The model/operator catalog is **46 tools** (24 read, 17 write, 5 exec); `workflow_status` is the
+one app-only MCP Apps bridge used by the progress widget and is documented separately. Session/memory tools add durable conversation context without creating
+dynamic per-project tool names; `project_capabilities` and `project_function_call` remain the
+stable project-automation seam.
## Opt-in project MCP/function capabilities
@@ -325,6 +326,34 @@ through `realpath` again.
its `project`, and the bootstrap carries a `discovery.complete` flag plus a
`[Discovery] partial scan` trace line when the catalog was truncated.
+## MCP-first cognitive runtime
+
+MSO keeps the public MCP catalog capability-complete and scope-stable, but its own terminal
+agent does not stuff every schema into every model turn. A provider-neutral router keeps a
+small core (`workflow_*`, `skills_search`, project/session discovery), scores the current user
+intent plus recent tool evidence, and normally loads at most 14 relevant schemas plus required
+companions. `skills_search` already searches tools as well as skills/recipes, so a tool named by
+discovery becomes available on the next model round without changing permissions. Public MCP
+`tools/list` remains the full scope-filtered catalog for interoperability.
+
+Generic MCP text results are also context-budgeted: 32 KiB by default, with explicit bounded
+exceptions for file reads and long-job output. Oversize results return a parseable
+`msoTruncated` envelope with byte counts, a preview, and a narrowing hint instead of flooding
+the model context. Explicit MCP Apps structured projections remain separate. The same rule
+applies regardless of whether the selected provider is OpenAI, Anthropic, Google, Qwen, GLM,
+DeepSeek, or another compatible backend.
+
+The CLI persists much more session history than it shows the model. Before a model call, recent
+history is projected to roughly 55% of the model's context window (capped at 120k history
+tokens) so system instructions, memory, skill/tool schemas, reasoning and output retain
+headroom. At the durable 700k session threshold, structured compaction + sanitized archival
+reduces storage context and feeds the compact summary back into later turns.
+
+Run `bun run bench:cognitive` for the reproducible provider-neutral routing/footprint gate. It
+requires 100% required-tool recall and deterministic routing across the checked scenarios.
+Hermes is compared only where an equivalent offline `prompt-size` metric exists; OpenClaw is
+reported but is not declared beaten on a non-comparable metric.
+
## Semantic skill search and learned workflows
MSO does not need to rediscover the same safe procedure on every conversation.
@@ -337,8 +366,10 @@ For a multi-step task, `workflow_start` is the **single bootstrap call**. It:
5. recommends the closest successful recipe and execution policy.
Every operational tool advertises an optional `workflow_id`. Carry the exact id returned
-by `workflow_start` on each step in that run. Multiple conversations may hold isolated
-workflows in parallel on the same token. A call that omits the id is deliberately
+by `workflow_start` on each step in that run. Active workflow/job ownership is derived from the
+durable conversation session (ChatGPT uses a hash of `_meta["openai/session"]` when present),
+while learned recipes are keyed to the stable client principal. Multiple conversations may
+hold isolated workflows in parallel on the same token. A call that omits the id is deliberately
standalone, and an unknown id is refused before the operation runs.
On approval, MSO returns the validated PKCE callback to the consent client, which uses
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 80ccad43..f0883c27 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,18 @@
Running log of what shipped each phase. Newest at top.
+## 2026-09-02 — MCP-first Cognitive Runtime P0 — SHIPPED
+
+MSO CLI **1.6.0** moves agent quality into the provider-neutral harness instead of relying on one model vendor. ChatGPT/MCP identity is now layered as **authenticated client → durable conversation session → workflow/job**: `_meta["openai/session"]` is hashed with the stable client principal and the raw opaque conversation id is never persisted, transport-session rotation does not split a ChatGPT conversation, active workflows/jobs are session-scoped, and verified learned recipes remain reusable at the stable client-principal boundary. This lets parallel chats benefit from prior successful procedures without being able to status, finish, cancel, or attach to each other's live work.
+
+Durable session context now has an explicit lifecycle. MSO estimates stored context provider-neutrally, compacts at **700,000 tokens** by default, preserves a structured summary plus roughly **140,000 recent tokens**, writes a recursively redacted owner-only gzip archive before compaction, and prunes archives after **30 days** both after archival and at boot. CLI continuation uses copy-on-resume across MCP/terminal surfaces. Separately, one model call receives only recent projected history—roughly 55% of the advertised context window, capped at 120k history tokens—so system policy, memory, active Skills/tools, reasoning and output retain headroom; assistant tool-use + matching result rows are projected atomically. `/status` distinguishes active model context from durable session/lifetime counters and compaction/archive counts.
+
+Tool context is now budgeted at both schema and result layers. The public MCP transport remains capability-complete at **47 tools**; the documented model/operator catalog is **46 tools** (**24 read, 17 write, 5 exec**) plus app-only `workflow_status`. MSO's own terminal harness uses a deterministic per-turn router with a 14-schema soft target, core discovery/control tools, recently used tools and required companions. Generic MCP result text is capped at **32 KiB** by default, `exec_run` at 48 KiB, and file/long-job outputs at 64 KiB; oversize results return a parseable `msoTruncated` preview/hint instead of flooding the model context. MCP toolset version is **2026.09.02.1**.
+
+`bun run bench:cognitive` is now a release-quality provider-neutral harness. On the release host, the full MSO catalog is **47 tools / 31,212 schema bytes**, while 14 representative scenarios select **14.6 tools / 11,074 schema bytes on average**, a **64.5% reduction**, with **100% required-tool recall** and deterministic routing. The installed Hermes v0.20.0 baseline reports **27 tools / 44,758 tool-schema bytes**, so P0 is smaller on that exact comparable schema-footprint metric while preserving benchmark recall. This is deliberately **not** an overall Hermes claim. Installed OpenClaw 2026.7.1-2 has no directly equivalent offline prompt-size probe exposed to this harness, so no OpenClaw superiority claim is made yet; equivalent task-success, tool-error, token-per-success, latency and policy-compliance scenarios remain the proper overall benchmark target.
+
+Final repository verification passes **271 test files / 1,972 passing tests** with **1 expected-fail and 7 skipped**. TypeScript passes; lint has **0 errors** and only five existing `max-lines` warnings; value cycles are 0; docs report 49 current Markdown files and exact MCP parity; contrast has 0 WCAG failures; all 11 official skill flows validate; and the high/critical dependency audit is clean. `docs/COGNITIVE-RUNTIME.md` is the SSOT for these invariants and the P1 path: provenance/temporal typed memory, Tool/Skill quality telemetry, eval-gated Tool Forge, scope-preserving programmatic orchestration, and genuinely comparable Hermes/OpenClaw task-quality benchmarks.
+
## 2026-09-01 — External TTY Ctrl+C handoff hardening — SHIPPED
MSO Agent 1.5.8 closes one live-only SIGINT edge case found after the 1.5.7 deployment: cancelling the `/model` child TUI could leave the shared terminal in cooked mode, so the next Ctrl+C arrived as an OS `SIGINT` while the parent composer was awaiting a keypress. The interrupt manager correctly requested exit, but the waiting prompt was not resolved. `AgentComposer` now exposes one idempotent `cancelCurrent()` primitive shared by raw-key Ctrl+C and OS-level SIGINT. The parent SIGINT bridge wakes the current prompt on exit/interrupt, so child TTY handoffs cannot strand the Agent.
diff --git a/docs/README.md b/docs/README.md
index 6b40db0a..06f68a06 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -21,6 +21,7 @@ evidence and review freshness. The repository quality gate runs both automatical
|---|---|
| [`../README.md`](../README.md) | Product overview and quickstart |
| [`ARCHITECTURE.md`](./ARCHITECTURE.md) | Current runtime, shell, role, host, MCP and deployment architecture |
+| [`COGNITIVE-RUNTIME.md`](./COGNITIVE-RUNTIME.md) | Provider-neutral MCP/session/context/tool-routing runtime and benchmark contract |
| [`COMPARISON.md`](./COMPARISON.md) | Generated product comparison methodology, evidence and notes |
| [`COMPETITIVE-ROADMAP.md`](./COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate specialist boundaries and next investments |
| [`INSTALL.md`](./INSTALL.md) | Owner installation, TLS, updates, backup and uninstall |
diff --git a/instrumentation.ts b/instrumentation.ts
index ba8f1271..4a8a1490 100644
--- a/instrumentation.ts
+++ b/instrumentation.ts
@@ -6,6 +6,12 @@ import type { Instrumentation } from "next";
export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs") return;
+ // Enforce private session-archive retention at boot even when no new session
+ // reaches the compaction threshold for weeks. Best-effort: retention cleanup
+ // must never make the application fail to start.
+ void import("./lib/agent/session-archive")
+ .then(({ pruneAgentSessionArchives }) => pruneAgentSessionArchives())
+ .catch(() => undefined);
// systemd liveness: when the unit sets WatchdogSec, systemd exposes
// NOTIFY_SOCKET + WATCHDOG_USEC. Node has no native AF_UNIX SOCK_DGRAM
// (dgram is UDP-only), so we ping via the `systemd-notify` binary — which
diff --git a/lib/agent/session-archive.ts b/lib/agent/session-archive.ts
new file mode 100644
index 00000000..88f49584
--- /dev/null
+++ b/lib/agent/session-archive.ts
@@ -0,0 +1,75 @@
+import { 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 { promisify } from "node:util";
+import { gzip } from "node:zlib";
+import type { AgentSession } from "./session-types";
+import { redactUnknown } from "@/lib/security/redact-text";
+
+const gzipAsync = promisify(gzip);
+const ARCHIVE_FILE = /^\d{8}_\d{6}_[a-f0-9]{8}__\d{8}T\d{6}Z__[a-z0-9-]+\.json\.gz$/;
+
+function expandHome(value: string): string {
+ return value.replace(/^~(?=$|\/)/, os.homedir());
+}
+
+export function agentSessionArchiveRoot(): string {
+ return path.resolve(expandHome(process.env.OS_AGENT_SESSION_ARCHIVE_DIR || path.join(os.homedir(), ".mso", "agent-session-archive")));
+}
+
+export function archiveRetentionDays(): number {
+ const raw = Number(process.env.OS_AGENT_SESSION_ARCHIVE_DAYS);
+ return Number.isFinite(raw) ? Math.max(1, Math.min(365, Math.trunc(raw))) : 30;
+}
+
+function stamp(now: Date): string {
+ return now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
+}
+
+function safeReason(reason: string): string {
+ return reason.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 32) || "backup";
+}
+
+async function secureRoot(): Promise<string> {
+ const root = agentSessionArchiveRoot();
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
+ await fs.chmod(root, 0o700).catch(() => undefined);
+ return root;
+}
+
+export async function archiveAgentSession(record: AgentSession, reason: string, now = new Date()): Promise<string> {
+ const root = await secureRoot();
+ const name = `${record.id}__${stamp(now)}__${safeReason(reason)}.json.gz`;
+ if (!ARCHIVE_FILE.test(name)) throw new Error("invalid agent session archive name");
+ const target = path.join(root, name);
+ const payload = Buffer.from(JSON.stringify(redactUnknown({ schemaVersion: 1, archivedAt: now.toISOString(), reason, session: record }), null, 2));
+ const compressed = await gzipAsync(payload, { level: 9 });
+ const tmp = `${target}.${randomUUID()}.tmp`;
+ await fs.writeFile(tmp, compressed, { mode: 0o600, flag: "wx" });
+ await fs.chmod(tmp, 0o600);
+ await fs.rename(tmp, target);
+ await fs.chmod(target, 0o600);
+ return target;
+}
+
+export async function pruneAgentSessionArchives(now = Date.now()): Promise<{ removed: number; kept: number }> {
+ const root = await secureRoot();
+ const cutoff = now - archiveRetentionDays() * 86_400_000;
+ const names = await fs.readdir(root).catch(() => [] as string[]);
+ let removed = 0, kept = 0;
+ for (const name of names) {
+ if (!ARCHIVE_FILE.test(name)) continue;
+ const file = path.join(root, name);
+ 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() || (typeof process.getuid === "function" && stat.uid !== process.getuid())) continue;
+ if (stat.mtimeMs >= cutoff) { kept++; continue; }
+ } catch { continue; }
+ finally { await handle?.close().catch(() => undefined); }
+ await fs.unlink(file).then(() => { removed++; }).catch(() => undefined);
+ }
+ return { removed, kept };
+}
diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.ts
new file mode 100644
index 00000000..885b7574
--- /dev/null
+++ b/lib/agent/session-files.ts
@@ -0,0 +1,92 @@
+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 { compactThresholdTokens, inferredTitleSource, MAX_EVENTS, MAX_HISTORY, safeTitle, sessionContextTokens } from "./session-policy";
+import type { AgentSession } from "./session-types";
+
+const ROOT = path.resolve((process.env.OS_AGENT_SESSIONS_DIR || path.join(os.homedir(), ".mso", "agent-sessions")).replace(/^~(?=$|\/)/, os.homedir()));
+export const SESSION_LOCK_TARGET = path.join(ROOT, ".sessions");
+export const SESSION_ID = /^\d{8}_\d{6}_[a-f0-9]{8}$/;
+const MAX_SESSION_BYTES = 16 * 1024 * 1024;
+
+export function principalHash(principal: string): string {
+ if (!principal || principal.length > 512) throw new Error("invalid agent session principal");
+ return createHash("sha256").update(principal).digest("hex");
+}
+
+export function newAgentSessionId(now = new Date()): string {
+ const iso = now.toISOString();
+ return `${iso.slice(0, 10).replaceAll("-", "")}_${iso.slice(11, 19).replaceAll(":", "")}_${randomBytes(4).toString("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;
+}
+
+export function normalizeSession(raw: AgentSession): AgentSession {
+ const title = safeTitle(raw.title);
+ const threshold = Number(raw.compactThresholdTokens) || compactThresholdTokens();
+ const base = {
+ ...raw,
+ title,
+ titleSource: inferredTitleSource(title, raw.titleSource),
+ history: Array.isArray(raw.history) ? raw.history.slice(-MAX_HISTORY) : [],
+ events: Array.isArray(raw.events) ? raw.events.slice(-MAX_EVENTS) : [],
+ compactThresholdTokens: threshold,
+ compactionCount: Math.max(0, Number(raw.compactionCount) || 0),
+ archiveCount: Math.max(0, Number(raw.archiveCount) || 0),
+ lifetimeEstimatedTokens: Math.max(0, Number(raw.lifetimeEstimatedTokens) || 0),
+ } as AgentSession;
+ const estimatedTokens = sessionContextTokens(base);
+ return { ...base, estimatedTokens, lifetimeEstimatedTokens: Math.max(base.lifetimeEstimatedTokens, estimatedTokens) };
+}
+
+export async function readSessionFile(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() || stat.size <= 0 || stat.size > MAX_SESSION_BYTES) throw new Error("agent session has an invalid file shape");
+ 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 normalizeSession(raw);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw error;
+ } finally { await handle?.close().catch(() => undefined); }
+}
+
+export async function writeSessionFile(record: AgentSession): Promise<void> {
+ await fs.mkdir(ROOT, { recursive: true, mode: 0o700 });
+ await fs.chmod(ROOT, 0o700).catch(() => undefined);
+ const normalized = normalizeSession(record);
+ const body = JSON.stringify(normalized, null, 2);
+ if (Buffer.byteLength(body, "utf8") > MAX_SESSION_BYTES) throw new Error("agent session exceeds 16 MiB before compaction");
+ const file = fileFor(record.id), 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);
+}
+
+export async function listSessionRecords(): Promise<AgentSession[]> {
+ let names: string[];
+ try { names = await fs.readdir(ROOT); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
+ throw error;
+ }
+ const out: AgentSession[] = [];
+ for (const name of names.slice(0, 5000)) {
+ if (!name.endsWith(".json")) continue;
+ const id = name.slice(0, -5);
+ if (!SESSION_ID.test(id)) continue;
+ try { const row = await readSessionFile(id); if (row) out.push(row); } catch { /* isolate corrupt rows */ }
+ }
+ return out;
+}
diff --git a/lib/agent/session-policy.ts b/lib/agent/session-policy.ts
new file mode 100644
index 00000000..24e7cf68
--- /dev/null
+++ b/lib/agent/session-policy.ts
@@ -0,0 +1,111 @@
+import { createHash } from "node:crypto";
+import { redactText } from "@/lib/security/redact-text";
+import type { AgentSession, AgentSessionEvent, AgentSessionTitleSource } from "./session-types";
+
+export const MAX_HISTORY = 4096;
+export const MAX_EVENTS = 400;
+const DEFAULT_COMPACT_TOKENS = 700_000;
+const DEFAULT_RECENT_TOKENS = 140_000;
+const GENERIC_TITLES = /^(MSO Agent session|ChatGPT\/MCP|ChatGPT session|MCP legacy session)/i;
+
+function intEnv(name: string, fallback: number, min: number, max: number): number {
+ const value = Number(process.env[name]);
+ return Number.isFinite(value) ? Math.max(min, Math.min(max, Math.trunc(value))) : fallback;
+}
+
+export function compactThresholdTokens(): number {
+ return intEnv("OS_AGENT_SESSION_COMPACT_TOKENS", DEFAULT_COMPACT_TOKENS, 10_000, 5_000_000);
+}
+
+export function recentContextTargetTokens(): number {
+ return Math.min(compactThresholdTokens() - 1_000, intEnv("OS_AGENT_SESSION_RECENT_TOKENS", DEFAULT_RECENT_TOKENS, 5_000, 500_000));
+}
+
+export function estimateTokens(value: unknown): number {
+ let text: string;
+ try { text = typeof value === "string" ? value : JSON.stringify(value ?? ""); }
+ catch { text = String(value ?? ""); }
+ return Math.ceil(Buffer.byteLength(text, "utf8") / 4);
+}
+
+export function safeTitle(value: string | undefined): string {
+ const text = String(value ?? "MSO Agent session").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();
+ return (text || "MSO Agent session").slice(0, 120);
+}
+
+export function autoSessionTitle(hint: string): string {
+ const clean = redactText(String(hint).replace(/[`*_#>]+/g, " ").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim(), 500);
+ const clause = clean.split(/\s+[—–|]\s+|[.!?](?:\s|$)/)[0]?.trim() || clean;
+ return safeTitle(clause.slice(0, 88) || "MSO Agent session");
+}
+
+export function inferredTitleSource(title: string, source?: AgentSessionTitleSource): AgentSessionTitleSource {
+ if (source) return source;
+ return GENERIC_TITLES.test(title) ? "default" : "auto";
+}
+
+export function conversationHash(principal: string, raw: string): string {
+ return createHash("sha256").update(principal).update("\0").update(raw).digest("hex");
+}
+
+export function sessionContextTokens(record: Pick<AgentSession, "memorySnapshot" | "contextSummary" | "history" | "events">): number {
+ return estimateTokens(record.memorySnapshot) + estimateTokens(record.contextSummary ?? "") + estimateTokens(record.history) + estimateTokens(record.events);
+}
+
+function lineFromHistory(row: unknown): string | null {
+ if (!row || typeof row !== "object") return null;
+ const item = row as Record<string, unknown>;
+ const role = typeof item.role === "string" ? item.role : "context";
+ const text = typeof item.text === "string" ? item.text : typeof item.content === "string" ? item.content : "";
+ if (!text.trim()) return null;
+ return `${role}: ${redactText(text.replace(/\s+/g, " ").trim(), 700)}`;
+}
+
+function summaryFrom(record: AgentSession, at: string): string {
+ const prior = record.contextSummary ? redactText(record.contextSummary, 12_000) : "";
+ const turns = record.history.map(lineFromHistory).filter((v): v is string => Boolean(v)).slice(-28);
+ const events = record.events.slice(-24).map((e: AgentSessionEvent) =>
+ `${e.at} ${e.tool || e.kind}${e.state ? `:${e.state}` : ""}${e.detail ? ` — ${redactText(e.detail, 360)}` : ""}`,
+ );
+ return [
+ `MSO session context compacted at ${at}.`,
+ prior ? `Previous compact summary:\n${prior}` : "",
+ turns.length ? `Key recent conversation turns:\n${turns.map((v) => `- ${v}`).join("\n")}` : "",
+ events.length ? `Recent operational timeline:\n${events.map((v) => `- ${v}`).join("\n")}` : "",
+ ].filter(Boolean).join("\n\n").slice(0, 32_000);
+}
+
+function compactRow(row: unknown): unknown {
+ if (typeof row === "string") return row.length > 24_000 ? row.slice(0, 24_000) + "\n[compacted]" : row;
+ if (!row || typeof row !== "object") return row;
+ const copy = structuredClone(row) as Record<string, unknown>;
+ for (const [key, value] of Object.entries(copy)) {
+ if (typeof value === "string" && value.length > 24_000) copy[key] = value.slice(0, 24_000) + "\n[compacted]";
+ else if (Array.isArray(value) && value.length > 40) copy[key] = value.slice(-40);
+ }
+ return copy;
+}
+
+export function compactSessionContext(record: AgentSession, at: string): AgentSession {
+ const target = recentContextTargetTokens();
+ const kept: unknown[] = [];
+ let used = 0;
+ for (const raw of [...record.history].reverse()) {
+ const row = compactRow(raw);
+ const cost = estimateTokens(row);
+ if (kept.length && used + cost > target) break;
+ kept.unshift(row); used += cost;
+ if (used >= target) break;
+ }
+ const event: AgentSessionEvent = { at, kind: "compacted", detail: `context exceeded ${record.compactThresholdTokens} estimated tokens` };
+ const next: AgentSession = {
+ ...record,
+ contextSummary: summaryFrom(record, at),
+ history: kept.slice(-MAX_HISTORY),
+ events: [...record.events.slice(-(MAX_EVENTS - 1)), event],
+ compactionCount: record.compactionCount + 1,
+ lastCompactedAt: at,
+ updatedAt: at,
+ };
+ return { ...next, estimatedTokens: sessionContextTokens(next) };
+}
diff --git a/lib/agent/session-query.ts b/lib/agent/session-query.ts
new file mode 100644
index 00000000..47237437
--- /dev/null
+++ b/lib/agent/session-query.ts
@@ -0,0 +1,48 @@
+import { createAgentSession, getAgentSession, listAgentSessionsOwner } from "./session-store";
+import { listSessionRecords, principalHash } from "./session-files";
+import { redactText } from "@/lib/security/redact-text";
+import type { AgentSession } from "./session-types";
+
+function cleanRef(value: string): string {
+ return value.trim().replace(/^-(?=\d{8}_\d{6}_[a-f0-9]{8}$)/, "");
+}
+
+function choose(records: AgentSession[], refValue: string): AgentSession {
+ const ref = cleanRef(refValue), q = ref.toLowerCase();
+ const exactId = records.find((row) => row.id === ref); if (exactId) return exactId;
+ const idPrefix = records.filter((row) => row.id.startsWith(ref)); if (idPrefix.length === 1) return idPrefix[0]!;
+ const exactTitle = records.filter((row) => row.title.toLowerCase() === q); if (exactTitle.length === 1) return exactTitle[0]!;
+ const titlePrefix = records.filter((row) => row.title.toLowerCase().startsWith(q)); if (titlePrefix.length === 1) return titlePrefix[0]!;
+ const matches = [...idPrefix, ...exactTitle, ...titlePrefix];
+ if (matches.length > 1) throw new Error(`session reference is ambiguous: ${[...new Set(matches.map((row) => row.id))].slice(0, 6).join(", ")}`);
+ throw new Error("session_not_found");
+}
+
+export async function resolveAgentSessionRef(principal: string, ref: string): Promise<AgentSession> {
+ const owner = principalHash(principal);
+ return choose((await listSessionRecords()).filter((row) => row.principalHash === owner), ref);
+}
+
+export async function resolveAgentSessionOwnerRef(ref: string): Promise<AgentSession> {
+ return choose(await listSessionRecords(), ref);
+}
+
+function resumedSummary(target: AgentSession): string {
+ const events = target.events.slice(-20).map((row) =>
+ `${row.at} ${row.tool || row.kind}${row.state ? `:${row.state}` : ""}${row.detail ? ` — ${redactText(row.detail, 260)}` : ""}`,
+ );
+ return [target.contextSummary || "", `Resumed in CLI from ${target.id} (${target.source}) at ${new Date().toISOString()}.`, events.length ? `Recent source events:\n${events.map((v) => `- ${v}`).join("\n")}` : ""]
+ .filter(Boolean).join("\n\n").slice(0, 32_000);
+}
+
+export async function resumeAgentSessionForOwner(cliPrincipal: string, ref: string): Promise<AgentSession> {
+ const target = await resolveAgentSessionOwnerRef(ref);
+ const existing = await getAgentSession(cliPrincipal, target.id).catch(() => null);
+ if (existing?.source === "cli") return existing;
+ return createAgentSession(cliPrincipal, "cli", {
+ title: `Resume · ${target.title}`, titleSource: "auto", resumedFrom: target.id,
+ memorySnapshot: target.memorySnapshot, contextSummary: resumedSummary(target), history: target.history.slice(-24),
+ });
+}
+
+export async function ownerSessionSummaries(limit = 100) { return listAgentSessionsOwner(limit); }
diff --git a/lib/agent/session-store.test.ts b/lib/agent/session-store.test.ts
new file mode 100644
index 00000000..7f43b19a
--- /dev/null
+++ b/lib/agent/session-store.test.ts
@@ -0,0 +1,70 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+import { gunzip } from "node:zlib";
+
+const gunzipAsync = promisify(gunzip);
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-agent-session-p0-"));
+const sessions = path.join(root, "sessions");
+const memory = path.join(root, "memory");
+const archives = path.join(root, "archives");
+
+process.env.OS_AGENT_SESSIONS_DIR = sessions;
+process.env.OS_AGENT_MEMORY_DIR = memory;
+process.env.OS_AGENT_SESSION_ARCHIVE_DIR = archives;
+process.env.OS_AGENT_SESSION_COMPACT_TOKENS = "10000";
+process.env.OS_AGENT_SESSION_RECENT_TOKENS = "5000";
+process.env.OS_AGENT_SESSION_ARCHIVE_DAYS = "30";
+afterAll(async () => {
+ for (const key of ["OS_AGENT_SESSIONS_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSION_ARCHIVE_DIR", "OS_AGENT_SESSION_COMPACT_TOKENS", "OS_AGENT_SESSION_RECENT_TOKENS", "OS_AGENT_SESSION_ARCHIVE_DAYS"]) delete process.env[key];
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+// Import after env setup so module-level secure paths point only at this fixture.
+vi.resetModules();
+const store = await import("./session-store");
+const archive = await import("./session-archive");
+
+describe("durable agent session context policy", () => {
+ it("compacts at the token threshold, archives a sanitized backup, and tracks timestamps/counters", async () => {
+ const session = await store.createAgentSession("principal:compact", "cli", { title: "Compaction test" });
+ const history = Array.from({ length: 28 }, (_, i) => ({
+ role: i % 2 ? "assistant" : "user",
+ text: `${i} deployment decision api_key=should-not-survive ${"x".repeat(2200)}`,
+ }));
+ const compacted = await store.updateAgentSessionHistory("principal:compact", session.id, history);
+ expect(compacted.compactionCount).toBe(1);
+ expect(compacted.archiveCount).toBe(1);
+ expect(compacted.lastCompactedAt).toMatch(/T/);
+ expect(compacted.lastArchivedAt).toMatch(/T/);
+ expect(compacted.contextSummary).toContain("MSO session context compacted");
+ expect(compacted.estimatedTokens).toBeLessThan(compacted.compactThresholdTokens);
+ expect(compacted.lifetimeEstimatedTokens).toBeGreaterThan(compacted.estimatedTokens);
+
+ const files = (await fs.readdir(archives)).filter((name) => name.endsWith(".json.gz"));
+ expect(files).toHaveLength(1);
+ const archived = (await gunzipAsync(await fs.readFile(path.join(archives, files[0])))).toString("utf8");
+ expect(archived).not.toContain("should-not-survive");
+ expect(archived).toContain("[redacted]");
+ });
+
+ it("prunes archives older than the default 30-day retention window", async () => {
+ const [name] = (await fs.readdir(archives)).filter((row) => row.endsWith(".json.gz"));
+ const file = path.join(archives, name);
+ const old = new Date(Date.now() - 31 * 86_400_000);
+ await fs.utimes(file, old, old);
+ const result = await archive.pruneAgentSessionArchives();
+ expect(result.removed).toBe(1);
+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("keeps manual titles locked against later auto-title hints", async () => {
+ const session = await store.createAgentSession("principal:title", "cli", { title: "Manual name", titleSource: "manual" });
+ await store.maybeAutoTitleAgentSession("principal:title", session.id, "Deploy a very different project");
+ const current = await store.getAgentSession("principal:title", session.id);
+ expect(current?.title).toBe("Manual name");
+ expect(current?.titleSource).toBe("manual");
+ });
+});
diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.ts
index 62513447..27bdc969 100644
--- a/lib/agent/session-store.ts
+++ b/lib/agent/session-store.ts
@@ -1,227 +1,148 @@
-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";
+import { redactText } from "@/lib/security/redact-text";
+import { snapshotAgentMemory, type AgentMemorySnapshot } from "./memory-store";
+import { archiveAgentSession, pruneAgentSessionArchives } from "./session-archive";
+import { listSessionRecords, newAgentSessionId, principalHash, readSessionFile, SESSION_LOCK_TARGET, writeSessionFile } from "./session-files";
+import { autoSessionTitle, compactSessionContext, compactThresholdTokens, estimateTokens, MAX_EVENTS, MAX_HISTORY, safeTitle, sessionContextTokens } from "./session-policy";
+import type { AgentSession, AgentSessionEvent, AgentSessionResumePacket, AgentSessionSource, AgentSessionSummary, AgentSessionTitleSource } 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")}`;
+interface CreateOptions {
+ id?: string; title?: string; titleSource?: AgentSessionTitleSource; resumedFrom?: string;
+ conversationHash?: string; memorySnapshot?: AgentMemorySnapshot; contextSummary?: string; history?: unknown[];
}
-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 {
+function summary(record: AgentSession): AgentSessionSummary {
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) : [],
+ id: record.id, source: record.source, title: record.title, titleSource: record.titleSource,
+ createdAt: record.createdAt, updatedAt: record.updatedAt,
+ ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
+ estimatedTokens: record.estimatedTokens, lifetimeEstimatedTokens: record.lifetimeEstimatedTokens,
+ compactThresholdTokens: record.compactThresholdTokens, compactionCount: record.compactionCount,
+ archiveCount: record.archiveCount,
+ ...(record.lastCompactedAt ? { lastCompactedAt: record.lastCompactedAt } : {}),
+ ...(record.lastArchivedAt ? { lastArchivedAt: record.lastArchivedAt } : {}),
+ eventCount: record.events.length, historyTurns: record.history.length,
};
}
-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);
+async function buildRecord(principal: string, source: AgentSessionSource, options: CreateOptions): Promise<AgentSession> {
+ const now = new Date().toISOString();
+ const memorySnapshot = options.memorySnapshot ?? await snapshotAgentMemory(principal);
+ const created: AgentSessionEvent = { at: now, kind: "created", ...(options.resumedFrom ? { detail: `resumed from ${options.resumedFrom}` } : {}) };
+ const record: AgentSession = {
+ id: options.id ?? newAgentSessionId(), principalHash: principalHash(principal), source,
+ title: safeTitle(options.title), titleSource: options.titleSource ?? "default",
+ ...(options.conversationHash ? { conversationHash: options.conversationHash } : {}),
+ createdAt: now, updatedAt: now, ...(options.resumedFrom ? { resumedFrom: options.resumedFrom } : {}),
+ memorySnapshot, ...(options.contextSummary ? { contextSummary: options.contextSummary } : {}),
+ history: (options.history ?? []).slice(-MAX_HISTORY),
+ events: [created],
+ estimatedTokens: 0, lifetimeEstimatedTokens: 0, compactThresholdTokens: compactThresholdTokens(),
+ compactionCount: 0, archiveCount: 0,
+ };
+ const estimatedTokens = sessionContextTokens(record);
+ return { ...record, estimatedTokens, lifetimeEstimatedTokens: estimatedTokens };
}
-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 compactIfNeeded(record: AgentSession, reason: string): Promise<AgentSession> {
+ record.estimatedTokens = sessionContextTokens(record);
+ if (record.estimatedTokens < record.compactThresholdTokens) return record;
+ const now = new Date();
+ await archiveAgentSession(record, reason, now);
+ let next = compactSessionContext(record, now.toISOString());
+ const archived: AgentSessionEvent = { at: now.toISOString(), kind: "archived", detail: `${reason}; 30-day retention` };
+ next = { ...next, events: [...next.events.slice(-(MAX_EVENTS - 1)), archived], archiveCount: record.archiveCount + 1, lastArchivedAt: now.toISOString() };
+ next.estimatedTokens = sessionContextTokens(next);
+ void pruneAgentSessionArchives().catch(() => undefined);
+ return next;
}
async function requireOwned(principal: string, id: string): Promise<AgentSession> {
- const record = await readFile(id);
+ const record = await readSessionFile(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 createAgentSession(principal: string, source: AgentSessionSource, options: CreateOptions = {}): Promise<AgentSession> {
+ return withSecurityStoreLock(SESSION_LOCK_TARGET, async () => {
+ const record = await buildRecord(principal, source, options);
+ if (await readSessionFile(record.id)) throw new Error("agent session id already exists");
+ await writeSessionFile(record); return record;
+ });
+}
+
+export async function findOrCreateAgentSessionForConversation(principal: string, hash: string, title = "ChatGPT session"): Promise<AgentSession> {
+ if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error("invalid conversation hash");
+ return withSecurityStoreLock(SESSION_LOCK_TARGET, async () => {
+ const owner = principalHash(principal);
+ const existing = (await listSessionRecords()).find((row) => row.principalHash === owner && row.source === "mcp" && row.conversationHash === hash);
+ if (existing) return existing;
+ const record = await buildRecord(principal, "mcp", { title, titleSource: "default", conversationHash: hash });
+ await writeSessionFile(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;
+ const record = await readSessionFile(id);
+ return record?.principalHash === principalHash(principal) ? record : null;
}
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.
+ const owner = principalHash(principal), wanted = Math.max(1, Math.min(200, Math.trunc(limit) || 30));
+ return (await listSessionRecords()).filter((row) => row.principalHash === owner)
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, wanted).map(summary);
+}
+
+export async function listAgentSessionsOwner(limit = 100): Promise<AgentSessionSummary[]> {
+ const wanted = Math.max(1, Math.min(500, Math.trunc(limit) || 100));
+ return (await listSessionRecords()).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, wanted).map(summary);
+}
+
+export async function updateAgentSessionHistory(principal: string, id: string, history: unknown[], title?: string, titleSource: AgentSessionTitleSource = "auto"): Promise<AgentSession> {
+ return withSecurityStoreLock(SESSION_LOCK_TARGET, async () => {
+ let record = await requireOwned(principal, id);
+ const oldTokens = estimateTokens(record.history), newHistory = Array.isArray(history) ? history.slice(-MAX_HISTORY) : [];
+ record.history = newHistory;
+ record.lifetimeEstimatedTokens += Math.max(0, estimateTokens(newHistory) - oldTokens);
+ if (title && (titleSource === "manual" || record.titleSource !== "manual")) {
+ record.title = safeTitle(title); record.titleSource = titleSource;
}
- }
- return out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, wanted);
+ record.updatedAt = new Date().toISOString(); record = await compactIfNeeded(record, "context-threshold");
+ await writeSessionFile(record); return record;
+ });
}
-export async function updateAgentSessionHistory(
- principal: string,
- id: string,
- history: unknown[],
- title?: string,
-): Promise<AgentSession> {
- return withSecurityStoreLock(LOCK_TARGET, async () => {
+export async function maybeAutoTitleAgentSession(principal: string, id: string, hint: string): Promise<AgentSession | null> {
+ return withSecurityStoreLock(SESSION_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;
+ if (record.titleSource === "manual" || record.titleSource === "auto") return record;
+ record.title = autoSessionTitle(hint); record.titleSource = "auto"; record.updatedAt = new Date().toISOString();
+ await writeSessionFile(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) } : {}),
+export async function renameAgentSession(principal: string, id: string, title: string): Promise<AgentSession> {
+ return updateAgentSessionHistory(principal, id, (await requireOwned(principal, id)).history, title, "manual");
+}
+
+export async function appendAgentSessionEvent(principal: string, id: string, event: Omit<AgentSessionEvent, "at"> & { at?: string }): Promise<void> {
+ await withSecurityStoreLock(SESSION_LOCK_TARGET, async () => {
+ let record = await requireOwned(principal, id); const at = event.at ?? new Date().toISOString();
+ const row: AgentSessionEvent = { at, 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);
+ ...(event.detail ? { detail: redactText(event.detail.replace(/[\r\n\t]+/g, " ").trim(), 500) } : {}), };
+ record.events = [...record.events, row].slice(-MAX_EVENTS); record.updatedAt = at;
+ record.lifetimeEstimatedTokens += estimateTokens(row); record = await compactIfNeeded(record, "event-threshold");
+ await writeSessionFile(record);
});
}
-export async function resumeAgentSession(
- principal: string,
- targetId: string,
- currentId?: string,
-): Promise<AgentSessionResumePacket> {
+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) };
+ if (currentId && currentId !== targetId) await appendAgentSessionEvent(principal, currentId, { kind: "resumed", detail: `resumed ${targetId}` });
+ return { session: summary(target), memorySnapshot: target.memorySnapshot, ...(target.contextSummary ? { contextSummary: target.contextSummary } : {}), recentHistory: target.history.slice(-24), recentEvents: target.events.slice(-40) };
}
-export function agentSessionSummary(record: AgentSession): AgentSessionSummary {
- return summary(record);
-}
+export function agentSessionSummary(record: AgentSession): AgentSessionSummary { return summary(record); }
diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.ts
index fc28e543..c65e5814 100644
--- a/lib/agent/session-types.ts
+++ b/lib/agent/session-types.ts
@@ -1,10 +1,11 @@
import type { AgentMemorySnapshot } from "./memory-store";
export type AgentSessionSource = "cli" | "mcp" | "alfa";
+export type AgentSessionTitleSource = "default" | "auto" | "manual";
export interface AgentSessionEvent {
at: string;
- kind: "created" | "resumed" | "tool" | "workflow" | "note";
+ kind: "created" | "resumed" | "tool" | "workflow" | "note" | "compacted" | "archived";
tool?: string;
state?: string;
workflowId?: string;
@@ -16,21 +17,39 @@ export interface AgentSession {
principalHash: string;
source: AgentSessionSource;
title: string;
+ titleSource: AgentSessionTitleSource;
+ conversationHash?: string;
createdAt: string;
updatedAt: string;
resumedFrom?: string;
memorySnapshot: AgentMemorySnapshot;
+ contextSummary?: string;
history: unknown[];
events: AgentSessionEvent[];
+ estimatedTokens: number;
+ lifetimeEstimatedTokens: number;
+ compactThresholdTokens: number;
+ compactionCount: number;
+ archiveCount: number;
+ lastCompactedAt?: string;
+ lastArchivedAt?: string;
}
export interface AgentSessionSummary {
id: string;
source: AgentSessionSource;
title: string;
+ titleSource: AgentSessionTitleSource;
createdAt: string;
updatedAt: string;
resumedFrom?: string;
+ estimatedTokens: number;
+ lifetimeEstimatedTokens: number;
+ compactThresholdTokens: number;
+ compactionCount: number;
+ archiveCount: number;
+ lastCompactedAt?: string;
+ lastArchivedAt?: string;
eventCount: number;
historyTurns: number;
}
@@ -38,5 +57,7 @@ export interface AgentSessionSummary {
export interface AgentSessionResumePacket {
session: AgentSessionSummary;
memorySnapshot: AgentMemorySnapshot;
+ contextSummary?: string;
+ recentHistory: unknown[];
recentEvents: AgentSessionEvent[];
}
diff --git a/lib/mcp/dispatch-actors.ts b/lib/mcp/dispatch-actors.ts
new file mode 100644
index 00000000..434bfb1c
--- /dev/null
+++ b/lib/mcp/dispatch-actors.ts
@@ -0,0 +1,11 @@
+import type { McpAgentContext } from "./dispatch-types";
+
+/** Active workflow/job ownership is conversation-scoped when a durable session exists. */
+export function workflowActor(actor: string | undefined, context?: McpAgentContext): string | undefined {
+ return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;
+}
+
+/** Verified recipes intentionally survive conversation boundaries for one stable client principal. */
+export function recipeActor(actor: string | undefined, context?: McpAgentContext): string | undefined {
+ return context?.principal ?? actor;
+}
diff --git a/lib/mcp/dispatch-tool-support.ts b/lib/mcp/dispatch-tool-support.ts
new file mode 100644
index 00000000..02befcc5
--- /dev/null
+++ b/lib/mcp/dispatch-tool-support.ts
@@ -0,0 +1,56 @@
+import { appendAgentSessionEvent } from "@/lib/agent/session-store";
+import type { ActiveWorkflow } from "@/lib/skills/memory";
+import { isMcpDirectResult } from "./tool-kit";
+import { boundedResultText } from "./result-budget";
+import { TOOLS_BY_NAME } from "./tools";
+import type { McpAgentContext } from "./dispatch-types";
+
+export 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;
+}
+
+export 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);
+}
+
+export function flowFields(workflow: ActiveWorkflow | null | undefined) {
+ return workflow ? { workflowId: workflow.id, workflowIntent: workflow.intent, workflowProject: workflow.project } : {};
+}
+
+export function workflowFromResult(result: unknown): ActiveWorkflow | null {
+ if (!result || typeof result !== "object") return null;
+ const workflow = (result as { workflow?: unknown }).workflow;
+ if (!workflow || typeof workflow !== "object") return null;
+ const row = workflow as Partial<ActiveWorkflow>;
+ return typeof row.id === "string" && typeof row.intent === "string" ? row as ActiveWorkflow : null;
+}
+
+export function structuredResult(toolName: string, result: unknown) {
+ const tool = TOOLS_BY_NAME.get(toolName);
+ const content = [{ type: "text" as const, text: boundedResultText(result, tool?.result) }];
+ const structured = tool?.toStructuredContent
+ ? tool.toStructuredContent(result)
+ : result !== null && typeof result === "object" && !Array.isArray(result)
+ ? result as Record<string, unknown>
+ : undefined;
+ if (isMcpDirectResult(result)) return { content: result.content, ...(result.isError ? { isError: true } : {}) };
+ return tool?.outputSchema && structured ? { structuredContent: structured, content } : { content };
+}
diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.ts
new file mode 100644
index 00000000..da186a5b
--- /dev/null
+++ b/lib/mcp/dispatch-tools.ts
@@ -0,0 +1,92 @@
+import { audit, rateLimited } from "@/lib/host";
+import { maybeAutoTitleAgentSession } from "@/lib/agent/session-store";
+import { activeWorkflowForActor, recordWorkflowStep } from "@/lib/skills/memory";
+import { activityTarget, newActivityId, recordMcpActivity } from "./activity";
+import { allows, type Scope } from "./scope";
+import { TOOLS_BY_NAME } from "./tools";
+import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";
+import { recipeActor, workflowActor } from "./dispatch-actors";
+import { flowFields, recordAgentEvent, sessionDetail, structuredResult, workflowFromResult } from "./dispatch-tool-support";
+
+export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: string, context?: McpAgentContext) {
+ const id = req.id ?? null;
+ const name = String(req.params?.name ?? ""), args = req.params?.arguments ?? {};
+ const tool = TOOLS_BY_NAME.get(name);
+ if (!tool) return rpcFail(id, -32602, `unknown tool: ${name}`);
+
+ const workflowProbe = name === "workflow_status";
+ const requestedWorkflowId = typeof args.workflow_id === "string" && args.workflow_id ? args.workflow_id : undefined;
+ const flowActor = workflowActor(actor, context), learnedActor = recipeActor(actor, context);
+ const lifecycle = name === "workflow_finish" || name === "workflow_cancel";
+ const activeWorkflow = requestedWorkflowId ? await activeWorkflowForActor(flowActor, requestedWorkflowId) : null;
+ const initialFlow = flowFields(activeWorkflow), target = activityTarget(args);
+
+ if (!allows(scope, tool.scope)) {
+ void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: `scope ${scope} < ${tool.scope}` });
+ const activityId = newActivityId();
+ if (!workflowProbe) {
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "denied", scope, ...initialFlow, target, detail: `scope ${scope} < ${tool.scope}` });
+ await recordWorkflowStep(flowActor, activeWorkflow?.id, { id: activityId, tool: name, state: "denied", target, args, ts: new Date().toISOString() });
+ await recordAgentEvent(context, name, "denied", args, activeWorkflow?.id, target);
+ }
+ return rpcOk(id, { content: [{ type: "text", text: `error: this token holds scope "${scope}"; ${name} needs "${tool.scope}".` }], isError: true });
+ }
+
+ for (const key of tool.inputSchema.required ?? []) {
+ if (args[key] == null) return rpcFail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);
+ }
+ if (requestedWorkflowId && !lifecycle && !workflowProbe && name !== "workflow_start" && name !== "skills_search" && !activeWorkflow) {
+ const activityId = newActivityId(), message = "workflow_id was not found for this MSO session";
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "failed", scope, target, detail: message });
+ await recordAgentEvent(context, name, "failed", args, undefined, target);
+ return rpcOk(id, { content: [{ type: "text", text: `error: ${message}. Use this conversation's exact workflow_id.` }], isError: true });
+ }
+
+ if (tool.limit) {
+ const suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");
+ if (rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs)) {
+ void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "rate limited" });
+ const activityId = newActivityId();
+ if (!workflowProbe) {
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "rate_limited", scope, ...initialFlow, target, detail: "rate limited" });
+ await recordWorkflowStep(flowActor, activeWorkflow?.id, { id: activityId, tool: name, state: "rate_limited", target, args, ts: new Date().toISOString() });
+ await recordAgentEvent(context, name, "rate_limited", args, activeWorkflow?.id, target);
+ }
+ return rpcOk(id, { content: [{ type: "text", text: `error: ${name} is rate limited.` }], isError: true });
+ }
+ }
+
+ const trail = tool.audit, auditTarget = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;
+ const activityId = newActivityId(), startedAt = Date.now();
+ if (!workflowProbe) void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });
+ try {
+ const titleHint = sessionDetail(name, args, target);
+ if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status"].includes(name)) {
+ await maybeAutoTitleAgentSession(context.principal, context.sessionId, titleHint).catch(() => undefined);
+ }
+ const result = await tool.run(args, {
+ actor, principal: context?.principal, sessionId: context?.sessionId, scope,
+ workflowId: activeWorkflow?.id, workflowActor: flowActor, recipeActor: learnedActor,
+ });
+ 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 } });
+ }
+ const durationMs = Date.now() - startedAt, completedWorkflow = workflowFromResult(result) ?? activeWorkflow;
+ if (!workflowProbe) {
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "completed", scope, ...flowFields(completedWorkflow), target, durationMs });
+ await recordWorkflowStep(flowActor, completedWorkflow?.id, { id: activityId, tool: name, state: "completed", target, args, durationMs, ts: new Date().toISOString() });
+ await recordAgentEvent(context, name, "completed", args, completedWorkflow?.id, target);
+ }
+ return rpcOk(id, structuredResult(name, result));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error), durationMs = Date.now() - startedAt;
+ if (trail) void audit({ action: trail.action, actor, target: auditTarget, ok: false, detail: message.slice(0, 200), meta: { via: "mcp", scope } });
+ if (!workflowProbe) {
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "failed", scope, ...initialFlow, target, durationMs, detail: message.slice(0, 220) });
+ await recordWorkflowStep(flowActor, activeWorkflow?.id, { id: activityId, tool: name, state: "failed", target, args, durationMs, ts: new Date().toISOString() });
+ await recordAgentEvent(context, name, "failed", args, activeWorkflow?.id, target);
+ }
+ return rpcOk(id, { content: [{ type: "text", text: "error: " + message.slice(0, 500) }], isError: true });
+ }
+}
diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.ts
new file mode 100644
index 00000000..db9d0177
--- /dev/null
+++ b/lib/mcp/dispatch-types.ts
@@ -0,0 +1,25 @@
+export interface RpcRequest {
+ jsonrpc?: string;
+ id?: string | number | null;
+ method?: string;
+ _meta?: Record<string, unknown>;
+ params?: {
+ name?: string;
+ arguments?: Record<string, unknown>;
+ protocolVersion?: string;
+ uri?: string;
+ _meta?: Record<string, unknown>;
+ };
+}
+
+export interface McpAgentContext {
+ principal?: string;
+ sessionId?: string;
+}
+
+export type RpcId = string | number | null | undefined;
+
+export const rpcOk = (id: RpcId, result: unknown) =>
+ ({ jsonrpc: "2.0", id: id ?? null, result });
+export const rpcFail = (id: RpcId, code: number, message: string) =>
+ ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index a6cbd2d5..d76b9b34 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { beforeEach, describe, it, expect, vi } from "vitest";
// The catalog reaches lib/camoufox + lib/managed-apps, which are `server-only`.
// Next aliases that specifier internally; vitest does not, so stub it — same
// pattern as lib/managed-apps/manager.test.ts.
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index 920f212f..203cce98 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -1,66 +1,15 @@
-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";
-import { isMcpDirectResult } from "./tool-kit";
import { MCP_SERVER_VERSION, toolsetInfo } from "./toolset";
-import { TOOLS, TOOLS_BY_NAME } from "./tools";
+import { TOOLS } from "./tools";
import { listUiResources, readUiResource } from "./ui-resources";
-
-export interface RpcRequest {
- jsonrpc?: string;
- id?: string | number | null;
- method?: string;
- params?: { name?: string; arguments?: Record<string, unknown>; protocolVersion?: string; uri?: string };
-}
+import { dispatchToolCall } from "./dispatch-tools";
+import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";
+export type { McpAgentContext, RpcRequest } from "./dispatch-types";
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 } });
-
export function isNotification(body: unknown): boolean {
const b = body as RpcRequest | null;
return b?.id == null && String(b?.method ?? "").startsWith("notifications/");
@@ -68,9 +17,7 @@ export function isNotification(body: unknown): boolean {
const visibleTools = (scope: Scope) => TOOLS.filter((tool) => allows(scope, tool.scope));
const toolList = (scope: Scope) => visibleTools(scope).map((tool) => ({
- name: tool.name,
- description: tool.description,
- inputSchema: tool.inputSchema,
+ name: tool.name, description: tool.description, inputSchema: tool.inputSchema,
...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
...(tool.annotations ? { annotations: tool.annotations } : {}),
...(tool.meta ? { _meta: tool.meta } : {}),
@@ -78,167 +25,41 @@ const toolList = (scope: Scope) => visibleTools(scope).map((tool) => ({
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} 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) {
- return workflow ? {
- workflowId: workflow.id,
- workflowIntent: workflow.intent,
- workflowProject: workflow.project,
- } : {};
-}
-
-function workflowFromResult(result: unknown): ActiveWorkflow | null {
- if (!result || typeof result !== "object") return null;
- const workflow = (result as { workflow?: unknown }).workflow;
- if (!workflow || typeof workflow !== "object") return null;
- const row = workflow as Partial<ActiveWorkflow>;
- return typeof row.id === "string" && typeof row.intent === "string"
- ? row as ActiveWorkflow
- : null;
-}
-
-function structuredResult(toolName: string, result: unknown) {
- const tool = TOOLS_BY_NAME.get(toolName);
- const content = [{ type: "text" as const, text: typeof result === "string" ? result : JSON.stringify(result) }];
- const structured = tool?.toStructuredContent
- ? tool.toStructuredContent(result)
- : result !== null && typeof result === "object" && !Array.isArray(result)
- ? result as Record<string, unknown>
- : undefined;
- return tool?.outputSchema && structured
- ? { structuredContent: structured, content }
- : { content };
+ ? "This token is read-only: use skills_search for capability discovery, then bounded read tools."
+ : "For multi-step work call workflow_start once, pass its exact workflow_id on every operation in this conversation, verify, then workflow_finish or workflow_cancel.";
+ return `${startup} ChatGPT conversation identity is isolated from OAuth/audit identity; workflows are session-scoped while learned successful recipes remain client-scoped. agent_session_current exposes only the current durable MSO session. Use agent_sessions_list and agent_session_resume for explicit recovery. Session context has an estimated-token budget, private archive/compaction, and timestamps; MSO never claims access to hidden ChatGPT transcript. Prefer bounded tools; use exec_job_start for long tests/builds. Never expose private chain-of-thought.`;
}
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": {
- const toolset = toolsetInfo(visibleTools(scope), scope);
- return ok(id, {
+ case "initialize":
+ case "server/discover": {
+ const tools = visibleTools(scope), toolset = toolsetInfo(tools, scope);
+ return rpcOk(id, {
protocolVersion: req.params?.protocolVersion ?? PROTOCOL,
capabilities: { tools: { listChanged: false }, resources: { listChanged: false } },
- serverInfo: { name: "mso", version: MCP_SERVER_VERSION },
- instructions: instructions(scope),
+ serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: instructions(scope),
_meta: { toolset, ...(agentContext?.sessionId ? { agentSessionId: agentContext.sessionId } : {}) },
});
}
case "notifications/initialized":
- case "ping":
- return ok(id, {});
+ case "ping": return rpcOk(id, {});
case "tools/list": {
const tools = visibleTools(scope);
- return ok(id, { tools: toolList(scope), _meta: { toolset: toolsetInfo(tools, scope) } });
+ return rpcOk(id, { tools: toolList(scope), _meta: { toolset: toolsetInfo(tools, scope) } });
}
- case "resources/list":
- return ok(id, { resources: listUiResources() });
+ case "resources/list": return rpcOk(id, { resources: listUiResources() });
case "resources/read": {
const uri = String(req.params?.uri ?? "");
- if (!uri) return fail(id, -32602, "resources/read needs { uri }");
+ if (!uri) return rpcFail(id, -32602, "resources/read needs { uri }");
const resource = readUiResource(uri);
- if (!resource) return fail(id, -32602, `unknown resource: ${uri}`);
- return ok(id, {
- contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.text, _meta: resource._meta }],
- });
- }
- case "tools/call": {
- const name = String(req.params?.name ?? "");
- const args = req.params?.arguments ?? {};
- const tool = TOOLS_BY_NAME.get(name);
- if (!tool) return fail(id, -32602, `unknown tool: ${name}`);
- const workflowProbe = name === "workflow_status";
- const requestedWorkflowId = typeof args.workflow_id === "string" && args.workflow_id ? args.workflow_id : undefined;
- const lifecycle = name === "workflow_finish" || name === "workflow_cancel";
- const activeWorkflow = requestedWorkflowId
- ? await activeWorkflowForActor(actor, requestedWorkflowId)
- : null;
- const initialFlow = flowFields(activeWorkflow);
- if (!allows(scope, tool.scope)) {
- void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: `scope ${scope} < ${tool.scope}` });
- const deniedId = newActivityId();
- const target = activityTarget(args);
- if (!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.` }],
- isError: true,
- });
- }
- for (const key of tool.inputSchema.required ?? []) {
- if (args[key] == null) return fail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);
- }
- if (requestedWorkflowId && !lifecycle && !workflowProbe && name !== "workflow_start" && name !== "skills_search" && !activeWorkflow) {
- const mismatchId = newActivityId();
- const 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,
- });
- }
- if (tool.limit) {
- const suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");
- if (rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs)) {
- void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "rate limited" });
- const limitedId = newActivityId();
- const target = activityTarget(args);
- if (!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.` }],
- isError: true,
- });
- }
- }
-
- const trail = tool.audit;
- const auditTarget = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;
- const activityId = newActivityId();
- const startedAt = Date.now();
- const 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, 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 } });
- }
- const durationMs = Date.now() - startedAt;
- const completedWorkflow = workflowFromResult(result) ?? activeWorkflow;
- if (!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));
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- if (trail) void audit({ action: trail.action, actor, target: auditTarget, ok: false, detail: message.slice(0, 200), meta: { via: "mcp", scope } });
- const durationMs = Date.now() - startedAt;
- if (!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 });
- }
+ if (!resource) return rpcFail(id, -32602, `unknown resource: ${uri}`);
+ return rpcOk(id, { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.text, _meta: resource._meta }] });
}
- default:
- return fail(id, -32601, `unknown method: ${req.method}`);
+ case "tools/call": return dispatchToolCall(req, scope, actor, agentContext);
+ default: return rpcFail(id, -32601, `unknown method: ${req.method}`);
}
}
-export { fail as rpcError };
+export const rpcError = rpcFail;
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index a63c7f4b..8ab94097 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -45,6 +45,7 @@ const MCP_ONLY: Record<string, string> = {
"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.rename": "durable MCP/terminal session titles are metadata in the isolated agent-session store; Alfa keeps its separate in-app thread/title lifecycle",
"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",
@@ -122,6 +123,8 @@ describe("MCP rate limits mirror the routes", () => {
// workflow_status is app-only polling. Keep its own bucket so UI refreshes
// neither consume lifecycle capacity nor bypass the server-wide token limit.
"workflow.status": 30,
+ "agent.session": 30,
+ "agent.memory": 30,
"exec.job.start": 12,
"exec.job.status": 120,
"exec.job.cancel": 30,
diff --git a/lib/mcp/result-budget.test.ts b/lib/mcp/result-budget.test.ts
new file mode 100644
index 00000000..cab6c2a8
--- /dev/null
+++ b/lib/mcp/result-budget.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { boundedResultText, DEFAULT_MCP_RESULT_BYTES } from "./result-budget";
+
+describe("MCP result budget", () => {
+ it("leaves small exact outputs unchanged", () => {
+ const result = { ok: true, rows: [1, 2, 3] };
+ expect(boundedResultText(result)).toBe(JSON.stringify(result));
+ });
+
+ it("returns a parseable compact envelope instead of flooding model context", () => {
+ const raw = { stdout: "x".repeat(80_000), stderr: "", code: 0 };
+ const text = boundedResultText(raw);
+ const parsed = JSON.parse(text) as { msoTruncated: boolean; originalBytes: number; preview: string; hint: string };
+ expect(parsed.msoTruncated).toBe(true);
+ expect(parsed.originalBytes).toBeGreaterThan(DEFAULT_MCP_RESULT_BYTES);
+ expect(parsed.preview).toContain("stdout");
+ expect(Buffer.byteLength(text, "utf8")).toBeLessThanOrEqual(DEFAULT_MCP_RESULT_BYTES + 512);
+ expect(parsed.hint).toContain("narrower");
+ });
+
+ it("supports a larger per-tool budget without allowing unbounded output", () => {
+ const text = boundedResultText("z".repeat(200_000), { maxTextBytes: 64 * 1024, overflowHint: "Use pagination." });
+ const parsed = JSON.parse(text) as { msoTruncated: boolean; hint: string };
+ expect(parsed.msoTruncated).toBe(true);
+ expect(parsed.hint).toBe("Use pagination.");
+ expect(Buffer.byteLength(text, "utf8")).toBeLessThan(66 * 1024);
+ });
+});
diff --git a/lib/mcp/result-budget.ts b/lib/mcp/result-budget.ts
new file mode 100644
index 00000000..0328e120
--- /dev/null
+++ b/lib/mcp/result-budget.ts
@@ -0,0 +1,58 @@
+export const DEFAULT_MCP_RESULT_BYTES = 32 * 1024;
+export const MAX_MCP_RESULT_BYTES = 128 * 1024;
+
+function clampBudget(value?: number): number {
+ if (!Number.isFinite(value)) return DEFAULT_MCP_RESULT_BYTES;
+ return Math.max(4 * 1024, Math.min(MAX_MCP_RESULT_BYTES, Math.trunc(value!)));
+}
+
+function utf8Bytes(value: string): number {
+ return Buffer.byteLength(value, "utf8");
+}
+
+function truncateUtf8(value: string, maxBytes: number): string {
+ if (utf8Bytes(value) <= maxBytes) return value;
+ let low = 0, high = value.length;
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2);
+ if (utf8Bytes(value.slice(0, mid)) <= maxBytes) low = mid;
+ else high = mid - 1;
+ }
+ return value.slice(0, low);
+}
+
+export type McpResultBudget = {
+ maxTextBytes?: number;
+ overflowHint?: string;
+};
+
+/**
+ * Bound the model-visible text fallback of a tool result. Large tool payloads
+ * are one of the easiest ways to destroy agent context quality: the operation
+ * succeeded, but its raw logs/file/list then crowd out the goal and plan.
+ *
+ * The original result object is left untouched for any explicit structured UI
+ * projection. Only the generic text fallback is compacted here.
+ */
+export function boundedResultText(result: unknown, policy?: McpResultBudget): string {
+ let raw: string;
+ try { raw = typeof result === "string" ? result : JSON.stringify(result); }
+ catch { raw = String(result); }
+ const max = clampBudget(policy?.maxTextBytes);
+ const bytes = utf8Bytes(raw);
+ if (bytes <= max) return raw;
+
+ const hint = (policy?.overflowHint || "Refine the request or use a narrower read/search call for the omitted details.")
+ .replace(/[\r\n\t]+/g, " ").trim().slice(0, 320);
+ // Leave room for the metadata envelope itself so the final fallback remains
+ // close to the requested budget even with multibyte content.
+ const previewBudget = Math.max(1024, max - 1024);
+ const preview = truncateUtf8(raw, previewBudget);
+ return JSON.stringify({
+ msoTruncated: true,
+ originalBytes: bytes,
+ returnedPreviewBytes: utf8Bytes(preview),
+ preview,
+ hint,
+ });
+}
diff --git a/lib/mcp/session-context.test.ts b/lib/mcp/session-context.test.ts
new file mode 100644
index 00000000..486e0ef2
--- /dev/null
+++ b/lib/mcp/session-context.test.ts
@@ -0,0 +1,60 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ findOrCreate: vi.fn(),
+ newId: vi.fn(() => "20260901_120000_11223344"),
+}));
+vi.mock("@/lib/agent/session-store", () => ({ findOrCreateAgentSessionForConversation: mocks.findOrCreate }));
+vi.mock("@/lib/agent/session-files", () => ({ newAgentSessionId: mocks.newId }));
+
+const { resolveMcpSession } = await import("./session-context");
+
+const req = (transport = "transport-a") => new Request("https://mso.test/mcp", { headers: { "Mcp-Session-Id": transport } });
+const call = (conversation?: string) => ({
+ id: 1, method: "tools/call",
+ params: { name: "sys_stats", arguments: {}, ...(conversation ? { _meta: { "openai/session": conversation } } : {}) },
+});
+
+describe("MCP conversation/session correlation", () => {
+ beforeEach(() => {
+ mocks.findOrCreate.mockReset().mockImplementation(async (_principal: string, hash: string) => ({ id: `s-${hash.slice(0, 10)}`, source: "mcp" }));
+ mocks.newId.mockClear();
+ });
+
+ it("uses the same durable session across transport-id rotation for one ChatGPT conversation", async () => {
+ const a = await resolveMcpSession(req("transport-a"), call("conversation-A"), "mcp-client:x", "MSO");
+ const b = await resolveMcpSession(req("transport-b"), call("conversation-A"), "mcp-client:x", "MSO");
+ expect("response" in a || "response" in b).toBe(false);
+ if ("response" in a || "response" in b) return;
+ expect(a.agentSessionId).toBe(b.agentSessionId);
+ expect(a.responseSessionId).toBe("transport-a");
+ expect(b.responseSessionId).toBe("transport-b");
+ expect(a.conversationBound).toBe(true);
+ expect(mocks.findOrCreate.mock.calls[0][1]).toMatch(/^[a-f0-9]{64}$/);
+ expect(mocks.findOrCreate.mock.calls[0][1]).not.toContain("conversation-A");
+ });
+
+ it("separates two ChatGPT conversations using the same authenticated client", async () => {
+ const a = await resolveMcpSession(req(), call("conversation-A"), "mcp-client:x", "MSO");
+ const b = await resolveMcpSession(req(), call("conversation-B"), "mcp-client:x", "MSO");
+ if ("response" in a || "response" in b) throw new Error("unexpected response");
+ expect(a.agentSessionId).not.toBe(b.agentSessionId);
+ expect(mocks.findOrCreate.mock.calls[0][1]).not.toBe(mocks.findOrCreate.mock.calls[1][1]);
+ });
+
+ it("keeps legacy transport fallback isolated instead of merging all token calls", async () => {
+ const a = await resolveMcpSession(req("legacy-a"), call(), "mcp-client:x", "MSO");
+ const b = await resolveMcpSession(req("legacy-b"), call(), "mcp-client:x", "MSO");
+ if ("response" in a || "response" in b) throw new Error("unexpected response");
+ expect(a.conversationBound).toBe(false);
+ expect(a.agentSessionId).not.toBe(b.agentSessionId);
+ });
+
+ it("initialize allocates transport compatibility only and does not create durable agent state", async () => {
+ const result = await resolveMcpSession(req(), { id: 1, method: "initialize" }, "mcp-client:x", "MSO");
+ if ("response" in result) throw new Error("unexpected response");
+ expect(result.responseSessionId).toBe("20260901_120000_11223344");
+ expect(result.agentSessionId).toBeUndefined();
+ expect(mocks.findOrCreate).not.toHaveBeenCalled();
+ });
+});
diff --git a/lib/mcp/session-context.ts b/lib/mcp/session-context.ts
new file mode 100644
index 00000000..973214f9
--- /dev/null
+++ b/lib/mcp/session-context.ts
@@ -0,0 +1,52 @@
+import { findOrCreateAgentSessionForConversation } from "@/lib/agent/session-store";
+import { newAgentSessionId } from "@/lib/agent/session-files";
+import { conversationHash } from "@/lib/agent/session-policy";
+
+const MCP_SESSION_HEADER = "Mcp-Session-Id";
+
+type RpcLike = {
+ id?: string | number | null;
+ method?: string;
+ _meta?: Record<string, unknown>;
+ params?: { _meta?: Record<string, unknown> };
+};
+
+export interface ResolvedMcpSession {
+ responseSessionId?: string;
+ agentSessionId?: string;
+ conversationBound: boolean;
+}
+
+export function mcpClientMeta(rpc: RpcLike): Record<string, unknown> {
+ return { ...(rpc._meta ?? {}), ...(rpc.params?._meta ?? {}) };
+}
+
+function openAiSession(rpc: RpcLike): string | undefined {
+ const value = mcpClientMeta(rpc)["openai/session"];
+ return typeof value === "string" && value.length > 0 && value.length <= 1024 ? value : undefined;
+}
+
+function errorResponse(rpc: RpcLike, status: number, message: string): Response {
+ return Response.json({ jsonrpc: "2.0", id: rpc.id ?? null, error: { code: -32600, message } }, { status, headers: { "Cache-Control": "no-store" } });
+}
+
+export async function resolveMcpSession(req: Request, rpc: RpcLike, principal: string, label: string): Promise<ResolvedMcpSession | { response: Response }> {
+ const transportId = (req.headers.get(MCP_SESSION_HEADER) ?? "").trim() || undefined;
+ if (rpc.method === "initialize") return { responseSessionId: newAgentSessionId(), conversationBound: false };
+ if (rpc.method !== "tools/call") return { responseSessionId: transportId, conversationBound: false };
+
+ const conversation = openAiSession(rpc);
+ if (conversation) {
+ const session = await findOrCreateAgentSessionForConversation(principal, conversationHash(principal, conversation), `ChatGPT · ${label || "MSO"}`);
+ return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: true };
+ }
+
+ if (!transportId) return { response: errorResponse(rpc, 400, "missing ChatGPT conversation metadata or legacy MCP session id") };
+ const legacyHash = conversationHash(principal, `legacy:${transportId}`);
+ const session = await findOrCreateAgentSessionForConversation(principal, legacyHash, `MCP legacy · ${label || "MSO"}`);
+ return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: false };
+}
+
+export function mcpSessionHeaders(sessionId?: string): Record<string, string> {
+ return { "Cache-Control": "no-store", ...(sessionId ? { [MCP_SESSION_HEADER]: sessionId } : {}) };
+}
diff --git a/lib/mcp/session-workflow-isolation.test.ts b/lib/mcp/session-workflow-isolation.test.ts
new file mode 100644
index 00000000..883b4768
--- /dev/null
+++ b/lib/mcp/session-workflow-isolation.test.ts
@@ -0,0 +1,61 @@
+import { afterAll, beforeEach, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const file = path.join(os.tmpdir(), `mso-session-flow-${process.pid}.json`);
+process.env.OS_SKILL_MEMORY_STORE = file;
+const memory = await import("@/lib/skills/memory");
+const { searchSkillMemory } = await import("@/lib/skills/search");
+const { recipeActor, workflowActor } = await import("./dispatch-actors");
+
+beforeEach(async () => {
+ await fs.rm(file, { force: true });
+ memory.resetSkillMemoryCache();
+});
+afterAll(async () => {
+ await fs.rm(file, { force: true });
+ delete process.env.OS_SKILL_MEMORY_STORE;
+ memory.resetSkillMemoryCache();
+});
+
+describe("conversation-scoped workflow ownership", () => {
+ it("isolates active runs but shares verified recipes at the stable client principal", async () => {
+ const auditActor = "mcp:same-token";
+ const principal = "mcp-client:shared-client";
+ const aContext = { principal, sessionId: "20260901_120000_aaaaaaaa" };
+ const bContext = { principal, sessionId: "20260901_120001_bbbbbbbb" };
+ const aOwner = workflowActor(auditActor, aContext)!;
+ const bOwner = workflowActor(auditActor, bContext)!;
+ const learnedOwnerA = recipeActor(auditActor, aContext)!;
+ const learnedOwnerB = recipeActor(auditActor, bContext)!;
+ const intent = "verify the repeated session-scoped deployment recipe";
+
+ expect(aOwner).not.toBe(bOwner);
+ expect(learnedOwnerA).toBe(principal);
+ expect(learnedOwnerB).toBe(principal);
+
+ const started = await memory.startWorkflow({ actor: aOwner, scope: "write", intent });
+ expect(await memory.activeWorkflowForActor(bOwner, started.workflow.id)).toBeNull();
+ await expect(memory.finishWorkflow({
+ actor: bOwner, workflowId: started.workflow.id, summary: "must not cross sessions", success: true,
+ recipeActor: learnedOwnerB,
+ })).rejects.toThrow("workflow_id was not found for this MSO session");
+
+ await memory.recordWorkflowStep(aOwner, started.workflow.id, {
+ id: "step-1", tool: "sys_stats", state: "completed", ts: new Date().toISOString(),
+ });
+ await memory.finishWorkflow({
+ actor: aOwner, workflowId: started.workflow.id, summary: "verified in session A", success: true,
+ recipeActor: learnedOwnerA,
+ });
+
+ const search = await searchSkillMemory(intent, {
+ recipeAccess: { actor: learnedOwnerB, scope: "write" },
+ projects: [],
+ });
+ expect(search.hits).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: "recipe", source: "learned" }),
+ ]));
+ });
+});
diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.ts
index ee57f6ce..f5a1287f 100644
--- a/lib/mcp/tool-kit.ts
+++ b/lib/mcp/tool-kit.ts
@@ -35,6 +35,10 @@ export interface McpRunContext {
sessionId?: string;
scope: Scope;
workflowId?: string;
+ /** Session-scoped workflow owner; prevents cross-conversation workflow access. */
+ workflowActor?: string;
+ /** Client-scoped learned-recipe owner; survives individual session rotation. */
+ recipeActor?: string;
}
export interface McpTool {
@@ -67,6 +71,8 @@ export interface McpTool {
* "did not throw", which is a lie for anything that has an exit code. */
outcome?: (result: unknown) => { ok: boolean; action?: AuditAction; detail?: string };
};
+ /** Bound the generic model-visible text fallback without changing an explicit structured UI projection. */
+ result?: { maxTextBytes?: number; overflowHint?: string };
/** 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.ts
index 53a1219c..f2501edd 100644
--- a/lib/mcp/tools-agent.ts
+++ b/lib/mcp/tools-agent.ts
@@ -1,12 +1,11 @@
import { forgetAgentMemory, readAgentMemory, rememberAgentMemory, type AgentMemoryDocument } from "@/lib/agent/memory-store";
-import { appendAgentSessionEvent, getAgentSession, listAgentSessions, resumeAgentSession } from "@/lib/agent/session-store";
+import { agentSessionSummary, appendAgentSessionEvent, getAgentSession, listAgentSessions, renameAgentSession, 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");
@@ -16,92 +15,70 @@ function document(a: Record<string, unknown>): AgentMemoryDocument {
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({}),
+ description: "Return this ChatGPT conversation's isolated durable MSO session, timestamps and estimated context-token budget.",
+ 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");
+ if (!context.sessionId) throw new Error("this tool call has no conversation-bound 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,
- };
+ return agentSessionSummary(session);
},
},
{
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 },
+ description: "List durable MSO sessions owned by this MCP client, newest first. Each ChatGPT conversation is a separate 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"]),
+ description: "Read the safe resume packet for one prior MSO session owned by this client. It returns summary/recent context, never ChatGPT hidden transcript.",
+ scope: "read", annotations: { readOnlyHint: true, idempotentHint: true },
+ inputSchema: S({ session_id: { type: "string", description: "Exact MSO session id from agent_session_current/list." } }, ["session_id"]),
run: (a, context) => resumeAgentSession(principal(context), str(a, "session_id"), context.sessionId),
},
+ {
+ name: "agent_session_rename",
+ description: "Manually rename the current MSO session. Manual names are locked and will not be replaced by automatic workflow-based naming.",
+ scope: "write", limit: { key: "agent.session", max: 20, windowMs: 60_000 },
+ audit: { action: "agent.session", targetArg: "title" },
+ inputSchema: S({ title: { type: "string", description: "New session title, max 120 characters." } }, ["title"]),
+ run: async (a, context) => {
+ if (!context.sessionId) throw new Error("this tool call has no conversation-bound MSO session");
+ return agentSessionSummary(await renameAgentSession(principal(context), context.sessionId, str(a, "title")));
+ },
+ },
{
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" },
+ description: "Attach one concise durable note to the current MSO session for later resume. Never store secrets.",
+ scope: "write", limit: { key: "agent.session", 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");
+ if (!context.sessionId) throw new Error("this tool call has no conversation-bound 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({}),
+ description: "Read this MCP client's persistent USER.md and MEMORY.md. New sessions capture a frozen snapshot.",
+ 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"]),
+ description: "Create/replace a keyed entry in this MCP client's USER.md or MEMORY.md. Never store secrets.",
+ scope: "write", limit: { key: "agent.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" }, value: { type: "string" } }, ["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"]),
+ description: "Remove one keyed entry from this MCP client's USER.md or MEMORY.md.",
+ scope: "write", limit: { key: "agent.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-learning.ts b/lib/mcp/tools-learning.ts
index 8e489d3c..3338355d 100644
--- a/lib/mcp/tools-learning.ts
+++ b/lib/mcp/tools-learning.ts
@@ -123,8 +123,9 @@ export const LEARNING_TOOLS: McpTool[] = [
constraints: { type: "string", description: "Optional important constraints, such as no downtime or WebP only." },
}, ["intent"]),
run: async (a, context) => {
- const actor = context.actor;
- if (!actor) throw new Error("workflow memory needs an authenticated MCP actor");
+ const actor = context.workflowActor ?? context.actor;
+ const recipeOwner = context.recipeActor ?? context.actor;
+ if (!actor || !recipeOwner) throw new Error("workflow memory needs an authenticated session and client");
const intent = str(a, "intent");
const projectHint = opt(a, "project");
const project = projectHint ? await resolveProjectHint(projectHint).catch(() => null) : null;
@@ -134,7 +135,7 @@ export const LEARNING_TOOLS: McpTool[] = [
// received an id for and therefore cannot close.
const search = await searchSkillMemory(intent, {
topK: 8,
- recipeAccess: { actor, scope: context.scope },
+ recipeAccess: { actor: recipeOwner, scope: context.scope },
toolDocs: tools.map((tool) => ({
name: tool.name, description: tool.description, scope: tool.scope, inputSchema: tool.inputSchema,
})),
@@ -160,7 +161,7 @@ export const LEARNING_TOOLS: McpTool[] = [
// Recommendation telemetry is useful, but failure to persist lastUsedAt must
// never turn a successfully-created workflow into an opaque tool failure.
if (search.recommendedRecipe) {
- await markRecipeUsed(search.recommendedRecipe.id, { actor, scope: context.scope }).catch(() => undefined);
+ await markRecipeUsed(search.recommendedRecipe.id, { actor: recipeOwner, scope: context.scope }).catch(() => undefined);
}
return {
...started,
@@ -205,7 +206,7 @@ export const LEARNING_TOOLS: McpTool[] = [
}),
run: async (a, context) => {
const workflowId = str(a, "workflow_id");
- const workflow = await activeWorkflowForActor(context.actor, workflowId);
+ const workflow = await activeWorkflowForActor(context.workflowActor ?? context.actor, workflowId);
if (!workflow) {
return { active: false, workflowId, stepCount: 0, steps: [] };
}
@@ -226,7 +227,7 @@ export const LEARNING_TOOLS: McpTool[] = [
reason: { type: "string", description: "Optional concise reason; no secrets or file contents." },
}, ["workflow_id"]),
run: (a, context) => cancelWorkflow({
- actor: context.actor,
+ actor: context.workflowActor ?? context.actor,
workflowId: str(a, "workflow_id"),
reason: opt(a, "reason"),
}),
@@ -246,7 +247,8 @@ export const LEARNING_TOOLS: McpTool[] = [
success: { type: "boolean", description: "True only after the requested result is verified." },
}, ["workflow_id", "summary", "success"]),
run: (a, context) => finishWorkflow({
- actor: context.actor,
+ actor: context.workflowActor ?? context.actor,
+ recipeActor: context.recipeActor ?? context.actor,
workflowId: str(a, "workflow_id"),
summary: str(a, "summary"),
success: a.success === true,
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index df96d7fb..126f052c 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -29,6 +29,7 @@ export const READ_TOOLS: McpTool[] = [
"check the extension from fs_list first. NOT for finding a file: use fs_search.",
scope: "read",
annotations: READ_ONLY,
+ result: { maxTextBytes: 64 * 1024, overflowHint: "Read a narrower file/range through a project-specific function or inspect only the relevant section." },
inputSchema: S(PATH_P, ["path"]),
run: async (a) => {
const content = await readFile(str(a, "path"));
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 0d9dddd8..2a7ddc84 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -159,7 +159,7 @@ const MUTATE_TOOLS: McpTool[] = [
cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
}, ["command"]),
run: (a, context) => startExecJob({
- command: str(a, "command"), cwd: opt(a, "cwd"), actor: context.actor, workflowId: context.workflowId,
+ command: str(a, "command"), cwd: opt(a, "cwd"), actor: context.workflowActor ?? context.actor, workflowId: context.workflowId,
}),
},
{
@@ -169,8 +169,9 @@ const MUTATE_TOOLS: McpTool[] = [
"Read one asynchronous exec job owned by this MCP client. Returns state, bounded stdout/stderr, exit code when finished, and whether output was truncated.",
scope: "read",
annotations: { readOnlyHint: true, idempotentHint: true },
+ result: { maxTextBytes: 64 * 1024, overflowHint: "The job output is larger than the model context budget; rerun a focused grep/tail after completion if more detail is needed." },
inputSchema: S({ job_id: { type: "string", description: "Exact id returned by exec_job_start." } }, ["job_id"]),
- run: (a, context) => Promise.resolve(getExecJob(str(a, "job_id"), context.actor, context.workflowId)),
+ run: (a, context) => Promise.resolve(getExecJob(str(a, "job_id"), context.workflowActor ?? context.actor, context.workflowId)),
},
{
name: "exec_job_cancel",
@@ -181,7 +182,7 @@ const MUTATE_TOOLS: McpTool[] = [
scope: "exec",
annotations: { destructiveHint: true, idempotentHint: true },
inputSchema: S({ job_id: { type: "string", description: "Exact id returned by exec_job_start." } }, ["job_id"]),
- run: (a, context) => Promise.resolve(cancelExecJob(str(a, "job_id"), context.actor, context.workflowId)),
+ run: (a, context) => Promise.resolve(cancelExecJob(str(a, "job_id"), context.workflowActor ?? context.actor, context.workflowId)),
},
{
name: "exec_run",
@@ -206,6 +207,7 @@ const MUTATE_TOOLS: McpTool[] = [
"Long-running or interactive commands will time out: this is not a terminal session.",
scope: "exec",
annotations: { destructiveHint: true, openWorldHint: true },
+ result: { maxTextBytes: 48 * 1024, overflowHint: "Command output was compacted; rerun a narrower command (grep/head/tail) for the omitted evidence." },
inputSchema: S({
command: { type: "string", description: "The shell command line to run." },
cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 2c470d5f..4e3ab7cb 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -3,8 +3,8 @@ import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
export const MCP_SERVER_VERSION = "1.6.0";
-export const MCP_TOOLSET_VERSION = "2026.08.31.1";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-01T07:55:00Z";
+export const MCP_TOOLSET_VERSION = "2026.09.02.1";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-01T18:01:00Z";
export type McpToolsetInfo = {
serverVersion: string;
@@ -27,6 +27,7 @@ export function toolsetInfo(tools: readonly McpTool[], scope?: Scope): McpToolse
outputSchema: tool.outputSchema,
annotations: tool.annotations,
meta: tool.meta,
+ result: tool.result,
limit: tool.limit,
}));
const hash = createHash("sha256").update(JSON.stringify(hashInput)).digest("hex").slice(0, 16);
diff --git a/lib/security/redact-text.ts b/lib/security/redact-text.ts
new file mode 100644
index 00000000..8abc0a10
--- /dev/null
+++ b/lib/security/redact-text.ts
@@ -0,0 +1,34 @@
+const SECRET = /([\w.-]*(?:api[_-]?key|auth[_-]?token|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|token|secret|password|passwd|authorization|credential)s?)(["']?\s*[:=]\s*["']?)([^\s"',;)\]}]+)/gi;
+const SECRET_VALUE = new RegExp([
+ "gh[pousr]_[A-Za-z0-9]{16,}", "github_pat_[A-Za-z0-9_]{20,}",
+ "sk-[A-Za-z0-9_-]{16,}", "npm_[A-Za-z0-9]{20,}", "xox[abprs]-[A-Za-z0-9-]{10,}",
+ "AKIA[0-9A-Z]{16}", "eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}",
+].map((shape) => `\\b${shape}`).join("|"), "g");
+const URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s/@]+)@/gi;
+
+export function redactText(value: string, max = Number.POSITIVE_INFINITY): string {
+ return value
+ .replace(/\bbearer\s+[^\s,;]+/gi, "Bearer [redacted]")
+ .replace(URL_CREDENTIALS, "$1$2:[redacted]@")
+ .replace(SECRET, "$1$2[redacted]")
+ .replace(SECRET_VALUE, "[redacted]")
+ .slice(0, max);
+}
+
+
+export function redactUnknown(value: unknown, depth = 0): unknown {
+ if (depth > 12) return "[depth-limit]";
+ if (typeof value === "string") return redactText(value);
+ if (Array.isArray(value)) return value.map((item) => redactUnknown(item, depth + 1));
+ if (!value || typeof value !== "object") return value;
+ const out: Record<string, unknown> = {};
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
+ const lower = key.toLowerCase();
+ if (/(?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|authorization|credential)/.test(lower)) {
+ out[key] = "[redacted]";
+ continue;
+ }
+ out[key] = redactUnknown(item, depth + 1);
+ }
+ return out;
+}
diff --git a/lib/skills/memory.ts b/lib/skills/memory.ts
index b785984f..731660da 100644
--- a/lib/skills/memory.ts
+++ b/lib/skills/memory.ts
@@ -480,7 +480,7 @@ export async function cancelWorkflow(input: {
const actor = actorKey(input.actor);
const store = await loadStore();
const workflow = workflowFor(store, actor, input.workflowId);
- if (!workflow) throw new Error("workflow_id was not found for this MCP client");
+ if (!workflow) throw new Error("workflow_id was not found for this MSO session");
removeActiveWorkflow(store, actor, input.workflowId);
await persist(store);
const reason = input.reason ? safeMemoryText(input.reason, 500) || undefined : undefined;
@@ -489,19 +489,21 @@ export async function cancelWorkflow(input: {
export async function finishWorkflow(input: {
actor?: string;
+ recipeActor?: string;
workflowId: string;
summary: string;
success: boolean;
}): Promise<FinishWorkflowResult> {
const actor = actorKey(input.actor);
+ const recipeOwner = actorKey(input.recipeActor ?? input.actor);
const store = await loadStore();
const workflow = workflowFor(store, actor, input.workflowId);
- if (!workflow) throw new Error("workflow_id was not found for this MCP client");
+ if (!workflow) throw new Error("workflow_id was not found for this MSO session");
const now = new Date();
const wallMs = Math.max(0, now.getTime() - new Date(workflow.startedAt).getTime());
const durationMs = elapsedMs(workflow.steps, wallMs);
- const existing = closestRecipe(store, actor, workflow.scope, workflow.intent, workflow.project);
+ const existing = closestRecipe(store, recipeOwner, workflow.scope, workflow.intent, workflow.project);
const previousFastestMs = existing?.fastestDurationMs;
const summary = safeMemoryText(input.summary, 1200) || (input.success ? "completed" : "failed");
const vector = embedSkillText(recipeText(workflow.intent, workflow.project, summary));
@@ -516,7 +518,7 @@ export async function finishWorkflow(input: {
const faster = input.success && (existing.fastestDurationMs == null || durationMs < existing.fastestDurationMs);
recipe = {
...existing,
- actor,
+ actor: recipeOwner,
scope: workflow.scope,
intent: workflow.intent,
normalizedIntent: normalizeSemanticText(workflow.intent),
@@ -539,7 +541,7 @@ export async function finishWorkflow(input: {
} else {
recipe = {
id: randomUUID(),
- actor,
+ actor: recipeOwner,
scope: workflow.scope,
intent: workflow.intent,
normalizedIntent: normalizeSemanticText(workflow.intent),
@@ -593,16 +595,20 @@ export async function finishWorkflow(input: {
export async function listLearnedRecipes(access: RecipeAccess): Promise<LearnedRecipe[]> {
const store = await loadStore();
- return Object.values(store.recipes)
- .filter((recipe) => access.ownerView || (recipe.actor === access.actor && allows(access.scope, recipe.scope)))
- .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
+ const recipes = Object.values(store.recipes);
+ const visible = access.ownerView
+ ? recipes
+ : recipes.filter((recipe) => recipe.actor === access.actor && allows(access.scope, recipe.scope));
+ return visible.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
}
export async function markRecipeUsed(id: string, access: RecipeAccess): Promise<void> {
const store = await loadStore();
const recipe = store.recipes[id];
if (!recipe) return;
- if (!access.ownerView && (recipe.actor !== access.actor || !allows(access.scope, recipe.scope))) return;
+ if (!access.ownerView) {
+ if (recipe.actor !== access.actor || !allows(access.scope, recipe.scope)) return;
+ }
recipe.lastUsedAt = new Date().toISOString();
await persist(store);
}
diff --git a/package.json b/package.json
index 6404eeab..da5b0b8b 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,8 @@
"icons:app": "node scripts/gen-app-icons.mjs && python3 scripts/gen-remaining-platform-icons.py",
"skill:new": "node scripts/create-skill-flow.mjs",
"skill:check": "node scripts/check-skill-flows.mjs",
- "comparison": "node scripts/gen-comparison.mjs"
+ "comparison": "node scripts/gen-comparison.mjs",
+ "bench:cognitive": "bun scripts/bench-cognitive-runtime.mjs"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.120.0",
diff --git a/scripts/bench-cognitive-runtime.mjs b/scripts/bench-cognitive-runtime.mjs
new file mode 100755
index 00000000..0e86b1f6
--- /dev/null
+++ b/scripts/bench-cognitive-runtime.mjs
@@ -0,0 +1,102 @@
+#!/usr/bin/env bun
+import { execFileSync } from "node:child_process";
+import { mock } from "bun:test";
+import { selectToolsForTurn } from "./mso-agent-tool-router.mjs";
+
+mock.module("server-only", () => ({}));
+const { TOOLS } = await import("../lib/mcp/tools.ts");
+
+const scenarios = [
+ { id: "app-logs", prompt: "Hermes is down. Check managed app state and inspect its recent logs.", required: ["apps_list", "apps_logs"] },
+ { id: "server-health", prompt: "How is the VPS doing? Check cpu, ram, disk and top processes.", required: ["sys_stats", "sys_processes"] },
+ { id: "safe-edit", prompt: "Inspect README then safely update that file without overwriting concurrent changes.", required: ["fs_read", "fs_write"] },
+ { id: "long-build", prompt: "Run the full test and production build pipeline; it may take several minutes.", required: ["exec_job_start", "exec_job_status", "exec_job_cancel"] },
+ { id: "short-shell", prompt: "Run a short git status command in the repository.", required: ["exec_run"] },
+ { id: "project-function", prompt: "Find the project and execute its declared automation function.", required: ["projects_list", "project_capabilities", "project_function_call"] },
+ { id: "cloudflare-dns", prompt: "Update the Cloudflare DNS record after finding the correct zone.", required: ["cloudflare_zones_list", "cloudflare_dns_upsert"] },
+ { id: "hostinger-dns", prompt: "Update a Hostinger DNS record for this domain.", required: ["hostinger_dns_upsert"] },
+ { id: "dokploy", prompt: "List Dokploy projects and ensure the deployment project exists.", required: ["dokploy_projects_list", "dokploy_project_ensure"] },
+ { id: "browser", prompt: "Check the Camoufox browser state and start it if it is stopped.", required: ["browser_status", "browser_power"] },
+ { id: "screenshot", prompt: "Take a screenshot of the MSO desktop so I can inspect the UI.", required: ["screen_capture"] },
+ { id: "memory", prompt: "Read my agent memory and remember this project convention for later sessions.", required: ["agent_memory_read", "agent_memory_remember"] },
+ { id: "resume", prompt: "List previous agent sessions and resume the deployment session.", required: ["agent_sessions_list", "agent_session_resume"] },
+ { id: "skills", prompt: "Find the best trusted skill for a repository security review and read its instructions.", required: ["skills_search", "skills_read"] },
+];
+
+const toolShape = (tool) => ({ name: tool.name, description: tool.description, input_schema: tool.inputSchema });
+const bytes = (tools) => Buffer.byteLength(JSON.stringify(tools.map(toolShape)), "utf8");
+const fullBytes = bytes(TOOLS);
+let selectedBytes = 0, selectedCount = 0, requiredTotal = 0, requiredHit = 0, deterministic = true;
+const rows = scenarios.map((scenario) => {
+ const history = [{ role: "user", text: scenario.prompt }];
+ const a = selectToolsForTurn(TOOLS, history);
+ const b = selectToolsForTurn(TOOLS, history);
+ deterministic &&= JSON.stringify(a.selectedNames) === JSON.stringify(b.selectedNames);
+ const missing = scenario.required.filter((name) => !a.selectedNames.includes(name));
+ requiredTotal += scenario.required.length; requiredHit += scenario.required.length - missing.length;
+ const schemaBytes = bytes(a.tools); selectedBytes += schemaBytes; selectedCount += a.activeCount;
+ return { id: scenario.id, required: scenario.required, missing, activeTools: a.activeCount, schemaBytes };
+});
+
+function hermesBaseline() {
+ try {
+ return JSON.parse(execFileSync("hermes", ["prompt-size", "--platform", "cli", "--json"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }));
+ } catch { return null; }
+}
+function version(command) {
+ try { return execFileSync(command, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim().split("\n")[0]; }
+ catch { return null; }
+}
+
+const hermes = hermesBaseline();
+const avgSelectedBytes = Math.round(selectedBytes / scenarios.length);
+const avgActiveTools = Math.round((selectedCount / scenarios.length) * 10) / 10;
+const routingRecall = requiredTotal ? requiredHit / requiredTotal : 0;
+const result = {
+ generatedAt: new Date().toISOString(),
+ providerNeutral: true,
+ mso: {
+ fullToolCount: TOOLS.length,
+ fullToolSchemaBytes: fullBytes,
+ averageActiveTools: avgActiveTools,
+ averageActiveSchemaBytes: avgSelectedBytes,
+ schemaReductionPct: Math.round((1 - avgSelectedBytes / fullBytes) * 1000) / 10,
+ routingRecallPct: Math.round(routingRecall * 1000) / 10,
+ deterministic,
+ scenarios: rows,
+ },
+ hermes: hermes ? {
+ version: version("hermes"), toolCount: hermes.tools?.count ?? null,
+ toolSchemaBytes: hermes.tools?.json_bytes ?? null,
+ systemPromptBytes: hermes.system_prompt?.bytes ?? null,
+ skillsIndexBytes: hermes.skills_index?.bytes ?? null,
+ } : { available: false },
+ openclaw: {
+ version: version("openclaw"),
+ comparablePromptFootprintProbe: false,
+ note: "Installed OpenClaw has no directly equivalent offline prompt-size probe exposed by this benchmark; do not infer an overall win from schema footprint alone.",
+ },
+};
+result.gates = {
+ routingRecall100: routingRecall === 1,
+ deterministicRouting: deterministic,
+ activeSchemaSmallerThanFull: avgSelectedBytes < fullBytes,
+ beatsHermesToolSchemaBytes: Boolean(hermes?.tools?.json_bytes && avgSelectedBytes < hermes.tools.json_bytes),
+};
+result.passed = Object.values(result.gates).every(Boolean);
+
+if (process.argv.includes("--json")) console.log(JSON.stringify(result, null, 2));
+else {
+ console.log("MSO Cognitive Runtime P0 benchmark");
+ console.log(` full catalog ${TOOLS.length} tools · ${fullBytes.toLocaleString()} schema bytes`);
+ console.log(` active per turn ${avgActiveTools} tools avg · ${avgSelectedBytes.toLocaleString()} bytes avg · ${result.mso.schemaReductionPct}% reduction`);
+ console.log(` routing ${result.mso.routingRecallPct}% required-tool recall · deterministic=${deterministic}`);
+ if (hermes?.tools) console.log(` Hermes baseline ${hermes.tools.count} tools · ${Number(hermes.tools.json_bytes).toLocaleString()} schema bytes`);
+ else console.log(" Hermes baseline unavailable");
+ console.log(` OpenClaw ${result.openclaw.version || "unavailable"} · no comparable offline prompt-size probe`);
+ for (const [gate, pass] of Object.entries(result.gates)) console.log(` ${pass ? "PASS" : "FAIL"} ${gate}`);
+ if (!result.passed) {
+ for (const row of rows.filter((r) => r.missing.length)) console.log(` ${row.id}: missing ${row.missing.join(", ")}`);
+ process.exitCode = 1;
+ }
+}
diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs
index bec00801..f2568439 100755
--- a/scripts/check-docs.mjs
+++ b/scripts/check-docs.mjs
@@ -21,6 +21,7 @@ const toolFiles = [
"lib/mcp/tools-learning.ts",
"lib/mcp/tools-infra.ts",
"lib/mcp/tools-power.ts",
+ "lib/mcp/tools-agent.ts",
];
const tools = new Map();
for (const file of toolFiles) {
diff --git a/scripts/mso-agent-context.mjs b/scripts/mso-agent-context.mjs
new file mode 100644
index 00000000..80b20ad1
--- /dev/null
+++ b/scripts/mso-agent-context.mjs
@@ -0,0 +1,51 @@
+export const DEFAULT_MODEL_HISTORY_BUDGET = 48_000;
+export const MAX_MODEL_HISTORY_BUDGET = 120_000;
+
+export function estimateContextTokens(value) {
+ let raw = "";
+ try { raw = typeof value === "string" ? value : JSON.stringify(value ?? ""); }
+ catch { raw = String(value ?? ""); }
+ return Math.ceil(Buffer.byteLength(raw, "utf8") / 4);
+}
+
+export function modelHistoryBudget(contextWindow) {
+ const limit = Number(contextWindow || 0);
+ if (!Number.isFinite(limit) || limit <= 0) return DEFAULT_MODEL_HISTORY_BUDGET;
+ // Reserve almost half the window for system/memory, active skill/tool schemas,
+ // reasoning/output and provider framing. Very large windows still stop at 120k:
+ // more historical text is usually worse than targeted retrieval/compaction.
+ return Math.min(MAX_MODEL_HISTORY_BUDGET, Math.max(16_000, Math.floor(limit * 0.55)));
+}
+
+function messageGroups(history) {
+ const rows = Array.isArray(history) ? history : [];
+ const groups = [];
+ for (let i = 0; i < rows.length; i += 1) {
+ const row = rows[i];
+ if (row?.role === "assistant" && Array.isArray(row.toolUses) && row.toolUses.length && rows[i + 1]?.role === "tool") {
+ groups.push([row, rows[i + 1]]); i += 1;
+ } else groups.push([row]);
+ }
+ return groups;
+}
+
+export function projectHistoryForModel(history, contextWindow) {
+ const budget = modelHistoryBudget(contextWindow);
+ const groups = messageGroups(history);
+ const kept = [];
+ let used = 0;
+ for (let i = groups.length - 1; i >= 0; i -= 1) {
+ const group = groups[i];
+ const cost = estimateContextTokens(group);
+ if (kept.length && used + cost > budget) break;
+ kept.unshift(group); used += cost;
+ if (used >= budget) break;
+ }
+ const messages = kept.flat();
+ return {
+ messages,
+ estimatedTokens: used,
+ budgetTokens: budget,
+ omittedRows: Math.max(0, (Array.isArray(history) ? history.length : 0) - messages.length),
+ };
+}
diff --git a/scripts/mso-agent-context.test.ts b/scripts/mso-agent-context.test.ts
new file mode 100644
index 00000000..3407c412
--- /dev/null
+++ b/scripts/mso-agent-context.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { modelHistoryBudget, projectHistoryForModel } from "./mso-agent-context.mjs";
+
+describe("MSO model context projection", () => {
+ it("reserves provider-neutral headroom instead of filling the whole context window", () => {
+ expect(modelHistoryBudget(32_000)).toBe(17_600);
+ expect(modelHistoryBudget(128_000)).toBe(70_400);
+ expect(modelHistoryBudget(1_000_000)).toBe(120_000);
+ });
+
+ it("keeps recent context while omitting old bulk", () => {
+ const history = Array.from({ length: 80 }, (_, i) => ({ role: i % 2 ? "assistant" : "user", text: `${i}:${"x".repeat(4000)}` }));
+ const out = projectHistoryForModel(history, 32_000);
+ expect(out.messages.length).toBeLessThan(history.length);
+ expect(out.messages.at(-1)).toEqual(history.at(-1));
+ expect(out.estimatedTokens).toBeLessThanOrEqual(out.budgetTokens + 2_000);
+ expect(out.omittedRows).toBeGreaterThan(0);
+ });
+
+ it("never splits an assistant tool call from its following tool result", () => {
+ const old = Array.from({ length: 30 }, (_, i) => ({ role: "user", text: `${i}${"x".repeat(3000)}` }));
+ const call = { role: "assistant", text: "", toolUses: [{ id: "c1", name: "sys_stats", input: {} }] };
+ const result = { role: "tool", results: [{ id: "c1", content: "ok" }] };
+ const out = projectHistoryForModel([...old, call, result], 32_000);
+ expect(out.messages.slice(-2)).toEqual([call, result]);
+ });
+});
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
index 8c4ab117..49fc33d2 100644
--- a/scripts/mso-agent-runtime.mjs
+++ b/scripts/mso-agent-runtime.mjs
@@ -1,5 +1,7 @@
import fs from "node:fs";
import process from "node:process";
+import { selectToolsForTurn } from "./mso-agent-tool-router.mjs";
+import { projectHistoryForModel } from "./mso-agent-context.mjs";
import { C, fit, MSO_TITLE_ART, printAgentBanner } from "./mso-agent-ui.mjs";
export { C, MSO_TITLE_ART } from "./mso-agent-ui.mjs";
@@ -60,6 +62,10 @@ export async function loadCliSession(id) {
const out = await api(`/api/v1/agent-sessions?id=${encodeURIComponent(id)}`);
return out.session;
}
+export async function resumeCliSession(ref) {
+ const out = await api("/api/v1/agent-sessions", { method: "POST", body: JSON.stringify({ action: "resume", ref }) });
+ 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 : [];
@@ -80,6 +86,7 @@ function sessionSystem(agentSession, skillContext = null) {
const snapshot = agentSession?.memorySnapshot || {};
const user = fit(snapshot.user || "", 12000);
const memory = fit(snapshot.memory || "", 12000);
+ const contextSummary = fit(agentSession?.contextSummary || "", 24000);
const cwd = process.cwd();
const skillInstructions = skillContext?.content ? String(skillContext.content).slice(0, 24000) : "";
const skillProject = skillContext?.project?.path ? ` Project context: ${skillContext.project.name || skillContext.project.id} at ${skillContext.project.path}.` : "";
@@ -89,6 +96,7 @@ function sessionSystem(agentSession, skillContext = null) {
`Terminal working directory: ${cwd}. Treat a project containing this directory as the current project context unless the user explicitly selects another project.`,
skillInstructions ? `The user explicitly selected skill ${skillContext.id || skillContext.name} for this turn.${skillProject} Follow these instructions for this turn:\n<SKILL.md>\n${skillInstructions}\n</SKILL.md>` : "",
"Use the provided tools to do real work instead of only describing commands. Prefer bounded tools over exec_run.",
+ "MSO loads a compact capability subset per turn. If a needed tool is not currently visible, call skills_search; matching tool schemas are loaded on the next tool round without changing permissions.",
"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.",
@@ -97,6 +105,7 @@ function sessionSystem(agentSession, skillContext = null) {
"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>` : "",
+ contextSummary ? `\n<COMPACTED_SESSION_CONTEXT>\n${contextSummary}\n</COMPACTED_SESSION_CONTEXT>` : "",
"Be concise. Explain only decisions the user needs to make or concrete results/errors.",
].filter(Boolean).join(" ");
}
@@ -112,11 +121,13 @@ function toolForModel(tool) {
* @param {any} [skillContext]
* @param {AbortSignal | undefined} [signal]
*/
-export async function streamTurn(messages, tools, agentSession, skillContext = null, signal = undefined) {
+export async function streamTurn(messages, tools, agentSession, skillContext = null, signal = undefined, contextWindow = undefined) {
+ const projected = projectHistoryForModel(messages, contextWindow);
+ const activeTools = selectToolsForTurn(tools, projected.messages, skillContext);
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: sessionSystem(agentSession, skillContext) }),
+ body: JSON.stringify({ messages: projected.messages, tools: activeTools.tools.map(toolForModel), system: sessionSystem(agentSession, skillContext) }),
signal,
});
if (!res.ok || !res.body) {
diff --git a/scripts/mso-agent-session-ui.mjs b/scripts/mso-agent-session-ui.mjs
index afb80fb5..d1ece674 100644
--- a/scripts/mso-agent-session-ui.mjs
+++ b/scripts/mso-agent-session-ui.mjs
@@ -1,4 +1,4 @@
-import { C, createCliSession, listCliSessions, loadCliSession, saveCliSession } from "./mso-agent-runtime.mjs";
+import { C, createCliSession, listCliSessions, resumeCliSession, saveCliSession } from "./mso-agent-runtime.mjs";
import { resolveSessionQuery, sessionCompletionItems } from "./mso-agent-sessions.mjs";
function autoTitle(history) {
@@ -10,6 +10,7 @@ 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 };
+ if (Array.isArray(saved?.history)) session.history = saved.history;
}
export function printSessions(rows) {
@@ -38,11 +39,11 @@ async function resolveResume(query, rows = null) {
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");
+ const loaded = await resumeCliSession(target.id);
+ if (!loaded || loaded.source !== "cli") throw new Error("could not create a CLI continuation session");
Object.assign(session, {
agentSession: loaded,
- history: Array.isArray(loaded.history) ? loaded.history.slice(-48) : [],
+ history: Array.isArray(loaded.history) ? loaded.history : [],
pendingSkill: null,
activeSkill: null,
lastInvokedSkill: null,
@@ -79,5 +80,5 @@ 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);
+ return resumeCliSession(target.id);
}
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
index cf7696e0..d3eba959 100644
--- a/scripts/mso-agent-status.mjs
+++ b/scripts/mso-agent-status.mjs
@@ -1,5 +1,6 @@
import os from "node:os";
import path from "node:path";
+import { projectHistoryForModel } from "./mso-agent-context.mjs";
function compactNumber(value) {
const n = Number(value || 0);
@@ -21,12 +22,15 @@ export function historyContextEstimate(history) {
}
export function contextStatus(history, modelMeta) {
- const used = historyContextEstimate(history);
const limit = Number(modelMeta?.context || 0);
+ const projected = projectHistoryForModel(history, limit);
return {
- used,
+ used: projected.estimatedTokens,
+ stored: historyContextEstimate(history),
+ omittedRows: projected.omittedRows,
+ budget: projected.budgetTokens,
limit: Number.isFinite(limit) && limit > 0 ? limit : null,
- percent: limit > 0 ? Math.min(999, Math.round((used / limit) * 100)) : null,
+ percent: limit > 0 ? Math.min(999, Math.round((projected.estimatedTokens / limit) * 100)) : null,
};
}
@@ -70,6 +74,7 @@ export function statusParts(session, cwd = process.cwd()) {
`${provider}/${model}`,
skill ? `skill ${skill.state === "invoked" ? "✓" : "◆"} /${skill.name}${skill.state === "queued" ? " queued" : skill.state === "invoking" ? " invoking" : ""}` : null,
ctx.limit ? `ctx ~${compactNumber(ctx.used)}/${compactNumber(ctx.limit)} ${ctx.percent}%` : `ctx ~${compactNumber(ctx.used)}/?`,
+ session?.agentSession?.compactThresholdTokens ? `session ~${compactNumber(session.agentSession.estimatedTokens)}/${compactNumber(session.agentSession.compactThresholdTokens)}` : null,
usage.totalTokens > 0 ? `tokens ${compactNumber(usage.totalTokens)}` : null,
`turns ${turns}`,
elapsed > 0 ? `${(elapsed / 1000).toFixed(elapsed >= 10_000 ? 0 : 1)}s` : null,
@@ -94,6 +99,12 @@ export function detailedStatus(session, cwd = process.cwd()) {
contextEstimatedTokens: ctx.used,
contextWindow: ctx.limit,
contextPercent: ctx.percent,
+ contextOmittedRows: ctx.omittedRows,
+ sessionEstimatedTokens: Number(session?.agentSession?.estimatedTokens || ctx.stored || 0),
+ sessionLifetimeEstimatedTokens: Number(session?.agentSession?.lifetimeEstimatedTokens || 0),
+ sessionCompactThresholdTokens: Number(session?.agentSession?.compactThresholdTokens || 0),
+ sessionCompactionCount: Number(session?.agentSession?.compactionCount || 0),
+ sessionArchiveCount: Number(session?.agentSession?.archiveCount || 0),
providerReportedUsage: usage,
skill: skillStatus(session),
turns: (session?.history || []).filter((row) => row?.role === "user").length,
@@ -108,7 +119,8 @@ export function printDetailedStatus(session, C, cwd = process.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}%)` : " / ?"}`);
+ console.log(` context ~${row.contextEstimatedTokens}${row.contextWindow ? ` / ${row.contextWindow} (${row.contextPercent}%)` : " / ?"}${row.contextOmittedRows ? ` · ${row.contextOmittedRows} older rows projected out` : ""}`);
+ if (row.sessionCompactThresholdTokens) console.log(` session ~${row.sessionEstimatedTokens} / ${row.sessionCompactThresholdTokens} stored · lifetime ~${row.sessionLifetimeEstimatedTokens} · ${row.sessionCompactionCount} compactions · ${row.sessionArchiveCount} archives`);
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");
diff --git a/scripts/mso-agent-tool-router.mjs b/scripts/mso-agent-tool-router.mjs
new file mode 100644
index 00000000..e2ee9ae0
--- /dev/null
+++ b/scripts/mso-agent-tool-router.mjs
@@ -0,0 +1,124 @@
+const CORE_TOOL_NAMES = new Set([
+ "workflow_start", "workflow_status", "workflow_finish", "workflow_cancel",
+ "skills_search", "projects_list", "project_capabilities", "agent_session_current",
+]);
+
+export const MAX_ACTIVE_TOOLS = 14;
+
+const DEPENDENCIES = new Map([
+ ["apps_logs", ["apps_list"]],
+ ["project_function_call", ["project_capabilities"]],
+ ["exec_job_start", ["exec_job_status", "exec_job_cancel"]],
+ ["fs_write", ["fs_read"]],
+ ["agent_session_resume", ["agent_sessions_list"]],
+]);
+
+const ALIASES = new Map([
+ ["logs", ["log", "journal", "error", "crash", "down"]],
+ ["processes", ["process", "cpu", "memory", "ram", "load"]],
+ ["stats", ["health", "cpu", "memory", "ram", "disk", "uptime", "server", "vps"]],
+ ["projects", ["project", "repo", "repository", "checkout", "workspace"]],
+ ["skills", ["skill", "capability", "recipe", "workflow", "how"]],
+ ["read", ["read", "inspect", "show", "cat", "file"]],
+ ["write", ["write", "edit", "update", "modify", "patch", "file"]],
+ ["exec", ["run", "shell", "command", "terminal", "test", "build", "lint", "deploy"]],
+ ["browser", ["browser", "camoufox", "firefox", "vnc"]],
+ ["screen", ["screen", "screenshot", "visual", "image"]],
+ ["cloudflare", ["cloudflare", "dns", "zone", "record"]],
+ ["dokploy", ["dokploy", "deploy", "deployment", "project"]],
+ ["hostinger", ["hostinger", "dns", "domain", "record"]],
+ ["apps", ["app", "service", "hermes", "openclaw", "install", "restart", "status"]],
+]);
+
+function words(value) {
+ const raw = String(value || "").toLowerCase().replace(/[^a-z0-9_./-]+/g, " ");
+ const out = new Set(raw.split(/\s+/).filter((v) => v.length >= 2));
+ for (const [key, terms] of ALIASES) if (terms.some((term) => out.has(term))) out.add(key);
+ return out;
+}
+
+function messageText(row) {
+ if (!row || typeof row !== "object") return "";
+ if (typeof row.text === "string") return row.text;
+ if (row.role === "tool" && Array.isArray(row.results)) return row.results.map((r) => String(r?.content || "")).join("\n");
+ return "";
+}
+
+export function turnSearchText(history = [], skillContext = null) {
+ const recent = history.slice(-8).map(messageText).filter(Boolean).join("\n");
+ const skill = skillContext?.content ? String(skillContext.content).slice(0, 16000) : "";
+ return `${recent}\n${skill}`.slice(-48000);
+}
+
+function toolHaystack(tool) {
+ const props = Object.keys(tool?.inputSchema?.properties || {}).join(" ");
+ return `${tool?.name || ""} ${tool?.description || ""} ${props}`.toLowerCase();
+}
+
+function score(tool, queryWords, rawQuery) {
+ const hay = toolHaystack(tool);
+ const name = String(tool?.name || "").toLowerCase();
+ let value = 0;
+ for (const token of queryWords) {
+ if (name === token) value += 12;
+ else if (name.includes(token)) value += 5;
+ if (hay.includes(token)) value += 1;
+ }
+ if (rawQuery.includes(name) && name) value += 18;
+ const prefix = name.split("_")[0];
+ if (prefix && queryWords.has(prefix)) value += 3;
+ return value;
+}
+
+function referencedTools(allTools, text) {
+ const lower = text.toLowerCase();
+ return allTools.filter((tool) => lower.includes(String(tool.name).toLowerCase())).map((tool) => tool.name);
+}
+
+function previousToolNames(history = []) {
+ const names = [];
+ for (const row of history.slice(-12)) {
+ if (row?.role !== "assistant" || !Array.isArray(row.toolUses)) continue;
+ for (const call of row.toolUses) if (call?.name) names.push(String(call.name));
+ }
+ return names;
+}
+
+export function selectToolsForTurn(allTools = [], history = [], skillContext = null, maxActive = MAX_ACTIVE_TOOLS) {
+ const byName = new Map(allTools.map((tool) => [String(tool.name), tool]));
+ const text = turnSearchText(history, skillContext);
+ const queryWords = words(text);
+ const selected = new Set();
+ const add = (name) => { if (byName.has(name)) selected.add(name); };
+
+ for (const name of CORE_TOOL_NAMES) add(name);
+ for (const name of previousToolNames(history)) add(name);
+ for (const name of referencedTools(allTools, text)) add(name);
+
+ const ranked = allTools
+ .map((tool) => ({ tool, score: score(tool, queryWords, text.toLowerCase()) }))
+ .filter((row) => row.score > 0)
+ .sort((a, b) => b.score - a.score || String(a.tool.name).localeCompare(String(b.tool.name)));
+
+ for (const { tool } of ranked) {
+ if (selected.size >= maxActive) break;
+ add(String(tool.name));
+ }
+
+ for (const name of [...selected]) {
+ for (const dependency of DEPENDENCIES.get(name) || []) add(dependency);
+ }
+
+ // Core + dependency safety may exceed the soft cap by a few entries. Prefer
+ // capability correctness over silently dropping the status/cancel companion.
+ const tools = allTools.filter((tool) => selected.has(String(tool.name)));
+ return {
+ tools,
+ selectedNames: tools.map((tool) => String(tool.name)),
+ fullCount: allTools.length,
+ activeCount: tools.length,
+ softLimit: maxActive,
+ };
+}
+
+export function coreToolNames() { return [...CORE_TOOL_NAMES]; }
diff --git a/scripts/mso-agent-tool-router.test.ts b/scripts/mso-agent-tool-router.test.ts
new file mode 100644
index 00000000..3c113467
--- /dev/null
+++ b/scripts/mso-agent-tool-router.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { MAX_ACTIVE_TOOLS, selectToolsForTurn } from "./mso-agent-tool-router.mjs";
+
+const tool = (name: string, description: string) => ({ name, description, scope: "read", inputSchema: { type: "object", properties: {} } });
+const catalog = [
+ tool("workflow_start", "Start multi-step workflow"), tool("workflow_status", "Workflow status"),
+ tool("workflow_finish", "Finish workflow"), tool("workflow_cancel", "Cancel workflow"),
+ tool("skills_search", "Search capabilities skills tools recipes"), tool("projects_list", "List projects repositories"),
+ tool("project_capabilities", "Inspect project functions"), tool("agent_session_current", "Current session"),
+ tool("sys_stats", "Live VPS CPU memory disk uptime health"), tool("sys_processes", "Top CPU processes"),
+ tool("apps_list", "Managed apps hermes openclaw"), tool("apps_logs", "Recent application logs"),
+ tool("fs_read", "Read a text file"), tool("fs_write", "Write or update a text file"),
+ tool("exec_run", "Run a short shell command"), tool("exec_job_start", "Run long tests and builds"),
+ tool("exec_job_status", "Read long job status"), tool("exec_job_cancel", "Cancel long job"),
+ tool("screen_capture", "Capture screenshot"), tool("browser_status", "Camoufox browser state"),
+ tool("cloudflare_zones_list", "List Cloudflare DNS zones"), tool("hostinger_dns_upsert", "Update Hostinger DNS record"),
+];
+
+describe("MSO per-turn tool router", () => {
+ it("keeps core discovery while selecting the relevant bounded tools", () => {
+ const out = selectToolsForTurn(catalog, [{ role: "user", text: "why is hermes down? inspect its logs" }]);
+ expect(out.selectedNames).toContain("skills_search");
+ expect(out.selectedNames).toContain("apps_logs");
+ expect(out.selectedNames).toContain("apps_list");
+ expect(out.activeCount).toBeLessThan(catalog.length);
+ expect(out.softLimit).toBe(MAX_ACTIVE_TOOLS);
+ });
+
+ it("loads a tool explicitly named by a discovery result on the next turn", () => {
+ const history = [
+ { role: "user", text: "update DNS" },
+ { role: "assistant", toolUses: [{ name: "skills_search", input: {} }] },
+ { role: "tool", results: [{ content: "best tool: hostinger_dns_upsert" }] },
+ ];
+ expect(selectToolsForTurn(catalog, history).selectedNames).toContain("hostinger_dns_upsert");
+ });
+
+ it("keeps long-job companions when build work selects exec_job_start", () => {
+ const out = selectToolsForTurn(catalog, [{ role: "user", text: "run the full build and test pipeline" }]);
+ expect(out.selectedNames).toContain("exec_job_start");
+ expect(out.selectedNames).toContain("exec_job_status");
+ expect(out.selectedNames).toContain("exec_job_cancel");
+ });
+});
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 9d82a4e1..31950c1e 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -57,7 +57,7 @@ async function agentRound(rl, session, skillContext = null, signal = undefined,
beginSkillInvocation(session, skillContext, C);
try {
for (let turn = 0; turn < 10; turn++) {
- const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext, signal); if (skillContext) session.lastInvokedSkill = skillContext;
+ const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext, signal, session.state.modelMeta?.context); if (skillContext) session.lastInvokedSkill = skillContext;
session.usage = addUsage(session.usage, result.usage);
session.lastElapsedMs = Date.now() - startedAt;
session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });
@@ -109,7 +109,7 @@ async function main() {
const session = {
state: s,
agentSession,
- history: Array.isArray(agentSession.history) ? agentSession.history.slice(-48) : [],
+ history: Array.isArray(agentSession.history) ? agentSession.history : [],
pendingSkill: null,
activeSkill: null,
lastInvokedSkill: null,
@@ -154,7 +154,6 @@ async function main() {
continue;
}
session.history.push({ role: "user", text: line });
- if (session.history.length > 48) session.history.splice(0, session.history.length - 48);
const skillContext = session.pendingSkill;
session.pendingSkill = null;
await runInteractiveRound(rl, session, skillContext, interrupts);
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index 53b9a8c0..0b31a356 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -14,7 +14,7 @@ const all = [cli, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
- expect(cli).toContain('VERSION="1.5.8"');
+ expect(cli).toContain('VERSION="1.6.0"');
expect(cli).toContain("models * Configure AI providers/auth");
expect(cli).toContain("model [ref] Select active model");
expect(agentCli).toContain("run_models()");