Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
refactor: extract capability kernel and architecture ratchets
Rahmanb30acc92b7fa
diff --git a/app/a2a/v1/route.ts b/app/a2a/v1/route.tsindex bd0b38d0..c52759cd 100644--- a/app/a2a/v1/route.ts+++ b/app/a2a/v1/route.ts@@ -1,10 +1,11 @@import { handleA2ARequest } from "@/lib/a2a/server";+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";export const runtime = "nodejs";export const dynamic = "force-dynamic";export async function POST(req: Request) {- return handleA2ARequest(req);+ return handleA2ARequest(req, msoCapabilityRuntime);}export async function GET() {return Response.json(diff --git a/app/api/v1/a2a/route-messages.ts b/app/api/v1/a2a/route-messages.tsindex e4766063..b31114ac 100644--- a/app/api/v1/a2a/route-messages.ts+++ b/app/api/v1/a2a/route-messages.ts@@ -9,6 +9,7 @@ import {sendA2AStreamingMessage,} from "@/lib/a2a";import { audit } from "@/lib/host";+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";import { a2aHash, a2aLimited } from "./route-shared";export async function handleA2AMessageAction(@@ -30,7 +31,7 @@ export async function handleA2AMessageAction({ error: "session_and_objective_required" },{ status: 400 },);- const result = await handoffA2ALocalSession(sessionRef, objective);+ const result = await handoffA2ALocalSession(sessionRef, objective, msoCapabilityRuntime);void audit({action: "a2a.send",actor,@@ -57,6 +58,7 @@ export async function handleA2AMessageAction(sourceSessionRef,objective,title: typeof body.title === "string" ? body.title : undefined,+ capabilities: msoCapabilityRuntime,});void audit({action: "a2a.send",diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex a947b864..59511d5d 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -9,6 +9,7 @@ import { detectMcpToolProfile } from "@/lib/mcp/client-profile";import { supportedMcpProtocol } from "@/lib/mcp/protocol";import { visibleToolsForProfile } from "@/lib/mcp/tool-contract";import { mcpSessionHeaders, resolveMcpSession } from "@/lib/mcp/session-context";+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -89,7 +90,7 @@ export async function POST(req: Request) {void touchToken(token.hash).catch(() => {});const actor = `mcp:${token.hash.slice(0, 16)}`;- const agentContext = { principal, ...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}), toolProfile };+ const agentContext = { principal, ...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}), toolProfile, capabilities: msoCapabilityRuntime };const result = await dispatch(rpc, effectiveScope, actor, agentContext);return Response.json(result, { status: 200, headers });}diff --git a/architecture.boundaries.json b/architecture.boundaries.jsonnew file mode 100644index 00000000..d827fb6a--- /dev/null+++ b/architecture.boundaries.json@@ -0,0 +1,17 @@+{+ "schemaVersion": 1,+ "ratchets": {+ "structuralCycles": 46,+ "crossDomainCycles": 21,+ "filesOver220": 55,+ "filesOver500": 2,+ "serverFrontendImports": 6,+ "appshellSelfBarrelImports": 23,+ "nonMcpMcpImports": 0,+ "crossProtocolCycles": 0+ },+ "notes": {+ "policy": "Ratchets may only stay equal or decrease. Raise a baseline only with an explicit architecture decision.",+ "goal": "Zero value cycles, zero cross-domain protocol cycles, one-way server/frontend contracts, and no internal AppShell self-barrel imports."+ }+}diff --git a/lib/a2a/credentials-inbound.ts b/lib/a2a/credentials-inbound.tsindex b30e9b45..796961ec 100644--- a/lib/a2a/credentials-inbound.ts+++ b/lib/a2a/credentials-inbound.ts@@ -7,7 +7,7 @@ import {import os from "node:os";import path from "node:path";import { withSecurityStoreLock } from "@/lib/security-store-lock";-import { parseScope, type Scope } from "@/lib/mcp/scope";+import { parseScope, type Scope } from "@/lib/capabilities/scope";import type { A2AInboundTokenSummary } from "./types";import {cleanA2ACredentialId,diff --git a/lib/a2a/inbound-agent.test.ts b/lib/a2a/inbound-agent.test.tsindex 6b686351..d30c1867 100644--- a/lib/a2a/inbound-agent.test.ts+++ b/lib/a2a/inbound-agent.test.ts@@ -7,36 +7,21 @@ const mocks = vi.hoisted(() => ({model: "test",})),stream: vi.fn(),- dispatch: vi.fn(),+ invoke: vi.fn(),}));vi.mock("@/lib/ai/selected-model-stream", () => ({prepareSelectedModel: mocks.prepare,streamPreparedSelectedModel: mocks.stream,}));-vi.mock("@/lib/mcp/dispatch", () => ({ dispatch: mocks.dispatch }));-vi.mock("@/lib/mcp/tools", () => ({- TOOLS: [- {- name: "sys_stats",- description: "bounded read",- scope: "read",- inputSchema: { type: "object", properties: {} },- },- {- name: "agent_memory_read",- description: "owner memory",- scope: "read",- inputSchema: { type: "object", properties: {} },- },- {- name: "exec_run",- description: "host exec",- scope: "exec",- inputSchema: { type: "object", properties: {} },- },- ],-}));+const capabilities = {+ list: vi.fn(() => [+ { name: "sys_stats", description: "bounded read", scope: "read" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "agent_memory_read", description: "owner memory", scope: "read" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "exec_run", description: "host exec", scope: "exec" as const, inputSchema: { type: "object" as const, properties: {} } },+ ]),+ invoke: mocks.invoke,+};const { runInboundA2AAgent } = await import("./inbound-agent");@@ -54,9 +39,7 @@ describe("inbound A2A model boundary", () => {emit("delta", "done");}});- mocks.dispatch.mockResolvedValue({- result: { content: [{ type: "text", text: "ok" }] },- });+ mocks.invoke.mockResolvedValue({ content: [{ type: "text", text: "ok" }] });const result = await runInboundA2AAgent({prompt: "inspect",@@ -64,17 +47,17 @@ describe("inbound A2A model boundary", () => {principal: "a2a:in-peer",taskId: "task-123",signal: new AbortController().signal,+ capabilities,});expect(result.text).toBe("done");- expect(mocks.dispatch).toHaveBeenCalledWith(- expect.objectContaining({- method: "tools/call",- params: { name: "sys_stats", arguments: {} },- }),- "read",- "a2a:in-peer",- { principal: "a2a:in-peer", sessionId: "task-123" },- );+ expect(mocks.invoke).toHaveBeenCalledWith({+ name: "sys_stats",+ args: {},+ scope: "read",+ actor: "a2a:in-peer",+ principal: "a2a:in-peer",+ sessionId: "task-123",+ });});});diff --git a/lib/a2a/inbound-agent.ts b/lib/a2a/inbound-agent.tsindex 8648b2b9..375e1284 100644--- a/lib/a2a/inbound-agent.ts+++ b/lib/a2a/inbound-agent.ts@@ -1,6 +1,5 @@-import { allows, type Scope } from "@/lib/mcp/scope";-import { dispatch } from "@/lib/mcp/dispatch";-import { TOOLS } from "@/lib/mcp/tools";+import { allows, type Scope } from "@/lib/capabilities/scope";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import {prepareSelectedModel,streamPreparedSelectedModel,@@ -90,8 +89,8 @@ function sessionHistory(session?: AgentSession): OaMsg[] {return out;}-function modelTools(scope: Scope): OaTool[] {- return TOOLS.filter(+function modelTools(runtime: CapabilityRuntime, scope: Scope): OaTool[] {+ return runtime.list(scope).filter((tool) => allows(scope, tool.scope) && !EXTERNAL_TOOL_DENY.has(tool.name),).map((tool) => ({name: tool.name,@@ -108,25 +107,16 @@ function bounded(value: string, max = MAX_RESULT_BYTES): string {return `${out}\n…[truncated by MSO A2A result budget]`;}-function toolResultText(rpc: Record<string, unknown>): {+function toolResultText(result: Awaited<ReturnType<CapabilityRuntime["invoke"]>>): {content: string;isError: boolean;} {- if (rpc.error)- return {- content: bounded(`error: ${JSON.stringify(rpc.error)}`),- isError: true,- };- const result = (rpc.result ?? {}) as {- content?: Array<{ type?: string; text?: string }>;- isError?: boolean;- };- const text = (result.content ?? [])- .filter((row) => row.type === "text")- .map((row) => row.text ?? "")+ const text = result.content+ .filter((row): row is Extract<(typeof result.content)[number], { type: "text" }> => row.type === "text")+ .map((row) => row.text).join("\n");return {- content: bounded(text || JSON.stringify(result.content ?? [])),+ content: bounded(text || JSON.stringify(result.content)),isError: Boolean(result.isError),};}@@ -139,13 +129,14 @@ export async function runInboundA2AAgent(input: {session?: AgentSession;signal: AbortSignal;onDelta?: (text: string) => void | Promise<void>;+ capabilities: CapabilityRuntime;}): Promise<{text: string;rounds: number;toolCalls: Array<{ name: string; ok: boolean }>;}> {const prepared = await prepareSelectedModel();- const tools = modelTools(input.scope);+ const tools = modelTools(input.capabilities, input.scope);const messages: OaMsg[] = [...sessionHistory(input.session),{ role: "user", text: input.prompt },@@ -181,12 +172,8 @@ export async function runInboundA2AAgent(input: {const results: { id: string; content: string; isError?: boolean }[] = [];for (const call of uses) {- const tool = TOOLS.find((entry) => entry.name === call.name);- if (- !tool ||- EXTERNAL_TOOL_DENY.has(call.name) ||- !allows(input.scope, tool.scope)- ) {+ const tool = input.capabilities.list(input.scope).find((entry) => entry.name === call.name);+ if (!tool || EXTERNAL_TOOL_DENY.has(call.name) || !allows(input.scope, tool.scope)) {results.push({id: call.id,content: "error: tool is unavailable to this A2A credential",@@ -195,17 +182,15 @@ export async function runInboundA2AAgent(input: {toolCalls.push({ name: call.name, ok: false });continue;}- const rpc = await dispatch(- {- id: call.id,- method: "tools/call",- params: { name: call.name, arguments: call.input ?? {} },- },- input.scope,- input.principal,- { principal: input.principal, sessionId: input.taskId },- );- const result = toolResultText(rpc);+ const invoked = await input.capabilities.invoke({+ name: call.name,+ args: call.input ?? {},+ scope: input.scope,+ actor: input.principal,+ principal: input.principal,+ sessionId: input.taskId,+ });+ const result = toolResultText(invoked);results.push({id: call.id,content: result.content,diff --git a/lib/a2a/local-session.test.ts b/lib/a2a/local-session.test.tsindex 43d2485f..1b11ad99 100644--- a/lib/a2a/local-session.test.ts+++ b/lib/a2a/local-session.test.ts@@ -24,6 +24,7 @@ const {} = await import("./local-session");afterAll(() => rmSync(root, { recursive: true, force: true }));+const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };async function bece() {return createAgentSession("cli:owner", "cli", {@@ -72,6 +73,7 @@ describe("same-host A2A durable-session agents", () => {const result = await handoffA2ALocalSession(session.id,"review local change",+ capabilities,);expect(result.task.status.state).toBe("TASK_STATE_COMPLETED");expect(result.task.artifacts[0].parts[0].text).toBe("bece result");@@ -84,10 +86,10 @@ describe("same-host A2A durable-session agents", () => {expect(principal).toBe(`a2a:local:${session.id}`);return { text: "offline worker result", rounds: 1, toolCalls: [] };});- const result = await handoffOwnerLocalSession("cli:owner", session.id, "answer this");+ const result = await handoffOwnerLocalSession("cli:owner", session.id, "answer this", capabilities);expect(result.session.id).toBe(session.id);expect(result.task.artifacts[0].parts[0].text).toBe("offline worker result");- await expect(handoffOwnerLocalSession("cli:owner", session.id, "answer this", session.id)).rejects.toThrow(/same session/);+ await expect(handoffOwnerLocalSession("cli:owner", session.id, "answer this", capabilities, session.id)).rejects.toThrow(/same session/);});it("spawns a durable child agent that inherits context/cwd but has its own id", async () => {@@ -105,6 +107,7 @@ describe("same-host A2A durable-session agents", () => {sourceSessionRef: source.id,objective: "independent review",title: "reviewer",+ capabilities,});expect(result.session.title).toBe("reviewer");expect(result.session.parentSessionId).toBe(source.id);diff --git a/lib/a2a/local-session.ts b/lib/a2a/local-session.tsindex 3be38259..908c5dd5 100644--- a/lib/a2a/local-session.ts+++ b/lib/a2a/local-session.ts@@ -9,6 +9,7 @@ import {resolveAgentSessionRef,} from "@/lib/agent/session-query";import type { AgentSession } from "@/lib/agent/session-types";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import { a2aLoopbackOrigin } from "./network";import { executeInboundA2ATask } from "./server-execution";import { createA2ATask, taskPublicView } from "./tasks";@@ -42,7 +43,7 @@ export async function resolveA2ALocalSession(return resolveAgentSessionOwnerRef(ref);}-async function runLocalSessionTask(session: AgentSession, objective: string) {+async function runLocalSessionTask(session: AgentSession, objective: string, capabilities: CapabilityRuntime) {const prompt = String(objective || "").trim();if (!prompt) throw new Error("A2A local objective is required");const principal = `a2a:local:${session.id}`;@@ -61,26 +62,27 @@ async function runLocalSessionTask(session: AgentSession, objective: string) {LOCAL_PROFILE,prompt,session,+ capabilities,);return taskPublicView(completed);}-export async function handoffA2ALocalSession(ref: string, objective: string) {+export async function handoffA2ALocalSession(ref: string, objective: string, capabilities: CapabilityRuntime) {const session = await resolveA2ALocalSession(ref);return {session: agentSessionSummary(session),- task: await runLocalSessionTask(session, objective),+ task: await runLocalSessionTask(session, objective, capabilities),};}/** Execute against a same-owner durable session without requiring its terminal* process to be present. This is a fresh bounded agent run, never a TTY wake. */-export async function handoffOwnerLocalSession(principal: string, ref: string, objective: string, currentSessionId?: string) {+export async function handoffOwnerLocalSession(principal: string, ref: string, objective: string, capabilities: CapabilityRuntime, currentSessionId?: string) {const session = await resolveAgentSessionRef(principal, ref);if (session.id === currentSessionId) throw new Error("cannot run a local agent request against the same session");return {session: agentSessionSummary(session),- task: await runLocalSessionTask(session, objective),+ task: await runLocalSessionTask(session, objective, capabilities),};}@@ -89,6 +91,7 @@ export async function spawnA2ALocalSubagent(input: {sourceSessionRef: string;objective: string;title?: string;+ capabilities: CapabilityRuntime;}) {const source = await resolveA2ALocalSession(input.sourceSessionRef);const title =@@ -106,6 +109,6 @@ export async function spawnA2ALocalSubagent(input: {});return {session: agentSessionSummary(child),- task: await runLocalSessionTask(child, input.objective),+ task: await runLocalSessionTask(child, input.objective, input.capabilities),};}diff --git a/lib/a2a/server-execution.ts b/lib/a2a/server-execution.tsindex 3250c8c1..324a0254 100644--- a/lib/a2a/server-execution.ts+++ b/lib/a2a/server-execution.ts@@ -1,5 +1,6 @@import { audit } from "@/lib/host";import type { AgentSession } from "@/lib/agent/session-types";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import type { A2AAuthenticatedProfile } from "./server-protocol";import { runInboundA2AAgent } from "./inbound-agent";import {@@ -22,7 +23,8 @@ export async function executeInboundA2ATask(task: A2ATaskRecord,profile: A2AAuthenticatedProfile,prompt: string,- session?: AgentSession,+ session: AgentSession | undefined,+ capabilities: CapabilityRuntime,): Promise<A2ATaskRecord> {const principal = task.principal;const controller = new AbortController();@@ -48,6 +50,7 @@ export async function executeInboundA2ATask(taskId: task.id,session,signal: controller.signal,+ capabilities,onDelta(chunk) {if (pendingDelta) {publishA2AEvent(@@ -108,6 +111,7 @@ export function a2aSseResponse(id: A2ARpcId,task: A2ATaskRecord,profile: A2AAuthenticatedProfile,+ capabilities: CapabilityRuntime,prompt?: string,session?: AgentSession,): Response {@@ -129,7 +133,7 @@ export function a2aSseResponse(emit({ task: taskPublicView(task) });unsubscribe = subscribeA2AEvent(task.id, emit);if (prompt !== undefined) {- void executeInboundA2ATask(task, profile, prompt, session).finally(+ void executeInboundA2ATask(task, profile, prompt, session, capabilities).finally(() => {unsubscribe();if (!closed) {diff --git a/lib/a2a/server.test.ts b/lib/a2a/server.test.tsindex d051eb12..5c447313 100644--- a/lib/a2a/server.test.ts+++ b/lib/a2a/server.test.ts@@ -17,6 +17,8 @@ const { createA2AInboundToken } = await import("./credentials");const { createA2ATask } = await import("./tasks");const { handleA2ARequest } = await import("./server");const { inboundAgentCard } = await import("./inbound-config");+const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };+const handle = (req: Request) => handleA2ARequest(req, capabilities);afterAll(() => rmSync(root, { recursive: true, force: true }));@@ -45,7 +47,7 @@ describe("authenticated inbound A2A server", () => {});it("requires HTTP Bearer auth before A2A method dispatch", async () => {- const response = await handleA2ARequest(+ const response = await handle(rpc(null, { jsonrpc: "2.0", id: 1, method: "ListTasks", params: {} }),);expect(response.status).toBe(401);@@ -60,7 +62,7 @@ describe("authenticated inbound A2A server", () => {expect(principal).toBe(`a2a:${profile.id}`);return { text: "done", rounds: 1, toolCalls: [] };});- const response = await handleA2ARequest(+ const response = await handle(rpc(token, {jsonrpc: "2.0",id: "send-1",@@ -89,7 +91,7 @@ describe("authenticated inbound A2A server", () => {toolCalls: [],});const sent = await (- await handleA2ARequest(+ await handle(rpc(first.token, {jsonrpc: "2.0",id: 2,@@ -106,7 +108,7 @@ describe("authenticated inbound A2A server", () => {).json();const taskId = sent.result.task.id;const hidden = await (- await handleA2ARequest(+ await handle(rpc(second.token, {jsonrpc: "2.0",id: 3,@@ -125,7 +127,7 @@ describe("authenticated inbound A2A server", () => {onDelta?.("lo");return { text: "hello", rounds: 1, toolCalls: [] };});- const response = await handleA2ARequest(+ const response = await handle(rpc(token, {jsonrpc: "2.0",id: "stream-1",@@ -173,7 +175,7 @@ describe("authenticated inbound A2A server", () => {});}const first = await (- await handleA2ARequest(+ await handle(rpc(token, {jsonrpc: "2.0",id: "page-1",@@ -187,7 +189,7 @@ describe("authenticated inbound A2A server", () => {expect(first.result.nextPageToken).toBeTruthy();const second = await (- await handleA2ARequest(+ await handle(rpc(token, {jsonrpc: "2.0",id: "page-2",@@ -200,7 +202,7 @@ describe("authenticated inbound A2A server", () => {expect(second.result.nextPageToken).toBe("");const invalid = await (- await handleA2ARequest(+ await handle(rpc(token, {jsonrpc: "2.0",id: "page-bad",diff --git a/lib/a2a/server.ts b/lib/a2a/server.tsindex 96d8b078..72b99c6a 100644--- a/lib/a2a/server.ts+++ b/lib/a2a/server.ts@@ -1,7 +1,8 @@import { audit, rateLimited } from "@/lib/host";-import { clientIp } from "@/lib/mcp/origin";+import { clientIp } from "@/lib/host/request-ip";import { resolveAgentSessionOwnerRef } from "@/lib/agent/session-query";import type { AgentSession } from "@/lib/agent/session-types";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import { a2aInboundOriginForRequest } from "./inbound-config";import {cancelA2AActiveTask,@@ -26,7 +27,7 @@ import {type A2ARpcBody,} from "./server-protocol";-export async function handleA2ARequest(req: Request): Promise<Response> {+export async function handleA2ARequest(req: Request, capabilities: CapabilityRuntime): Promise<Response> {if (!a2aInboundOriginForRequest(req.url))return a2aJson({ error: "not_found" }, 404);if (req.method !== "POST")@@ -82,9 +83,9 @@ export async function handleA2ARequest(req: Request): Promise<Response> {targetSession?.id,);if (method === "SendStreamingMessage")- return a2aSseResponse(id, task, profile, parsed.prompt, targetSession);+ return a2aSseResponse(id, task, profile, capabilities, parsed.prompt, targetSession);if (parsed.returnImmediately) {- void executeInboundA2ATask(task, profile, parsed.prompt, targetSession);+ void executeInboundA2ATask(task, profile, parsed.prompt, targetSession, capabilities);return a2aJson(a2aRpcOk(id, { task: taskPublicView(task) }));}const completed = await executeInboundA2ATask(@@ -92,6 +93,7 @@ export async function handleA2ARequest(req: Request): Promise<Response> {profile,parsed.prompt,targetSession,+ capabilities,);return a2aJson(a2aRpcOk(id, { task: taskPublicView(completed) }));}@@ -142,7 +144,7 @@ export async function handleA2ARequest(req: Request): Promise<Response> {(row) => row.id === taskId,);return full- ? a2aSseResponse(id, full, profile, undefined, targetSession)+ ? a2aSseResponse(id, full, profile, capabilities, undefined, targetSession): a2aJson(a2aRpcError(id, -32001, "Task not found"));}return a2aJson(a2aRpcError(id, -32601, "Method not found"));diff --git a/lib/a2a/task-store.ts b/lib/a2a/task-store.tsindex 169a658f..8abc2b01 100644--- a/lib/a2a/task-store.ts+++ b/lib/a2a/task-store.ts@@ -3,7 +3,7 @@ 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 type { Scope } from "@/lib/mcp/scope";+import type { Scope } from "@/lib/capabilities/scope";import { isA2ATaskActive } from "./task-active";import type { A2AMessage, A2ATaskRecord, A2ATaskState } from "./task-types";diff --git a/lib/a2a/task-types.ts b/lib/a2a/task-types.tsindex 63231e63..d92153cf 100644--- a/lib/a2a/task-types.ts+++ b/lib/a2a/task-types.ts@@ -1,4 +1,4 @@-import type { Scope } from "@/lib/mcp/scope";+import type { Scope } from "@/lib/capabilities/scope";export type A2ATaskState =| "TASK_STATE_SUBMITTED"diff --git a/lib/a2a/types.ts b/lib/a2a/types.tsindex 1fd46014..b752e2c5 100644--- a/lib/a2a/types.ts+++ b/lib/a2a/types.ts@@ -1,4 +1,4 @@-import type { Scope } from "@/lib/mcp/scope";+import type { Scope } from "@/lib/capabilities/scope";export type A2AStandardBinding = "JSONRPC" | "HTTP+JSON";diff --git a/lib/agent/subagent-runner.test.ts b/lib/agent/subagent-runner.test.tsindex 16e215e1..a3e0fae2 100644--- a/lib/agent/subagent-runner.test.ts+++ b/lib/agent/subagent-runner.test.ts@@ -9,16 +9,16 @@ vi.mock("@/lib/ai/selected-model-stream", () => ({prepareSelectedModel: vi.fn(async () => ({ kind: "openai", provider: "x", model: "x", resolved: {}, customProvider: false })),streamPreparedSelectedModel: stream,}));-vi.mock("@/lib/mcp/tools", () => ({- TOOLS: [- { name: "fs_read", description: "read", scope: "read", inputSchema: { type: "object", properties: {} } },- { name: "fs_write", description: "write", scope: "write", inputSchema: { type: "object", properties: {} } },- { name: "local_agent_message_send", description: "local", scope: "write", inputSchema: { type: "object", properties: {} } },- { name: "agent_subagent_run", description: "nested", scope: "exec", inputSchema: { type: "object", properties: {} } },- { name: "project_agent_run", description: "nested project wrapper", scope: "exec", inputSchema: { type: "object", properties: {} } },- ],-}));-vi.mock("@/lib/mcp/dispatch", () => ({ dispatch }));+const capabilities = {+ list: vi.fn(() => [+ { name: "fs_read", description: "read", scope: "read" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "fs_write", description: "write", scope: "write" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "local_agent_message_send", description: "local", scope: "write" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "agent_subagent_run", description: "nested", scope: "exec" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "project_agent_run", description: "nested project wrapper", scope: "exec" as const, inputSchema: { type: "object" as const, properties: {} } },+ ]),+ invoke: dispatch,+};const { runSessionSubagent } = await import("./subagent-runner");@@ -32,21 +32,21 @@ describe("same-session subagent runner", () => {firstPayload = JSON.stringify({ system: opts.system, messages: opts.messages });opts.emit("tool_use", { id: "tool-1", name: "fs_read", input: {} });}).mockImplementationOnce(async ({ emit }) => emit("delta", "review complete"));- dispatch.mockResolvedValue({ result: { content: [{ type: "text", text: "file data" }] } });- const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "review auth" });+ dispatch.mockResolvedValue({ content: [{ type: "text", text: "file data" }] });+ const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "review auth", capabilities });expect(seenTools).toEqual(["fs_read"]);expect(result).toMatchObject({ status: "completed", text: "review complete", rounds: 2, maxScope: "read" });expect(result.toolCalls).toEqual([{ name: "fs_read", ok: true }]);expect(firstPayload).not.toContain("TOP SECRET");- expect(dispatch).toHaveBeenCalledWith(- expect.objectContaining({ method: "tools/call" }), "read", expect.stringContaining("#subagent_"), { principal: "mcp-client:x" },- );+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({+ name: "fs_read", scope: "read", actor: expect.stringContaining("#subagent_"), principal: "mcp-client:x",+ }));});it("never exposes local-agent or recursive subagent tools even with exec scope", async () => {let names: string[] = [];stream.mockImplementationOnce(async ({ tools, emit }) => { names = tools.map((tool: { name: string }) => tool.name); emit("delta", "done"); });- const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "inspect", maxScope: "exec" });+ const result = await runSessionSubagent({ principal: "mcp-client:x", parentSessionId: "session-a", objective: "inspect", maxScope: "exec", capabilities });expect(names).toContain("fs_read");expect(names).toContain("fs_write");expect(names).not.toContain("local_agent_message_send");diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.tsindex 5b533a14..086a1e18 100644--- a/lib/agent/subagent-runner.ts+++ b/lib/agent/subagent-runner.ts@@ -2,7 +2,8 @@ import { randomUUID } from "node:crypto";import { getAgentSession } from "./session-store";import { prepareSelectedModel, streamPreparedSelectedModel } from "@/lib/ai/selected-model-stream";import type { OaMsg, OaTool, OaToolUse } from "@/lib/ai/openai-stream";-import { allows, parseScope, type Scope } from "@/lib/mcp/scope";+import { allows, parseScope, type Scope } from "@/lib/capabilities/scope";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";const MAX_RESULT_BYTES = 64 * 1024;const DEFAULT_TURNS = 6;@@ -58,6 +59,7 @@ export async function runSessionSubagent(input: {maxTurns?: number;timeoutMs?: number;explicitContext?: string;+ capabilities: CapabilityRuntime;}) {const parent = await getAgentSession(input.principal, input.parentSessionId);if (!parent) throw new Error("parent MSO Agent session not found");@@ -69,8 +71,7 @@ export async function runSessionSubagent(input: {const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || DEFAULT_TURNS)));const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));const subagentId = `subagent_${randomUUID()}`;- const [{ TOOLS }, { dispatch }] = await Promise.all([import("@/lib/mcp/tools"), import("@/lib/mcp/dispatch")]);- const toolDefs = TOOLS.filter((tool) => allows(maxScope, tool.scope) && allowedTool(tool.name));+ const toolDefs = input.capabilities.list(maxScope).filter((tool) => allows(maxScope, tool.scope) && allowedTool(tool.name));const tools: OaTool[] = toolDefs.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.inputSchema }));const prepared = await prepareSelectedModel();const messages: OaMsg[] = [{ role: "user", text: objective }];@@ -102,13 +103,11 @@ export async function runSessionSubagent(input: {toolCalls.push({ name: call.name, ok: false });continue;}- const rpc = await dispatch(- { id: call.id, method: "tools/call", params: { name: call.name, arguments: call.input ?? {} } },- maxScope,- `${input.principal}#${subagentId}`,- { principal: input.principal },- );- const outcome = resultText(rpc);+ const invoked = await input.capabilities.invoke({+ name: call.name, args: call.input ?? {}, scope: maxScope,+ actor: `${input.principal}#${subagentId}`, principal: input.principal,+ });+ const outcome = resultText({ result: invoked });results.push({ id: call.id, content: outcome.content, ...(outcome.isError ? { isError: true } : {}) });toolCalls.push({ name: call.name, ok: !outcome.isError });}diff --git a/lib/capabilities/activity.ts b/lib/capabilities/activity.tsnew file mode 100644index 00000000..2960dcdc--- /dev/null+++ b/lib/capabilities/activity.ts@@ -0,0 +1,93 @@+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { randomUUID } from "crypto";++export type CapabilityActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited" | "invalid_args";++export interface CapabilityActivityEntry {+ id: string;+ ts: string;+ actor?: string | null;+ tool: string;+ state: CapabilityActivityState;+ scope?: string;+ workflowId?: string;+ workflowIntent?: string;+ workflowProject?: string;+ target?: string;+ durationMs?: number;+ detail?: string;+}++function activityPath(): string {+ const env = process.env.OS_MCP_ACTIVITY_LOG;+ if (env && env.trim()) return env.replace(/^~(?=$|\/)/, os.homedir());+ return path.join(os.homedir(), ".mso", "mcp-activity.log");+}++function trunc(v: string | undefined, max = 180): string | undefined {+ if (!v) return undefined;+ return v.length > max ? v.slice(0, max) + "…" : v;+}++function safeActivityText(value: string): string {+ return value+ .replace(/([?&](?:token|key|secret|password|code)=)[^&\s]+/gi, "$1[redacted]")+ .replace(/\b(password|token|secret|api[_-]?key)\s*[:=]\s*\S+/gi, "$1=[redacted]")+ .replace(/\b(?:bearer\s+)?(?:sk|pk|ghp|mso_mcp)_[a-z0-9_-]{8,}\b/gi, "[redacted]")+ .replace(/\b[a-f0-9]{48,}\b/gi, "[opaque-id]");+}++let chain: Promise<void> = Promise.resolve();++export function newActivityId(): string {+ return randomUUID();+}++export function activityTarget(args: Record<string, unknown>): string | undefined {+ // Never serialize fs_write.content or arbitrary payloads. Prefer the one field+ // that explains what the tool is acting on without leaking the body.+ for (const key of ["path", "id", "target", "query", "intent", "project", "from", "command", "on", "workflow_id"] as const) {+ const v = args[key];+ if (typeof v === "string" && v) return trunc(safeActivityText(v));+ if (typeof v === "boolean") return String(v);+ }+ return undefined;+}++export function recordCapabilityActivity(entry: Omit<CapabilityActivityEntry, "ts"> & { ts?: string }): Promise<void> {+ if (process.env.VITEST && !process.env.OS_MCP_ACTIVITY_LOG) return Promise.resolve();+ const line = JSON.stringify({+ ...entry,+ ts: entry.ts ?? new Date().toISOString(),+ workflowIntent: trunc(entry.workflowIntent ? safeActivityText(entry.workflowIntent) : undefined, 500),+ workflowProject: trunc(entry.workflowProject ? safeActivityText(entry.workflowProject) : undefined, 240),+ target: trunc(entry.target),+ detail: trunc(entry.detail, 220),+ }) + "\n";+ chain = chain.then(async () => {+ const file = activityPath();+ try {+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });+ await fs.appendFile(file, line, { mode: 0o600 });+ } catch (e) {+ console.error("[capability-activity] write failed:", e instanceof Error ? e.message : e);+ }+ });+ return chain;+}++export async function readCapabilityActivity(limit = 80): Promise<CapabilityActivityEntry[]> {+ const raw = await fs.readFile(activityPath(), "utf8").catch(() => "");+ return raw+ .split("\n")+ .filter(Boolean)+ .slice(-800)+ .map((line) => {+ try { return JSON.parse(line) as CapabilityActivityEntry; } catch { return null; }+ })+ .filter((v): v is CapabilityActivityEntry => Boolean(v?.id && v?.tool && v?.state))+ .slice(-Math.min(Math.max(limit, 1), 200))+ .reverse();+}diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.tsnew file mode 100644index 00000000..4afe3301--- /dev/null+++ b/lib/capabilities/actors.ts@@ -0,0 +1,9 @@+import type { CapabilityToolProfile } from "./tool";++export interface CapabilityAgentContext { principal?: string; sessionId?: string; toolProfile?: CapabilityToolProfile; }+export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {+ return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;+}+export function recipeActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {+ return context?.principal ?? actor;+}diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.tsnew file mode 100644index 00000000..4b4e6b9e--- /dev/null+++ b/lib/capabilities/execute.ts@@ -0,0 +1,140 @@+import { audit } from "@/lib/host";+import { maybeAutoTitleAgentSession } from "@/lib/agent/session-store";+import { touchLocalAgentPresence } from "@/lib/agent/local-agent-presence";+import { activeWorkflowForActor, recordWorkflowStep } from "@/lib/skills/memory";+import { allows, type Scope } from "./scope";+import type { CapabilityRuntime } from "./runtime";+import type { CapabilityTool } from "./tool";+import { activityTarget, newActivityId, recordCapabilityActivity } from "./activity";+import { recipeActor, workflowActor, type CapabilityAgentContext } from "./actors";+import { capabilityRateLimited } from "./rate-limit";+import { flowFields, recordAgentEvent, sessionDetail, workflowFromResult } from "./execution-support";++export interface CapabilityExecutionContext extends CapabilityAgentContext {+ capabilities?: CapabilityRuntime;+}++export type CapabilityExecutionResult =+ | { kind: "protocol_error"; code: number; message: string }+ | { kind: "error"; message: string }+ | { kind: "success"; result: unknown };++/**+ * One execution authority for every adapter. Scope, required arguments, workflow+ * correlation, rate limiting, audit/activity and session telemetry are enforced+ * here once; transports only serialize the returned outcome.+ */+export async function executeCapabilityCall(input: {+ tool: CapabilityTool;+ args: Record<string, unknown>;+ scope: Scope;+ actor?: string;+ context?: CapabilityExecutionContext;+}): Promise<CapabilityExecutionResult> {+ const { tool, args, scope, actor, context } = input;+ const name = tool.name;+ const presence = context?.principal?.startsWith("mcp-") && context.sessionId+ ? { principal: context.principal, sessionId: context.sessionId, instanceId: `mcp:${context.sessionId}` }+ : null;+ if (presence)+ await touchLocalAgentPresence(presence.principal, presence.sessionId, "ready", presence.instanceId).catch(() => undefined);++ 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 recordCapabilityActivity({ 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 { kind: "error", message: `error: this token holds scope "${scope}"; ${name} needs "${tool.scope}".` };+ }++ for (const key of tool.inputSchema.required ?? []) {+ if (args[key] != null) continue;+ const activityId = newActivityId(), detail = `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`;+ if (!workflowProbe) {+ void recordCapabilityActivity({ id: activityId, actor, tool: name, state: "invalid_args", scope, ...initialFlow, target, detail });+ await recordWorkflowStep(flowActor, activeWorkflow?.id, { id: activityId, tool: name, state: "invalid_args", target, args, ts: new Date().toISOString() });+ await recordAgentEvent(context, name, "invalid_args", args, activeWorkflow?.id, target);+ }+ return { kind: "protocol_error", code: -32602, message: detail };+ }++ 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 recordCapabilityActivity({ id: activityId, actor, tool: name, state: "failed", scope, target, detail: message });+ await recordAgentEvent(context, name, "failed", args, undefined, target);+ return { kind: "error", message: `error: ${message}. Use this conversation's exact workflow_id.` };+ }++ if (capabilityRateLimited(tool, args, actor)) {+ void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "rate limited" });+ const activityId = newActivityId();+ if (!workflowProbe) {+ void recordCapabilityActivity({ 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 { kind: "error", message: `error: ${name} is rate limited.` };+ }++ const trail = tool.audit, auditTarget = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;+ const activityId = newActivityId(), startedAt = Date.now();+ if (!workflowProbe) void recordCapabilityActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });+ try {+ if (presence)+ await touchLocalAgentPresence(+ presence.principal,+ presence.sessionId,+ name === "local_agent_inbox" ? "idle" : "busy",+ presence.instanceId,+ ).catch(() => undefined);+ const titleHint = sessionDetail(name, args, target);+ if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status", "agent_subagent_run"].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,+ capabilities: context?.capabilities,+ toolProfile: context?.toolProfile,+ });+ 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 recordCapabilityActivity({ 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);+ }+ if (presence)+ await touchLocalAgentPresence(presence.principal, presence.sessionId, "idle", presence.instanceId).catch(() => undefined);+ return { kind: "success", 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 recordCapabilityActivity({ 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);+ }+ if (presence)+ await touchLocalAgentPresence(presence.principal, presence.sessionId, "idle", presence.instanceId).catch(() => undefined);+ return { kind: "error", message: "error: " + message.slice(0, 500) };+ }+}diff --git a/lib/capabilities/execution-support.ts b/lib/capabilities/execution-support.tsnew file mode 100644index 00000000..977e0d35--- /dev/null+++ b/lib/capabilities/execution-support.ts@@ -0,0 +1,42 @@+import { appendAgentSessionEvent } from "@/lib/agent/session-store";+import type { ActiveWorkflow } from "@/lib/skills/memory";+import type { CapabilityAgentContext } from "./actors";++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: CapabilityAgentContext | 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;+}+diff --git a/lib/capabilities/rate-limit.ts b/lib/capabilities/rate-limit.tsnew file mode 100644index 00000000..b8a37dd3--- /dev/null+++ b/lib/capabilities/rate-limit.ts@@ -0,0 +1,12 @@+import { rateLimited } from "@/lib/host/rate-limit";+import type { CapabilityTool } from "./tool";++export function capabilityRateLimited(+ tool: CapabilityTool,+ args: Record<string, unknown>,+ actor?: string,+): boolean {+ if (!tool.limit) return false;+ const suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");+ return rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs);+}diff --git a/lib/capabilities/result-budget.ts b/lib/capabilities/result-budget.tsnew file mode 100644index 00000000..68d5a8ad--- /dev/null+++ b/lib/capabilities/result-budget.ts@@ -0,0 +1,60 @@+export const DEFAULT_CAPABILITY_RESULT_BYTES = 32 * 1024;+export const MAX_CAPABILITY_RESULT_BYTES = 128 * 1024;++function clampBudget(value?: number): number {+ if (!Number.isFinite(value)) return DEFAULT_CAPABILITY_RESULT_BYTES;+ return Math.max(4 * 1024, Math.min(MAX_CAPABILITY_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 CapabilityResultBudget = {+ 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?: CapabilityResultBudget): string {+ let raw: string;+ try {+ const encoded = typeof result === "string" ? result : JSON.stringify(result);+ raw = encoded === undefined ? "null" : encoded;+ } 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/capabilities/runtime.ts b/lib/capabilities/runtime.tsnew file mode 100644index 00000000..2330fdb2--- /dev/null+++ b/lib/capabilities/runtime.ts@@ -0,0 +1,31 @@+import type { Scope } from "./scope";++export type CapabilityContent =+ | { type: "text"; text: string }+ | { type: "image"; data: string; mimeType: string };++export interface CapabilityDescriptor {+ name: string;+ description: string;+ scope: Scope;+ inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };+}++export interface CapabilityInvocation {+ name: string;+ args?: Record<string, unknown>;+ scope: Scope;+ actor?: string;+ principal?: string;+ sessionId?: string;+}++export interface CapabilityInvocationResult {+ content: CapabilityContent[];+ isError?: boolean;+}++export interface CapabilityRuntime {+ list(scope: Scope): CapabilityDescriptor[];+ invoke(input: CapabilityInvocation): Promise<CapabilityInvocationResult>;+}diff --git a/lib/capabilities/scope.ts b/lib/capabilities/scope.tsnew file mode 100644index 00000000..47041bda--- /dev/null+++ b/lib/capabilities/scope.ts@@ -0,0 +1,19 @@+/** Transport-neutral authority tiers shared by MCP, A2A and internal agent delegation. */+export const SCOPES = ["read", "write", "exec"] as const;+export type Scope = (typeof SCOPES)[number];++const RANK: Record<Scope, number> = { read: 0, write: 1, exec: 2 };++export function scopeRank(scope: Scope): number { return RANK[scope]; }++export function parseScope(raw: string | undefined | null): Scope {+ const asked = String(raw ?? "")+ .split(/[\s,]+/)+ .filter((value): value is Scope => (SCOPES as readonly string[]).includes(value));+ if (asked.length === 0) return "read";+ return asked.reduce((a, b) => (RANK[b] > RANK[a] ? b : a));+}++export function allows(held: Scope, needed: Scope): boolean {+ return RANK[held] >= RANK[needed];+}diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.tsnew file mode 100644index 00000000..3c2d7ee7--- /dev/null+++ b/lib/capabilities/tool.ts@@ -0,0 +1,81 @@+import type { AuditAction } from "@/lib/contracts/audit";+import type { CapabilityRuntime } from "./runtime";+import type { Scope } from "./scope";++export type CapabilityToolProfile = "full" | "chatgpt";++export type CapabilityContent =+ | { type: "text"; text: string }+ | { type: "image"; data: string; mimeType: string };++export interface CapabilityDirectResult {+ __mcpDirect: true;+ content: CapabilityContent[];+ isError?: boolean;+ /** Optional safe structured projection for transports that advertise an output schema.+ * Never put binary/base64 payloads or secrets here. */+ structuredContent?: Record<string, unknown>;+}++/** Compatibility marker stays __mcpDirect until the public MCP result contract is versioned. */+export function capabilityDirect(+ content: CapabilityContent[],+ isError = false,+ structuredContent?: Record<string, unknown>,+): CapabilityDirectResult {+ return { __mcpDirect: true, content, ...(isError ? { isError: true } : {}), ...(structuredContent ? { structuredContent } : {}) };+}++export function isCapabilityDirectResult(value: unknown): value is CapabilityDirectResult {+ return Boolean(value && typeof value === "object" && (value as CapabilityDirectResult).__mcpDirect === true);+}++export interface CapabilityRunContext {+ actor?: string;+ principal?: string;+ sessionId?: string;+ scope: Scope;+ workflowId?: string;+ workflowActor?: string;+ recipeActor?: string;+ capabilities?: CapabilityRuntime;+ toolProfile?: CapabilityToolProfile;+}++/**+ * Transport-neutral executable capability. MCP-specific metadata is kept as an+ * optional extension because MCP is one adapter over this catalog, not its owner.+ */+export interface CapabilityTool {+ name: string;+ title?: string;+ description: string;+ chatgptDescription?: string;+ scope: Scope;+ inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };+ outputSchema?: Record<string, unknown>;+ toStructuredContent?: (result: unknown) => Record<string, unknown> | undefined;+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean; openWorldHint?: boolean; idempotentHint?: boolean };+ securitySchemes?: Array<{ type: "oauth2"; scopes: string[] } | { type: "noauth" }>;+ meta?: Record<string, unknown>;+ run: (args: Record<string, unknown>, context: CapabilityRunContext) => Promise<unknown>;+ audit?: {+ action: AuditAction;+ targetArg?: string;+ outcome?: (result: unknown) => { ok: boolean; action?: AuditAction; detail?: string };+ };+ result?: { maxTextBytes?: number; overflowHint?: string };+ limit?: { max: number; windowMs: number; keyArg?: string; key: string };+}++export const str = (args: Record<string, unknown>, key: string): string => {+ const value = args[key];+ if (typeof value !== "string" || !value) throw new Error(`${key} must be a non-empty string`);+ return value;+};+export const opt = (args: Record<string, unknown>, key: string): string | undefined =>+ typeof args[key] === "string" && args[key] ? (args[key] as string) : undefined;+export const S = (properties: Record<string, unknown>, required?: string[]) =>+ ({ type: "object" as const, properties, ...(required ? { required } : {}) });+export const PATH_P = { path: { type: "string", description: "Absolute path on the VPS, or ~/… for the owner's home." } };+export const READ_ONLY = { readOnlyHint: true, idempotentHint: true };diff --git a/lib/contracts/audit.ts b/lib/contracts/audit.tsnew file mode 100644index 00000000..21afa577--- /dev/null+++ b/lib/contracts/audit.ts@@ -0,0 +1,49 @@+// Shared forensic action contract; persistence lives in lib/host/audit.+export type AuditAction =+ | "exec.run"+ | "exec.blocked"+ | "exec.job.start"+ | "exec.job.cancel"+ | "term.open"+ | "term.close"+ | "fs.write"+ | "fs.delete"+ | "fs.move"+ | "fs.copy"+ | "fs.mkdir"+ | "fs.upload"+ | "fs.zip"+ | "sys.cleanup"+ | "sys.service"+ /** The cockpit replacing its own code (Settings → About, or `mso update run`). */+ | "sys.update"+ | "managed-app.action"+ | "infra.write"+ | "camoufox.power"+ | "workflow.start"+ | "workflow.cancel"+ | "workflow.finish"+ | "agent.session"+ | "agent.message"+ | "agent.subagent"+ | "agent.memory"+ | "tool.forge.propose"+ | "tool.forge.evaluate"+ | "tool.forge.promote"+ | "a2a.registry"+ | "a2a.credential"+ | "a2a.inbound"+ | "a2a.task"+ | "a2a.send"+ | "a2a.cancel"+ /** An MCP token asked for a tool above its scope. Not an error — it is the+ * signal that matters: a `read` connector repeatedly reaching for `exec_run`+ * is what a prompt-injected model looks like from the outside. */+ | "mcp.denied"+ | "auth.login"+ | "auth.pending"+ | "auth.denied"+ | "auth.ratelimited"+ | "auth.logout"+ | "auth.device"+ | "framework.error";diff --git a/lib/forge/evaluate.ts b/lib/forge/evaluate.tsindex 28f2bab2..3f54d261 100644--- a/lib/forge/evaluate.ts+++ b/lib/forge/evaluate.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";import { promises as fs } from "node:fs";import path from "node:path";-import type { Scope } from "@/lib/mcp/scope";+import type { Scope } from "@/lib/capabilities/scope";import { runForgeFixture, validateForgeCommand } from "./sandbox";import type { ForgeCandidate, ForgeCheck, ForgeEvaluation, ForgeFixture, ForgeFunctionSpec } from "./types";diff --git a/lib/forge/types.ts b/lib/forge/types.tsindex e527b4f7..d76187d5 100644--- a/lib/forge/types.ts+++ b/lib/forge/types.ts@@ -1,4 +1,4 @@-import type { Scope } from "@/lib/mcp/scope";+import type { Scope } from "@/lib/capabilities/scope";import type { WorkflowQuality, WorkflowStep } from "@/lib/skills/memory";export const FORGE_VERSION = 1 as const;diff --git a/lib/host/audit.ts b/lib/host/audit.tsindex dcfc92e6..ec82f862 100644--- a/lib/host/audit.ts+++ b/lib/host/audit.ts@@ -9,54 +9,8 @@ import { promises as fs } from "fs";import os from "os";import path from "path";-export type AuditAction =- | "exec.run"- | "exec.blocked"- | "exec.job.start"- | "exec.job.cancel"- | "term.open"- | "term.close"- | "fs.write"- | "fs.delete"- | "fs.move"- | "fs.copy"- | "fs.mkdir"- | "fs.upload"- | "fs.zip"- | "sys.cleanup"- | "sys.service"- /** The cockpit replacing its own code (Settings → About, or `mso update run`). */- | "sys.update"- | "managed-app.action"- | "infra.write"- | "camoufox.power"- | "workflow.start"- | "workflow.cancel"- | "workflow.finish"- | "agent.session"- | "agent.message"- | "agent.subagent"- | "agent.memory"- | "tool.forge.propose"- | "tool.forge.evaluate"- | "tool.forge.promote"- | "a2a.registry"- | "a2a.credential"- | "a2a.inbound"- | "a2a.task"- | "a2a.send"- | "a2a.cancel"- /** An MCP token asked for a tool above its scope. Not an error — it is the- * signal that matters: a `read` connector repeatedly reaching for `exec_run`- * is what a prompt-injected model looks like from the outside. */- | "mcp.denied"- | "auth.login"- | "auth.pending"- | "auth.denied"- | "auth.ratelimited"- | "auth.logout"- | "auth.device"- | "framework.error";+import type { AuditAction } from "@/lib/contracts/audit";+export type { AuditAction } from "@/lib/contracts/audit";export interface AuditEntry {action: AuditAction;diff --git a/lib/host/request-ip.ts b/lib/host/request-ip.tsnew file mode 100644index 00000000..b50a0c04--- /dev/null+++ b/lib/host/request-ip.ts@@ -0,0 +1,8 @@+/** Best-effort client IP for pre-auth rate limiting only. Never authorization. */+export function clientIp(req: Request): string {+ return (+ req.headers.get("x-forwarded-for")?.split(",")[0].trim() ||+ req.headers.get("x-real-ip")?.trim() ||+ "unknown"+ );+}diff --git a/lib/mcp/activity.ts b/lib/mcp/activity.tsindex 0d859fa1..b9a68f00 100644--- a/lib/mcp/activity.ts+++ b/lib/mcp/activity.ts@@ -1,93 +1,2 @@-import { promises as fs } from "fs";-import os from "os";-import path from "path";-import { randomUUID } from "crypto";--export type McpActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited" | "invalid_args";--export interface McpActivityEntry {- id: string;- ts: string;- actor?: string | null;- tool: string;- state: McpActivityState;- scope?: string;- workflowId?: string;- workflowIntent?: string;- workflowProject?: string;- target?: string;- durationMs?: number;- detail?: string;-}--function activityPath(): string {- const env = process.env.OS_MCP_ACTIVITY_LOG;- if (env && env.trim()) return env.replace(/^~(?=$|\/)/, os.homedir());- return path.join(os.homedir(), ".mso", "mcp-activity.log");-}--function trunc(v: string | undefined, max = 180): string | undefined {- if (!v) return undefined;- return v.length > max ? v.slice(0, max) + "…" : v;-}--function safeActivityText(value: string): string {- return value- .replace(/([?&](?:token|key|secret|password|code)=)[^&\s]+/gi, "$1[redacted]")- .replace(/\b(password|token|secret|api[_-]?key)\s*[:=]\s*\S+/gi, "$1=[redacted]")- .replace(/\b(?:bearer\s+)?(?:sk|pk|ghp|mso_mcp)_[a-z0-9_-]{8,}\b/gi, "[redacted]")- .replace(/\b[a-f0-9]{48,}\b/gi, "[opaque-id]");-}--let chain: Promise<void> = Promise.resolve();--export function newActivityId(): string {- return randomUUID();-}--export function activityTarget(args: Record<string, unknown>): string | undefined {- // Never serialize fs_write.content or arbitrary payloads. Prefer the one field- // that explains what the tool is acting on without leaking the body.- for (const key of ["path", "id", "target", "query", "intent", "project", "from", "command", "on", "workflow_id"] as const) {- const v = args[key];- if (typeof v === "string" && v) return trunc(safeActivityText(v));- if (typeof v === "boolean") return String(v);- }- return undefined;-}--export function recordMcpActivity(entry: Omit<McpActivityEntry, "ts"> & { ts?: string }): Promise<void> {- if (process.env.VITEST && !process.env.OS_MCP_ACTIVITY_LOG) return Promise.resolve();- const line = JSON.stringify({- ...entry,- ts: entry.ts ?? new Date().toISOString(),- workflowIntent: trunc(entry.workflowIntent ? safeActivityText(entry.workflowIntent) : undefined, 500),- workflowProject: trunc(entry.workflowProject ? safeActivityText(entry.workflowProject) : undefined, 240),- target: trunc(entry.target),- detail: trunc(entry.detail, 220),- }) + "\n";- chain = chain.then(async () => {- const file = activityPath();- try {- await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });- await fs.appendFile(file, line, { mode: 0o600 });- } catch (e) {- console.error("[mcp-activity] write failed:", e instanceof Error ? e.message : e);- }- });- return chain;-}--export async function readMcpActivity(limit = 80): Promise<McpActivityEntry[]> {- const raw = await fs.readFile(activityPath(), "utf8").catch(() => "");- return raw- .split("\n")- .filter(Boolean)- .slice(-800)- .map((line) => {- try { return JSON.parse(line) as McpActivityEntry; } catch { return null; }- })- .filter((v): v is McpActivityEntry => Boolean(v?.id && v?.tool && v?.state))- .slice(-Math.min(Math.max(limit, 1), 200))- .reverse();-}+export { activityTarget, newActivityId, recordCapabilityActivity as recordMcpActivity, readCapabilityActivity as readMcpActivity } from "@/lib/capabilities/activity";+export type { CapabilityActivityEntry as McpActivityEntry, CapabilityActivityState as McpActivityState } from "@/lib/capabilities/activity";diff --git a/lib/mcp/capability-runtime.ts b/lib/mcp/capability-runtime.tsnew file mode 100644index 00000000..7060c442--- /dev/null+++ b/lib/mcp/capability-runtime.ts@@ -0,0 +1,44 @@+import { allows } from "@/lib/capabilities/scope";+import { executeCapabilityCall } from "@/lib/capabilities/execute";+import { boundedResultText } from "@/lib/capabilities/result-budget";+import { isCapabilityDirectResult } from "@/lib/capabilities/tool";+import type { CapabilityInvocationResult, CapabilityRuntime } from "@/lib/capabilities/runtime";+import { TOOLS, TOOLS_BY_NAME } from "./tools";++function successResult(toolName: string, result: unknown): CapabilityInvocationResult {+ if (isCapabilityDirectResult(result))+ return { content: result.content, ...(result.isError ? { isError: true } : {}) };+ const tool = TOOLS_BY_NAME.get(toolName);+ return { content: [{ type: "text", text: boundedResultText(result, tool?.result) }] };+}++/** Concrete MSO catalog composed once; MCP/A2A/subagents are adapters over it. */+export const msoCapabilityRuntime: CapabilityRuntime = {+ list(scope) {+ return TOOLS.filter((tool) => allows(scope, tool.scope)).map((tool) => ({+ name: tool.name,+ description: tool.description,+ scope: tool.scope,+ inputSchema: tool.inputSchema,+ }));+ },+ async invoke(input) {+ const tool = TOOLS_BY_NAME.get(input.name);+ if (!tool) return { content: [{ type: "text", text: `error: unknown tool: ${input.name}` }], isError: true };+ const outcome = await executeCapabilityCall({+ tool,+ args: input.args ?? {},+ scope: input.scope,+ actor: input.actor,+ context: {+ principal: input.principal,+ sessionId: input.sessionId,+ capabilities: msoCapabilityRuntime,+ },+ });+ if (outcome.kind === "protocol_error")+ return { content: [{ type: "text", text: `error: ${outcome.message}` }], isError: true };+ if (outcome.kind === "error") return { content: [{ type: "text", text: outcome.message }], isError: true };+ return successResult(input.name, outcome.result);+ },+};diff --git a/lib/mcp/dispatch-actors.ts b/lib/mcp/dispatch-actors.tsindex 434bfb1c..b0be8347 100644--- a/lib/mcp/dispatch-actors.ts+++ b/lib/mcp/dispatch-actors.ts@@ -1,11 +1 @@-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;-}+export { workflowActor, recipeActor } from "@/lib/capabilities/actors";diff --git a/lib/mcp/dispatch-tool-support.ts b/lib/mcp/dispatch-tool-support.tsindex fe8178c3..357cc878 100644--- a/lib/mcp/dispatch-tool-support.ts+++ b/lib/mcp/dispatch-tool-support.ts@@ -1,54 +1,15 @@-import { appendAgentSessionEvent } from "@/lib/agent/session-store";-import type { ActiveWorkflow } from "@/lib/skills/memory";+export { sessionDetail, recordAgentEvent, flowFields, workflowFromResult } from "@/lib/capabilities/execution-support";import { isMcpDirectResult } from "./tool-kit";import { boundedResultText } from "./result-budget";import { TOOLS_BY_NAME } from "./tools";-import type { McpAgentContext } from "./dispatch-types";import type { McpToolProfile } from "./tool-contract";-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;-}-function boundedStructuredValue(result: unknown, policy?: { maxTextBytes?: number; overflowHint?: string }): unknown {const text = boundedResultText(result, policy);try { return JSON.parse(text); } catch { return text; }}+/** MCP/profile serialization only. Execution policy lives in lib/capabilities. */export function structuredResult(toolName: string, result: unknown, profile: McpToolProfile = "full") {const tool = TOOLS_BY_NAME.get(toolName);if (isMcpDirectResult(result)) {@@ -72,8 +33,7 @@ export function structuredResult(toolName: string, result: unknown, profile: Mcpif (profile === "chatgpt") {return {structuredContent: { result: boundedStructuredValue(result, tool?.result) },- // Do not duplicate the full JSON in ChatGPT's transcript: the structured- // result already contains it. Generic MCP clients keep the old text-only form.+ // Avoid duplicating the same bounded JSON in the ChatGPT transcript.content: [{ type: "text" as const, text: `Structured result returned by ${toolName}.` }],};}diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.tsindex b823ec30..41de10db 100644--- a/lib/mcp/dispatch-tools.ts+++ b/lib/mcp/dispatch-tools.ts@@ -1,115 +1,18 @@-import { audit } from "@/lib/host";-import { maybeAutoTitleAgentSession } from "@/lib/agent/session-store";-import { touchLocalAgentPresence } from "@/lib/agent/local-agent-presence";-import { activeWorkflowForActor, recordWorkflowStep } from "@/lib/skills/memory";-import { activityTarget, newActivityId, recordMcpActivity } from "./activity";-import { allows, type Scope } from "./scope";+import { executeCapabilityCall } from "@/lib/capabilities/execute";+import type { Scope } from "./scope";import { TOOLS_BY_NAME } from "./tools";import { toolAllowedForProfile } from "./tool-contract";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";-import { toolRateLimited } from "./tool-rate-limit";+import { structuredResult } 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 || !toolAllowedForProfile(name, context?.toolProfile ?? "full")) return rpcFail(id, -32602, `unknown tool: ${name}`);- const mcpPresence = context?.principal?.startsWith("mcp-") && context.sessionId- ? { principal: context.principal, sessionId: context.sessionId, instanceId: `mcp:${context.sessionId}` }- : null;- if (mcpPresence)- await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "ready", mcpPresence.instanceId).catch(() => undefined);-- 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) continue;- const activityId = newActivityId(), detail = `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`;- if (!workflowProbe) {- void recordMcpActivity({ id: activityId, actor, tool: name, state: "invalid_args", scope, ...initialFlow, target, detail });- await recordWorkflowStep(flowActor, activeWorkflow?.id, { id: activityId, tool: name, state: "invalid_args", target, args, ts: new Date().toISOString() });- await recordAgentEvent(context, name, "invalid_args", args, activeWorkflow?.id, target);- }- return rpcFail(id, -32602, detail);- }- 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 (toolRateLimited(tool, args, actor)) {- 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 {- if (mcpPresence)- await touchLocalAgentPresence(- mcpPresence.principal,- mcpPresence.sessionId,- name === "local_agent_inbox" ? "idle" : "busy",- mcpPresence.instanceId,- ).catch(() => undefined);- const titleHint = sessionDetail(name, args, target);- if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status", "agent_subagent_run"].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, toolProfile: context?.toolProfile,- });- 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);- }- if (mcpPresence)- await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "idle", mcpPresence.instanceId).catch(() => undefined);- return rpcOk(id, structuredResult(name, result, context?.toolProfile ?? "full"));- } 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);- }- if (mcpPresence)- await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "idle", mcpPresence.instanceId).catch(() => undefined);- return rpcOk(id, { content: [{ type: "text", text: "error: " + message.slice(0, 500) }], isError: true });- }+ const profile = context?.toolProfile ?? "full";+ if (!tool || !toolAllowedForProfile(name, profile)) return rpcFail(id, -32602, `unknown tool: ${name}`);+ const outcome = await executeCapabilityCall({ tool, args, scope, actor, context });+ if (outcome.kind === "protocol_error") return rpcFail(id, outcome.code, outcome.message);+ if (outcome.kind === "error") return rpcOk(id, { content: [{ type: "text", text: outcome.message }], isError: true });+ return rpcOk(id, structuredResult(name, outcome.result, profile));}diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.tsindex 49119c78..505d5375 100644--- a/lib/mcp/dispatch-types.ts+++ b/lib/mcp/dispatch-types.ts@@ -1,3 +1,4 @@+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import type { McpToolProfile } from "./tool-contract";export interface RpcRequest {@@ -19,11 +20,9 @@ export interface McpAgentContext {principal?: string;sessionId?: string;toolProfile?: McpToolProfile;+ capabilities?: CapabilityRuntime;}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 } });+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.tsindex db652e75..81a7a604 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -131,11 +131,12 @@ describe("local agent request dispatch", () => {session: { id: "20260902_120000_11111111", name: "milo" },task: { state: "completed", artifacts: [{ parts: [{ text: "worker result" }] }] },});- const context = { principal: "cli:test-dispatch", sessionId: "20260902_120001_22222222" };+ const capabilities = { list: () => [], invoke: vi.fn(async () => ({ content: [] })) };+ const context = { principal: "cli:test-dispatch", sessionId: "20260902_120001_22222222", capabilities };const r = await dispatch(call("local_agent_request", { target: "milo", objective: "inspect this" }), "exec", "tester", context);expect(r.error).toBeUndefined();expect(localSessionMock.handoffOwnerLocalSession).toHaveBeenCalledWith(- context.principal, "milo", "inspect this", context.sessionId,+ context.principal, "milo", "inspect this", capabilities, context.sessionId,);expect(JSON.stringify(r.result)).toContain("worker result");});diff --git a/lib/mcp/origin.ts b/lib/mcp/origin.tsindex 21d368f4..81794dde 100644--- a/lib/mcp/origin.ts+++ b/lib/mcp/origin.ts@@ -115,13 +115,4 @@ export function publicOrigin(req: Request): string {return `${proto}://${host}`;}-/** Best-effort client IP for the pre-auth rate limiter. Spoofable behind a proxy- * that does not overwrite the header — which is why it only ever gates rate- * limits, never authorization. */-export function clientIp(req: Request): string {- return (- req.headers.get("x-forwarded-for")?.split(",")[0].trim() ||- req.headers.get("x-real-ip")?.trim() ||- "unknown"- );-}+export { clientIp } from "@/lib/host/request-ip";diff --git a/lib/mcp/pkce.ts b/lib/mcp/pkce.tsindex a30a250a..9d50633e 100644--- a/lib/mcp/pkce.ts+++ b/lib/mcp/pkce.ts@@ -1,53 +1,10 @@-import { createHash, randomBytes, timingSafeEqual } from "node:crypto";--// PKCE (RFC 7636) + the hashing every MCP secret is stored under. Raw codes and-// raw bearers exist only in flight: the store only ever holds sha256, so a leaked-// ~/.mso/mcp.json cannot be replayed against the server.--export function sha256hex(s: string): string {- return createHash("sha256").update(s).digest("hex");-}--/** base64url, NOT base64 — `+`→`-`, `/`→`_`, no padding. Standard base64 here- * silently produces a challenge that never matches (RFC 7636 §4.2). */-export function sha256b64url(s: string): string {- return createHash("sha256").update(s).digest("base64url");-}--export function randomToken(prefix: string, bytes = 32): string {- return prefix + randomBytes(bytes).toString("base64url");-}--/** Constant-time for equal-length input; length itself is not a secret. */-export function safeEqualHex(a: string, b: string): boolean {- if (a.length !== b.length) return false;- return timingSafeEqual(Buffer.from(a), Buffer.from(b));-}--/**- * True when `verifier` is the one that produced `challenge`.- *- * `plain` is refused outright — OAuth 2.1 drops it, and accepting it would mean a- * proxy that saw the authorization redirect could complete the exchange itself.- * The 43..128 bound is RFC 7636 §4.1: anything outside it cannot be a verifier at- * all, so rejecting early keeps a malformed value out of the hash comparison.- */-export function verifyPkce(verifier: string, challenge: string, method: string): boolean {- if (method !== "S256") return false;- if (typeof verifier !== "string" || verifier.length < 43 || verifier.length > 128) return false;- if (!/^[A-Za-z0-9\-._~]+$/.test(verifier)) return false;- const computed = sha256b64url(verifier);- return computed.length === challenge.length && safeEqualHex(computed, challenge);-}--/** https, or loopback for a desktop client's local callback. Anything else — a- * custom scheme, an http host on the internet — can leak the code in transit. */-export function isAllowedRedirect(u: string): boolean {- try {- const url = new URL(u);- if (url.protocol === "https:") return true;- return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");- } catch {- return false;- }-}+// Compatibility surface: OAuth/MCP callers keep their import path while the+// cryptographic primitives live in the protocol-neutral security layer.+export {+ sha256hex,+ sha256b64url,+ randomToken,+ safeEqualHex,+ verifyPkce,+ isAllowedRedirect,+} from "@/lib/security/pkce";diff --git a/lib/mcp/result-budget.ts b/lib/mcp/result-budget.tsindex b1477c85..9fe2c4f6 100644--- a/lib/mcp/result-budget.ts+++ b/lib/mcp/result-budget.ts@@ -1,60 +1,2 @@-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 {- const encoded = typeof result === "string" ? result : JSON.stringify(result);- raw = encoded === undefined ? "null" : encoded;- } 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,- });-}+export { boundedResultText, DEFAULT_CAPABILITY_RESULT_BYTES as DEFAULT_MCP_RESULT_BYTES, MAX_CAPABILITY_RESULT_BYTES as MAX_MCP_RESULT_BYTES } from "@/lib/capabilities/result-budget";+export type { CapabilityResultBudget as McpResultBudget } from "@/lib/capabilities/result-budget";diff --git a/lib/mcp/scope.ts b/lib/mcp/scope.tsindex 0ffcf945..135b018b 100644--- a/lib/mcp/scope.ts+++ b/lib/mcp/scope.ts@@ -1,26 +1,6 @@-// What an MCP bearer is allowed to do. mso is single-owner, so a token is not an-// identity — it IS the capability, and the only thing standing between a leaked-// bearer and the host is this tier.-//-// Deliberately three tiers, not one: "let ChatGPT read my VPS" and "let ChatGPT-// run shell commands as me" are wildly different bets, and a connector that only-// ever needs to read files should not hold the second one. The owner picks per-// token on the consent page.--export const SCOPES = ["read", "write", "exec"] as const;-export type Scope = (typeof SCOPES)[number];--/** Ranked: holding a tier implies every tier below it. */-const RANK: Record<Scope, number> = { read: 0, write: 1, exec: 2 };--export function parseScope(raw: string | undefined | null): Scope {- const asked = String(raw ?? "")- .split(/[\s,]+/)- .filter((s): s is Scope => (SCOPES as readonly string[]).includes(s));- if (asked.length === 0) return "read"; // unknown/absent → least privilege- return asked.reduce((a, b) => (RANK[b] > RANK[a] ? b : a));-}-+// MCP-specific policy layered on the transport-neutral capability scope.+export { SCOPES, allows, parseScope, type Scope } from "@/lib/capabilities/scope";+import { SCOPES, scopeRank, type Scope } from "@/lib/capabilities/scope";/** OAuth scope strings are cumulative so a standards-compliant host can see that an exec token also satisfies read/write tool schemes. */export function oauthScopeString(scope: Scope, offline = false): string {@@ -29,22 +9,11 @@ export function oauthScopeString(scope: Scope, offline = false): string {return values.join(" ");}-export function allows(held: Scope, needed: Scope): boolean {- return RANK[held] >= RANK[needed];-}--/** MCP is OFF unless the owner turns it on. An install that never sets this has- * no MCP surface at all — not an unauthenticated one, none. Demo mode disables- * login entirely, so it must never expose a host-control endpoint either. */export function mcpEnabled(): boolean {if (process.env.NEXT_PUBLIC_OS_DEMO === "1") return false;return process.env.OS_MCP_ENABLED === "1";}-/** The ceiling the deployment allows, whatever a consent page asks for. The- * owner wants full MCP capability on a fresh install, so an absent value defaults- * to `exec`. Set `OS_MCP_MAX_SCOPE=read` or `write` to opt down. A malformed explicit- * value still fails closed to `write` rather than silently granting shell access. */export function maxScope(): Scope {const raw = process.env.OS_MCP_MAX_SCOPE;if (!raw) return "exec";@@ -54,10 +23,7 @@ export function maxScope(): Scope {export function clampScope(asked: Scope): Scope {const ceiling = maxScope();- return RANK[asked] > RANK[ceiling] ? ceiling : asked;+ return scopeRank(asked) > scopeRank(ceiling) ? ceiling : asked;}-/** OAuth consent starts at the deployment ceiling; the owner may select a lower tier. */-export function defaultConsentScope(ceiling: Scope): Scope {- return ceiling;-}+export function defaultConsentScope(ceiling: Scope): Scope { return ceiling; }diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.tsindex f254d15e..c3f43d3d 100644--- a/lib/mcp/tool-kit.ts+++ b/lib/mcp/tool-kit.ts@@ -1,108 +1,16 @@-import type { AuditAction } from "@/lib/host";-import type { Scope } from "./scope";-import type { McpToolProfile } from "./tool-contract";--// Shared shapes for the MCP tool catalog. EVERY handler goes through lib/host — never node fs or-// child_process directly — so all of it inherits the bounds that already guard-// /api/v1: OS_FS_READ_ROOTS / OS_FS_WRITE_ROOTS, the credential denylist-// (~/.ssh, ~/.mso itself, cloud + AI tokens), realpath escape checks, and the-// catastrophic-command filter in exec.ts. That is the whole reason this file is-// thin: a tool that reimplemented an operation would reimplement its guard too.--export type McpContent =- | { type: "text"; text: string }- | { type: "image"; data: string; mimeType: string };--export interface McpDirectResult {- __mcpDirect: true;- content: McpContent[];- isError?: boolean;- /** Optional safe structured projection for clients that advertise outputSchema.- * Never put binary/base64 payloads or secrets here. */- structuredContent?: Record<string, unknown>;-}--export function mcpDirect(- content: McpContent[],- isError = false,- structuredContent?: Record<string, unknown>,-): McpDirectResult {- return { __mcpDirect: true, content, ...(isError ? { isError: true } : {}), ...(structuredContent ? { structuredContent } : {}) };-}--export function isMcpDirectResult(value: unknown): value is McpDirectResult {- return Boolean(value && typeof value === "object" && (value as McpDirectResult).__mcpDirect === true);-}--export interface McpRunContext {- actor?: string;- /** Stable principal for persistent agent session/memory ownership. Unlike the- * token-scoped audit actor, this may survive an OAuth token refresh. */- principal?: string;- /** Durable Streamable HTTP / terminal-agent session id, when available. */- sessionId?: string;- scope: Scope;- workflowId?: string;- /** Session-scoped workflow owner; prevents cross-conversation workflow access. */- workflowActor?: string;- /** Client-scoped learned-recipe owner; survives individual session rotation. */- recipeActor?: string;- /** Client-specific static tool projection; project capabilities stay dynamic. */- toolProfile?: McpToolProfile;-}--export interface McpTool {- name: string;- /** Human-readable label advertised to MCP hosts. Generated from name when omitted. */- title?: string;- description: string;- /** Optional shorter description for the compact ChatGPT scan profile. */- chatgptDescription?: string;- scope: Scope;- inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };- /** MCP Apps structured output contract. */- outputSchema?: Record<string, unknown>;- /** Optional projection for the structured result. Use this to keep the portable- * text fallback backward compatible while exposing a smaller, explicitly safe- * object to a widget. */- toStructuredContent?: (result: unknown) => Record<string, unknown> | undefined;- annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean; openWorldHint?: boolean; idempotentHint?: boolean };- /** Per-tool auth policy advertised to MCP hosts. Defaults to OAuth with this tool's minimum MSO scope. */- securitySchemes?: Array<{ type: "oauth2"; scopes: string[] } | { type: "noauth" }>;- /** MCP Apps / OpenAI metadata: UI resource binding, visibility and file params. */- meta?: Record<string, unknown>;- run: (a: Record<string, unknown>, context: McpRunContext) => Promise<unknown>;- /** Which audit action this writes, and which argument names the target. Reads- * are deliberately unaudited (bounded + high-volume, same rule the /api/v1- * routes follow); a tool without this field writes nothing.- *- * This exists because MCP tools call lib/host DIRECTLY. The /api/v1 routes- * audit at the ROUTE layer, so without this every write, delete and exec that- * arrived over MCP would be invisible in the only forensic trail there is. */- audit?: {- action: AuditAction;- targetArg?: string;- /** Derive the outcome from the RESULT, for a handler that reports failure by- * returning rather than throwing. Without it the dispatcher can only record- * "did not throw", which is a lie for anything that has an exit code. */- 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 };-}--export const str = (a: Record<string, unknown>, k: string): string => {- const v = a[k];- if (typeof v !== "string" || !v) throw new Error(`${k} must be a non-empty string`);- return v;-};-export const opt = (a: Record<string, unknown>, k: string): string | undefined =>- typeof a[k] === "string" && a[k] ? (a[k] as string) : undefined;--export const S = (properties: Record<string, unknown>, required?: string[]) =>- ({ type: "object" as const, properties, ...(required ? { required } : {}) });--export const PATH_P = { path: { type: "string", description: "Absolute path on the VPS, or ~/… for the owner's home." } };-export const READ_ONLY = { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true };+// MCP compatibility aliases over the transport-neutral capability contract.+export {+ capabilityDirect as mcpDirect,+ isCapabilityDirectResult as isMcpDirectResult,+ str,+ opt,+ S,+ PATH_P,+ READ_ONLY,+} from "@/lib/capabilities/tool";+export type {+ CapabilityContent as McpContent,+ CapabilityDirectResult as McpDirectResult,+ CapabilityRunContext as McpRunContext,+ CapabilityTool as McpTool,+} from "@/lib/capabilities/tool";diff --git a/lib/mcp/tool-rate-limit.ts b/lib/mcp/tool-rate-limit.tsindex a8fa80c1..566512b2 100644--- a/lib/mcp/tool-rate-limit.ts+++ b/lib/mcp/tool-rate-limit.ts@@ -1,13 +1 @@-import { rateLimited } from "@/lib/host/rate-limit";-import type { McpTool } from "./tool-kit";--/** Shared per-tool bucket semantics for direct MCP calls and server-side read pipelines. */-export function toolRateLimited(- tool: McpTool,- args: Record<string, unknown>,- actor?: string,-): boolean {- if (!tool.limit) return false;- const suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");- return rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs);-}+export { capabilityRateLimited as toolRateLimited } from "@/lib/capabilities/rate-limit";diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.tsindex 348b660b..78f90d22 100644--- a/lib/mcp/tools-local-agents.ts+++ b/lib/mcp/tools-local-agents.ts@@ -62,7 +62,8 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [}, ["target", "objective"]),run: async (a, context) => {const current = sessionContext(context);- const result = await handoffOwnerLocalSession(current.principal, str(a, "target"), str(a, "objective"), current.sessionId);+ if (!context.capabilities) throw new Error("capability runtime unavailable for local-agent delegation");+ const result = await handoffOwnerLocalSession(current.principal, str(a, "target"), str(a, "objective"), context.capabilities, current.sessionId);return { mode: "durable_session_worker", ...result };},},diff --git a/lib/mcp/tools-project-runtime.ts b/lib/mcp/tools-project-runtime.tsindex a0bd1112..c050a9bf 100644--- a/lib/mcp/tools-project-runtime.ts+++ b/lib/mcp/tools-project-runtime.ts@@ -78,6 +78,8 @@ export const PROJECT_RUNTIME_TOOLS: McpTool[] = [}, ["project", "message"]),run: async (a, context) => {if (!context.principal || !context.sessionId) throw new Error("project agent requires a conversation-bound MSO session");+ if (!context.capabilities) throw new Error("project agent capability runtime is unavailable");+ const capabilities = context.capabilities;const project = await selectedProject(str(a, "project"));const requested = parseScope(a.plan_mode === true ? "read" : (opt(a, "max_scope") ?? "write"));if (!allows(context.scope, requested)) throw new Error(`project agent max_scope ${requested} exceeds caller scope ${context.scope}`);@@ -91,6 +93,7 @@ export const PROJECT_RUNTIME_TOOLS: McpTool[] = [objective: `${mode}\nSelected project: ${project.path}\nUser task: ${message}`, maxScope: requested,maxTurns: typeof a.max_turns === "number" ? a.max_turns : undefined, timeoutMs: typeof a.timeout_ms === "number" ? a.timeout_ms : undefined,explicitContext: `Project id=${project.id}; path=${project.path}. Stay focused on this project.`,+ capabilities,});return updateProjectAgentTask(context.principal!, task.id, {status: result.status,diff --git a/lib/mcp/tools-subagents.ts b/lib/mcp/tools-subagents.tsindex 614b6203..be5f0954 100644--- a/lib/mcp/tools-subagents.ts+++ b/lib/mcp/tools-subagents.ts@@ -20,6 +20,7 @@ export const SUBAGENT_TOOLS: McpTool[] = [{if (!context.principal || !context.sessionId) throw new Error("subagent requires a conversation-bound MSO session");const requested = parseScope(typeof a.max_scope === "string" ? a.max_scope : "read");if (!allows(context.scope, requested)) throw new Error(`subagent max_scope ${requested} exceeds caller scope ${context.scope}`);+ if (!context.capabilities) throw new Error("capability runtime unavailable for subagent delegation");return runSessionSubagent({principal: context.principal,parentSessionId: context.sessionId,@@ -29,6 +30,7 @@ export const SUBAGENT_TOOLS: McpTool[] = [{maxTurns: Number(a.max_turns) || undefined,timeoutMs: Number(a.timeout_ms) || undefined,explicitContext: typeof a.context === "string" ? a.context : undefined,+ capabilities: context.capabilities,});},}];diff --git a/lib/security/pkce.ts b/lib/security/pkce.tsnew file mode 100644index 00000000..5e9b13a5--- /dev/null+++ b/lib/security/pkce.ts@@ -0,0 +1,52 @@+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";++// PKCE (RFC 7636) and secret-hashing primitives shared by protocol adapters.+// Raw codes/bearers stay in flight; persistent callers store only hashes.++export function sha256hex(s: string): string {+ return createHash("sha256").update(s).digest("hex");+}++/** base64url, NOT base64 — `+`→`-`, `/`→`_`, no padding. Standard base64 here+ * silently produces a challenge that never matches (RFC 7636 §4.2). */+export function sha256b64url(s: string): string {+ return createHash("sha256").update(s).digest("base64url");+}++export function randomToken(prefix: string, bytes = 32): string {+ return prefix + randomBytes(bytes).toString("base64url");+}++/** Constant-time for equal-length input; length itself is not a secret. */+export function safeEqualHex(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));+}++/**+ * True when `verifier` is the one that produced `challenge`.+ *+ * `plain` is refused outright — OAuth 2.1 drops it, and accepting it would mean a+ * proxy that saw the authorization redirect could complete the exchange itself.+ * The 43..128 bound is RFC 7636 §4.1: anything outside it cannot be a verifier at+ * all, so rejecting early keeps a malformed value out of the hash comparison.+ */+export function verifyPkce(verifier: string, challenge: string, method: string): boolean {+ if (method !== "S256") return false;+ if (typeof verifier !== "string" || verifier.length < 43 || verifier.length > 128) return false;+ if (!/^[A-Za-z0-9\-._~]+$/.test(verifier)) return false;+ const computed = sha256b64url(verifier);+ return computed.length === challenge.length && safeEqualHex(computed, challenge);+}++/** https, or loopback for a desktop client's local callback. Anything else — a+ * custom scheme, an http host on the internet — can leak the code in transit. */+export function isAllowedRedirect(u: string): boolean {+ try {+ const url = new URL(u);+ if (url.protocol === "https:") return true;+ return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");+ } catch {+ return false;+ }+}diff --git a/lib/security/property-fuzz.test.ts b/lib/security/property-fuzz.test.tsindex c097042d..affc1d3e 100644--- a/lib/security/property-fuzz.test.ts+++ b/lib/security/property-fuzz.test.ts@@ -3,7 +3,7 @@ import * as fc from "fast-check";import { describe, expect, it } from "vitest";import { isUnderRoot } from "@/lib/host/paths";import { assertSafeUrl, isForbiddenProviderAddress } from "@/lib/host/ssrf";-import { safeEqualHex, sha256b64url, verifyPkce } from "@/lib/mcp/pkce";+import { safeEqualHex, sha256b64url, verifyPkce } from "@/lib/security/pkce";const segmentChar = fc.constantFrom(..."abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-");const segment = fc.array(segmentChar, { minLength: 1, maxLength: 18 }).map((chars) => chars.join(""));diff --git a/lib/skills/memory.ts b/lib/skills/memory.tsindex dc74c952..d21935be 100644--- a/lib/skills/memory.ts+++ b/lib/skills/memory.ts@@ -4,7 +4,7 @@ import { promises as fs } from "fs";import os from "os";import path from "path";import { embedSkillText, hybridSemanticScore, normalizeSemanticText, SKILL_EMBEDDING_VERSION } from "./semantic";-import { allows, type Scope } from "@/lib/mcp/scope";+import { allows, type Scope } from "@/lib/capabilities/scope";import type { WorkflowOrchestrationSnapshot } from "@/lib/orchestration/types";export type WorkflowStepState = "completed" | "failed" | "denied" | "rate_limited" | "invalid_args";diff --git a/package.json b/package.jsonindex 74294b98..e89bef41 100644--- a/package.json+++ b/package.json@@ -13,7 +13,7 @@"typecheck": "tsc --noEmit","test": "vitest run","coverage": "vitest run --coverage",- "check": "node scripts/check-cycles.mjs && node scripts/check-docs.mjs && node scripts/gen-comparison.mjs --check && node scripts/check-contrast.mjs && node scripts/check-skill-flows.mjs",+ "check": "node scripts/check-cycles.mjs && node scripts/check-architecture.mjs && node scripts/check-docs.mjs && node scripts/gen-comparison.mjs --check && node scripts/check-contrast.mjs && node scripts/check-skill-flows.mjs","audit": "node scripts/audit.mjs","verify": "bun run typecheck && bun run lint && bun run coverage && bun run check && bun run audit","security:ultimate": "bash scripts/security-ultimate.sh",diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjsnew file mode 100755index 00000000..a2cb9a84--- /dev/null+++ b/scripts/check-architecture.mjs@@ -0,0 +1,52 @@+#!/usr/bin/env node+import { readFileSync } from "node:fs";+import { resolve as pathResolve } from "node:path";+import { fileURLToPath } from "node:url";+import { buildImportGraph, findCycles, rel, walkSource } from "./lib/import-graph.mjs";++const ROOT = pathResolve(fileURLToPath(import.meta.url), "../..");+const policy = JSON.parse(readFileSync(pathResolve(ROOT, "architecture.boundaries.json"), "utf8"));+const { graph, barrel, imports } = buildImportGraph(ROOT);+const cycles = findCycles(graph, barrel), structural = cycles.filter((row) => row.kind === "type");+const domain = (file) => {+ const name = rel(ROOT, file);+ if (name.startsWith("lib/")) return name.split("/").slice(0, 2).join("/");+ if (name.startsWith("frontend/slices/")) return name.split("/").slice(0, 3).join("/");+ return name.split("/")[0];+};+const crossDomain = structural.filter(({ ring }) => new Set(ring.slice(0, -1).map(domain)).size > 1);+const sourceFiles = walkSource(ROOT, ["app", "frontend", "lib", "scripts", "bin"], [".ts", ".tsx", ".mjs", ".js", ".sh"]);+const lineCount = (file) => readFileSync(file, "utf8").split("\n").filter((line) => line.trim() && !line.trim().startsWith("//")).length;+const physicalLines = (file) => readFileSync(file, "utf8").split("\n").length;+const filesOver220 = sourceFiles.filter((file) => physicalLines(file) > 220).length;+const filesOver500 = sourceFiles.filter((file) => physicalLines(file) > 500).length;+const serverFrontendImports = imports.filter((row) => rel(ROOT, row.from).startsWith("lib/") && row.spec.startsWith("@/features/")).length;+const appshellSelfBarrelImports = imports.filter((row) => rel(ROOT, row.from).startsWith("frontend/slices/appshell/") && row.spec === "@/features/appshell").length;+const nonMcpMcpImports = imports.filter((row) => {+ const from = rel(ROOT, row.from);+ return from.startsWith("lib/") && !from.startsWith("lib/mcp/") && row.spec.startsWith("@/lib/mcp/");+}).length;+const crossProtocol = structural.filter(({ ring }) => {+ const domains = new Set(ring.slice(0, -1).map(domain));+ return domains.has("lib/mcp") && (domains.has("lib/a2a") || domains.has("lib/agent"));+});+const metrics = { structuralCycles: structural.length, crossDomainCycles: crossDomain.length, crossProtocolCycles: crossProtocol.length, filesOver220, filesOver500, serverFrontendImports, appshellSelfBarrelImports, nonMcpMcpImports };+let failed = false;+console.log("Architecture health");+for (const [key, current] of Object.entries(metrics)) {+ const max = policy.ratchets[key];+ const ok = Number.isFinite(max) && current <= max;+ console.log(` ${key.padEnd(26)} ${String(current).padStart(4)} / max ${String(max).padStart(4)} ${ok ? "PASS" : "FAIL"}`);+ if (!ok) failed = true;+}+const valueCycles = cycles.filter((row) => row.kind === "value").length;+console.log(` ${"valueCycles".padEnd(26)} ${String(valueCycles).padStart(4)} / max 0 ${valueCycles === 0 ? "PASS" : "FAIL"}`);+if (valueCycles) failed = true;+if (process.argv.includes("--verbose")) {+ for (const row of crossDomain) console.log("\n [cross-domain] " + row.ring.map((file) => rel(ROOT, file)).join("\n → "));+}+if (failed) {+ console.error("architecture: ratchet regression — reduce the metric or update the policy only with an explicit architecture decision.");+ process.exit(1);+}+console.log("architecture: healthy within ratchets.");diff --git a/scripts/lib/import-graph.mjs b/scripts/lib/import-graph.mjsnew file mode 100644index 00000000..6594f8ca--- /dev/null+++ b/scripts/lib/import-graph.mjs@@ -0,0 +1,105 @@+import { readFileSync, statSync, readdirSync } from "node:fs";+import { dirname, join, relative, resolve as pathResolve } from "node:path";++export const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mjs", ".js"];+const IMPORT_RE = /(?:^|[\s;])(?:(import\s+type\s+[^"']*?from\s+["']([^"']+)["'])|(export\s+type\s+[^"']*?from\s+["']([^"']+)["'])|(export\s*\*\s*from\s+["']([^"']+)["'])|(export\s*\{[^}]*\}\s*from\s+["']([^"']+)["'])|(import\s+[^"']*?from\s+["']([^"']+)["'])|(import\s*["']([^"']+)["']))/g;++export function walkSource(root, dirs = ["frontend", "lib"], extensions = [".ts", ".tsx"]) {+ const out = [];+ const walk = (dir) => {+ let entries;+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }+ for (const entry of entries) {+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;+ const full = join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (extensions.some((ext) => full.endsWith(ext))) out.push(full);+ }+ };+ for (const dir of dirs) walk(join(root, dir));+ return out;+}++const isFile = (path) => statSync(path, { throwIfNoEntry: false })?.isFile();+function tryResolve(base, extensions) {+ if (isFile(base)) return base;+ for (const ext of extensions) if (isFile(base + ext)) return base + ext;+ for (const ext of extensions) if (isFile(join(base, "index" + ext))) return join(base, "index" + ext);+ return null;+}++export function resolveImport(root, from, spec, extensions = SOURCE_EXTENSIONS) {+ if (spec.startsWith("@/features/")) return tryResolve(join(root, "frontend/slices", spec.slice(11)), extensions);+ if (spec.startsWith("@/")) return tryResolve(join(root, spec.slice(2)), extensions);+ if (spec.startsWith(".")) return tryResolve(pathResolve(dirname(from), spec), extensions);+ return null;+}++export function importsFromSource(source) {+ const rows = [];+ for (const match of source.matchAll(IMPORT_RE)) {+ const spec = match[2] ?? match[4] ?? match[6] ?? match[8] ?? match[10] ?? match[12];+ if (!spec) continue;+ const kind = match[1] || match[3] || match[5] || match[7] ? "type" : "value";+ rows.push({ spec, kind });+ }+ return rows;+}++export function isPureBarrel(source) {+ const clean = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|\n)\s*\/\/[^\n]*/g, "");+ if (/(^|\n)\s*import\s+(?!type\b)(?![\s]*["'])/.test(clean)) return false;+ return !/(^|\n)\s*(?:const|let|var|function|class|if|for|while|switch|return|throw|await|async\s+function)\b/.test(clean);+}++export function buildImportGraph(root, options = {}) {+ const dirs = options.dirs ?? ["frontend", "lib"];+ const extensions = options.extensions ?? [".ts", ".tsx"];+ const files = walkSource(root, dirs, extensions);+ const graph = new Map(), barrel = new Map(), imports = [];+ for (const file of files) {+ const source = readFileSync(file, "utf8");+ barrel.set(file, isPureBarrel(source));+ const edges = new Map();+ for (const row of importsFromSource(source)) {+ const target = resolveImport(root, file, row.spec, extensions);+ imports.push({ from: file, to: target, spec: row.spec, kind: row.kind });+ if (!target || target === file) continue;+ if (edges.get(target) !== "value") edges.set(target, row.kind);+ }+ graph.set(file, edges);+ }+ return { files, graph, barrel, imports };+}++export function findCycles(graph, barrel) {+ const WHITE = 0, GRAY = 1, BLACK = 2;+ const color = new Map(), stack = [], cycles = [], seen = new Set();+ const canonical = (ring) => {+ const body = ring.slice(0, -1);+ const variants = body.map((_, i) => [...body.slice(i), ...body.slice(0, i)].join("|"));+ return variants.sort()[0] ?? "";+ };+ const dfs = (node) => {+ color.set(node, GRAY); stack.push(node);+ for (const [next] of graph.get(node) ?? []) {+ const state = color.get(next) ?? WHITE;+ if (state === GRAY) {+ const index = stack.indexOf(next);+ if (index < 0) continue;+ const ring = stack.slice(index).concat(next), key = canonical(ring);+ if (seen.has(key)) continue;+ seen.add(key);+ let anyType = false;+ for (let k = index; k < stack.length; k += 1)+ if (graph.get(stack[k])?.get(stack[k + 1] ?? next) === "type") anyType = true;+ cycles.push({ ring, kind: anyType || barrel.get(next) ? "type" : "value" });+ } else if (state === WHITE) dfs(next);+ }+ stack.pop(); color.set(node, BLACK);+ };+ for (const file of graph.keys()) if ((color.get(file) ?? WHITE) === WHITE) dfs(file);+ return cycles;+}++export const rel = (root, file) => relative(root, file).replaceAll("\\", "/");