Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(settings): clarify MCP navigation and enforce zero-warning tests

Rahman40c979d28234
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4dd5dd41..b30bf8fc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -55,13 +55,7 @@ jobs:
run: bash scripts/provision-forge-sandbox.sh
- name: Tests and coverage
- run: |
- set -euo pipefail
- test ! -e .env.local
- umask 077
- printf '# Synthetic denylist fixture; no credentials.\n' > .env.local
- trap 'rm -f .env.local' EXIT
- bun run coverage
+ run: bun run coverage
- name: Repository checks
run: bun run check
diff --git a/app/api/v1/a2a/route-access.test.ts b/app/api/v1/a2a/route-access.test.ts
new file mode 100644
index 00000000..5406471f
--- /dev/null
+++ b/app/api/v1/a2a/route-access.test.ts
@@ -0,0 +1,114 @@
+import { NextRequest } from "next/server";
+import { describe, expect, it } from "vitest";
+import { GET, mocks, POST, post } from "./route-fixture";
+
+describe("A2A owner and local access", () => {
+ it("returns owner A2A state without credential secrets and manages profiles", async () => {
+ mocks.list.mockResolvedValue([
+ {
+ id: "peer-1",
+ alias: "peer",
+ card: { securitySchemeNames: [], securitySchemes: {} },
+ },
+ ]);
+ mocks.listCreds.mockResolvedValue([
+ { id: "cred-1", agentId: "peer-1", label: "prod", kind: "bearer" },
+ ]);
+ const state = await (
+ await GET(new NextRequest("http://localhost/api/v1/a2a?action=state"))
+ ).json();
+ expect(state.credentials[0]).not.toHaveProperty("secret");
+ mocks.createCred.mockResolvedValue({
+ id: "cred-2",
+ agentId: "peer-1",
+ label: "new",
+ kind: "bearer",
+ });
+ mocks.setCred.mockResolvedValue({
+ id: "peer-1",
+ credentialProfileId: "cred-2",
+ });
+ const created = await POST(
+ post({
+ action: "credential-create",
+ agentId: "peer-1",
+ label: "new",
+ kind: "bearer",
+ secret: "top-secret",
+ }),
+ );
+ expect(created.status).toBe(200);
+ expect(mocks.createCred).toHaveBeenCalledWith(
+ expect.objectContaining({ secret: "top-secret" }),
+ );
+ expect(mocks.audit.mock.calls.flat().join(" ")).not.toContain("top-secret");
+ mocks.createInbound.mockResolvedValue({
+ token: "mso_a2a_once",
+ profile: { id: "in-1", label: "peer", scope: "read" },
+ });
+ const inbound = await (
+ await POST(
+ post({ action: "inbound-token-create", label: "peer", scope: "read" }),
+ )
+ ).json();
+ expect(inbound.token).toBe("mso_a2a_once");
+ });
+ it("routes same-host session list, handoff, spawn, and inbox without exposing credentials", async () => {
+ mocks.localSessions.mockResolvedValue([
+ { id: "local-session", title: "bece", cwd: "/srv/bece" },
+ ]);
+ const listed = await (
+ await GET(
+ new NextRequest("http://localhost/api/v1/a2a?action=local-sessions"),
+ )
+ ).json();
+ expect(listed.sessions[0].title).toBe("bece");
+
+ const handoff = await POST(
+ post({
+ action: "local-handoff",
+ sessionRef: "bece",
+ objective: "review this",
+ }),
+ );
+ expect(handoff.status).toBe(200);
+ expect(mocks.localHandoff).toHaveBeenCalledWith(
+ "bece",
+ "review this",
+ expect.objectContaining({ list: expect.any(Function), invoke: expect.any(Function) }),
+ );
+
+ const spawn = await POST(
+ post({
+ action: "local-spawn",
+ sourceSessionRef: "bece",
+ objective: "audit this",
+ title: "reviewer",
+ }),
+ );
+ expect(spawn.status).toBe(200);
+ expect(mocks.localSpawn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ ownerPrincipal: "cli:cli-test",
+ sourceSessionRef: "bece",
+ objective: "audit this",
+ title: "reviewer",
+ }),
+ );
+
+ mocks.tasksOwner.mockResolvedValue([
+ { id: "for-bece", targetSessionId: "local-session" },
+ { id: "other", targetSessionId: "other-session" },
+ ]);
+ const inbox = await (
+ await GET(
+ new NextRequest(
+ "http://localhost/api/v1/a2a?action=local-inbox&session=bece",
+ ),
+ )
+ ).json();
+ expect(inbox.tasks).toEqual([
+ { id: "for-bece", targetSessionId: "local-session" },
+ ]);
+ });
+});
diff --git a/app/api/v1/a2a/route-fixture.ts b/app/api/v1/a2a/route-fixture.ts
new file mode 100644
index 00000000..753df859
--- /dev/null
+++ b/app/api/v1/a2a/route-fixture.ts
@@ -0,0 +1,105 @@
+import { NextRequest } from "next/server";
+import { beforeEach, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ list: vi.fn(),
+ discover: vi.fn(),
+ register: vi.fn(),
+ remove: vi.fn(),
+ resolve: vi.fn(),
+ send: vi.fn(),
+ stream: vi.fn(),
+ get: vi.fn(),
+ cancel: vi.fn(),
+ handoff: vi.fn(),
+ audit: vi.fn(),
+ rate: vi.fn(),
+ listCreds: vi.fn(),
+ getCred: vi.fn(),
+ createCred: vi.fn(),
+ removeCred: vi.fn(),
+ setCred: vi.fn(),
+ listInbound: vi.fn(),
+ createInbound: vi.fn(),
+ removeInbound: vi.fn(),
+ tasksOwner: vi.fn(),
+ auditTail: vi.fn(),
+ resolveBinding: vi.fn(),
+ localSessions: vi.fn(),
+ localResolve: vi.fn(),
+ localHandoff: vi.fn(),
+ localSpawn: vi.fn(),
+}));
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: vi.fn(async () => ({
+ role: "owner",
+ session: { device_id: "cli-test" },
+ })),
+}));
+vi.mock("@/lib/a2a", () => ({
+ listA2AAgents: mocks.list,
+ discoverA2AAgent: mocks.discover,
+ registerA2AAgent: mocks.register,
+ removeA2AAgent: mocks.remove,
+ resolveA2AAgent: mocks.resolve,
+ sendA2AMessage: mocks.send,
+ sendA2AStreamingMessage: mocks.stream,
+ getA2ATask: mocks.get,
+ cancelA2ATask: mocks.cancel,
+ handoffA2A: mocks.handoff,
+ listA2AOutboundCredentials: mocks.listCreds,
+ getA2AOutboundCredential: mocks.getCred,
+ createA2AOutboundCredential: mocks.createCred,
+ removeA2AOutboundCredential: mocks.removeCred,
+ setA2AAgentCredential: mocks.setCred,
+ listA2AInboundTokens: mocks.listInbound,
+ createA2AInboundToken: mocks.createInbound,
+ removeA2AInboundToken: mocks.removeInbound,
+ listA2ATasksOwner: mocks.tasksOwner,
+ resolveA2ACredentialBinding: mocks.resolveBinding,
+ listA2ALocalSessions: mocks.localSessions,
+ resolveA2ALocalSession: mocks.localResolve,
+ handoffA2ALocalSession: mocks.localHandoff,
+ spawnA2ALocalSubagent: mocks.localSpawn,
+}));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit, readAuditTail: mocks.auditTail }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rate }));
+vi.mock("@/lib/host/request-api", () => ({
+ readJson: async (req: Request) => req.json().catch(() => null),
+}));
+vi.mock("@/lib/mcp/capability-runtime", () => ({
+ msoCapabilityRuntime: { list: () => [], invoke: vi.fn(async () => ({ content: [] })) },
+}));
+
+export const { GET, POST } = await import("./route");
+export const post = (body: object) =>
+ new NextRequest("http://localhost/api/v1/a2a", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.rate.mockReturnValue(false);
+ mocks.resolve.mockResolvedValue({ card: { name: "Peer" } });
+ mocks.list.mockResolvedValue([]);
+ mocks.listCreds.mockResolvedValue([]);
+ mocks.listInbound.mockResolvedValue([]);
+ mocks.tasksOwner.mockResolvedValue([]);
+ mocks.auditTail.mockResolvedValue([]);
+ mocks.resolveBinding.mockReturnValue({});
+ mocks.localSessions.mockResolvedValue([]);
+ mocks.localResolve.mockResolvedValue({ id: "local-session", title: "bece" });
+ mocks.localHandoff.mockResolvedValue({
+ session: { id: "local-session", title: "bece" },
+ task: { id: "local-task", artifacts: [] },
+ });
+ mocks.localSpawn.mockResolvedValue({
+ session: { id: "child-session", title: "reviewer" },
+ task: { id: "child-task", artifacts: [] },
+ });
+});
+
+
+export { mocks };
diff --git a/app/api/v1/a2a/route.test.ts b/app/api/v1/a2a/route.test.ts
index 7d61f530..2f5ff48c 100644
--- a/app/api/v1/a2a/route.test.ts
+++ b/app/api/v1/a2a/route.test.ts
@@ -1,105 +1,6 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
-
-const mocks = vi.hoisted(() => ({
- list: vi.fn(),
- discover: vi.fn(),
- register: vi.fn(),
- remove: vi.fn(),
- resolve: vi.fn(),
- send: vi.fn(),
- stream: vi.fn(),
- get: vi.fn(),
- cancel: vi.fn(),
- handoff: vi.fn(),
- audit: vi.fn(),
- rate: vi.fn(),
- listCreds: vi.fn(),
- getCred: vi.fn(),
- createCred: vi.fn(),
- removeCred: vi.fn(),
- setCred: vi.fn(),
- listInbound: vi.fn(),
- createInbound: vi.fn(),
- removeInbound: vi.fn(),
- tasksOwner: vi.fn(),
- auditTail: vi.fn(),
- resolveBinding: vi.fn(),
- localSessions: vi.fn(),
- localResolve: vi.fn(),
- localHandoff: vi.fn(),
- localSpawn: vi.fn(),
-}));
-vi.mock("@/lib/auth/require-session", () => ({
- getSessionContext: vi.fn(async () => ({
- role: "owner",
- session: { device_id: "cli-test" },
- })),
-}));
-vi.mock("@/lib/a2a", () => ({
- listA2AAgents: mocks.list,
- discoverA2AAgent: mocks.discover,
- registerA2AAgent: mocks.register,
- removeA2AAgent: mocks.remove,
- resolveA2AAgent: mocks.resolve,
- sendA2AMessage: mocks.send,
- sendA2AStreamingMessage: mocks.stream,
- getA2ATask: mocks.get,
- cancelA2ATask: mocks.cancel,
- handoffA2A: mocks.handoff,
- listA2AOutboundCredentials: mocks.listCreds,
- getA2AOutboundCredential: mocks.getCred,
- createA2AOutboundCredential: mocks.createCred,
- removeA2AOutboundCredential: mocks.removeCred,
- setA2AAgentCredential: mocks.setCred,
- listA2AInboundTokens: mocks.listInbound,
- createA2AInboundToken: mocks.createInbound,
- removeA2AInboundToken: mocks.removeInbound,
- listA2ATasksOwner: mocks.tasksOwner,
- resolveA2ACredentialBinding: mocks.resolveBinding,
- listA2ALocalSessions: mocks.localSessions,
- resolveA2ALocalSession: mocks.localResolve,
- handoffA2ALocalSession: mocks.localHandoff,
- spawnA2ALocalSubagent: mocks.localSpawn,
-}));
-vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit, readAuditTail: mocks.auditTail }));
-vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rate }));
-vi.mock("@/lib/host/request-api", () => ({
- readJson: async (req: Request) => req.json().catch(() => null),
-}));
-vi.mock("@/lib/mcp/capability-runtime", () => ({
- msoCapabilityRuntime: { list: () => [], invoke: vi.fn(async () => ({ content: [] })) },
-}));
-
-const { GET, POST } = await import("./route");
-const post = (body: object) =>
- new NextRequest("http://localhost/api/v1/a2a", {
- method: "POST",
- body: JSON.stringify(body),
- headers: { "content-type": "application/json" },
- });
-
-beforeEach(() => {
- vi.clearAllMocks();
- mocks.rate.mockReturnValue(false);
- mocks.resolve.mockResolvedValue({ card: { name: "Peer" } });
- mocks.list.mockResolvedValue([]);
- mocks.listCreds.mockResolvedValue([]);
- mocks.listInbound.mockResolvedValue([]);
- mocks.tasksOwner.mockResolvedValue([]);
- mocks.auditTail.mockResolvedValue([]);
- mocks.resolveBinding.mockReturnValue({});
- mocks.localSessions.mockResolvedValue([]);
- mocks.localResolve.mockResolvedValue({ id: "local-session", title: "bece" });
- mocks.localHandoff.mockResolvedValue({
- session: { id: "local-session", title: "bece" },
- task: { id: "local-task", artifacts: [] },
- });
- mocks.localSpawn.mockResolvedValue({
- session: { id: "child-session", title: "reviewer" },
- task: { id: "child-task", artifacts: [] },
- });
-});
+import { describe, expect, it } from "vitest";
+import { GET, mocks, POST, post } from "./route-fixture";
describe("A2A CLI API", () => {
it("lists and discovers agents", async () => {
@@ -167,112 +68,4 @@ describe("A2A CLI API", () => {
expect(mocks.handoff.mock.calls[0][1]).toBe("research");
expect(mocks.handoff.mock.calls[0][2]).toBe("only this");
});
- it("returns owner A2A state without credential secrets and manages profiles", async () => {
- mocks.list.mockResolvedValue([
- {
- id: "peer-1",
- alias: "peer",
- card: { securitySchemeNames: [], securitySchemes: {} },
- },
- ]);
- mocks.listCreds.mockResolvedValue([
- { id: "cred-1", agentId: "peer-1", label: "prod", kind: "bearer" },
- ]);
- const state = await (
- await GET(new NextRequest("http://localhost/api/v1/a2a?action=state"))
- ).json();
- expect(state.credentials[0]).not.toHaveProperty("secret");
- mocks.createCred.mockResolvedValue({
- id: "cred-2",
- agentId: "peer-1",
- label: "new",
- kind: "bearer",
- });
- mocks.setCred.mockResolvedValue({
- id: "peer-1",
- credentialProfileId: "cred-2",
- });
- const created = await POST(
- post({
- action: "credential-create",
- agentId: "peer-1",
- label: "new",
- kind: "bearer",
- secret: "top-secret",
- }),
- );
- expect(created.status).toBe(200);
- expect(mocks.createCred).toHaveBeenCalledWith(
- expect.objectContaining({ secret: "top-secret" }),
- );
- expect(mocks.audit.mock.calls.flat().join(" ")).not.toContain("top-secret");
- mocks.createInbound.mockResolvedValue({
- token: "mso_a2a_once",
- profile: { id: "in-1", label: "peer", scope: "read" },
- });
- const inbound = await (
- await POST(
- post({ action: "inbound-token-create", label: "peer", scope: "read" }),
- )
- ).json();
- expect(inbound.token).toBe("mso_a2a_once");
- });
- it("routes same-host session list, handoff, spawn, and inbox without exposing credentials", async () => {
- mocks.localSessions.mockResolvedValue([
- { id: "local-session", title: "bece", cwd: "/srv/bece" },
- ]);
- const listed = await (
- await GET(
- new NextRequest("http://localhost/api/v1/a2a?action=local-sessions"),
- )
- ).json();
- expect(listed.sessions[0].title).toBe("bece");
-
- const handoff = await POST(
- post({
- action: "local-handoff",
- sessionRef: "bece",
- objective: "review this",
- }),
- );
- expect(handoff.status).toBe(200);
- expect(mocks.localHandoff).toHaveBeenCalledWith(
- "bece",
- "review this",
- expect.objectContaining({ list: expect.any(Function), invoke: expect.any(Function) }),
- );
-
- const spawn = await POST(
- post({
- action: "local-spawn",
- sourceSessionRef: "bece",
- objective: "audit this",
- title: "reviewer",
- }),
- );
- expect(spawn.status).toBe(200);
- expect(mocks.localSpawn).toHaveBeenCalledWith(
- expect.objectContaining({
- ownerPrincipal: "cli:cli-test",
- sourceSessionRef: "bece",
- objective: "audit this",
- title: "reviewer",
- }),
- );
-
- mocks.tasksOwner.mockResolvedValue([
- { id: "for-bece", targetSessionId: "local-session" },
- { id: "other", targetSessionId: "other-session" },
- ]);
- const inbox = await (
- await GET(
- new NextRequest(
- "http://localhost/api/v1/a2a?action=local-inbox&session=bece",
- ),
- )
- ).json();
- expect(inbox.tasks).toEqual([
- { id: "for-bece", targetSessionId: "local-session" },
- ]);
- });
});
diff --git a/architecture.boundaries.json b/architecture.boundaries.json
index d9486c87..1c128062 100644
--- a/architecture.boundaries.json
+++ b/architecture.boundaries.json
@@ -3,7 +3,7 @@
"ratchets": {
"structuralCycles": 0,
"crossDomainCycles": 0,
- "filesOver220": 54,
+ "filesOver220": 43,
"filesOver500": 0,
"serverFrontendImports": 0,
"appshellSelfBarrelImports": 0,
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index ef517d7c..b64d388a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `settings` clarify MCP navigation and enforce zero-warning tests
- persist the ready tunnel process identity after launcher exec
- reject login redirects normalized into external destinations
- isolate legacy browser credentials and close scanner findings
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 01cb928d..3e23a025 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -31,6 +31,10 @@ bun run audit:strict # fail closed on missing/malformed dependency evide
bun run security:ultimate # release assurance: independent scanners + component security review + DAST
```
+The supported full-test host is Linux with Docker available. Provision the local-only fixture image once with `bun run forge:sandbox` before running `bun run verify`; missing sandbox prerequisites now fail the Forge tests instead of skipping them. Secret-path tests create disposable synthetic home/app directories and never read or create production `.env.local`.
+
+`bun run lint` accepts zero warnings. Unit/integration suites contain no conditional skips. The four HTTP smoke tests belong to the explicit production suite (`E2E_BASE_URL=http://host:port bun run smoke`); missing configuration fails, and every required release journey runs them against its built synthetic server before browser checks.
+
The **committed source of truth** for pre-push policy is `scripts/gates.sh`. The
actual `.git/hooks/pre-push` file is an intentionally tiny untracked shim; reinstall it
idempotently with `bash scripts/gates.sh --install`.
diff --git a/docs/MCP.md b/docs/MCP.md
index 0cc6ad6e..61cfce00 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -18,6 +18,12 @@ It is **off by default**. While `OS_MCP_ENABLED` is unset, `/mcp` and both OAuth
discovery documents return 404. There is no MCP surface at all, not an
unauthenticated one.
+## Settings navigation
+
+Settings → MCP opens a task index: **Connect an app**, **Connected apps**, **Recent activity**, **Tools & updates**, and **Connection details**. Setup first asks for the client and shows only that client's steps. Use **MCP overview** to return; technical OAuth/tunnel fields live under Connection details. Connected apps separates active access from expired/revoked history and confirms disconnection. Tools & updates stores only a browser-local refresh reminder, never a verified client-health claim.
+
+Anonymous visitors see an Owner sign-in entry, not private API requests or an endless loading state. Failed settings/activity loads expose a retry action; activity failures never become an empty-success state. The public `/settings?section=mcp` deep link returns sign-in users to MCP.
+
## Turn it on
```bash
@@ -672,7 +678,7 @@ lib/mcp/tools-learning.ts one-call bootstrap + start / cancel / finish
lib/mcp/tools-power.ts apps_power + browser_power
lib/mcp/tools-infra.ts provider status/doctor + bounded Dokploy/Cloudflare/Hostinger operations
lib/mcp/toolset.ts server/toolset version, schema hash and scoped manifest
-lib/mcp/tools.ts fs write tier and the assembled catalog
+lib/mcp/tools.ts assembled catalog (write/exec declarations: tools-mutate.ts)
lib/mcp/activity.ts workflow-correlated live activity
lib/mcp/dispatch.ts JSON-RPC, scope checks, metadata, activity + recipe capture
lib/host/projects.ts project resolution across every container, plus aliases
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 20175156..dd4e9796 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,9 @@
+## 2026-09-09 — Zero-warning quality gate and layered MCP settings
+
+User review found MCP confusing despite the earlier release. Live public inspection reproduced an endless MCP loading placeholder after unauthorized access. Owner setup mixed client guides, transport details, access tokens, catalog signatures and audit activity in one scroll. MCP now starts with a task index and drills into client selection then one guide. Connection details, connected-app management, audit and tools each have a separate view and explicit return path. Signed-out users get a direct Owner login preserving the MCP destination; delegated users retain the Owner boundary. Requests are bounded and failed activity never masquerades as no events. Disconnection requires an inline confirmation; active access and expired/revoked history are separated. Refresh acknowledgement explicitly remains a browser-local reminder. Settings icons use theme tokens; navigation and copy targets are larger and clipboard failures are visible. Manual OAuth copy now matches the implemented one-hour access / rotating refresh contract.
+
+All eleven file-length warnings are resolved by responsibility-based extraction, including session creation/mutation/summary, filesystem credential/recursive policy, write/exec catalog declarations, CLI local commands/help, device locking, widgets, and focused test suites. Filesystem containment checks remain in their original sink branches. The lint release gate accepts zero warnings and the physical-line architecture ratchet is reduced. Secret tests use real disposable synthetic files; Forge Docker tests execute unconditionally with the official locally built sandbox. Four live HTTP smoke tests run as a required separate production suite inside release verification and fail on missing configuration. No tests are removed or disabled to get a green report. Browser regression coverage exercises MCP owner/public navigation, client selection, cancel/revoke, error/retry, mobile reflow and automated accessibility.
+
## 2026-09-09 — Audit hardening and required browser release journeys
The audit found outdated security dependencies, implicit command retargeting, historical connection checks presented as current health, and an indirect sign-in path. Patched dependency floors retain the existing stack. Explicit invalid cwd now fails before exec/job/PTY launch; successful one-shot results expose their resolved cwd. Connection doctor pins credentials and records a bounded result for that exact revision; rejected access and unavailable providers no longer display an old green Verified state. Credential rotation and later checks reject stale results.
diff --git a/frontend/slices/appshell/features/widgets/components/timer-widget.tsx b/frontend/slices/appshell/features/widgets/components/timer-widget.tsx
new file mode 100644
index 00000000..2571e56c
--- /dev/null
+++ b/frontend/slices/appshell/features/widgets/components/timer-widget.tsx
@@ -0,0 +1,39 @@
+"use client";
+import { cn } from "@/lib/utils";
+import { Timer as TimerIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { Card } from "./widget-cards";
+const btn = "rounded-lg border border-white/10 bg-black/10 px-2 py-1 text-xs hover:bg-white/10";
+
+// Stopwatch — start/pause/reset. The interval only ticks while running.
+export function TimerWidget() {
+ const [ms, setMs] = useState(0);
+ const [running, setRunning] = useState(false);
+ useEffect(() => {
+ if (!running) return;
+ const t = setInterval(() => setMs((m) => m + 100), 100);
+ return () => clearInterval(t);
+ }, [running]);
+ const s = Math.floor(ms / 1000);
+ const label = `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
+ return (
+ <Card className="pointer-events-auto">
+ <div className="mb-2 flex items-center gap-2">
+ <TimerIcon className="size-4 text-muted-foreground" />
+ <span className="text-[12.5px] font-semibold">Timer</span>
+ <span className="ml-auto font-mono text-lg font-bold tabular-nums">{label}</span>
+ </div>
+ <div className="flex gap-2">
+ <button type="button" onClick={() => setRunning((r) => !r)} className={cn(btn, "flex-1")}>
+ {running ? "Pause" : "Start"}
+ </button>
+ <button type="button" onClick={() => { setRunning(false); setMs(0); }} className={cn(btn, "flex-1")}>
+ Reset
+ </button>
+ </div>
+ </Card>
+ );
+}
+
+// Embeds a URL in an iframe (frameable content only — CSP + the target's
+// X-Frame-Options still apply). URL persists to localStorage.
diff --git a/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx b/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx
index 5d398224..484eb655 100644
--- a/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx
+++ b/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx
@@ -1,13 +1,14 @@
"use client";
-import { useEffect, useState } from "react";
-import { Code2, FileText, Globe, Moon, Palette, Sun, Timer as TimerIcon } from "lucide-react";
-import { setShell, shellsForSurface, useActiveShell, useShellPrefs } from "../../../registry/shells";
-import { useShellAppearance } from "../../../registry/capabilities";
import { cn } from "@/lib/utils";
-import { Card } from "./widget-cards";
-import { mdToHtml } from "./md";
+import { Code2, FileText, Globe, Moon, Palette, Sun } from "lucide-react";
+import { useState } from "react";
+import { useShellAppearance } from "../../../registry/capabilities";
+import { setShell, shellsForSurface, useActiveShell, useShellPrefs } from "../../../registry/shells";
import { safeEmbedUrl } from "./embed-url";
+import { mdToHtml } from "./md";
+import { TimerWidget } from "./timer-widget";
+import { Card } from "./widget-cards";
// VPS-native + content widgets ported from the original shell widget set: a stopwatch,
// a URL embed, a sandboxed-HTML snippet, a markdown note, an active-shell picker,
@@ -20,38 +21,6 @@ const MD_KEY = "mso:widget:markdown";
const ls = (k: string) => (typeof localStorage !== "undefined" ? localStorage.getItem(k) ?? "" : "");
const btn = "rounded-lg border border-white/10 bg-black/10 px-2 py-1 text-xs hover:bg-white/10";
-// Stopwatch — start/pause/reset. The interval only ticks while running.
-function TimerWidget() {
- const [ms, setMs] = useState(0);
- const [running, setRunning] = useState(false);
- useEffect(() => {
- if (!running) return;
- const t = setInterval(() => setMs((m) => m + 100), 100);
- return () => clearInterval(t);
- }, [running]);
- const s = Math.floor(ms / 1000);
- const label = `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
- return (
- <Card className="pointer-events-auto">
- <div className="mb-2 flex items-center gap-2">
- <TimerIcon className="size-4 text-muted-foreground" />
- <span className="text-[12.5px] font-semibold">Timer</span>
- <span className="ml-auto font-mono text-lg font-bold tabular-nums">{label}</span>
- </div>
- <div className="flex gap-2">
- <button type="button" onClick={() => setRunning((r) => !r)} className={cn(btn, "flex-1")}>
- {running ? "Pause" : "Start"}
- </button>
- <button type="button" onClick={() => { setRunning(false); setMs(0); }} className={cn(btn, "flex-1")}>
- Reset
- </button>
- </div>
- </Card>
- );
-}
-
-// Embeds a URL in an iframe (frameable content only — CSP + the target's
-// X-Frame-Options still apply). URL persists to localStorage.
function EmbedWidget() {
const initial = typeof window === "undefined" ? "" : safeEmbedUrl(ls(EMBED_KEY), window.location.origin) ?? "";
const [url, setUrl] = useState(initial);
diff --git a/frontend/slices/os-settings/app.tsx b/frontend/slices/os-settings/app.tsx
index f308e070..6c8acb26 100644
--- a/frontend/slices/os-settings/app.tsx
+++ b/frontend/slices/os-settings/app.tsx
@@ -1,5 +1,7 @@
"use client";
+import { useSearchParams } from "next/navigation";
+import { SECTIONS } from "./lib/sections";
import { useEffect, useState } from "react";
import { useAppearance, effectiveServerTarget } from "@/lib/appearance";
import { useSession } from "@/features/auth";
@@ -14,6 +16,8 @@ import { SettingsShell } from "./components/settings-shell";
// Default export so os-shell can lazy-load it as a window app.
export default function OsSettings() {
+ const params = useSearchParams();
+ const initial = SECTIONS.find(section => section.id === params.get("section"))?.id;
const { tweaks } = useAppearance();
const { status, role } = useSession();
// Shared Settings state stays here; SettingsShell selects the presentation profile.
@@ -23,7 +27,7 @@ export default function OsSettings() {
// On mobile we start on the section list (no selection drilled in); desktop
// always shows a selected pane. `null` = list view, an id = detail view.
const [active, setActive] = useState<SectionId | null>(
- surface === "mobile" ? null : "appearance",
+ initial ?? (surface === "mobile" ? null : "appearance"),
);
const serverTarget = effectiveServerTarget(tweaks.server);
diff --git a/frontend/slices/os-settings/components/ios-settings.tsx b/frontend/slices/os-settings/components/ios-settings.tsx
index 1aabfe40..08f7512f 100644
--- a/frontend/slices/os-settings/components/ios-settings.tsx
+++ b/frontend/slices/os-settings/components/ios-settings.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useMemo, useState } from "react";
-import { ChevronRight, Search } from "lucide-react";
import { cn } from "@/lib/utils";
+import { ChevronRight, Search } from "lucide-react";
+import { useMemo, useState } from "react";
import { filterSettingsSections, groupSettingsSections, settingsSection, type SectionId } from "../lib/sections";
import { SettingsSectionBody } from "./sections";
@@ -65,7 +65,7 @@ function IosSettingsIndex({ onSelect }: { onSelect: (id: SectionId) => void }) {
className="grid size-[31px] shrink-0 place-items-center rounded-[8px] shadow-[0_1px_2px_rgba(0,0,0,0.22)]"
style={{ background: section.color }}
>
- <Icon className="size-[18px] text-white" aria-hidden />
+ <Icon className="size-[18px] text-primary-foreground" aria-hidden />
</span>
<span className="min-w-0 flex-1 truncate text-[17px] font-normal leading-tight text-foreground">{section.label}</span>
<ChevronRight className="size-[17px] shrink-0 text-muted-foreground/55" aria-hidden />
@@ -88,7 +88,7 @@ function IosSettingsDetail({ id }: { id: SectionId }) {
const meta = settingsSection(id);
// Appearance/Theme are control-first. About already has the Manef Shell OS
// identity block, so a second category hero would duplicate its header.
- const showHero = id !== "appearance" && id !== "theme" && id !== "about";
+ const showHero = id !== "appearance" && id !== "theme" && id !== "about" && id !== "mcp";
const Icon = meta.icon;
return (
@@ -97,7 +97,7 @@ function IosSettingsDetail({ id }: { id: SectionId }) {
{showHero && (
<section data-slot="ios-settings-hero" className="rounded-[18px] bg-card px-5 py-6 text-center">
<span className="mx-auto grid size-[64px] place-items-center rounded-[16px] shadow-[0_2px_5px_rgba(0,0,0,0.22)]" style={{ background: meta.color }}>
- <Icon className="size-9 text-white" aria-hidden />
+ <Icon className="size-9 text-primary-foreground" aria-hidden />
</span>
<h1 className="mt-3 text-[24px] font-bold leading-tight tracking-[-0.02em] text-foreground">{meta.label}</h1>
<p className="mx-auto mt-2 max-w-[32rem] text-[16px] leading-[1.35] text-foreground/90">{meta.blurb}</p>
diff --git a/frontend/slices/os-settings/components/mcp-activity.tsx b/frontend/slices/os-settings/components/mcp-activity.tsx
new file mode 100644
index 00000000..42f30588
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-activity.tsx
@@ -0,0 +1,23 @@
+"use client";
+import { Button } from "@/components/ui/button";
+import { useEffect, useState } from "react";
+import { McpAuditSection, type McpAuditRow } from "./mcp-audit-section";
+
+export function McpActivity() {
+ const [result, setResult] = useState<{ entries?: McpAuditRow[]; error?: string } | null>(null);
+ const [attempt, setAttempt] = useState(0);
+ useEffect(() => {
+ let current = true;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 10_000);
+ fetch("/api/v1/sys/audit?actor=mcp%3A&limit=20", { cache: "no-store", signal: controller.signal })
+ .then(async response => { if (!response.ok) throw new Error("Activity could not be loaded."); return response.json(); })
+ .then(data => { if (current) setResult({ entries: data.entries ?? [] }); })
+ .catch(() => { if (current) setResult({ error: "Activity could not be loaded. Try again." }); })
+ .finally(() => clearTimeout(timer));
+ return () => { current = false; clearTimeout(timer); controller.abort(); };
+ }, [attempt]);
+ if (!result) return <p role="status">Loading recent activity…</p>;
+ if (result.error) return <div className="space-y-3"><p role="alert">{result.error}</p><Button onClick={() => setAttempt(value => value + 1)}>Try again</Button></div>;
+ return <McpAuditSection trail={result.entries ?? []} />;
+}
diff --git a/frontend/slices/os-settings/components/mcp-audit-section.tsx b/frontend/slices/os-settings/components/mcp-audit-section.tsx
index 4a444e5a..468064e0 100644
--- a/frontend/slices/os-settings/components/mcp-audit-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-audit-section.tsx
@@ -23,10 +23,10 @@ export function McpAuditSection({ trail }: { trail: McpAuditRow[] }) {
<SettingsBlock className="p-0">
<div className="flex min-h-[46px] items-center justify-between gap-3 border-b border-border/60 px-4 py-2.5">
<div>
- <p className="text-[13px] font-medium">Privileged MCP log</p>
- <p className="text-[10px] text-muted-foreground">Newest events first</p>
+ <p className="text-sm font-medium">Privileged MCP log</p>
+ <p className="text-xs text-muted-foreground">Newest events first</p>
</div>
- <span className="shrink-0 rounded-md bg-secondary px-2 py-1 text-[10px] text-muted-foreground">Latest {trail.length}</span>
+ <span className="shrink-0 rounded-md bg-secondary px-2 py-1 text-xs text-muted-foreground">Latest {trail.length}</span>
</div>
{trail.length === 0 ? (
<div className="grid min-h-32 place-items-center px-4 py-8 text-center text-xs text-muted-foreground">
@@ -42,13 +42,13 @@ export function McpAuditSection({ trail }: { trail: McpAuditRow[] }) {
<li key={`${entry.ts ?? "event"}-${index}`} className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-2.5 gap-y-1 px-4 py-3 sm:grid-cols-[auto_minmax(0,1fr)_auto]">
<StatusIcon className={failed ? "mt-0.5 size-3.5 text-destructive" : "mt-0.5 size-3.5 text-success"} />
<div className="min-w-0">
- <code className={failed ? "font-mono text-[11px] font-medium text-destructive" : "font-mono text-[11px] font-medium"}>{entry.action}</code>
+ <code className={failed ? "font-mono text-sm font-medium text-destructive" : "font-mono text-sm font-medium"}>{entry.action}</code>
{(entry.target || entry.detail) && (
- <p className="mt-0.5 line-clamp-2 break-all font-mono text-[10px] leading-relaxed text-muted-foreground">{entry.target ?? entry.detail}</p>
+ <p className="mt-0.5 line-clamp-2 break-all font-mono text-xs leading-relaxed text-muted-foreground">{entry.target ?? entry.detail}</p>
)}
- {entry.actor && <p className="mt-0.5 truncate text-[10px] text-muted-foreground">{entry.actor}</p>}
+ {entry.actor && <p className="mt-0.5 truncate text-xs text-muted-foreground">{entry.actor}</p>}
</div>
- <time className="col-start-2 shrink-0 text-[10px] text-muted-foreground sm:col-start-3 sm:row-start-1">
+ <time className="col-start-2 shrink-0 text-xs text-muted-foreground sm:col-start-3 sm:row-start-1">
{entry.ts ? new Date(entry.ts).toLocaleString() : ""}
</time>
</li>
diff --git a/frontend/slices/os-settings/components/mcp-client-picker.tsx b/frontend/slices/os-settings/components/mcp-client-picker.tsx
new file mode 100644
index 00000000..ef1e2731
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-client-picker.tsx
@@ -0,0 +1,15 @@
+"use client";
+import { Button } from "@/components/ui/button";
+import { ChevronRight } from "lucide-react";
+import { MCP_CLIENTS, type McpClientId } from "./mcp-client-core";
+export function McpClientPicker({ onSelect }: { onSelect: (client: McpClientId) => void }) {
+ return <section aria-label="Choose an app" className="space-y-3">
+ <h3 className="text-base font-semibold">Which app do you want to connect?</h3>
+ <p className="text-sm text-muted-foreground">Choose one to see only the steps it needs.</p>
+ <div className="divide-y divide-border rounded-xl border border-border bg-card">
+ {MCP_CLIENTS.map(client => <Button key={client.id} variant="ghost" onClick={() => onSelect(client.id)} className="h-auto min-h-16 w-full justify-start gap-3 whitespace-normal rounded-none px-4 py-3 text-left">
+ <span className="min-w-0 flex-1"><span className="block text-sm font-medium">{client.label}</span><span className="mt-1 block text-sm font-normal text-muted-foreground">{client.description}</span></span><ChevronRight className="size-4 shrink-0" aria-hidden />
+ </Button>)}
+ </div>
+ </section>;
+}
diff --git a/frontend/slices/os-settings/components/mcp-client-setup.tsx b/frontend/slices/os-settings/components/mcp-client-setup.tsx
index 49ffe4cb..296019b6 100644
--- a/frontend/slices/os-settings/components/mcp-client-setup.tsx
+++ b/frontend/slices/os-settings/components/mcp-client-setup.tsx
@@ -1,7 +1,6 @@
"use client";
import { Bot, TerminalSquare } from "lucide-react";
-import { cn } from "@/lib/utils";
import { MCP_CLIENTS, type McpClientId, type McpGuideStep } from "./mcp-client-core";
import { McpCopyField } from "./mcp-copy-field";
@@ -10,9 +9,9 @@ type ClientRow = (typeof MCP_CLIENTS)[number];
function StepRow({ number, title, body, copy }: McpGuideStep & { number: number }) {
return (
<div className="flex gap-3">
- <div className="flex size-7 shrink-0 items-center justify-center rounded-full border bg-secondary text-[11px] font-semibold">{number}</div>
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full border bg-secondary text-sm font-semibold">{number}</div>
<div className="min-w-0 flex-1 space-y-2">
- <div><p className="text-[13px] font-medium">{title}</p><p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">{body}</p></div>
+ <div><p className="text-sm font-medium">{title}</p><p className="mt-0.5 text-sm leading-relaxed text-muted-foreground">{body}</p></div>
{copy && <McpCopyField label={copy.label} value={copy.value} multiline={copy.multiline} />}
</div>
</div>
@@ -21,35 +20,18 @@ function StepRow({ number, title, body, copy }: McpGuideStep & { number: number
export function McpClientSetup({
client,
- onClientChange,
selected,
steps,
}: {
client: McpClientId;
- onClientChange: (client: McpClientId) => void;
selected: ClientRow;
steps: McpGuideStep[];
}) {
return (
<>
- <div>
- <p className="text-[13px] font-medium">Client setup</p>
- <p className="mt-0.5 text-[11px] text-muted-foreground">Choose a client to get its remote-MCP shape. Use Other MCP only for clients that explicitly support a Streamable HTTP URL.</p>
- </div>
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
- {MCP_CLIENTS.map((item) => (
- <button key={item.id} type="button" aria-pressed={client === item.id} onClick={() => onClientChange(item.id)} className={cn(
- "min-h-16 rounded-lg border p-2.5 text-left transition-colors [@media(pointer:coarse)]:min-h-[72px]",
- client === item.id ? "border-primary/45 bg-primary/10" : "border-border/70 bg-secondary/25 hover:bg-secondary/50",
- )}>
- <span className="block text-xs font-medium">{item.label}</span>
- <span className="mt-0.5 block text-[10px] leading-snug text-muted-foreground">{item.description}</span>
- </button>
- ))}
- </div>
<div className="flex items-center gap-2 rounded-lg bg-secondary/35 px-3 py-2">
{selected.kind === "cli" ? <TerminalSquare className="size-3.5 shrink-0" /> : <Bot className="size-3.5 shrink-0" />}
- <p className="text-[11px] text-muted-foreground">{selected.label} · {selected.description}</p>
+ <p className="text-sm text-muted-foreground">{selected.label} · {selected.description}</p>
</div>
{client === "chatgpt" && (
<div className="grid gap-3 rounded-lg border border-border/70 bg-secondary/20 p-3 sm:grid-cols-2">
diff --git a/frontend/slices/os-settings/components/mcp-connection-mode.tsx b/frontend/slices/os-settings/components/mcp-connection-mode.tsx
index b8d469be..a93e958a 100644
--- a/frontend/slices/os-settings/components/mcp-connection-mode.tsx
+++ b/frontend/slices/os-settings/components/mcp-connection-mode.tsx
@@ -15,8 +15,8 @@ export function McpConnectionMode({ endpoints, remote }: { endpoints: McpEndpoin
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<div>
- <p className="text-[13px] font-medium">Connection</p>
- <p className="mt-0.5 text-[11px] text-muted-foreground">Use the direct HTTPS URL when this MSO host is reachable; use a tunnel for private or developer-machine deployments.</p>
+ <p className="text-sm font-medium">Connection</p>
+ <p className="mt-0.5 text-sm text-muted-foreground">Use the direct HTTPS URL when this MSO host is reachable; use a tunnel for private or developer-machine deployments.</p>
</div>
<Globe2 className="size-4 shrink-0 text-muted-foreground" />
</div>
@@ -38,10 +38,10 @@ export function McpConnectionMode({ endpoints, remote }: { endpoints: McpEndpoin
</div>
</div>
) : (
- <div className="grid gap-3 sm:grid-cols-2">
+ <div className="grid gap-3 @min-[520px]:grid-cols-2">
<div className="rounded-lg border border-border/70 bg-secondary/25 p-3">
<div className="flex items-center gap-2"><CloudCog className="size-4" /><p className="text-xs font-medium">MSO Gateway</p></div>
- <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">Keep local/WSL MSO on loopback and create an outbound HTTPS gateway. A named tunnel/custom domain is the stable production choice.</p>
+ <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">Keep local/WSL MSO on loopback and create an outbound HTTPS gateway. A named tunnel/custom domain is the stable production choice.</p>
<div className="mt-3 space-y-2">
<McpCopyField label="Temporary gateway" value={'mso gateway start\nmso gateway url'} multiline />
<McpCopyField label="Stable origin" value={`mso gateway domain set ${remote ? endpoints.origin : "https://mso.example.com"}`} />
@@ -49,8 +49,8 @@ export function McpConnectionMode({ endpoints, remote }: { endpoints: McpEndpoin
</div>
<div className="rounded-lg border border-border/70 bg-secondary/25 p-3">
<div className="flex items-center gap-2"><Globe2 className="size-4" /><p className="text-xs font-medium">Custom domain / reverse proxy</p></div>
- <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">For a stable URL, route an HTTPS hostname to the loopback MSO runtime through your trusted tunnel or reverse proxy, then set that same origin in MSO.</p>
- <p className="mt-3 text-[10px] leading-relaxed text-muted-foreground">Keep the raw Next listener loopback-only. OAuth discovery, redirect validation, cookies, and MCP resource metadata must agree on one public origin.</p>
+ <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">For a stable URL, route an HTTPS hostname to the loopback MSO runtime through your trusted tunnel or reverse proxy, then set that same origin in MSO.</p>
+ <p className="mt-3 text-sm leading-relaxed text-muted-foreground">Keep the raw Next listener loopback-only. OAuth discovery, redirect validation, cookies, and MCP resource metadata must agree on one public origin.</p>
</div>
</div>
diff --git a/frontend/slices/os-settings/components/mcp-connection-section.tsx b/frontend/slices/os-settings/components/mcp-connection-section.tsx
index 89a8bf2e..3c1471c0 100644
--- a/frontend/slices/os-settings/components/mcp-connection-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-connection-section.tsx
@@ -1,25 +1,50 @@
"use client";
-import { Wrench } from "lucide-react";
-import { SettingsSection } from "@/features/shell-settings";
-import { McpSetupGuide } from "./mcp-setup-guide";
-import { McpToolsetCard, type McpToolsetInfo } from "./mcp-toolset-card";
+import { Button } from "@/components/ui/button";
+import { SettingsBlock } from "@/features/shell-settings";
+import { RefreshCw } from "lucide-react";
+import { useCallback, useEffect, useState } from "react";
+import { isRemoteMcpOrigin, mcpEndpoints, type McpProbeResult } from "./mcp-client-core";
+import { McpConnectionMode } from "./mcp-connection-mode";
+import { McpCopyField } from "./mcp-copy-field";
+import { probeMcpConnection } from "./mcp-probe";
+import { McpProbeStatus } from "./mcp-probe-status";
-export function McpConnectionSection({
- origin,
- maxScope,
- toolset,
-}: {
- origin: string;
- maxScope: string;
- toolset: McpToolsetInfo;
-}) {
- return (
- <div className="space-y-4 sm:space-y-5">
- <McpSetupGuide origin={origin} maxScope={maxScope} />
- <SettingsSection icon={<Wrench />} title="Toolset status" bare>
- <McpToolsetCard info={toolset} />
- </SettingsSection>
- </div>
- );
+function sameOriginFetch(input: RequestInfo | URL, init?: RequestInit) {
+ const target = new URL(String(input));
+ return fetch(`${target.pathname}${target.search}`, init);
+}
+export function McpConnectionSection({ origin }: { origin: string }) {
+ const [result, setResult] = useState<McpProbeResult | null>(null);
+ const [checking, setChecking] = useState(true);
+ const endpoints = mcpEndpoints(origin);
+ const apply = useCallback((next: McpProbeResult | null) => { setResult(next); setChecking(false); }, []);
+ useEffect(() => {
+ let current = true;
+ probeMcpConnection(origin, sameOriginFetch).then(next => { if (current) apply(next); }).catch(() => { if (current) apply(null); });
+ return () => { current = false; };
+ }, [origin, apply]);
+ async function check() { setChecking(true); apply(await probeMcpConnection(origin, sameOriginFetch).catch(() => null)); }
+ return <div className="space-y-4">
+ <SettingsBlock className="space-y-3 py-4">
+ <McpProbeStatus state={checking ? "checking" : result?.ready ? "ready" : "error"} result={result} endpoint={endpoints.mcp} />
+ <Button variant="secondary" disabled={checking} onClick={() => void check()} className="min-h-11"><RefreshCw className="size-4" />{checking ? "Checking…" : "Check connection"}</Button>
+ </SettingsBlock>
+ <SettingsBlock className="py-4"><McpConnectionMode endpoints={endpoints} remote={isRemoteMcpOrigin(origin)} /></SettingsBlock>
+ <SettingsBlock className="py-4">
+ <details><summary className="min-h-11 cursor-pointer py-3 text-sm font-medium">Manual OAuth configuration</summary>
+ <p className="mb-3 text-sm text-muted-foreground">Only needed if your app asks for individual OAuth endpoints.</p>
+ <div className="grid gap-3 @min-[520px]:grid-cols-2">
+ <McpCopyField label="MCP server URL" value={endpoints.mcp} />
+ <McpCopyField label="Authorization URL" value={endpoints.authorize} />
+ <McpCopyField label="Token URL" value={endpoints.token} />
+ <McpCopyField label="Dynamic registration" value={endpoints.register} />
+ <McpCopyField label="Protected-resource metadata" value={endpoints.protectedResource} />
+ <McpCopyField label="Authorization-server metadata" value={endpoints.authorizationServer} />
+ <McpCopyField label="Public client ID (manual fallback)" value="chatgpt-mso" />
+ </div>
+ <p className="mt-3 text-sm text-muted-foreground">OAuth authorization code with PKCE S256. No client secret. OAuth access tokens last one hour and renew through rotating refresh tokens, which expire after 90 days. Reconnect if renewal fails or access is revoked.</p>
+ </details>
+ </SettingsBlock>
+ </div>;
}
diff --git a/frontend/slices/os-settings/components/mcp-copy-field.tsx b/frontend/slices/os-settings/components/mcp-copy-field.tsx
index fe59dc32..a4b72ea7 100644
--- a/frontend/slices/os-settings/components/mcp-copy-field.tsx
+++ b/frontend/slices/os-settings/components/mcp-copy-field.tsx
@@ -1,31 +1,34 @@
"use client";
-import { useState } from "react";
-import { Check, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+import { Check, Copy } from "lucide-react";
+import { useState } from "react";
export function McpCopyField({ label, value, multiline = false }: { label: string; value: string; multiline?: boolean }) {
+ const [error, setError] = useState(false);
const [copied, setCopied] = useState(false);
return (
<div className="space-y-1.5">
- <span className="text-[11px] font-medium text-muted-foreground">{label}</span>
+ <span className="text-sm font-medium text-muted-foreground">{label}</span>
<div className="flex items-start gap-2 rounded-lg border border-border/70 bg-secondary/45 p-2.5">
- <code className={cn("min-w-0 flex-1 break-all font-mono text-[11px] leading-relaxed text-secondary-foreground", multiline && "whitespace-pre-wrap break-words")}>{value}</code>
+ <code className={cn("min-w-0 flex-1 break-all font-mono text-sm leading-relaxed text-secondary-foreground", multiline && "whitespace-pre-wrap break-words")}>{value}</code>
<Button
type="button"
variant="ghost"
size="icon"
- className="size-8 shrink-0 [@media(pointer:coarse)]:size-11"
+ className="size-11 shrink-0"
aria-label={`Copy ${label}`}
onClick={() => void navigator.clipboard.writeText(value).then(() => {
- setCopied(true);
+ setError(false); setCopied(true);
window.setTimeout(() => setCopied(false), 1500);
- })}
+ }).catch(() => setError(true))}
>
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
</Button>
</div>
+ {error && <p role="alert" className="text-sm text-destructive">Copy was unavailable. Select the text above to copy it manually.</p>}
+ {copied && <span role="status" className="sr-only">Copied {label}</span>}
</div>
);
}
diff --git a/frontend/slices/os-settings/components/mcp-navigation.tsx b/frontend/slices/os-settings/components/mcp-navigation.tsx
new file mode 100644
index 00000000..3e4e636b
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-navigation.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { SettingsBlock } from "@/features/shell-settings";
+import { ArrowLeft, ChevronRight, KeyRound, ListChecks, PlugZap, Settings2, Wrench } from "lucide-react";
+
+export const MCP_PAGES = [
+ { id: "connect", title: "Connect an app", description: "Choose ChatGPT, Claude, Cursor, or another client and follow its setup steps.", icon: PlugZap },
+ { id: "access", title: "Connected apps", description: "Review permissions, last use, and expiry. Disconnect access you no longer need.", icon: KeyRound },
+ { id: "activity", title: "Recent activity", description: "Review the latest actions requested through MCP.", icon: ListChecks },
+ { id: "tools", title: "Tools & updates", description: "Check the server tool catalog and your last client refresh reminder.", icon: Wrench },
+ { id: "connection", title: "Connection details", description: "Server address, reachability checks, tunnels, and manual OAuth settings.", icon: Settings2 },
+] as const;
+export type McpPage = "overview" | (typeof MCP_PAGES)[number]["id"];
+
+export function McpNavigation({ active, onSelect, activeCount }: { active: McpPage; onSelect: (page: McpPage) => void; activeCount: number }) {
+ if (active !== "overview") return (
+ <nav aria-label="MCP navigation" className="flex flex-wrap items-center gap-2 text-sm">
+ <Button variant="ghost" className="min-h-11 px-2" onClick={() => onSelect("overview")}><ArrowLeft className="size-4" /> MCP overview</Button>
+ <ChevronRight className="size-4 text-muted-foreground" aria-hidden />
+ <span aria-current="page">{MCP_PAGES.find(page => page.id === active)?.title}</span>
+ </nav>
+ );
+ return (
+ <nav aria-label="MCP navigation">
+ <SettingsBlock className="!p-0 divide-y divide-border">
+ {MCP_PAGES.map(({ id, title, description, icon: Icon }) => (
+ <Button key={id} variant="ghost" onClick={() => onSelect(id)} className="h-auto min-h-20 w-full justify-start gap-3 whitespace-normal rounded-none px-4 py-4 text-left">
+ <Icon className="size-5 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="min-w-0 flex-1"><span className="block text-sm font-medium">{title}{id === "access" ? ` (${activeCount})` : ""}</span><span className="mt-1 block text-sm font-normal leading-relaxed text-muted-foreground">{description}</span></span>
+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
+ </Button>
+ ))}
+ </SettingsBlock>
+ </nav>
+ );
+}
diff --git a/frontend/slices/os-settings/components/mcp-probe-status.tsx b/frontend/slices/os-settings/components/mcp-probe-status.tsx
index 32317029..96c99b3c 100644
--- a/frontend/slices/os-settings/components/mcp-probe-status.tsx
+++ b/frontend/slices/os-settings/components/mcp-probe-status.tsx
@@ -9,21 +9,21 @@ export type ProbeState = "checking" | "ready" | "error";
export function McpProbeStatus({ state, result, endpoint }: { state: ProbeState; result: McpProbeResult | null; endpoint: string }) {
const ready = state === "ready";
return (
- <div className={cn(
+ <div role="status" aria-live="polite" className={cn(
"space-y-2 rounded-lg border px-3 py-2.5",
ready ? "border-success/30 bg-success/10" : state === "error" ? "border-destructive/30 bg-destructive/10" : "border-border bg-secondary/35",
)}>
<div className="flex items-start gap-2">
{ready ? <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-success" /> : <CircleAlert className="mt-0.5 size-4 shrink-0 text-muted-foreground" />}
<div className="min-w-0">
- <p className="text-xs font-medium">{ready ? "MCP + OAuth discovery ready" : state === "error" ? "One or more connection checks failed" : "Checking MCP + OAuth discovery…"}</p>
- <p className="mt-0.5 break-all font-mono text-[10px] text-muted-foreground">{endpoint}</p>
+ <p className="text-sm font-medium">{ready ? "MCP + OAuth discovery ready" : state === "error" ? "One or more connection checks failed" : "Checking MCP + OAuth discovery…"}</p>
+ <p className="mt-0.5 break-all font-mono text-xs text-muted-foreground">{endpoint}</p>
</div>
</div>
{result && (
<div className="flex flex-wrap gap-1.5 pl-6">
{result.checks.map((check) => (
- <span key={check.id} className={cn("rounded-md px-2 py-1 text-[10px] font-medium", check.ok ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive")}>{MCP_PROBE_LABELS[check.id]}</span>
+ <span key={check.id} className={cn("rounded-md px-2 py-1 text-xs font-medium", check.ok ? "bg-success/10 text-success" : "bg-destructive/10 text-destructive")}>{check.ok ? "Ready: " : "Failed: "}{MCP_PROBE_LABELS[check.id]}</span>
))}
</div>
)}
diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsx
index 79a4d30f..3492e6ed 100644
--- a/frontend/slices/os-settings/components/mcp-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-section.tsx
@@ -1,107 +1,64 @@
"use client";
+import Link from "next/link";
-import { useCallback, useEffect, useState } from "react";
-import { Plug } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { useSession } from "@/features/auth";
import { SettingsBlock, SettingsSection } from "@/features/shell-settings";
-import { toast } from "@/features/appshell";
import { IS_DEMO } from "@/lib/demo";
-import { McpAuditSection, type McpAuditRow } from "./mcp-audit-section";
+import { Lock, Plug } from "lucide-react";
+import { useRef, useState } from "react";
+import { McpActivity } from "./mcp-activity";
import { McpConnectionSection } from "./mcp-connection-section";
-import { McpTokenSection, type McpTokenRow } from "./mcp-token-section";
-import type { McpToolsetInfo } from "./mcp-toolset-card";
import { McpCopyField } from "./mcp-copy-field";
-
-type McpState = {
- enabled: boolean;
- maxScope: string;
- toolset: McpToolsetInfo;
- tokens: McpTokenRow[];
- origin: string;
-};
+import { McpNavigation, type McpPage } from "./mcp-navigation";
+import { McpSetupGuide } from "./mcp-setup-guide";
+import { useMcpState } from "./mcp-state";
+import { McpTokenSection } from "./mcp-token-section";
+import { McpToolsetCard } from "./mcp-toolset-card";
export function McpSection() {
- const [state, setState] = useState<McpState | null>(null);
- const [trail, setTrail] = useState<McpAuditRow[]>([]);
-
- const load = useCallback(() => {
- if (IS_DEMO) return;
- fetch("/api/mcp/tokens", { cache: "no-store" })
- .then((response) => (response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`))))
- .then((next: McpState) => {
- setState(next);
- })
- .catch(() => toast("Couldn't load MCP tokens", { tone: "error" }));
-
- fetch("/api/v1/sys/audit?actor=mcp%3A&limit=20", { cache: "no-store" })
- .then((response) => (response.ok ? response.json() : { entries: [] }))
- .then((data: { entries?: McpAuditRow[] }) => setTrail(data.entries ?? []))
- .catch(() => setTrail([]));
- }, []);
-
- useEffect(load, [load]);
-
- async function revoke(id: string, what: string) {
- const response = await fetch(`/api/mcp/tokens?id=${encodeURIComponent(id)}`, { method: "DELETE" });
- if (!response.ok) {
- toast(`Couldn't revoke ${what}`, { tone: "error" });
- return;
- }
- toast(`Revoked ${what}. Any client using it is cut off now.`);
- load();
- }
-
- if (IS_DEMO) {
- return (
- <SettingsSection icon={<Plug />} title="MCP connection">
- <SettingsBlock className="space-y-1.5 py-4">
- <p className="text-sm font-medium">MCP is unavailable in demo mode</p>
- <p className="text-xs leading-relaxed text-muted-foreground">Connect to a live MSO host to configure OAuth, inspect tokens, and review MCP activity.</p>
- </SettingsBlock>
- </SettingsSection>
- );
- }
-
- if (!state) {
- return (
- <SettingsSection icon={<Plug />} title="MCP connection">
- <SettingsBlock>
- <div className="space-y-2" aria-live="polite">
- <div className="h-4 w-40 animate-pulse rounded bg-secondary" />
- <div className="h-3 w-3/4 animate-pulse rounded bg-secondary/70" />
- </div>
- </SettingsBlock>
- </SettingsSection>
- );
- }
+ const { status, role } = useSession();
+ if (status === "loading") return <p role="status" className="text-sm">Checking access…</p>;
+ if (IS_DEMO || status !== "in" || role !== "owner") return (
+ <SettingsSection icon={<Lock />} title="Connect your AI apps to MSO">
+ <SettingsBlock className="space-y-3 py-4">
+ <p className="text-sm leading-relaxed">MCP lets apps such as ChatGPT and Cursor use this server with the permissions you approve.</p>
+ <p className="text-sm text-muted-foreground">{IS_DEMO ? "MCP configuration is unavailable in this demo." : status === "in" ? "An Owner device is required to manage these connections." : "Sign in as Owner to connect an app, review its access, or check recent activity."}</p>
+ {!IS_DEMO && status !== "in" && <Button asChild className="min-h-11"><Link prefetch={false} href="/login?returnTo=%2Fsettings%3Fsection%3Dmcp">Sign in to manage MCP</Link></Button>}
+ </SettingsBlock>
+ </SettingsSection>
+ );
+ return <OwnerMcpSection />;
+}
- if (!state.enabled) {
- return (
- <SettingsSection
- icon={<Plug />}
- title="MCP connection"
- footnote="When disabled, the MCP endpoint and OAuth discovery documents return 404, so no unauthenticated MCP surface remains exposed."
- >
- <SettingsBlock className="space-y-3 py-4">
- <div>
- <p className="text-sm font-medium">Turn on MCP first</p>
- <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
- Add these values to <code className="font-mono">.env.local</code>. Start with read access; raise the ceiling only when you actually need writes or host execution.
- </p>
- </div>
- <McpCopyField label="Recommended starting config" value={"OS_MCP_ENABLED=1\nOS_MCP_MAX_SCOPE=read"} multiline />
- <p className="text-xs leading-relaxed text-muted-foreground">
- Apply it with <code className="font-mono">mso update --rebuild</code>. On WSL without systemd, MSO still rebuilds locally; reopen with <code className="font-mono">mso web</code> afterward.
- </p>
- </SettingsBlock>
- </SettingsSection>
- );
+function OwnerMcpSection() {
+ const { state, error, reload } = useMcpState();
+ const [page, setPage] = useState<McpPage>("overview");
+ const top = useRef<HTMLDivElement>(null);
+ function navigate(next: McpPage) {
+ setPage(next);
+ requestAnimationFrame(() => { top.current?.focus(); top.current?.scrollIntoView({ block: "nearest" }); });
}
-
+ if (error) return <SettingsBlock className="space-y-3"><p role="alert" className="text-sm">{error}</p><Button variant="secondary" onClick={reload}>Try again</Button><Button asChild variant="ghost"><Link prefetch={false} href="/login?returnTo=%2Fsettings%3Fsection%3Dmcp">Sign in</Link></Button></SettingsBlock>;
+ if (!state) return <SettingsBlock><p role="status" className="text-sm">Loading MCP settings…</p></SettingsBlock>;
+ if (!state.enabled) return (
+ <SettingsSection icon={<Plug />} title="MCP is off">
+ <SettingsBlock className="space-y-3 py-4">
+ <p className="text-sm">Enable MCP on this host before connecting an AI app.</p>
+ <McpCopyField label="Starting configuration in .env.local" value={"OS_MCP_ENABLED=1\nOS_MCP_MAX_SCOPE=read"} multiline />
+ <p className="text-sm text-muted-foreground">Apply with <code>mso update --rebuild</code>. Start with read access and expand permissions only when needed.</p>
+ </SettingsBlock>
+ </SettingsSection>
+ );
return (
- <div className="space-y-4 sm:space-y-5">
- <McpConnectionSection origin={state.origin} maxScope={state.maxScope} toolset={state.toolset} />
- <McpTokenSection tokens={state.tokens} onRevoke={revoke} />
- <McpAuditSection trail={trail} />
+ <div ref={top} tabIndex={-1} data-slot="mcp-page" className="space-y-4 outline-none">
+ {page === "overview" && <p className="text-sm leading-relaxed text-muted-foreground">Connect an AI app to this server, then manage its access here. Each app receives only the permissions you approve.</p>}
+ <McpNavigation active={page} onSelect={navigate} activeCount={state.tokens.filter(token => token.status === "active").length} />
+ {page === "connect" && <McpSetupGuide origin={state.origin} maxScope={state.maxScope} />}
+ {page === "connection" && <McpConnectionSection origin={state.origin} />}
+ {page === "access" && <McpTokenSection tokens={state.tokens} onChanged={reload} onConnect={() => navigate("connect")} />}
+ {page === "activity" && <McpActivity />}
+ {page === "tools" && <McpToolsetCard info={state.toolset} />}
</div>
);
}
diff --git a/frontend/slices/os-settings/components/mcp-setup-guide.tsx b/frontend/slices/os-settings/components/mcp-setup-guide.tsx
index bc115386..432e3185 100644
--- a/frontend/slices/os-settings/components/mcp-setup-guide.tsx
+++ b/frontend/slices/os-settings/components/mcp-setup-guide.tsx
@@ -1,96 +1,20 @@
"use client";
-
-import { useCallback, useEffect, useMemo, useState } from "react";
-import { Bot, PlugZap, RefreshCw, ShieldCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { SettingsBlock, SettingsSection } from "@/features/shell-settings";
-import { cn } from "@/lib/utils";
+import { ArrowLeft, PlugZap } from "lucide-react";
+import { useState } from "react";
+import { MCP_CLIENTS, type McpClientId } from "./mcp-client-core";
+import { McpClientPicker } from "./mcp-client-picker";
import { McpClientSetup } from "./mcp-client-setup";
-import { MCP_CLIENTS, isRemoteMcpOrigin, mcpEndpoints, type McpClientId, type McpProbeResult } from "./mcp-client-core";
-import { probeMcpConnection } from "./mcp-probe";
import { mcpClientSteps } from "./mcp-client-steps";
-import { McpConnectionMode } from "./mcp-connection-mode";
-import { McpCopyField } from "./mcp-copy-field";
-import { McpProbeStatus, type ProbeState } from "./mcp-probe-status";
-
-function sameOriginFetch(input: RequestInfo | URL, init?: RequestInit) {
- const target = new URL(String(input));
- return fetch(`${target.pathname}${target.search}`, init);
-}
export function McpSetupGuide({ origin, maxScope }: { origin: string; maxScope: string }) {
- const [client, setClient] = useState<McpClientId>("chatgpt");
- const [probeState, setProbeState] = useState<ProbeState>("checking");
- const [probeResult, setProbeResult] = useState<McpProbeResult | null>(null);
- const endpoints = useMemo(() => mcpEndpoints(origin), [origin]);
- const steps = useMemo(() => mcpClientSteps(client, origin), [client, origin]);
- const selected = MCP_CLIENTS.find((item) => item.id === client) ?? MCP_CLIENTS[0];
-
- const applyProbe = useCallback((result: McpProbeResult | null) => {
- setProbeResult(result);
- setProbeState(result?.ready ? "ready" : "error");
- }, []);
-
- const testConnection = useCallback(async () => {
- setProbeState("checking");
- setProbeResult(null);
- applyProbe(await probeMcpConnection(origin, sameOriginFetch).catch(() => null));
- }, [applyProbe, origin]);
-
- useEffect(() => {
- let current = true;
- void probeMcpConnection(origin, sameOriginFetch).then((result) => { if (current) applyProbe(result); }).catch(() => { if (current) applyProbe(null); });
- return () => { current = false; };
- }, [applyProbe, origin]);
-
- return (
- <SettingsSection
- icon={<PlugZap />}
- title="Connect an AI client"
- footnote={<>MSO uses remote Streamable HTTP + OAuth/PKCE. The server ceiling is <strong>{maxScope}</strong>; each authorization can choose a lower scope.</>}
- >
- <SettingsBlock className="space-y-3 py-4">
- <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
- <div className="min-w-0">
- <div className="flex items-center gap-2"><Bot className="size-4 shrink-0" /><p className="text-sm font-medium">Connect MSO to ChatGPT, coding agents, and MCP-capable editors</p></div>
- <p className="mt-1 text-xs leading-relaxed text-muted-foreground">The client receives only the scope you approve. MSO keeps host boundaries, revocation, rate limits, and audit server-side.</p>
- </div>
- <Button type="button" variant="secondary" size="sm" className="min-h-9 shrink-0 [@media(pointer:coarse)]:min-h-[44px]" onClick={() => void testConnection()}>
- <RefreshCw className={cn("mr-1.5 size-3.5", probeState === "checking" && "animate-spin")} />Test connection
- </Button>
- </div>
- <McpProbeStatus state={probeState} result={probeResult} endpoint={endpoints.mcp} />
- </SettingsBlock>
-
- <SettingsBlock className="py-4"><McpConnectionMode endpoints={endpoints} remote={isRemoteMcpOrigin(origin)} /></SettingsBlock>
-
- <SettingsBlock className="space-y-4 py-4">
- <McpClientSetup client={client} onClientChange={setClient} selected={selected} steps={steps} />
- </SettingsBlock>
-
- <SettingsBlock className="space-y-3 py-4">
- <details className="group rounded-lg border border-border/70 bg-secondary/25 px-3 py-2.5">
- <summary className="cursor-pointer select-none text-xs font-medium">Advanced OAuth settings</summary>
- <div className="mt-3 grid gap-3 sm:grid-cols-2">
- <McpCopyField label="MCP Server URL / Resource" value={endpoints.mcp} />
- <McpCopyField label="Authorization URL" value={endpoints.authorize} />
- <McpCopyField label="Token URL" value={endpoints.token} />
- <McpCopyField label="Dynamic registration" value={endpoints.register} />
- <McpCopyField label="Protected-resource metadata" value={endpoints.protectedResource} />
- <McpCopyField label="Authorization-server metadata" value={endpoints.authorizationServer} />
- <McpCopyField label="Public Client ID (manual fallback)" value="chatgpt-mso" />
- <McpCopyField label="Authentication" value="OAuth · authorization_code · PKCE S256" />
- </div>
- <p className="mt-3 text-[11px] leading-relaxed text-muted-foreground">Client secret: none · token endpoint auth: none · access-token TTL: 90 days · refresh token: not issued · reconnect after expiry/revocation.</p>
- </details>
- <div className="flex gap-2 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2.5">
- <ShieldCheck className="mt-0.5 size-4 shrink-0" />
- <div className="text-xs leading-relaxed">
- <p className="font-medium">Choose the lowest authority that works</p>
- <p className="mt-0.5 text-muted-foreground"><strong>read</strong> inspects data, <strong>write</strong> can change files/apps, and <strong>exec</strong> can execute host commands as the MSO service user. Treat exec like remote shell access.</p>
- </div>
- </div>
- </SettingsBlock>
- </SettingsSection>
- );
+ const [client, setClient] = useState<McpClientId | null>(null);
+ if (!client) return <McpClientPicker onSelect={setClient} />;
+ const selected = MCP_CLIENTS.find(item => item.id === client)!;
+ return <SettingsSection icon={<PlugZap />} title={`Connect ${selected.label}`}>
+ <Button variant="ghost" className="min-h-11" onClick={() => setClient(null)}><ArrowLeft className="size-4" /> Choose another app</Button>
+ <SettingsBlock className="space-y-4 py-4"><McpClientSetup client={client} selected={selected} steps={mcpClientSteps(client, origin)} /></SettingsBlock>
+ <p className="text-sm leading-relaxed text-muted-foreground">Choose the access your app needs when approving the connection: <strong>read</strong> inspects data, <strong>write</strong> changes data, and <strong>exec</strong> runs host commands. This server allows up to <strong>{maxScope}</strong>.</p>
+ </SettingsSection>;
}
diff --git a/frontend/slices/os-settings/components/mcp-state.ts b/frontend/slices/os-settings/components/mcp-state.ts
new file mode 100644
index 00000000..26c84f21
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-state.ts
@@ -0,0 +1,28 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import type { McpTokenRow } from "./mcp-token-section";
+import type { McpToolsetInfo } from "./mcp-toolset-card";
+
+export type McpState = { enabled: boolean; maxScope: string; toolset: McpToolsetInfo; tokens: McpTokenRow[]; origin: string };
+export function useMcpState() {
+ const [state, setState] = useState<McpState | null>(null);
+ const [error, setError] = useState("");
+ const [attempt, setAttempt] = useState(0);
+ const reload = useCallback(() => setAttempt(value => value + 1), []);
+ useEffect(() => {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 10_000);
+ let current = true;
+ fetch("/api/mcp/tokens", { cache: "no-store", signal: controller.signal })
+ .then(async response => {
+ if (!response.ok) throw new Error(response.status === 401 || response.status === 403 ? "Owner access is required. Sign in again to manage MCP." : "MCP settings could not be loaded. Check the connection and try again.");
+ return response.json() as Promise<McpState>;
+ })
+ .then(next => { if (current) { setState(next); setError(""); } })
+ .catch(reason => { if (current) setError(controller.signal.aborted ? "The request timed out. Try again." : String(reason.message)); })
+ .finally(() => clearTimeout(timer));
+ return () => { current = false; clearTimeout(timer); controller.abort(); };
+ }, [attempt]);
+ return { state, error, reload };
+}
diff --git a/frontend/slices/os-settings/components/mcp-token-section.tsx b/frontend/slices/os-settings/components/mcp-token-section.tsx
index 055c87ba..a73ff92d 100644
--- a/frontend/slices/os-settings/components/mcp-token-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-token-section.tsx
@@ -1,78 +1,57 @@
"use client";
-import { KeyRound } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { SettingsActionRow, SettingsBlock, SettingsSection } from "@/features/shell-settings";
+import { SettingsBlock, SettingsSection } from "@/features/shell-settings";
+import { KeyRound } from "lucide-react";
+import { useState } from "react";
export type McpTokenRow = {
- id: string;
- label: string;
- clientId: string;
- scope: string;
- createdAt: number;
- expiresAt: number;
- lastUsedAt?: number;
- status: "active" | "revoked" | "expired";
+ id: string; label: string; clientId: string; scope: string; createdAt: number;
+ expiresAt: number; lastUsedAt?: number; status: "active" | "revoked" | "expired";
};
+const formatTime = (time?: number) => time ? new Date(time).toLocaleString() : "Never";
+const permissions: Record<string, string> = { read: "Read data", write: "Read and change data", exec: "Run host commands" };
-const formatTime = (time?: number) => (time ? new Date(time).toLocaleString() : "Never");
-
-export function McpTokenSection({
- tokens,
- onRevoke,
-}: {
- tokens: McpTokenRow[];
- onRevoke: (id: string, what: string) => Promise<void>;
-}) {
- const live = tokens.filter((token) => token.status === "active");
- return (
- <SettingsSection
- icon={<KeyRound />}
- title={`Access tokens (${tokens.length})`}
- footnote="Tokens are stored as hashes; the raw value is shown once when minted. Revocation is checked on every MCP call."
- >
- {tokens.length === 0 ? (
- <SettingsBlock className="py-4">
- <p className="text-xs leading-relaxed text-muted-foreground">No tokens yet. One is minted after you approve a client on the OAuth consent screen.</p>
- </SettingsBlock>
- ) : (
- tokens.map((token) => {
- const inactive = token.status !== "active";
- return (
- <SettingsBlock key={token.id} className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center">
- <div className="min-w-0 flex-1 space-y-1">
- <div className="flex flex-wrap items-center gap-1.5">
- <span className={inactive ? "text-sm font-medium text-muted-foreground line-through" : "text-sm font-medium"}>{token.label}</span>
- <span className="rounded-md bg-secondary px-2 py-0.5 font-mono text-[10px]">{token.scope}</span>
- {inactive && <span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">{token.status}</span>}
- </div>
- <p className="break-all font-mono text-[10px] leading-relaxed text-muted-foreground">{token.clientId}</p>
- <p className="text-[11px] leading-relaxed text-muted-foreground">
- Last used {formatTime(token.lastUsedAt)} · expires {formatTime(token.expiresAt)}
- </p>
- </div>
- {!inactive && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="min-h-9 shrink-0 self-end text-destructive sm:self-auto [@media(pointer:coarse)]:min-h-[44px]"
- onClick={() => void onRevoke(token.id, token.label)}
- >
- Revoke
- </Button>
- )}
- </SettingsBlock>
- );
- })
- )}
- {live.length > 0 && (
- <SettingsActionRow
- label={`Revoke all (${live.length})`}
- tone="destructive"
- onClick={() => void onRevoke("all", `all ${live.length} live token(s)`)}
- />
- )}
- </SettingsSection>
- );
+export function McpTokenSection({ tokens, onChanged, onConnect }: { tokens: McpTokenRow[]; onChanged: () => void; onConnect: () => void }) {
+ const [pending, setPending] = useState<{ id: string; label: string } | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [showInactive, setShowInactive] = useState(false);
+ const active = tokens.filter(token => token.status === "active");
+ const visible = showInactive ? tokens : active;
+ async function disconnect() {
+ if (!pending || busy) return;
+ setBusy(true); setError("");
+ try {
+ const response = await fetch(`/api/mcp/tokens?id=${encodeURIComponent(pending.id)}`, { method: "DELETE", signal: AbortSignal.timeout(10_000) });
+ if (!response.ok) throw new Error("Disconnect failed. Your selection is unchanged; try again.");
+ setPending(null); onChanged();
+ } catch { setError("Could not confirm disconnection. Refresh the list to check access before retrying."); }
+ finally { setBusy(false); }
+ }
+ return <SettingsSection icon={<KeyRound />} title="Connected apps" footnote="Disconnecting revokes the access token immediately. The app must reconnect to regain access.">
+ <SettingsBlock className="flex flex-wrap items-center justify-between gap-3 py-3">
+ <p className="text-sm">{active.length} active connection{active.length === 1 ? "" : "s"}</p>
+ <Button onClick={onConnect} className="min-h-11">Connect an app</Button>
+ </SettingsBlock>
+ {pending && <SettingsBlock className="space-y-3 border border-destructive/30 py-4">
+ <p className="text-sm font-medium">Disconnect {pending.label}?</p>
+ <p className="text-sm text-muted-foreground">Requests using this access will stop working immediately.</p>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <div className="flex flex-wrap gap-2"><Button variant="destructive" disabled={busy} onClick={() => void disconnect()} className="min-h-11">{busy ? "Disconnecting…" : "Confirm disconnect"}</Button><Button variant="secondary" disabled={busy} onClick={() => { setPending(null); setError(""); }} className="min-h-11">Cancel</Button></div>
+ </SettingsBlock>}
+ {visible.length === 0 && <SettingsBlock className="py-4"><p className="text-sm text-muted-foreground">No active connections. Choose “Connect an app” to get started.</p></SettingsBlock>}
+ {visible.map(token => <SettingsBlock key={token.id} className="space-y-3 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0 flex-1"><h3 className="break-words text-sm font-medium">{token.label}</h3><p className="mt-1 text-sm text-muted-foreground">{permissions[token.scope] ?? token.scope} · {token.status}</p></div>
+ {token.status === "active" && <Button variant="outline" disabled={busy} onClick={() => { setPending({ id: token.id, label: token.label }); setError(""); }} className="min-h-11">Disconnect<span className="sr-only"> {token.label}</span></Button>}
+ </div>
+ <p className="text-sm leading-relaxed text-muted-foreground">Last used {formatTime(token.lastUsedAt)}<br />Expires {formatTime(token.expiresAt)}</p>
+ <details><summary className="cursor-pointer py-2 text-sm text-muted-foreground">Client details</summary><p className="break-all font-mono text-xs">{token.clientId}</p></details>
+ </SettingsBlock>)}
+ <div className="flex flex-wrap gap-2">
+ {tokens.length > active.length && <Button variant="ghost" aria-pressed={showInactive} onClick={() => setShowInactive(value => !value)} className="min-h-11">{showInactive ? "Hide" : "Show"} expired & disconnected</Button>}
+ {active.length > 1 && <Button variant="ghost" disabled={busy} onClick={() => setPending({ id: "all", label: `all ${active.length} active connections` })} className="min-h-11 text-destructive">Disconnect all</Button>}
+ </div>
+ </SettingsSection>;
}
diff --git a/frontend/slices/os-settings/components/mcp-toolset-card.tsx b/frontend/slices/os-settings/components/mcp-toolset-card.tsx
index f15a70ef..5a1a0f14 100644
--- a/frontend/slices/os-settings/components/mcp-toolset-card.tsx
+++ b/frontend/slices/os-settings/components/mcp-toolset-card.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useMemo, useState, useSyncExternalStore } from "react";
-import { BadgeCheck, Copy, RefreshCw, Wrench } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { toast } from "@/features/appshell";
+import { BadgeCheck, Copy, RefreshCw, Wrench } from "lucide-react";
+import { useMemo, useState, useSyncExternalStore } from "react";
export type McpToolsetInfo = {
serverVersion: string;
@@ -23,7 +24,7 @@ const subscribeAck = (callback: () => void) => {
window.removeEventListener(ACK_EVENT, callback);
};
};
-const ackSnapshot = () => window.localStorage.getItem(ACK_KEY);
+const ackSnapshot = () => { try { return window.localStorage.getItem(ACK_KEY); } catch { return null; } };
const serverAckSnapshot = () => null;
export function McpToolsetCard({ info }: { info: McpToolsetInfo }) {
@@ -39,35 +40,35 @@ export function McpToolsetCard({ info }: { info: McpToolsetInfo }) {
<Wrench className="mt-0.5 size-4 shrink-0" />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
- <p className="text-sm font-medium">MCP toolset {info.version}</p>
+ <p className="text-sm font-medium">Available tools</p>
<span className="rounded-md bg-secondary px-2 py-0.5 font-mono text-[11px]">{info.toolCount} tools</span>
<span className="font-mono text-[11px] text-muted-foreground">{info.hash}</span>
</div>
<p className="mt-1.5 text-xs leading-relaxed text-muted-foreground">
Server {info.serverVersion} · read {info.byScope.read} · write {info.byScope.write} · exec {info.byScope.exec} · changed {info.changedAt.slice(0, 10)}
</p>
- <p className={`mt-2 text-xs leading-relaxed ${changed ? "text-warning" : "text-muted-foreground"}`}>
+ <p className={`mt-2 text-xs leading-relaxed ${changed ? "text-foreground" : "text-muted-foreground"}`}>
{current
- ? "ChatGPT action snapshot marked current for this browser."
+ ? "You marked this version as refreshed. This is a reminder saved in this browser; it does not verify the app connection."
: changed
? "Toolset signature changed. Refresh or reconnect the MSO app in ChatGPT, then mark it current."
- : "After refreshing the MSO app in ChatGPT, mark this signature current so future drift is visible."}
+ : "If tools are missing in your AI app, refresh or reconnect MSO there. You can then save a reminder below."}
</p>
</div>
- {current ? <BadgeCheck className="size-4 shrink-0 text-success" /> : <RefreshCw className="size-4 shrink-0 text-warning" />}
+ {current ? <BadgeCheck className="size-4 shrink-0 text-success" /> : <RefreshCw className="size-4 shrink-0 text-foreground" />}
</div>
<div className="mt-3 flex flex-col gap-2 sm:flex-row">
<Button
type="button" variant="secondary" size="sm" className="min-h-9 flex-1 text-xs sm:flex-none [@media(pointer:coarse)]:min-h-[44px]"
- onClick={() => { window.localStorage.setItem(ACK_KEY, signature); window.dispatchEvent(new Event(ACK_EVENT)); }}
+ onClick={() => { try { window.localStorage.setItem(ACK_KEY, signature); window.dispatchEvent(new Event(ACK_EVENT)); } catch { toast("This browser could not save the refresh reminder.", { tone: "error" }); } }}
>
- {current ? "Marked refreshed" : "Mark ChatGPT refreshed"}
+ {current ? "Refresh noted" : "I refreshed my AI app"}
</Button>
<Button
type="button" variant="ghost" size="sm" className="min-h-9 flex-1 text-xs sm:flex-none [@media(pointer:coarse)]:min-h-[44px]"
onClick={() => void navigator.clipboard.writeText(signature).then(() => {
setCopied(true); window.setTimeout(() => setCopied(false), 1500);
- })}
+ }).catch(() => toast("Copy unavailable. Select the signature above.", { tone: "error" }))}
>
<Copy className="mr-1 size-3.5" />{copied ? "Copied" : "Copy signature"}
</Button>
diff --git a/frontend/slices/os-settings/components/nav.tsx b/frontend/slices/os-settings/components/nav.tsx
index 4b43fb0d..45a44519 100644
--- a/frontend/slices/os-settings/components/nav.tsx
+++ b/frontend/slices/os-settings/components/nav.tsx
@@ -1,22 +1,22 @@
"use client";
-import { useState } from "react";
-import { Search, Monitor } from "lucide-react";
-import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
+import { Monitor, Search } from "lucide-react";
+import { useState } from "react";
import { filterSettingsSections, groupSettingsSections, SECTIONS, type SectionId } from "../lib/sections";
export type { SectionId } from "../lib/sections";
export function SettingsTabs({ active, onSelect }: { active: SectionId; onSelect: (id: SectionId) => void }) {
return (
- <nav role="tablist" aria-label="Settings" data-slot="settings-desktop-tabs" className="flex gap-1 overflow-x-auto p-2 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
+ <nav aria-label="Settings" data-slot="settings-desktop-tabs" className="flex gap-1 overflow-x-auto p-2 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
{SECTIONS.map(({ id, label, icon: Icon, blurb }) => {
const on = id === active;
return (
- <button key={id} type="button" role="tab" aria-selected={on} title={blurb} onClick={() => onSelect(id)}
- className={cn("flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] font-medium leading-none transition-colors", on ? "bg-primary text-primary-foreground shadow-sm" : "text-muted-foreground hover:bg-accent hover:text-foreground")}
+ <button key={id} type="button" aria-current={on ? "page" : undefined} title={blurb} onClick={() => onSelect(id)}
+ className={cn("flex min-h-11 shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] font-medium leading-none transition-colors", on ? "bg-primary text-primary-foreground shadow-sm" : "text-muted-foreground hover:bg-accent hover:text-foreground")}
>
<Icon className="size-4 shrink-0" />
<span>{label}</span>
@@ -48,10 +48,10 @@ export function SettingsSidebar({ active, onSelect, windows = false }: { active:
{group.map(({ id, label, icon: Icon, color, blurb }) => {
const on = id === active;
return <Button key={id} variant="ghost" aria-current={on ? "page" : undefined} title={blurb} onClick={() => onSelect(id)}
- className={cn("relative h-auto min-h-9 w-full justify-start gap-2.5 rounded-md px-2 py-1.5 text-left text-[13px] font-normal", on ? windows ? "bg-accent text-accent-foreground hover:bg-accent" : "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground" : "text-foreground hover:bg-accent")}>
+ className={cn("relative h-auto min-h-11 w-full justify-start gap-2.5 rounded-md px-2 py-1.5 text-left text-[13px] font-normal", on ? windows ? "bg-accent text-accent-foreground hover:bg-accent" : "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground" : "text-foreground hover:bg-accent")}>
{windows && on && <span className="absolute left-0 h-4 w-[3px] rounded-full bg-primary" />}
<span className={cn("grid shrink-0 place-items-center", windows ? "size-7" : "size-[25px] rounded-md shadow-sm")} style={windows ? undefined : { background: color }}>
- <Icon className={cn("size-4", !windows && "text-white")} />
+ <Icon className={cn("size-4", !windows && "text-primary-foreground")} />
</span>
<span className="min-w-0 flex-1 truncate">{label}</span>
</Button>;
diff --git a/frontend/slices/os-settings/components/sections.tsx b/frontend/slices/os-settings/components/sections.tsx
index 3bb4ebc0..169af547 100644
--- a/frontend/slices/os-settings/components/sections.tsx
+++ b/frontend/slices/os-settings/components/sections.tsx
@@ -1,24 +1,26 @@
"use client";
+import Link from "next/link";
-import { Lock, ShieldCheck } from "lucide-react";
+import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { cn } from "@/lib/utils";
-import { DevicesPanel, useSession } from "@/features/auth";
import { useActiveShell } from "@/features/appshell";
+import { DevicesPanel, useSession } from "@/features/auth";
import { SettingsSection } from "@/features/shell-settings";
+import { cn } from "@/lib/utils";
+import { Lock, ShieldCheck } from "lucide-react";
import { SECTIONS, type SectionId } from "../lib/sections";
-import { AutoLockRow } from "./auto-lock-row";
-import { AppearanceSection } from "./appearance-section";
-import { ThemeSection } from "./theme-section";
+import { A2ASection } from "./a2a-section";
+import { AboutSection } from "./about-section";
import { AiSection } from "./ai-section";
+import { AppearanceSection } from "./appearance-section";
+import { AutoLockRow } from "./auto-lock-row";
+import { BackupSection } from "./backup-section";
+import { CleanupSection } from "./cleanup-section";
+import { McpSection } from "./mcp-section";
import { MemorySection } from "./memory-section";
import { QuicklinksSection } from "./quicklinks-section";
-import { McpSection } from "./mcp-section";
-import { A2ASection } from "./a2a-section";
import { ServerSection } from "./server-section";
-import { CleanupSection } from "./cleanup-section";
-import { BackupSection } from "./backup-section";
-import { AboutSection } from "./about-section";
+import { ThemeSection } from "./theme-section";
// The section content — one functional panel per SectionId, shared verbatim by
// every shell's Settings layout (the per-shell seam only swaps the navigation
@@ -37,6 +39,11 @@ const OWNER_ONLY = new Set<SectionId>([
export function SettingsSectionBody({ id }: { id: SectionId }) {
const { status, role } = useSession();
+ const privateSection = ["a2a", "devices", "cleanup", "ai"].includes(id);
+ if (privateSection && status !== "in") return <SettingsSection icon={<Lock />} title="Sign in to manage this section">
+ <p className="mb-3 text-sm text-muted-foreground">These controls require an Owner device on this server.</p>
+ {status === "loading" ? <p role="status">Checking access…</p> : <Button asChild className="min-h-11"><Link prefetch={false} href="/login?returnTo=%2Fsettings">Sign in</Link></Button>}
+ </SettingsSection>;
if (status === "in" && role !== "owner" && OWNER_ONLY.has(id)) {
return (
<SettingsSection icon={<Lock />} title="Owner access required">
diff --git a/frontend/slices/os-settings/lib/sections.ts b/frontend/slices/os-settings/lib/sections.ts
index ce9e65b2..8cd11728 100644
--- a/frontend/slices/os-settings/lib/sections.ts
+++ b/frontend/slices/os-settings/lib/sections.ts
@@ -1,17 +1,17 @@
-import type { ComponentType } from "react";
import {
- DatabaseBackup,
- Info,
- Link2,
- Paintbrush,
- Palette,
- Plug,
- Network,
- Server,
- ShieldCheck,
- Sparkles,
- Trash2,
+DatabaseBackup,
+Info,
+Link2,
+Network,
+Paintbrush,
+Palette,
+Plug,
+Server,
+ShieldCheck,
+Sparkles,
+Trash2,
} from "lucide-react";
+import type { ComponentType } from "react";
export type SectionId =
| "appearance"
@@ -43,7 +43,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Appearance",
blurb: "Style, accent, wallpaper, device",
icon: Palette,
- color: "#0a84ff",
+ color: "var(--primary)",
group: "personalization",
},
{
@@ -51,7 +51,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Theme",
blurb: "Mode, presets, font, contrast",
icon: Paintbrush,
- color: "#ff375f",
+ color: "var(--primary)",
group: "personalization",
},
{
@@ -59,7 +59,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "AI",
blurb: "Model and API key",
icon: Sparkles,
- color: "#bf5af2",
+ color: "var(--primary)",
group: "services",
},
{
@@ -67,23 +67,23 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Quicklink",
blurb: "Website shortcuts with favicons",
icon: Link2,
- color: "#5e5ce6",
+ color: "var(--primary)",
group: "services",
},
{
id: "mcp",
label: "MCP",
- blurb: "Connect ChatGPT, Cursor & MCP clients",
+ blurb: "Connect ChatGPT, Cursor & AI apps; manage access and activity",
icon: Plug,
- color: "#00c7be",
+ color: "var(--primary)",
group: "services",
},
{
id: "a2a",
label: "A2A",
- blurb: "Agent peers, credentials, tasks & streaming",
+ blurb: "Connect agents and review their tasks",
icon: Network,
- color: "#32ade6",
+ color: "var(--primary)",
group: "services",
},
{
@@ -91,7 +91,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Devices",
blurb: "Approved browsers and sessions",
icon: ShieldCheck,
- color: "#30d158",
+ color: "var(--primary)",
group: "system",
},
{
@@ -99,7 +99,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Server",
blurb: "Mock or live host data",
icon: Server,
- color: "#ff9f0a",
+ color: "var(--primary)",
group: "system",
},
{
@@ -107,7 +107,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Cleanup",
blurb: "Free disk space safely",
icon: Trash2,
- color: "#64d2ff",
+ color: "var(--primary)",
group: "system",
},
{
@@ -115,7 +115,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "Backup",
blurb: "Export or restore browser data",
icon: DatabaseBackup,
- color: "#a2845e",
+ color: "var(--primary)",
group: "system",
},
{
@@ -123,7 +123,7 @@ export const SECTIONS: ReadonlyArray<SettingsSectionMeta> = [
label: "About",
blurb: "System info and reset",
icon: Info,
- color: "#8e8e93",
+ color: "var(--primary)",
group: "system",
},
];
diff --git a/lib/agent/session-create.ts b/lib/agent/session-create.ts
new file mode 100644
index 00000000..17dcd6b5
--- /dev/null
+++ b/lib/agent/session-create.ts
@@ -0,0 +1,109 @@
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { snapshotAgentMemory, type AgentMemorySnapshot } from "./memory-store";
+import { listSessionRecords, newAgentSessionId, principalHash, sessionNameLockTarget } from "./session-files";
+import { normalizeAgentSessionCwd } from "./session-location";
+import { allocateAgentSessionName, requireAgentSessionName } from "./session-name";
+import { MAX_HISTORY, compactThresholdTokens, safeTitle, sessionContextTokens } from "./session-policy";
+import type { AgentSession, AgentSessionEvent, AgentSessionSource, AgentSessionTitleSource } from "./session-types";
+
+export interface CreateOptions {
+ id?: string;
+ name?: string;
+ title?: string;
+ titleSource?: AgentSessionTitleSource;
+ resumedFrom?: string;
+ conversationHash?: string;
+ memorySnapshot?: AgentMemorySnapshot;
+ contextSummary?: string;
+ history?: unknown[];
+ cwd?: string;
+ parentSessionId?: string;
+}
+
+async function buildRecord(
+ principal: string,
+ source: AgentSessionSource,
+ options: CreateOptions,
+): Promise<AgentSession> {
+ const now = new Date().toISOString();
+ const owner = principalHash(principal);
+ const usedNames = (await listSessionRecords())
+ .filter((row) => row.principalHash === owner)
+ .map((row) => row.name);
+ const name = options.name ? requireAgentSessionName(options.name) : allocateAgentSessionName(usedNames);
+ if (usedNames.includes(name)) throw new Error(`session name @${name} is already in use`);
+ const memorySnapshot =
+ options.memorySnapshot ?? (await snapshotAgentMemory(principal));
+ const created: AgentSessionEvent = {
+ at: now,
+ kind: "created",
+ ...(options.resumedFrom
+ ? { detail: `resumed from ${options.resumedFrom}` }
+ : {}),
+ };
+ const record: AgentSession = {
+ id: options.id ?? newAgentSessionId(),
+ principalHash: principalHash(principal),
+ source,
+ name,
+ title: safeTitle(options.title),
+ titleSource: options.titleSource ?? "default",
+ ...(options.conversationHash
+ ? { conversationHash: options.conversationHash }
+ : {}),
+ createdAt: now,
+ updatedAt: now,
+ ...(options.resumedFrom ? { resumedFrom: options.resumedFrom } : {}),
+ ...(normalizeAgentSessionCwd(options.cwd)
+ ? { cwd: normalizeAgentSessionCwd(options.cwd) }
+ : {}),
+ ...(options.parentSessionId
+ ? { parentSessionId: options.parentSessionId }
+ : {}),
+ memorySnapshot,
+ ...(options.contextSummary
+ ? { contextSummary: options.contextSummary }
+ : {}),
+ history: (options.history ?? []).slice(-MAX_HISTORY),
+ events: [created],
+ estimatedTokens: 0,
+ lifetimeEstimatedTokens: 0,
+ compactThresholdTokens: compactThresholdTokens(),
+ compactionCount: 0,
+ archiveCount: 0,
+ };
+ const estimatedTokens = sessionContextTokens(record);
+ return {
+ ...record,
+ estimatedTokens,
+ lifetimeEstimatedTokens: estimatedTokens,
+ };
+}
+
+export async function withUniqueSessionName<T>(
+ principal: string,
+ source: AgentSessionSource,
+ options: CreateOptions,
+ commit: (record: AgentSession) => Promise<T>,
+): Promise<T> {
+ const owner = principalHash(principal);
+ const requested = options.name ? requireAgentSessionName(options.name) : undefined;
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ const used = (await listSessionRecords())
+ .filter((row) => row.principalHash === owner)
+ .map((row) => row.name);
+ const name = requested ?? allocateAgentSessionName(used);
+ try {
+ return await withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
+ const record = await buildRecord(principal, source, { ...options, name });
+ return commit(record);
+ });
+ } catch (error) {
+ const duplicate = error instanceof Error && /session name @.+ is already in use/.test(error.message);
+ if (!requested && duplicate) continue;
+ throw error;
+ }
+ }
+ throw new Error("could not allocate a unique session name");
+}
+
diff --git a/lib/agent/session-mutations.ts b/lib/agent/session-mutations.ts
new file mode 100644
index 00000000..a2bbeaaa
--- /dev/null
+++ b/lib/agent/session-mutations.ts
@@ -0,0 +1,131 @@
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { redactText } from "@/lib/security/redact-text";
+import { listSessionRecords, principalHash, sessionLockTarget, sessionNameLockTarget, writeSessionFile } from "./session-files";
+import { requireAgentSessionName } from "./session-name";
+import { autoSessionTitle, estimateTokens, MAX_EVENTS, MAX_HISTORY, safeTitle } from "./session-policy";
+import { compactIfNeeded, requireOwned } from "./session-record";
+import type { AgentSession, AgentSessionEvent, AgentSessionTitleSource } from "./session-types";
+
+export async function updateAgentSessionHistory(
+ principal: string,
+ id: string,
+ history: unknown[],
+ title?: string,
+ titleSource: AgentSessionTitleSource = "auto",
+): Promise<AgentSession> {
+ return withSecurityStoreLock(sessionLockTarget(id), async () => {
+ let record = await requireOwned(principal, id);
+ const oldTokens = estimateTokens(record.history),
+ newHistory = Array.isArray(history) ? history.slice(-MAX_HISTORY) : [];
+ record.history = newHistory;
+ record.lifetimeEstimatedTokens += Math.max(
+ 0,
+ estimateTokens(newHistory) - oldTokens,
+ );
+ const legacyCliDefault =
+ record.source === "cli" &&
+ record.titleSource === "manual" &&
+ record.title === "MSO Agent session";
+ if (
+ title &&
+ (titleSource === "manual" ||
+ record.titleSource !== "manual" ||
+ legacyCliDefault)
+ ) {
+ record.title = safeTitle(title);
+ record.titleSource = titleSource;
+ }
+ record.updatedAt = new Date().toISOString();
+ record = await compactIfNeeded(record, "context-threshold");
+ await writeSessionFile(record);
+ return record;
+ });
+}
+
+export async function maybeAutoTitleAgentSession(
+ principal: string,
+ id: string,
+ hint: string,
+): Promise<AgentSession | null> {
+ return withSecurityStoreLock(sessionLockTarget(id), async () => {
+ const record = await requireOwned(principal, id);
+ if (record.titleSource === "manual" || record.titleSource === "auto")
+ return record;
+ record.title = autoSessionTitle(hint);
+ record.titleSource = "auto";
+ record.updatedAt = new Date().toISOString();
+ await writeSessionFile(record);
+ return record;
+ });
+}
+
+export async function renameAgentSessionName(
+ principal: string,
+ id: string,
+ value: string,
+): Promise<AgentSession> {
+ const name = requireAgentSessionName(value);
+ const owner = principalHash(principal);
+ return withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
+ const duplicate = (await listSessionRecords()).find((row) =>
+ row.principalHash === owner && row.id !== id && row.name === name,
+ );
+ if (duplicate) throw new Error(`session name @${name} is already in use`);
+ return withSecurityStoreLock(sessionLockTarget(id), async () => {
+ const record = await requireOwned(principal, id);
+ record.name = name;
+ record.updatedAt = new Date().toISOString();
+ await writeSessionFile(record);
+ return record;
+ });
+ });
+}
+
+export async function renameAgentSession(
+ principal: string,
+ id: string,
+ title: string,
+): Promise<AgentSession> {
+ return withSecurityStoreLock(sessionLockTarget(id), async () => {
+ const record = await requireOwned(principal, id);
+ record.title = safeTitle(title);
+ record.titleSource = "manual";
+ record.updatedAt = new Date().toISOString();
+ await writeSessionFile(record);
+ return record;
+ });
+}
+
+export async function appendAgentSessionEvent(
+ principal: string,
+ id: string,
+ event: Omit<AgentSessionEvent, "at"> & { at?: string },
+): Promise<void> {
+ await withSecurityStoreLock(sessionLockTarget(id), async () => {
+ let record = await requireOwned(principal, id);
+ const at = event.at ?? new Date().toISOString();
+ const row: AgentSessionEvent = {
+ at,
+ kind: event.kind,
+ ...(event.tool ? { tool: event.tool.slice(0, 120) } : {}),
+ ...(event.state ? { state: event.state.slice(0, 40) } : {}),
+ ...(event.workflowId
+ ? { workflowId: event.workflowId.slice(0, 80) }
+ : {}),
+ ...(event.detail
+ ? {
+ detail: redactText(
+ event.detail.replace(/[\r\n\t]+/g, " ").trim(),
+ 500,
+ ),
+ }
+ : {}),
+ };
+ record.events = [...record.events, row].slice(-MAX_EVENTS);
+ record.updatedAt = at;
+ record.lifetimeEstimatedTokens += estimateTokens(row);
+ record = await compactIfNeeded(record, "event-threshold");
+ await writeSessionFile(record);
+ });
+}
+
diff --git a/lib/agent/session-record.ts b/lib/agent/session-record.ts
new file mode 100644
index 00000000..c7f2748d
--- /dev/null
+++ b/lib/agent/session-record.ts
@@ -0,0 +1,70 @@
+import { artifactLocation } from "./artifact-paths";
+import { archiveAgentSession, pruneAgentSessionArchives } from "./session-archive";
+import { principalHash, readSessionFile } from "./session-files";
+import { compactSessionContext, MAX_EVENTS, sessionContextTokens } from "./session-policy";
+import type { AgentSession, AgentSessionEvent, AgentSessionSummary } from "./session-types";
+
+export function summary(record: AgentSession): AgentSessionSummary {
+ return {
+ id: record.id,
+ source: record.source,
+ name: record.name,
+ title: record.title,
+ titleSource: record.titleSource,
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
+ ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
+ ...(record.cwd ? { cwd: record.cwd } : {}),
+ ...(record.parentSessionId
+ ? { parentSessionId: record.parentSessionId }
+ : {}),
+ estimatedTokens: record.estimatedTokens,
+ lifetimeEstimatedTokens: record.lifetimeEstimatedTokens,
+ compactThresholdTokens: record.compactThresholdTokens,
+ compactionCount: record.compactionCount,
+ archiveCount: record.archiveCount,
+ ...(record.lastCompactedAt
+ ? { lastCompactedAt: record.lastCompactedAt }
+ : {}),
+ ...(record.lastArchivedAt ? { lastArchivedAt: record.lastArchivedAt } : {}),
+ eventCount: record.events.length,
+ historyTurns: record.history.length,
+ artifacts: artifactLocation(record),
+ };
+}
+
+export async function compactIfNeeded(
+ record: AgentSession,
+ reason: string,
+): Promise<AgentSession> {
+ record.estimatedTokens = sessionContextTokens(record);
+ if (record.estimatedTokens < record.compactThresholdTokens) return record;
+ const now = new Date();
+ await archiveAgentSession(record, reason, now);
+ let next = compactSessionContext(record, now.toISOString());
+ const archived: AgentSessionEvent = {
+ at: now.toISOString(),
+ kind: "archived",
+ detail: `${reason}; 30-day retention`,
+ };
+ next = {
+ ...next,
+ events: [...next.events.slice(-(MAX_EVENTS - 1)), archived],
+ archiveCount: record.archiveCount + 1,
+ lastArchivedAt: now.toISOString(),
+ };
+ next.estimatedTokens = sessionContextTokens(next);
+ void pruneAgentSessionArchives().catch(() => undefined);
+ return next;
+}
+
+export async function requireOwned(
+ principal: string,
+ id: string,
+): Promise<AgentSession> {
+ const record = await readSessionFile(id);
+ if (!record || record.principalHash !== principalHash(principal))
+ throw new Error("agent session not found for this client");
+ return record;
+}
+
diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.ts
index 7681bec9..8b1ca1d0 100644
--- a/lib/agent/session-store.ts
+++ b/lib/agent/session-store.ts
@@ -1,216 +1,12 @@
-import { artifactLocation } from "./artifact-paths";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
-import { redactText } from "@/lib/security/redact-text";
+import { withUniqueSessionName, type CreateOptions } from "./session-create";
+import { conversationIndexReady, conversationLockTarget, listSessionRecords, principalHash, readConversationSession, readSessionFile, sessionLockTarget, writeConversationRef, writeSessionFile } from "./session-files";
import { normalizeAgentSessionCwd } from "./session-location";
-import { snapshotAgentMemory, type AgentMemorySnapshot } from "./memory-store";
-import {
- archiveAgentSession,
- pruneAgentSessionArchives,
-} from "./session-archive";
-import {
- conversationIndexReady,
- conversationLockTarget,
- listSessionRecords,
- newAgentSessionId,
- principalHash,
- readConversationSession,
- readSessionFile,
- sessionLockTarget,
- sessionNameLockTarget,
- writeConversationRef,
- writeSessionFile,
-} from "./session-files";
-import {
- autoSessionTitle,
- compactSessionContext,
- compactThresholdTokens,
- estimateTokens,
- MAX_EVENTS,
- MAX_HISTORY,
- safeTitle,
- sessionContextTokens,
-} from "./session-policy";
-import { allocateAgentSessionName, requireAgentSessionName } from "./session-name";
-import type {
- AgentSession,
- AgentSessionEvent,
- AgentSessionResumePacket,
- AgentSessionSource,
- AgentSessionSummary,
- AgentSessionTitleSource,
-} from "./session-types";
-export type {
- AgentSession,
- AgentSessionEvent,
- AgentSessionResumePacket,
- AgentSessionSource,
- AgentSessionSummary,
-} from "./session-types";
-
-interface CreateOptions {
- id?: string;
- name?: string;
- title?: string;
- titleSource?: AgentSessionTitleSource;
- resumedFrom?: string;
- conversationHash?: string;
- memorySnapshot?: AgentMemorySnapshot;
- contextSummary?: string;
- history?: unknown[];
- cwd?: string;
- parentSessionId?: string;
-}
-
-function summary(record: AgentSession): AgentSessionSummary {
- return {
- id: record.id,
- source: record.source,
- name: record.name,
- title: record.title,
- titleSource: record.titleSource,
- createdAt: record.createdAt,
- updatedAt: record.updatedAt,
- ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
- ...(record.cwd ? { cwd: record.cwd } : {}),
- ...(record.parentSessionId
- ? { parentSessionId: record.parentSessionId }
- : {}),
- estimatedTokens: record.estimatedTokens,
- lifetimeEstimatedTokens: record.lifetimeEstimatedTokens,
- compactThresholdTokens: record.compactThresholdTokens,
- compactionCount: record.compactionCount,
- archiveCount: record.archiveCount,
- ...(record.lastCompactedAt
- ? { lastCompactedAt: record.lastCompactedAt }
- : {}),
- ...(record.lastArchivedAt ? { lastArchivedAt: record.lastArchivedAt } : {}),
- eventCount: record.events.length,
- historyTurns: record.history.length,
- artifacts: artifactLocation(record),
- };
-}
-
-async function buildRecord(
- principal: string,
- source: AgentSessionSource,
- options: CreateOptions,
-): Promise<AgentSession> {
- const now = new Date().toISOString();
- const owner = principalHash(principal);
- const usedNames = (await listSessionRecords())
- .filter((row) => row.principalHash === owner)
- .map((row) => row.name);
- const name = options.name ? requireAgentSessionName(options.name) : allocateAgentSessionName(usedNames);
- if (usedNames.includes(name)) throw new Error(`session name @${name} is already in use`);
- const memorySnapshot =
- options.memorySnapshot ?? (await snapshotAgentMemory(principal));
- const created: AgentSessionEvent = {
- at: now,
- kind: "created",
- ...(options.resumedFrom
- ? { detail: `resumed from ${options.resumedFrom}` }
- : {}),
- };
- const record: AgentSession = {
- id: options.id ?? newAgentSessionId(),
- principalHash: principalHash(principal),
- source,
- name,
- title: safeTitle(options.title),
- titleSource: options.titleSource ?? "default",
- ...(options.conversationHash
- ? { conversationHash: options.conversationHash }
- : {}),
- createdAt: now,
- updatedAt: now,
- ...(options.resumedFrom ? { resumedFrom: options.resumedFrom } : {}),
- ...(normalizeAgentSessionCwd(options.cwd)
- ? { cwd: normalizeAgentSessionCwd(options.cwd) }
- : {}),
- ...(options.parentSessionId
- ? { parentSessionId: options.parentSessionId }
- : {}),
- memorySnapshot,
- ...(options.contextSummary
- ? { contextSummary: options.contextSummary }
- : {}),
- history: (options.history ?? []).slice(-MAX_HISTORY),
- events: [created],
- estimatedTokens: 0,
- lifetimeEstimatedTokens: 0,
- compactThresholdTokens: compactThresholdTokens(),
- compactionCount: 0,
- archiveCount: 0,
- };
- const estimatedTokens = sessionContextTokens(record);
- return {
- ...record,
- estimatedTokens,
- lifetimeEstimatedTokens: estimatedTokens,
- };
-}
-
-async function withUniqueSessionName<T>(
- principal: string,
- source: AgentSessionSource,
- options: CreateOptions,
- commit: (record: AgentSession) => Promise<T>,
-): Promise<T> {
- const owner = principalHash(principal);
- const requested = options.name ? requireAgentSessionName(options.name) : undefined;
- for (let attempt = 0; attempt < 100; attempt += 1) {
- const used = (await listSessionRecords())
- .filter((row) => row.principalHash === owner)
- .map((row) => row.name);
- const name = requested ?? allocateAgentSessionName(used);
- try {
- return await withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
- const record = await buildRecord(principal, source, { ...options, name });
- return commit(record);
- });
- } catch (error) {
- const duplicate = error instanceof Error && /session name @.+ is already in use/.test(error.message);
- if (!requested && duplicate) continue;
- throw error;
- }
- }
- throw new Error("could not allocate a unique session name");
-}
-
-async function compactIfNeeded(
- record: AgentSession,
- reason: string,
-): Promise<AgentSession> {
- record.estimatedTokens = sessionContextTokens(record);
- if (record.estimatedTokens < record.compactThresholdTokens) return record;
- const now = new Date();
- await archiveAgentSession(record, reason, now);
- let next = compactSessionContext(record, now.toISOString());
- const archived: AgentSessionEvent = {
- at: now.toISOString(),
- kind: "archived",
- detail: `${reason}; 30-day retention`,
- };
- next = {
- ...next,
- events: [...next.events.slice(-(MAX_EVENTS - 1)), archived],
- archiveCount: record.archiveCount + 1,
- lastArchivedAt: now.toISOString(),
- };
- next.estimatedTokens = sessionContextTokens(next);
- void pruneAgentSessionArchives().catch(() => undefined);
- return next;
-}
-
-async function requireOwned(
- principal: string,
- id: string,
-): Promise<AgentSession> {
- const record = await readSessionFile(id);
- if (!record || record.principalHash !== principalHash(principal))
- throw new Error("agent session not found for this client");
- return record;
-}
+import { appendAgentSessionEvent } from "./session-mutations";
+import { requireOwned, summary } from "./session-record";
+import type { AgentSession, AgentSessionResumePacket, AgentSessionSource, AgentSessionSummary } from "./session-types";
+export { appendAgentSessionEvent, maybeAutoTitleAgentSession, renameAgentSession, renameAgentSessionName, updateAgentSessionHistory } from "./session-mutations";
+export type { AgentSession,AgentSessionEvent,AgentSessionResumePacket,AgentSessionSource,AgentSessionSummary } from "./session-types";
export async function createAgentSession(
principal: string,
@@ -301,129 +97,6 @@ export async function listAgentSessionsOwner(
.map(summary);
}
-export async function updateAgentSessionHistory(
- principal: string,
- id: string,
- history: unknown[],
- title?: string,
- titleSource: AgentSessionTitleSource = "auto",
-): Promise<AgentSession> {
- return withSecurityStoreLock(sessionLockTarget(id), async () => {
- let record = await requireOwned(principal, id);
- const oldTokens = estimateTokens(record.history),
- newHistory = Array.isArray(history) ? history.slice(-MAX_HISTORY) : [];
- record.history = newHistory;
- record.lifetimeEstimatedTokens += Math.max(
- 0,
- estimateTokens(newHistory) - oldTokens,
- );
- const legacyCliDefault =
- record.source === "cli" &&
- record.titleSource === "manual" &&
- record.title === "MSO Agent session";
- if (
- title &&
- (titleSource === "manual" ||
- record.titleSource !== "manual" ||
- legacyCliDefault)
- ) {
- record.title = safeTitle(title);
- record.titleSource = titleSource;
- }
- record.updatedAt = new Date().toISOString();
- record = await compactIfNeeded(record, "context-threshold");
- await writeSessionFile(record);
- return record;
- });
-}
-
-export async function maybeAutoTitleAgentSession(
- principal: string,
- id: string,
- hint: string,
-): Promise<AgentSession | null> {
- return withSecurityStoreLock(sessionLockTarget(id), async () => {
- const record = await requireOwned(principal, id);
- if (record.titleSource === "manual" || record.titleSource === "auto")
- return record;
- record.title = autoSessionTitle(hint);
- record.titleSource = "auto";
- record.updatedAt = new Date().toISOString();
- await writeSessionFile(record);
- return record;
- });
-}
-
-export async function renameAgentSessionName(
- principal: string,
- id: string,
- value: string,
-): Promise<AgentSession> {
- const name = requireAgentSessionName(value);
- const owner = principalHash(principal);
- return withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
- const duplicate = (await listSessionRecords()).find((row) =>
- row.principalHash === owner && row.id !== id && row.name === name,
- );
- if (duplicate) throw new Error(`session name @${name} is already in use`);
- return withSecurityStoreLock(sessionLockTarget(id), async () => {
- const record = await requireOwned(principal, id);
- record.name = name;
- record.updatedAt = new Date().toISOString();
- await writeSessionFile(record);
- return record;
- });
- });
-}
-
-export async function renameAgentSession(
- principal: string,
- id: string,
- title: string,
-): Promise<AgentSession> {
- return withSecurityStoreLock(sessionLockTarget(id), async () => {
- const record = await requireOwned(principal, id);
- record.title = safeTitle(title);
- record.titleSource = "manual";
- record.updatedAt = new Date().toISOString();
- await writeSessionFile(record);
- return record;
- });
-}
-
-export async function appendAgentSessionEvent(
- principal: string,
- id: string,
- event: Omit<AgentSessionEvent, "at"> & { at?: string },
-): Promise<void> {
- await withSecurityStoreLock(sessionLockTarget(id), async () => {
- let record = await requireOwned(principal, id);
- const at = event.at ?? new Date().toISOString();
- const row: AgentSessionEvent = {
- at,
- kind: event.kind,
- ...(event.tool ? { tool: event.tool.slice(0, 120) } : {}),
- ...(event.state ? { state: event.state.slice(0, 40) } : {}),
- ...(event.workflowId
- ? { workflowId: event.workflowId.slice(0, 80) }
- : {}),
- ...(event.detail
- ? {
- detail: redactText(
- event.detail.replace(/[\r\n\t]+/g, " ").trim(),
- 500,
- ),
- }
- : {}),
- };
- record.events = [...record.events, row].slice(-MAX_EVENTS);
- record.updatedAt = at;
- record.lifetimeEstimatedTokens += estimateTokens(row);
- record = await compactIfNeeded(record, "event-threshold");
- await writeSessionFile(record);
- });
-}
-
export async function resumeAgentSession(
principal: string,
targetId: string,
diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.ts
index 8f85b342..d70ba0f7 100644
--- a/lib/config/env-example.test.ts
+++ b/lib/config/env-example.test.ts
@@ -36,6 +36,7 @@ const NOT_A_KNOB: Record<string, string> = {
VITEST: "set by the test runner",
// The OS gives these to every process.
SHELL: "the OS's",
+ PATH: "standard executable search path inherited by the lifecycle test harness",
HOME: "the OS's",
XDG_RUNTIME_DIR: "set by logind, or by the unit — see lib/managed-apps/user-bus.ts",
// systemd's, read by instrumentation for the watchdog handshake.
diff --git a/lib/forge/forge.test.ts b/lib/forge/forge.test.ts
index d03e65c8..4a124e15 100644
--- a/lib/forge/forge.test.ts
+++ b/lib/forge/forge.test.ts
@@ -1,11 +1,10 @@
-import { existsSync, promises as fs } from "node:fs";
-import { spawnSync } from "node:child_process";
-import path from "node:path";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { LearnedRecipe, WorkflowQuality } from "@/lib/workflow";
-import { projectSkillTrust } from "@/lib/skills/project-skills";
import { readProjectFunctionsManifest } from "@/lib/host/project-function-manifest";
import { runProjectFunction } from "@/lib/host/project-function-runner";
+import { projectSkillTrust } from "@/lib/skills/project-skills";
+import type { LearnedRecipe, WorkflowQuality } from "@/lib/workflow";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { evaluateForgeCandidate } from "./evaluate";
import { promoteForgeCandidate } from "./promote";
import { proposeForgeCandidate } from "./proposal";
@@ -39,10 +38,6 @@ async function tempProject(): Promise<{ root: string; project: string; forge: st
}
-const dockerSandboxAvailable = existsSync("/usr/bin/docker") && spawnSync(
- "/usr/bin/docker", ["image", "inspect", "mso-forge-sandbox:node22-v1"], { stdio: "ignore", timeout: 3000 },
-).status === 0;
-
const roots: string[] = [];
afterEach(async () => {
delete process.env.OS_TOOL_FORGE_DIR;
@@ -102,7 +97,7 @@ describe("eval-gated Tool Forge", () => {
expect(evaluation.fixtureCount).toBe(0);
});
- it.runIf(dockerSandboxAvailable)("runs fixtures in the Docker sandbox before promoting an existing project-owned Node function", async () => {
+ it("runs fixtures in the Docker sandbox before promoting an existing project-owned Node function", async () => {
const { root, project } = await tempProject(); roots.push(root);
const script = path.join(project, "echo-function.mjs");
await fs.writeFile(script, `let s=""; for await (const c of process.stdin) s+=c; const v=JSON.parse(s); console.log("OK:"+v.value);\n`, { mode: 0o700 });
@@ -124,7 +119,7 @@ describe("eval-gated Tool Forge", () => {
expect(result.stdout).toContain("OK:runtime");
});
- it.runIf(dockerSandboxAvailable)("refuses promotion when project-owned source changes after evaluation", async () => {
+ it("refuses promotion when project-owned source changes after evaluation", async () => {
const { root, project } = await tempProject(); roots.push(root);
const script = path.join(project, "drift.mjs");
await fs.writeFile(script, `console.log("v1");\n`, { mode: 0o700 });
@@ -139,7 +134,7 @@ describe("eval-gated Tool Forge", () => {
await expect(promoteForgeCandidate({ ...candidate, state: "evaluated", evaluation })).rejects.toThrow(/source changed after evaluation/i);
});
- it.runIf(dockerSandboxAvailable)("keeps the project mount read-only and network disabled inside Forge fixtures", async () => {
+ it("keeps the project mount read-only and network disabled inside Forge fixtures", async () => {
const { root, project } = await tempProject(); roots.push(root);
const script = path.join(project, "sandbox-proof.mjs");
await fs.writeFile(script, `import fs from "node:fs"; let ro=false, net=false; try { fs.writeFileSync("forge-escape.txt", "x"); } catch { ro=true; } try { await fetch("http://127.0.0.1:4005", { signal: AbortSignal.timeout(500) }); } catch { net=true; } console.log("RO:"+ro+" NET:"+net);\n`, { mode: 0o700 });
diff --git a/lib/host/path-credentials.ts b/lib/host/path-credentials.ts
new file mode 100644
index 00000000..4e690111
--- /dev/null
+++ b/lib/host/path-credentials.ts
@@ -0,0 +1,110 @@
+import { realpathSync } from "fs";
+import path from "path";
+import { homeDir, isUnderRoot } from "./path-roots";
+
+// Credential denylist: even inside a legal root, the app's OWN secret files are
+// off-limits to the FS API. Reading .env.local would leak OS_SESSION_SECRET —
+// turning one stolen session into the ability to mint cookies forever — and
+// ~/.mso holds the device allowlist, BYOK key and browser profile (cookies).
+// Other projects' .env files stay readable (session = owner, their call).
+const APP_DIR = (() => {
+ try {
+ return realpathSync(process.cwd());
+ } catch {
+ return process.cwd();
+ }
+})();
+
+// The app's own dir (realpath'd). Exposed so the zip stream can force-strip its
+// `.env*` secrets when a PARENT of it is archived — `zip -r` recurses past the
+// per-name credential gate, so that one blind spot needs an explicit exclude.
+export function appDir(): string {
+ return APP_DIR;
+}
+
+// Defense-in-depth: high-value credential material in $HOME is blocked even
+// though the session belongs to the owner — a hijacked session shouldn't walk
+// away with SSH keys or shell history. Override with OS_FS_ALLOW_SENSITIVE=1
+// (or narrow the roots entirely via OS_FS_READ_ROOTS).
+export const SENSITIVE_HOME = [
+ ".ssh", ".gnupg", ".secrets", ".npmrc", "vault",
+ // shell + REPL history (the host shell may be zsh/fish, not just bash)
+ ".bash_history", ".zsh_history", ".python_history", ".mysql_history",
+ // cloud / infra credentials
+ ".aws", ".config/gcloud", ".kube", ".docker", ".config/rclone",
+ ".git-credentials", ".netrc", ".config/git/credentials",
+ // AI/dev-tool + OS keyring credentials (account tokens = full account access)
+ ".claude", ".claude.json", ".config/gh", ".config/anthropic", ".local/share/keyrings",
+ ".config/claude", ".config/GitHub", ".codex", ".gemini", ".copilot", ".mcp-auth",
+ ".convex", ".openclaw/credentials", ".openclaw/identity",
+ // Camoufox browser profile + its session snapshots. cookies.sqlite there holds a
+ // LIVE Google session (SID/__Secure-1PSID/SAPISID) and LinkedIn's li_at — replaying
+ // those is account takeover with no password and no 2FA prompt. OS_FS_READ_ROOTS is
+ // ~, so without this an fs/read or an fs/zip of $HOME walks off with all of it, and
+ // assistant read-tools run with no approval gate. .vnc holds the VNC password file.
+ ".local/share/camoufox", ".local/state/camoufox", ".vnc",
+ // database creds + password-manager CLIs
+ ".pgpass", ".config/op", ".config/lpass",
+ // SHELL RC + PROFILE FILES. Not config-shaped paranoia: `export FOO_TOKEN=…` in
+ // ~/.bashrc is how most people (and this box — 8 of them the day this was added)
+ // keep API keys for CLIs, and every installer that says "add this to your shell
+ // profile" puts one there. The list already blocks shell HISTORY for the same
+ // reason; the file that DEFINES the environment is the richer target of the two.
+ // Editing them from the cockpit is a real loss — that is what OS_FS_ALLOW_SENSITIVE
+ // is for, and a terminal window is right there.
+ ".bashrc", ".bash_profile", ".bash_login", ".bash_aliases", ".profile",
+ ".zshrc", ".zprofile", ".zshenv", ".zlogin", ".kshrc",
+ ".config/fish/config.fish", ".config/fish/conf.d",
+ // root-level loose private keys; nested copies are caught by basename below too.
+ "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa",
+];
+
+// Loose private keys are identified by BASENAME anywhere inside a legal read root.
+// Keeping these in SENSITIVE_HOME only protected ~/id_rsa, while the common deploy-key
+// shape ~/projects/app/id_rsa stayed readable to a session/read-scope MCP bearer.
+const PRIVATE_KEY_BASENAMES = ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"] as const;
+const PRIVATE_KEY_NAMES = new Set<string>(PRIVATE_KEY_BASENAMES);
+
+export function isSensitivePath(real: string): boolean {
+ if (process.env.OS_FS_ALLOW_SENSITIVE === "1") return false;
+ const h = homeDir();
+ return SENSITIVE_HOME.some((n) => {
+ const p = path.join(h, n);
+ return real === p || isUnderRoot(real, p);
+ });
+}
+
+/** The app's OWN `.env*` — `.env.local` holds OS_SESSION_SECRET, so a copy of one
+ * into a readable spot turns one stolen session into forever-mintable cookies. */
+export function isAppSecret(real: string): boolean {
+ const base = path.basename(real);
+ return path.dirname(real) === APP_DIR && base.startsWith(".env") && base !== ".env.example";
+}
+
+/** Exported for the project/skill enumerators: they walk directory TREES the
+ * per-path resolvers never see, and must drop a credential directory themselves
+ * rather than discover it one `resolveReadable` too late. */
+export function isCredentialPath(real: string): boolean {
+ const store = path.join(homeDir(), ".mso");
+ if (real === store || isUnderRoot(real, store)) return true;
+ if (isSensitivePath(real)) return true;
+ const base = path.basename(real);
+ // Private keys land anywhere (heredoc dumps, deploy keys, downloaded service
+ // accounts). Their basename/extension is the reliable marker outside fixed ~/ paths.
+ if (PRIVATE_KEY_NAMES.has(base) && process.env.OS_FS_ALLOW_SENSITIVE !== "1") return true;
+ if (base.toLowerCase().endsWith(".pem")) return true;
+ return isAppSecret(real);
+}
+
+// `zip -r` validates the selected top-level names, then walks descendants itself.
+// These patterns enforce the same basename-anywhere private-key rule inside that
+// recursive walk. Info-ZIP `*` spans `/`; explicit root forms cover the no-slash case.
+export function looseCredentialExcludes(): string[] {
+ const privateNames = process.env.OS_FS_ALLOW_SENSITIVE === "1"
+ ? []
+ : PRIVATE_KEY_BASENAMES.flatMap((name) => [name, `*/${name}`]);
+ // *.pem has historically been a hard credential boundary, independent of the
+ // SENSITIVE_HOME escape hatch; keep that contract while extending id_* safely.
+ return ["*.pem", ...privateNames];
+}
+
diff --git a/lib/host/path-recursive.ts b/lib/host/path-recursive.ts
new file mode 100644
index 00000000..7be43bc8
--- /dev/null
+++ b/lib/host/path-recursive.ts
@@ -0,0 +1,117 @@
+import { existsSync, promises as fs, readdirSync } from "fs";
+import path from "path";
+import { HostError } from "./host-error";
+import { appDir, isAppSecret, isCredentialPath, SENSITIVE_HOME } from "./path-credentials";
+import { homeDir, isUnderRoot } from "./path-roots";
+
+/** The app's own secrets sitting UNDER `realBase` — empty when APP_DIR is not a
+ * descendant, or holds no secrets. The per-path gate is exact-or-under, so a
+ * recursive walk starting at a PARENT of APP_DIR never consults it for these. */
+function appSecretsUnder(realBase: string): string[] {
+ const dir = appDir();
+ if (dir === realBase || !isUnderRoot(dir, realBase)) return [];
+ try {
+ return readdirSync(dir)
+ .map((n) => path.join(dir, n))
+ .filter((p) => isAppSecret(p));
+ } catch {
+ return [];
+ }
+}
+
+// The per-path gate above is exact-or-under, so a PARENT of a denied entry never
+// matches it — and the two recursive callers (`zip -r`, `fs.cp {recursive}`) walk
+// straight past the gate into the children. Both need the nested locations named
+// explicitly. Filtered by existence so the callers never refuse (or exclude) over
+// a path that isn't on this box.
+function sensitiveUnder(realBase: string): string[] {
+ if (process.env.OS_FS_ALLOW_SENSITIVE === "1") return [];
+ const h = homeDir();
+ return [...SENSITIVE_HOME, ".mso"]
+ .map((n) => path.join(h, n))
+ .filter((p) => p !== realBase && isUnderRoot(p, realBase) && existsSync(p));
+}
+
+// Recursive READ (zip): NARROW the archive rather than refuse it — same shape as
+// appSecretExcludes. Info-ZIP `*` spans `/` and entries are stored relative to the
+// archive base, so `rel` drops a file and `rel/*` drops a whole dir.
+export function sensitiveExcludes(realBase: string): string[] {
+ return sensitiveUnder(realBase).flatMap((p) => {
+ const rel = path.relative(realBase, p);
+ return [rel, `${rel}/*`];
+ });
+}
+
+// Recursive WRITE (copy/move): REFUSE. Filtering is wrong for move — its EXDEV
+// branch is cp-then-rm, so a skipped file would be deleted instead of moved. And
+// a completed move relocates credentials OUT of their denylisted path, which makes
+// them plainly readable at the destination (relocate-then-read escalation).
+export function assertNoSensitiveDescendants(real: string): void {
+ const hit = sensitiveUnder(real)[0];
+ if (hit)
+ throw new HostError(
+ `Refusing: this directory contains a credential path (${path.relative(real, hit)})`,
+ );
+}
+
+/** Walk a recursive mutation source and apply the same credential predicate used
+ * by per-path reads/writes to every descendant. Directory operations otherwise
+ * let fs.cp/fs.rename/fs.rm walk past the top-level gate. Symlinks are inspected
+ * by their own path/name but never followed, so this guard cannot escape the
+ * already-resolved mutation root or traverse a cycle. */
+export async function assertNoCredentialDescendants(
+ realBase: string,
+ options: { ignoreAppSecrets?: boolean } = {},
+): Promise<void> {
+ const rootStat = await fs.lstat(realBase).catch(() => null);
+ if (!rootStat?.isDirectory()) return;
+
+ const stack = [realBase];
+ while (stack.length) {
+ const dir = stack.pop()!;
+ let entries: import("fs").Dirent[];
+ try {
+ entries = await fs.readdir(dir, { withFileTypes: true });
+ } catch (error) {
+ throw new HostError(`Refusing recursive mutation: cannot inspect ${path.relative(realBase, dir) || "."}`);
+ }
+ for (const entry of entries) {
+ const child = path.join(dir, entry.name);
+ const credential = isCredentialPath(child);
+ const ignoredAppSecret = options.ignoreAppSecrets === true && isAppSecret(child);
+ if (credential && !ignoredAppSecret) {
+ throw new HostError(
+ `Refusing: this directory contains a credential path (${path.relative(realBase, child)})`,
+ );
+ }
+ if (entry.isDirectory()) stack.push(child);
+ }
+ }
+}
+
+// The app's own `.env*` needed the narrower fix the ~/ list can't give: on the
+// DEFAULT roots (~ and ~/projects) APP_DIR is a descendant of a copyable dir, so
+// `copy(~/projects, ~/backup)` walked past the per-path gate and duplicated
+// .env.local somewhere /api/v1/fs/read serves. Refusing outright would block
+// copying ~/projects, which is an ordinary thing to do — so copy SKIPS them and
+// only move refuses.
+//
+// Recursive COPY: a filter for `fs.cp`. Returns undefined when there is nothing
+// to skip, so the ordinary copy path stays exactly as it was.
+export function appSecretCopyFilter(realBase: string): ((src: string) => boolean) | undefined {
+ const secrets = new Set(appSecretsUnder(realBase));
+ return secrets.size ? (src: string) => !secrets.has(src) : undefined;
+}
+
+// Recursive MOVE: REFUSE, for the same reason the ~/ list does. A filter is wrong
+// here — the EXDEV branch is cp-then-rm, so a skipped secret would be DELETED
+// rather than moved, and a completed move relocates it out of its denylisted path
+// and makes it plainly readable at the destination.
+export function assertNoAppSecretDescendants(real: string): void {
+ const hit = appSecretsUnder(real)[0];
+ if (hit)
+ throw new HostError(
+ `Refusing: this directory contains the cockpit's own secrets (${path.relative(real, hit)})`,
+ );
+}
+
diff --git a/lib/host/path-roots.ts b/lib/host/path-roots.ts
new file mode 100644
index 00000000..d8a064d6
--- /dev/null
+++ b/lib/host/path-roots.ts
@@ -0,0 +1,35 @@
+import os from "os";
+import path from "path";
+
+export function homeDir(): string {
+ return os.homedir();
+}
+
+function expandHome(p: string): string {
+ if (p === "~") return homeDir();
+ if (p.startsWith("~/")) return path.join(homeDir(), p.slice(2));
+ return p;
+}
+
+function rootsFromEnv(name: string, fallback: string[]): string[] {
+ const env = process.env[name];
+ if (env && env.trim())
+ return env.split(":").map((s) => s.trim()).filter(Boolean).map(expandHome);
+ return fallback;
+}
+
+export function readRootList(): string[] {
+ const h = homeDir();
+ return rootsFromEnv("OS_FS_READ_ROOTS", [h, path.join(h, "projects")]);
+}
+
+export function writeRootList(): string[] {
+ const h = homeDir();
+ return rootsFromEnv("OS_FS_WRITE_ROOTS", [h, path.join(h, "projects")]);
+}
+
+export function isUnderRoot(target: string, root: string): boolean {
+ const rel = path.relative(root, target);
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
+}
+
diff --git a/lib/host/paths-app-secrets.test.ts b/lib/host/paths-app-secrets.test.ts
new file mode 100644
index 00000000..80670373
--- /dev/null
+++ b/lib/host/paths-app-secrets.test.ts
@@ -0,0 +1,53 @@
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+const base = realpathSync(mkdtempSync(path.join(os.tmpdir(), "mso-app-secrets-")));
+const fakeHome = path.join(base, "home");
+const appDir = path.join(base, "app");
+const secret = path.join(appDir, ".env.local");
+let guards: typeof import("./paths");
+beforeAll(async () => {
+ for (const dir of [appDir, path.join(fakeHome, ".ssh"), path.join(fakeHome, ".mso")]) mkdirSync(dir, { recursive: true });
+ writeFileSync(secret, "# synthetic; no credentials");
+ writeFileSync(path.join(appDir, ".env.example"), "# public example");
+ writeFileSync(path.join(appDir, "package.json"), "{}");
+ vi.stubEnv("HOME", fakeHome);
+ vi.stubEnv("OS_FS_READ_ROOTS", base);
+ vi.stubEnv("OS_FS_ALLOW_SENSITIVE", "0");
+ vi.resetModules();
+ const cwd = vi.spyOn(process, "cwd").mockReturnValue(appDir);
+ try { guards = await import("./paths"); } finally { cwd.mockRestore(); }
+});
+afterAll(() => { vi.unstubAllEnvs(); rmSync(base, { recursive: true, force: true }); });
+
+describe("credential denylist with real synthetic files", () => {
+ it.each([".ssh", ".mso"])("blocks %s even inside a legal root", async name => {
+ await expect(guards.resolveReadable(path.join(fakeHome, name))).rejects.toThrow(/credential|sensitive/i);
+ });
+ it("blocks the app's own .env.local", async () => {
+ await expect(guards.resolveReadable(secret)).rejects.toThrow(/credential|sensitive/i);
+ });
+ it("still allows .env.example", async () => {
+ await expect(guards.resolveReadable(path.join(appDir, ".env.example"))).resolves.toBe(path.join(appDir, ".env.example"));
+ });
+ it("copy skips secrets when a parent of the app is the source", () => {
+ const filter = guards.appSecretCopyFilter(base);
+ expect(filter).toBeTypeOf("function");
+ expect(filter!(secret)).toBe(false);
+ expect(filter!(path.join(appDir, "package.json"))).toBe(true);
+ expect(filter!(path.join(appDir, ".env.example"))).toBe(true);
+ });
+ it("move refuses so its EXDEV branch cannot delete a skipped secret", () => {
+ expect(() => guards.assertNoAppSecretDescendants(base)).toThrow(/secret/i);
+ });
+ it("leaves an unrelated source alone", () => {
+ expect(guards.appSecretCopyFilter(path.join(base, "elsewhere"))).toBeUndefined();
+ expect(() => guards.assertNoAppSecretDescendants(path.join(base, "elsewhere"))).not.toThrow();
+ });
+ it("leaves direct app copies to the per-path gate", () => {
+ expect(guards.appSecretCopyFilter(appDir)).toBeUndefined();
+ expect(() => guards.assertNoAppSecretDescendants(appDir)).not.toThrow();
+ });
+});
diff --git a/lib/host/paths-credentials.test.ts b/lib/host/paths-credentials.test.ts
index e295d711..08e46a96 100644
--- a/lib/host/paths-credentials.test.ts
+++ b/lib/host/paths-credentials.test.ts
@@ -1,16 +1,14 @@
-import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
- appSecretCopyFilter,
- assertNoAppSecretDescendants,
- assertNoCredentialDescendants,
- assertNoSensitiveDescendants,
- isCredentialPath,
- isSensitivePath,
- looseCredentialExcludes,
- sensitiveExcludes,
+assertNoCredentialDescendants,
+assertNoSensitiveDescendants,
+isCredentialPath,
+isSensitivePath,
+looseCredentialExcludes,
+sensitiveExcludes
} from "./paths";
// The per-path credential gate is exact-or-under, so a PARENT of a denied entry
@@ -120,37 +118,3 @@ describe("recursive credential guard", () => {
expect(() => assertNoSensitiveDescendants(parent)).not.toThrow();
});
});
-
-// The app's own `.env*` are NOT on the ~/ list, and APP_DIR is fixed at module load
-// from process.cwd() — so unlike the block above, these run against the real repo.
-// On the DEFAULT roots (~ and ~/projects) APP_DIR is a descendant of a copyable dir,
-// which is exactly how `copy(~/projects, ~/backup)` used to duplicate .env.local to
-// somewhere /api/v1/fs/read still serves it.
-describe("the cockpit's own .env* under a recursive write", () => {
- const appDir = realpathSync(process.cwd());
- const above = path.dirname(appDir);
- const secret = path.join(appDir, ".env.local");
- const live = existsSync(secret);
-
- it.skipIf(!live)("copy skips them when a PARENT of APP_DIR is the source", () => {
- const filter = appSecretCopyFilter(above);
- expect(filter).toBeTypeOf("function");
- expect(filter!(secret)).toBe(false);
- expect(filter!(path.join(appDir, "package.json"))).toBe(true);
- expect(filter!(path.join(appDir, ".env.example"))).toBe(true);
- });
-
- it.skipIf(!live)("move REFUSES instead — its EXDEV branch would delete a skipped file", () => {
- expect(() => assertNoAppSecretDescendants(above)).toThrow(/secret/i);
- });
-
- it("leaves an unrelated source completely alone", () => {
- expect(appSecretCopyFilter(path.join(base, "elsewhere"))).toBeUndefined();
- expect(() => assertNoAppSecretDescendants(path.join(base, "elsewhere"))).not.toThrow();
- });
-
- it("does not fire when APP_DIR IS the source (the per-path gate owns that)", () => {
- expect(appSecretCopyFilter(appDir)).toBeUndefined();
- expect(() => assertNoAppSecretDescendants(appDir)).not.toThrow();
- });
-});
diff --git a/lib/host/paths.test.ts b/lib/host/paths.test.ts
index f09585cc..c5769aef 100644
--- a/lib/host/paths.test.ts
+++ b/lib/host/paths.test.ts
@@ -1,11 +1,10 @@
import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- realpathSync,
- rmSync,
- symlinkSync,
- writeFileSync,
+mkdirSync,
+mkdtempSync,
+realpathSync,
+rmSync,
+symlinkSync,
+writeFileSync
} from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -95,34 +94,6 @@ describe("resolveReadable bounds", () => {
});
});
-describe("credential denylist (read root = / so only the denylist gates)", () => {
- const home = os.homedir();
- const sshDir = path.join(home, ".ssh");
- const storeDir = path.join(home, ".mso");
- const envLocal = path.join(process.cwd(), ".env.local");
- const envExample = path.join(process.cwd(), ".env.example");
-
- it.skipIf(!existsSync(sshDir))("blocks ~/.ssh even inside a legal root", async () => {
- useRoots("/", writeRoot);
- await expect(resolveReadable(sshDir)).rejects.toThrow(/credential|sensitive/i);
- });
-
- it.skipIf(!existsSync(storeDir))("blocks the ~/.mso config store", async () => {
- useRoots("/", writeRoot);
- await expect(resolveReadable(storeDir)).rejects.toThrow(/credential|sensitive/i);
- });
-
- it.skipIf(!existsSync(envLocal))("blocks the app's own .env.local", async () => {
- useRoots("/", writeRoot);
- await expect(resolveReadable(envLocal)).rejects.toThrow(/credential|sensitive/i);
- });
-
- it.skipIf(!existsSync(envExample))("still allows .env.example (no secrets)", async () => {
- useRoots("/", writeRoot);
- await expect(resolveReadable(envExample)).resolves.toBe(realpathSync(envExample));
- });
-});
-
describe("assertUploadTarget (upload jail — same denylist + realpath bounds as writes)", () => {
it("allows a normal file and a nested new path inside the dest", async () => {
await expect(assertUploadTarget(path.join(writeRoot, "up.txt"), writeRoot)).resolves.toBeUndefined();
diff --git a/lib/host/paths.ts b/lib/host/paths.ts
index dddbf20c..bf4c7ed2 100644
--- a/lib/host/paths.ts
+++ b/lib/host/paths.ts
@@ -4,260 +4,15 @@
// browser shell can't clobber system files. Symlinks are realpath-resolved BEFORE the
// bounds check so a link can't escape a root. Configure with OS_FS_READ_ROOTS /
// OS_FS_WRITE_ROOTS (colon-separated; "~" = home, "/" = whole filesystem).
-import { existsSync, promises as fs, readdirSync, realpathSync } from "fs";
-import os from "os";
-import path from "path";
import type { FsRoot } from "@/lib/os-api/types";
+import { promises as fs } from "fs";
+import path from "path";
import { HostError } from "./host-error";
-
-export function homeDir(): string {
- return os.homedir();
-}
-
-function expandHome(p: string): string {
- if (p === "~") return homeDir();
- if (p.startsWith("~/")) return path.join(homeDir(), p.slice(2));
- return p;
-}
-
-function rootsFromEnv(name: string, fallback: string[]): string[] {
- const env = process.env[name];
- if (env && env.trim())
- return env.split(":").map((s) => s.trim()).filter(Boolean).map(expandHome);
- return fallback;
-}
-
-export function readRootList(): string[] {
- const h = homeDir();
- return rootsFromEnv("OS_FS_READ_ROOTS", [h, path.join(h, "projects")]);
-}
-
-export function writeRootList(): string[] {
- const h = homeDir();
- return rootsFromEnv("OS_FS_WRITE_ROOTS", [h, path.join(h, "projects")]);
-}
-
-export function isUnderRoot(target: string, root: string): boolean {
- const rel = path.relative(root, target);
- return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
-}
-
-// Credential denylist: even inside a legal root, the app's OWN secret files are
-// off-limits to the FS API. Reading .env.local would leak OS_SESSION_SECRET —
-// turning one stolen session into the ability to mint cookies forever — and
-// ~/.mso holds the device allowlist, BYOK key and browser profile (cookies).
-// Other projects' .env files stay readable (session = owner, their call).
-const APP_DIR = (() => {
- try {
- return realpathSync(process.cwd());
- } catch {
- return process.cwd();
- }
-})();
-
-// The app's own dir (realpath'd). Exposed so the zip stream can force-strip its
-// `.env*` secrets when a PARENT of it is archived — `zip -r` recurses past the
-// per-name credential gate, so that one blind spot needs an explicit exclude.
-export function appDir(): string {
- return APP_DIR;
-}
-
-// Defense-in-depth: high-value credential material in $HOME is blocked even
-// though the session belongs to the owner — a hijacked session shouldn't walk
-// away with SSH keys or shell history. Override with OS_FS_ALLOW_SENSITIVE=1
-// (or narrow the roots entirely via OS_FS_READ_ROOTS).
-const SENSITIVE_HOME = [
- ".ssh", ".gnupg", ".secrets", ".npmrc", "vault",
- // shell + REPL history (the host shell may be zsh/fish, not just bash)
- ".bash_history", ".zsh_history", ".python_history", ".mysql_history",
- // cloud / infra credentials
- ".aws", ".config/gcloud", ".kube", ".docker", ".config/rclone",
- ".git-credentials", ".netrc", ".config/git/credentials",
- // AI/dev-tool + OS keyring credentials (account tokens = full account access)
- ".claude", ".claude.json", ".config/gh", ".config/anthropic", ".local/share/keyrings",
- ".config/claude", ".config/GitHub", ".codex", ".gemini", ".copilot", ".mcp-auth",
- ".convex", ".openclaw/credentials", ".openclaw/identity",
- // Camoufox browser profile + its session snapshots. cookies.sqlite there holds a
- // LIVE Google session (SID/__Secure-1PSID/SAPISID) and LinkedIn's li_at — replaying
- // those is account takeover with no password and no 2FA prompt. OS_FS_READ_ROOTS is
- // ~, so without this an fs/read or an fs/zip of $HOME walks off with all of it, and
- // assistant read-tools run with no approval gate. .vnc holds the VNC password file.
- ".local/share/camoufox", ".local/state/camoufox", ".vnc",
- // database creds + password-manager CLIs
- ".pgpass", ".config/op", ".config/lpass",
- // SHELL RC + PROFILE FILES. Not config-shaped paranoia: `export FOO_TOKEN=…` in
- // ~/.bashrc is how most people (and this box — 8 of them the day this was added)
- // keep API keys for CLIs, and every installer that says "add this to your shell
- // profile" puts one there. The list already blocks shell HISTORY for the same
- // reason; the file that DEFINES the environment is the richer target of the two.
- // Editing them from the cockpit is a real loss — that is what OS_FS_ALLOW_SENSITIVE
- // is for, and a terminal window is right there.
- ".bashrc", ".bash_profile", ".bash_login", ".bash_aliases", ".profile",
- ".zshrc", ".zprofile", ".zshenv", ".zlogin", ".kshrc",
- ".config/fish/config.fish", ".config/fish/conf.d",
- // root-level loose private keys; nested copies are caught by basename below too.
- "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa",
-];
-
-// Loose private keys are identified by BASENAME anywhere inside a legal read root.
-// Keeping these in SENSITIVE_HOME only protected ~/id_rsa, while the common deploy-key
-// shape ~/projects/app/id_rsa stayed readable to a session/read-scope MCP bearer.
-const PRIVATE_KEY_BASENAMES = ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"] as const;
-const PRIVATE_KEY_NAMES = new Set<string>(PRIVATE_KEY_BASENAMES);
-
-export function isSensitivePath(real: string): boolean {
- if (process.env.OS_FS_ALLOW_SENSITIVE === "1") return false;
- const h = homeDir();
- return SENSITIVE_HOME.some((n) => {
- const p = path.join(h, n);
- return real === p || isUnderRoot(real, p);
- });
-}
-
-/** The app's OWN `.env*` — `.env.local` holds OS_SESSION_SECRET, so a copy of one
- * into a readable spot turns one stolen session into forever-mintable cookies. */
-export function isAppSecret(real: string): boolean {
- const base = path.basename(real);
- return path.dirname(real) === APP_DIR && base.startsWith(".env") && base !== ".env.example";
-}
-
-/** Exported for the project/skill enumerators: they walk directory TREES the
- * per-path resolvers never see, and must drop a credential directory themselves
- * rather than discover it one `resolveReadable` too late. */
-export function isCredentialPath(real: string): boolean {
- const store = path.join(homeDir(), ".mso");
- if (real === store || isUnderRoot(real, store)) return true;
- if (isSensitivePath(real)) return true;
- const base = path.basename(real);
- // Private keys land anywhere (heredoc dumps, deploy keys, downloaded service
- // accounts). Their basename/extension is the reliable marker outside fixed ~/ paths.
- if (PRIVATE_KEY_NAMES.has(base) && process.env.OS_FS_ALLOW_SENSITIVE !== "1") return true;
- if (base.toLowerCase().endsWith(".pem")) return true;
- return isAppSecret(real);
-}
-
-// `zip -r` validates the selected top-level names, then walks descendants itself.
-// These patterns enforce the same basename-anywhere private-key rule inside that
-// recursive walk. Info-ZIP `*` spans `/`; explicit root forms cover the no-slash case.
-export function looseCredentialExcludes(): string[] {
- const privateNames = process.env.OS_FS_ALLOW_SENSITIVE === "1"
- ? []
- : PRIVATE_KEY_BASENAMES.flatMap((name) => [name, `*/${name}`]);
- // *.pem has historically been a hard credential boundary, independent of the
- // SENSITIVE_HOME escape hatch; keep that contract while extending id_* safely.
- return ["*.pem", ...privateNames];
-}
-
-/** The app's own secrets sitting UNDER `realBase` — empty when APP_DIR is not a
- * descendant, or holds no secrets. The per-path gate is exact-or-under, so a
- * recursive walk starting at a PARENT of APP_DIR never consults it for these. */
-function appSecretsUnder(realBase: string): string[] {
- const dir = appDir();
- if (dir === realBase || !isUnderRoot(dir, realBase)) return [];
- try {
- return readdirSync(dir)
- .map((n) => path.join(dir, n))
- .filter((p) => isAppSecret(p));
- } catch {
- return [];
- }
-}
-
-// The per-path gate above is exact-or-under, so a PARENT of a denied entry never
-// matches it — and the two recursive callers (`zip -r`, `fs.cp {recursive}`) walk
-// straight past the gate into the children. Both need the nested locations named
-// explicitly. Filtered by existence so the callers never refuse (or exclude) over
-// a path that isn't on this box.
-function sensitiveUnder(realBase: string): string[] {
- if (process.env.OS_FS_ALLOW_SENSITIVE === "1") return [];
- const h = homeDir();
- return [...SENSITIVE_HOME, ".mso"]
- .map((n) => path.join(h, n))
- .filter((p) => p !== realBase && isUnderRoot(p, realBase) && existsSync(p));
-}
-
-// Recursive READ (zip): NARROW the archive rather than refuse it — same shape as
-// appSecretExcludes. Info-ZIP `*` spans `/` and entries are stored relative to the
-// archive base, so `rel` drops a file and `rel/*` drops a whole dir.
-export function sensitiveExcludes(realBase: string): string[] {
- return sensitiveUnder(realBase).flatMap((p) => {
- const rel = path.relative(realBase, p);
- return [rel, `${rel}/*`];
- });
-}
-
-// Recursive WRITE (copy/move): REFUSE. Filtering is wrong for move — its EXDEV
-// branch is cp-then-rm, so a skipped file would be deleted instead of moved. And
-// a completed move relocates credentials OUT of their denylisted path, which makes
-// them plainly readable at the destination (relocate-then-read escalation).
-export function assertNoSensitiveDescendants(real: string): void {
- const hit = sensitiveUnder(real)[0];
- if (hit)
- throw new HostError(
- `Refusing: this directory contains a credential path (${path.relative(real, hit)})`,
- );
-}
-
-/** Walk a recursive mutation source and apply the same credential predicate used
- * by per-path reads/writes to every descendant. Directory operations otherwise
- * let fs.cp/fs.rename/fs.rm walk past the top-level gate. Symlinks are inspected
- * by their own path/name but never followed, so this guard cannot escape the
- * already-resolved mutation root or traverse a cycle. */
-export async function assertNoCredentialDescendants(
- realBase: string,
- options: { ignoreAppSecrets?: boolean } = {},
-): Promise<void> {
- const rootStat = await fs.lstat(realBase).catch(() => null);
- if (!rootStat?.isDirectory()) return;
-
- const stack = [realBase];
- while (stack.length) {
- const dir = stack.pop()!;
- let entries: import("fs").Dirent[];
- try {
- entries = await fs.readdir(dir, { withFileTypes: true });
- } catch (error) {
- throw new HostError(`Refusing recursive mutation: cannot inspect ${path.relative(realBase, dir) || "."}`);
- }
- for (const entry of entries) {
- const child = path.join(dir, entry.name);
- const credential = isCredentialPath(child);
- const ignoredAppSecret = options.ignoreAppSecrets === true && isAppSecret(child);
- if (credential && !ignoredAppSecret) {
- throw new HostError(
- `Refusing: this directory contains a credential path (${path.relative(realBase, child)})`,
- );
- }
- if (entry.isDirectory()) stack.push(child);
- }
- }
-}
-
-// The app's own `.env*` needed the narrower fix the ~/ list can't give: on the
-// DEFAULT roots (~ and ~/projects) APP_DIR is a descendant of a copyable dir, so
-// `copy(~/projects, ~/backup)` walked past the per-path gate and duplicated
-// .env.local somewhere /api/v1/fs/read serves. Refusing outright would block
-// copying ~/projects, which is an ordinary thing to do — so copy SKIPS them and
-// only move refuses.
-//
-// Recursive COPY: a filter for `fs.cp`. Returns undefined when there is nothing
-// to skip, so the ordinary copy path stays exactly as it was.
-export function appSecretCopyFilter(realBase: string): ((src: string) => boolean) | undefined {
- const secrets = new Set(appSecretsUnder(realBase));
- return secrets.size ? (src: string) => !secrets.has(src) : undefined;
-}
-
-// Recursive MOVE: REFUSE, for the same reason the ~/ list does. A filter is wrong
-// here — the EXDEV branch is cp-then-rm, so a skipped secret would be DELETED
-// rather than moved, and a completed move relocates it out of its denylisted path
-// and makes it plainly readable at the destination.
-export function assertNoAppSecretDescendants(real: string): void {
- const hit = appSecretsUnder(real)[0];
- if (hit)
- throw new HostError(
- `Refusing: this directory contains the cockpit's own secrets (${path.relative(real, hit)})`,
- );
-}
+import { isCredentialPath } from "./path-credentials";
+import { homeDir, isUnderRoot, readRootList, writeRootList } from "./path-roots";
+export { appDir, isAppSecret, isCredentialPath, isSensitivePath, looseCredentialExcludes } from "./path-credentials";
+export { appSecretCopyFilter, assertNoAppSecretDescendants, assertNoCredentialDescendants, assertNoSensitiveDescendants, sensitiveExcludes } from "./path-recursive";
+export { homeDir, isUnderRoot, readRootList, writeRootList } from "./path-roots";
function assertNotCredential(real: string): void {
if (isCredentialPath(real)) throw new HostError("Access to credential/sensitive files is blocked");
diff --git a/lib/host/pty.test.ts b/lib/host/pty.test.ts
index 582e5ed6..8dd48c7f 100644
--- a/lib/host/pty.test.ts
+++ b/lib/host/pty.test.ts
@@ -4,7 +4,6 @@
import { describe, expect, it } from "vitest";
import { attachPty, closePty, hasPty, openPty, writePty } from "./pty";
-const isWin = process.platform === "win32";
async function until(cond: () => boolean, ms: number): Promise<void> {
const deadline = Date.now() + ms;
@@ -12,7 +11,7 @@ async function until(cond: () => boolean, ms: number): Promise<void> {
await new Promise((r) => setTimeout(r, 25));
}
-describe.skipIf(isWin)("pty session manager", () => {
+describe("pty session manager", () => {
it("opens a shell, runs echo, replays buffer, and dies on close", async () => {
const { id, cwd } = await openPty({ cols: 80, rows: 24 });
expect(cwd.length).toBeGreaterThan(0);
diff --git a/lib/mcp/dispatch-authorization.test.ts b/lib/mcp/dispatch-authorization.test.ts
new file mode 100644
index 00000000..42e7a751
--- /dev/null
+++ b/lib/mcp/dispatch-authorization.test.ts
@@ -0,0 +1,213 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+// The catalog reaches lib/camoufox + lib/managed-apps, which are `server-only`.
+// Next aliases that specifier internally; vitest does not, so stub it — same
+// pattern as lib/managed-apps/manager.test.ts.
+vi.mock("server-only", () => ({}));
+const localSessionMock = vi.hoisted(() => ({ handoffOwnerLocalSession: vi.fn() }));
+vi.mock("@/lib/a2a/local-session", () => localSessionMock);
+
+// Spy on the trail without writing to ~/.mso/audit.log. Everything else in
+// @/lib/host stays REAL — the point of these cases is that the dispatcher, not
+// each tool, is what records.
+const audited: { action: string; actor?: string; target?: string; ok?: boolean }[] = [];
+vi.mock("@/lib/host/audit-api", async (orig) => {
+ const real = await orig<typeof import("@/lib/host/audit-api")>();
+ return { ...real, audit: (e: { action: string }) => { audited.push(e); return Promise.resolve(); } };
+});
+
+const { dispatch } = await import("./dispatch");
+const { TOOLS } = await import("./tools");
+const { activeWorkflowForActor } = await import("@/lib/workflow");
+
+const call = (name: string, args: Record<string, unknown> = {}) =>
+ ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
+
+describe("tools/call enforces scope even when the tool was never listed", () => {
+ it("refuses exec_run for a write token, and says how to fix it", async () => {
+ const r = await dispatch(call("exec_run", { command: "id" }), "write");
+ const res = r.result as { isError: boolean; content: { text: string }[] };
+ expect(res.isError).toBe(true);
+ expect(res.content[0].text).toContain('needs "exec"');
+ // NOT a JSON-RPC error — ChatGPT hides those from the user entirely.
+ expect(r.error).toBeUndefined();
+ });
+
+ it("refuses fs_delete for a read token", async () => {
+ const r = await dispatch(call("fs_delete", { path: "/tmp/x" }), "read");
+ expect((r.result as { isError: boolean }).isError).toBe(true);
+ });
+
+ it("rejects an unknown tool name", async () => {
+ expect((await dispatch(call("rm_rf_slash"), "exec")).error).toMatchObject({ code: -32602 });
+ });
+
+ it("rejects a call missing a required argument before running anything", async () => {
+ expect((await dispatch(call("fs_read", {}), "read")).error).toMatchObject({ code: -32602 });
+ });
+
+
+ it("records missing required arguments as invalid_args inside the exact workflow", async () => {
+ const actor = "mcp:invalid-args";
+ const started = await dispatch(call("workflow_start", { intent: "test invalid argument telemetry" }), "write", actor);
+ const workflowId = (JSON.parse((started.result as { content: { text: string }[] }).content[0].text) as { workflow: { id: string } }).workflow.id;
+ const bad = await dispatch(call("fs_write", { path: "/tmp/test", workflow_id: workflowId }), "write", actor);
+ expect(bad.error).toMatchObject({ code: -32602 });
+ expect((await activeWorkflowForActor(actor, workflowId))?.steps.at(-1)).toMatchObject({ tool: "fs_write", state: "invalid_args" });
+ await dispatch(call("workflow_cancel", { workflow_id: workflowId, reason: "test cleanup" }), "write", actor);
+ });
+
+ it("returns a handler failure as isError text, never as a protocol error", async () => {
+ // Outside every read root → lib/host refuses. The point is the SHAPE.
+ const r = await dispatch(call("fs_read", { path: "/proc/1/environ" }), "read");
+ expect(r.error).toBeUndefined();
+ expect((r.result as { isError?: boolean }).isError).toBe(true);
+ });
+
+ it("isolates parallel runs and treats missing workflow ids as standalone", async () => {
+ const actor = "mcp:workflow-context";
+ const firstStart = await dispatch(call("workflow_start", {
+ intent: "check server stats as the first correlated test",
+ }), "write", actor);
+ const first = JSON.parse((firstStart.result as { content: { text: string }[] }).content[0].text) as {
+ workflow: { id: string };
+ };
+ const secondStart = await dispatch(call("workflow_start", {
+ intent: "check server stats as the second correlated test",
+ }), "write", actor);
+ const second = JSON.parse((secondStart.result as { content: { text: string }[] }).content[0].text) as {
+ workflow: { id: string };
+ };
+
+ await dispatch(call("sys_stats", { workflow_id: first.workflow.id }), "read", actor);
+ await dispatch(call("sys_stats", { workflow_id: second.workflow.id }), "read", actor);
+ expect((await activeWorkflowForActor(actor, first.workflow.id))?.steps.map((step) => step.tool)).toEqual(["sys_stats"]);
+ expect((await activeWorkflowForActor(actor, second.workflow.id))?.steps.map((step) => step.tool)).toEqual(["sys_stats"]);
+
+ await dispatch(call("sys_stats"), "read", actor);
+ expect((await activeWorkflowForActor(actor, first.workflow.id))?.steps).toHaveLength(1);
+ expect((await activeWorkflowForActor(actor, second.workflow.id))?.steps).toHaveLength(1);
+
+ const wrong = await dispatch(call("sys_stats", { workflow_id: "wrong" }), "read", actor);
+ expect((wrong.result as { isError?: boolean }).isError).toBe(true);
+ expect((await activeWorkflowForActor(actor, first.workflow.id))?.steps).toHaveLength(1);
+
+ await dispatch(call("workflow_cancel", { workflow_id: first.workflow.id, reason: "test cleanup" }), "write", actor);
+ await dispatch(call("workflow_cancel", { workflow_id: second.workflow.id, reason: "test cleanup" }), "write", actor);
+ await expect(activeWorkflowForActor(actor, first.workflow.id)).resolves.toBeNull();
+ await expect(activeWorkflowForActor(actor, second.workflow.id)).resolves.toBeNull();
+ });
+
+ it("supports direct MCP image content for visual tools", async () => {
+ const tool = TOOLS.find((t) => t.name === "screen_capture");
+ expect(tool).toBeTruthy();
+ // Do not launch Chrome in the unit suite; temporarily replace the handler so
+ // this test only locks the dispatcher response shape.
+ const original = tool!.run;
+ tool!.run = async () => ({
+ __mcpDirect: true,
+ content: [
+ { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
+ { type: "text", text: "shot" },
+ ],
+ });
+ try {
+ const r = await dispatch(call("screen_capture"), "read", "mcp:test");
+ const content = (r.result as { content: Array<{ type: string }> }).content;
+ expect(content.map((c) => c.type)).toEqual(["image", "text"]);
+ } finally {
+ tool!.run = original;
+ }
+ });
+});
+
+describe("catalog hygiene", () => {
+ it("every tool is snake_case and uniquely named", () => {
+ const names = TOOLS.map((t) => t.name);
+ expect(new Set(names).size).toBe(names.length);
+ for (const n of names) expect(n).toMatch(/^[a-z][a-z0-9_]*$/);
+ });
+
+ it("offers optional workflow correlation on every operational tool", () => {
+ const exempt = new Set(["skills_search", "workflow_start", "workflow_cancel", "workflow_finish"]);
+ for (const tool of TOOLS) {
+ if (exempt.has(tool.name)) continue;
+ expect(tool.inputSchema.properties, tool.name).toHaveProperty("workflow_id");
+ expect(tool.inputSchema.required ?? [], tool.name).not.toContain("workflow_id");
+ }
+ });
+
+ it("every required arg is declared in properties — a mismatch is unfixable by the model", () => {
+ for (const t of TOOLS) {
+ for (const k of t.inputSchema.required ?? []) {
+ expect(Object.keys(t.inputSchema.properties), `${t.name}.${k}`).toContain(k);
+ }
+ }
+ });
+
+ it("read-scope tools are all annotated readOnlyHint, and no write tool claims it", () => {
+ for (const t of TOOLS) {
+ if (t.scope === "read") expect(t.annotations?.readOnlyHint, t.name).toBe(true);
+ else expect(t.annotations?.readOnlyHint, t.name).not.toBe(true);
+ }
+ });
+
+ it("the irreversible tools carry destructiveHint so clients keep prompting", () => {
+ for (const name of ["fs_delete", "exec_run", "browser_power"]) {
+ expect(TOOLS.find((t) => t.name === name)?.annotations?.destructiveHint, name).toBe(true);
+ }
+ });
+});
+
+describe("audit trail", () => {
+ beforeEach(() => {
+ audited.length = 0;
+ });
+
+ it("records a scope refusal — a read token reaching for exec IS the injection signal", async () => {
+ await dispatch(call("exec_run", { command: "id" }), "read", "mcp:abc123");
+ expect(audited).toEqual([
+ expect.objectContaining({ action: "mcp.denied", actor: "mcp:abc123", target: "exec_run", ok: false }),
+ ]);
+ });
+
+ it("records a failed write with its target, so a blocked path is visible", async () => {
+ await dispatch(call("fs_write", { path: "/etc/shadow", content: "x" }), "write", "mcp:abc123");
+ expect(audited).toEqual([
+ expect.objectContaining({ action: "fs.write", actor: "mcp:abc123", target: "/etc/shadow", ok: false }),
+ ]);
+ expect(audited[0]).toMatchObject({ meta: { via: "mcp", scope: "write" } });
+ });
+
+ it("records exec_run with the command as the target", async () => {
+ await dispatch(call("exec_run", { command: "echo hi" }), "exec", "mcp:abc123");
+ expect(audited[0]).toMatchObject({ action: "exec.run", target: "echo hi", ok: true, detail: "exit 0" });
+ });
+
+ it("records a REFUSED command as exec.blocked, not a successful exec.run", async () => {
+ // runCommand refuses by RETURNING {code:126}, not by throwing, so "did not
+ // throw" is not success. This shipped wrong on 2026-08-10: a blocked command
+ // landed in the trail as ok:true, and exec.blocked could never be emitted over
+ // MCP at all. Mirrors app/api/v1/exec/run/route.ts.
+ await dispatch(call("exec_run", { command: "rm -rf /" }), "exec", "mcp:abc123");
+ expect(audited[0]).toMatchObject({ action: "exec.blocked", ok: false });
+ });
+
+ it("records a non-zero exit as a failure, with the code", async () => {
+ await dispatch(call("exec_run", { command: "exit 3" }), "exec", "mcp:abc123");
+ expect(audited[0]).toMatchObject({ action: "exec.run", ok: false, detail: "exit 3" });
+ });
+
+ it("does NOT record reads — bounded and high-volume, same rule /api/v1 follows", async () => {
+ await dispatch(call("sys_stats"), "read", "mcp:abc123");
+ await dispatch(call("fs_list", { path: "~/projects" }), "read", "mcp:abc123");
+ await dispatch({ id: 1, method: "tools/list" }, "exec", "mcp:abc123");
+ expect(audited).toEqual([]);
+ });
+
+ it("every write/exec tool declares an audit action, and no read tool does", () => {
+ for (const t of TOOLS) {
+ if (t.scope === "read") expect(t.audit, t.name).toBeUndefined();
+ else expect(t.audit?.action, t.name).toBeTruthy();
+ }
+ });
+});
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index d1b2274f..7f7e5919 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, it, expect, vi } from "vitest";
+import { describe, expect, it, vi } from "vitest";
// The catalog reaches lib/camoufox + lib/managed-apps, which are `server-only`.
// Next aliases that specifier internally; vitest does not, so stub it — same
// pattern as lib/managed-apps/manager.test.ts.
@@ -18,7 +18,6 @@ vi.mock("@/lib/host/audit-api", async (orig) => {
const { dispatch, isNotification } = await import("./dispatch");
const { TOOLS } = await import("./tools");
const { MCP_SERVER_VERSION } = await import("./toolset");
-const { activeWorkflowForActor } = await import("@/lib/workflow");
const call = (name: string, args: Record<string, unknown> = {}) =>
({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
@@ -163,193 +162,3 @@ describe("local agent request dispatch", () => {
expect(JSON.stringify(r.result)).toContain("worker result");
});
});
-
-describe("tools/call enforces scope even when the tool was never listed", () => {
- it("refuses exec_run for a write token, and says how to fix it", async () => {
- const r = await dispatch(call("exec_run", { command: "id" }), "write");
- const res = r.result as { isError: boolean; content: { text: string }[] };
- expect(res.isError).toBe(true);
- expect(res.content[0].text).toContain('needs "exec"');
- // NOT a JSON-RPC error — ChatGPT hides those from the user entirely.
- expect(r.error).toBeUndefined();
- });
-
- it("refuses fs_delete for a read token", async () => {
- const r = await dispatch(call("fs_delete", { path: "/tmp/x" }), "read");
- expect((r.result as { isError: boolean }).isError).toBe(true);
- });
-
- it("rejects an unknown tool name", async () => {
- expect((await dispatch(call("rm_rf_slash"), "exec")).error).toMatchObject({ code: -32602 });
- });
-
- it("rejects a call missing a required argument before running anything", async () => {
- expect((await dispatch(call("fs_read", {}), "read")).error).toMatchObject({ code: -32602 });
- });
-
-
- it("records missing required arguments as invalid_args inside the exact workflow", async () => {
- const actor = "mcp:invalid-args";
- const started = await dispatch(call("workflow_start", { intent: "test invalid argument telemetry" }), "write", actor);
- const workflowId = (JSON.parse((started.result as { content: { text: string }[] }).content[0].text) as { workflow: { id: string } }).workflow.id;
- const bad = await dispatch(call("fs_write", { path: "/tmp/test", workflow_id: workflowId }), "write", actor);
- expect(bad.error).toMatchObject({ code: -32602 });
- expect((await activeWorkflowForActor(actor, workflowId))?.steps.at(-1)).toMatchObject({ tool: "fs_write", state: "invalid_args" });
- await dispatch(call("workflow_cancel", { workflow_id: workflowId, reason: "test cleanup" }), "write", actor);
- });
-
- it("returns a handler failure as isError text, never as a protocol error", async () => {
- // Outside every read root → lib/host refuses. The point is the SHAPE.
- const r = await dispatch(call("fs_read", { path: "/proc/1/environ" }), "read");
- expect(r.error).toBeUndefined();
- expect((r.result as { isError?: boolean }).isError).toBe(true);
- });
-
- it("isolates parallel runs and treats missing workflow ids as standalone", async () => {
- const actor = "mcp:workflow-context";
- const firstStart = await dispatch(call("workflow_start", {
- intent: "check server stats as the first correlated test",
- }), "write", actor);
- const first = JSON.parse((firstStart.result as { content: { text: string }[] }).content[0].text) as {
- workflow: { id: string };
- };
- const secondStart = await dispatch(call("workflow_start", {
- intent: "check server stats as the second correlated test",
- }), "write", actor);
- const second = JSON.parse((secondStart.result as { content: { text: string }[] }).content[0].text) as {
- workflow: { id: string };
- };
-
- await dispatch(call("sys_stats", { workflow_id: first.workflow.id }), "read", actor);
- await dispatch(call("sys_stats", { workflow_id: second.workflow.id }), "read", actor);
- expect((await activeWorkflowForActor(actor, first.workflow.id))?.steps.map((step) => step.tool)).toEqual(["sys_stats"]);
- expect((await activeWorkflowForActor(actor, second.workflow.id))?.steps.map((step) => step.tool)).toEqual(["sys_stats"]);
-
- await dispatch(call("sys_stats"), "read", actor);
- expect((await activeWorkflowForActor(actor, first.workflow.id))?.steps).toHaveLength(1);
- expect((await activeWorkflowForActor(actor, second.workflow.id))?.steps).toHaveLength(1);
-
- const wrong = await dispatch(call("sys_stats", { workflow_id: "wrong" }), "read", actor);
- expect((wrong.result as { isError?: boolean }).isError).toBe(true);
- expect((await activeWorkflowForActor(actor, first.workflow.id))?.steps).toHaveLength(1);
-
- await dispatch(call("workflow_cancel", { workflow_id: first.workflow.id, reason: "test cleanup" }), "write", actor);
- await dispatch(call("workflow_cancel", { workflow_id: second.workflow.id, reason: "test cleanup" }), "write", actor);
- await expect(activeWorkflowForActor(actor, first.workflow.id)).resolves.toBeNull();
- await expect(activeWorkflowForActor(actor, second.workflow.id)).resolves.toBeNull();
- });
-
- it("supports direct MCP image content for visual tools", async () => {
- const tool = TOOLS.find((t) => t.name === "screen_capture");
- expect(tool).toBeTruthy();
- // Do not launch Chrome in the unit suite; temporarily replace the handler so
- // this test only locks the dispatcher response shape.
- const original = tool!.run;
- tool!.run = async () => ({
- __mcpDirect: true,
- content: [
- { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
- { type: "text", text: "shot" },
- ],
- });
- try {
- const r = await dispatch(call("screen_capture"), "read", "mcp:test");
- const content = (r.result as { content: Array<{ type: string }> }).content;
- expect(content.map((c) => c.type)).toEqual(["image", "text"]);
- } finally {
- tool!.run = original;
- }
- });
-});
-
-describe("catalog hygiene", () => {
- it("every tool is snake_case and uniquely named", () => {
- const names = TOOLS.map((t) => t.name);
- expect(new Set(names).size).toBe(names.length);
- for (const n of names) expect(n).toMatch(/^[a-z][a-z0-9_]*$/);
- });
-
- it("offers optional workflow correlation on every operational tool", () => {
- const exempt = new Set(["skills_search", "workflow_start", "workflow_cancel", "workflow_finish"]);
- for (const tool of TOOLS) {
- if (exempt.has(tool.name)) continue;
- expect(tool.inputSchema.properties, tool.name).toHaveProperty("workflow_id");
- expect(tool.inputSchema.required ?? [], tool.name).not.toContain("workflow_id");
- }
- });
-
- it("every required arg is declared in properties — a mismatch is unfixable by the model", () => {
- for (const t of TOOLS) {
- for (const k of t.inputSchema.required ?? []) {
- expect(Object.keys(t.inputSchema.properties), `${t.name}.${k}`).toContain(k);
- }
- }
- });
-
- it("read-scope tools are all annotated readOnlyHint, and no write tool claims it", () => {
- for (const t of TOOLS) {
- if (t.scope === "read") expect(t.annotations?.readOnlyHint, t.name).toBe(true);
- else expect(t.annotations?.readOnlyHint, t.name).not.toBe(true);
- }
- });
-
- it("the irreversible tools carry destructiveHint so clients keep prompting", () => {
- for (const name of ["fs_delete", "exec_run", "browser_power"]) {
- expect(TOOLS.find((t) => t.name === name)?.annotations?.destructiveHint, name).toBe(true);
- }
- });
-});
-
-describe("audit trail", () => {
- beforeEach(() => {
- audited.length = 0;
- });
-
- it("records a scope refusal — a read token reaching for exec IS the injection signal", async () => {
- await dispatch(call("exec_run", { command: "id" }), "read", "mcp:abc123");
- expect(audited).toEqual([
- expect.objectContaining({ action: "mcp.denied", actor: "mcp:abc123", target: "exec_run", ok: false }),
- ]);
- });
-
- it("records a failed write with its target, so a blocked path is visible", async () => {
- await dispatch(call("fs_write", { path: "/etc/shadow", content: "x" }), "write", "mcp:abc123");
- expect(audited).toEqual([
- expect.objectContaining({ action: "fs.write", actor: "mcp:abc123", target: "/etc/shadow", ok: false }),
- ]);
- expect(audited[0]).toMatchObject({ meta: { via: "mcp", scope: "write" } });
- });
-
- it("records exec_run with the command as the target", async () => {
- await dispatch(call("exec_run", { command: "echo hi" }), "exec", "mcp:abc123");
- expect(audited[0]).toMatchObject({ action: "exec.run", target: "echo hi", ok: true, detail: "exit 0" });
- });
-
- it("records a REFUSED command as exec.blocked, not a successful exec.run", async () => {
- // runCommand refuses by RETURNING {code:126}, not by throwing, so "did not
- // throw" is not success. This shipped wrong on 2026-08-10: a blocked command
- // landed in the trail as ok:true, and exec.blocked could never be emitted over
- // MCP at all. Mirrors app/api/v1/exec/run/route.ts.
- await dispatch(call("exec_run", { command: "rm -rf /" }), "exec", "mcp:abc123");
- expect(audited[0]).toMatchObject({ action: "exec.blocked", ok: false });
- });
-
- it("records a non-zero exit as a failure, with the code", async () => {
- await dispatch(call("exec_run", { command: "exit 3" }), "exec", "mcp:abc123");
- expect(audited[0]).toMatchObject({ action: "exec.run", ok: false, detail: "exit 3" });
- });
-
- it("does NOT record reads — bounded and high-volume, same rule /api/v1 follows", async () => {
- await dispatch(call("sys_stats"), "read", "mcp:abc123");
- await dispatch(call("fs_list", { path: "~/projects" }), "read", "mcp:abc123");
- await dispatch({ id: 1, method: "tools/list" }, "exec", "mcp:abc123");
- expect(audited).toEqual([]);
- });
-
- it("every write/exec tool declares an audit action, and no read tool does", () => {
- for (const t of TOOLS) {
- if (t.scope === "read") expect(t.audit, t.name).toBeUndefined();
- else expect(t.audit?.action, t.name).toBeTruthy();
- }
- });
-});
diff --git a/lib/mcp/tools-learning-evidence.test.ts b/lib/mcp/tools-learning-evidence.test.ts
new file mode 100644
index 00000000..aad8ce16
--- /dev/null
+++ b/lib/mcp/tools-learning-evidence.test.ts
@@ -0,0 +1,167 @@
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-workflow-bootstrap-"));
+const project = path.join(dir, "mso");
+await fs.mkdir(project);
+await fs.writeFile(path.join(project, "package.json"), JSON.stringify({
+ name: "mso", version: "9.9.9", scripts: { test: "vitest", build: "next build" },
+}));
+// A skill living inside a DIFFERENT project than the one the workflow names. The
+// bootstrap search must still find it: capability discovery is global, and an agent
+// that can only see the current project's skills relearns what the box already knows.
+const sibling = path.join(dir, "orchard");
+await fs.mkdir(path.join(sibling, ".claude/skills/orchard-harvest"), { recursive: true });
+await fs.writeFile(
+ path.join(sibling, ".claude/skills/orchard-harvest/SKILL.md"),
+ "---\nname: orchard-harvest\ndescription: Harvest and verify the orchard dataset export.\n---\n\n# Orchard harvest\n",
+);
+
+const previous = {
+ read: process.env.OS_FS_READ_ROOTS,
+ write: process.env.OS_FS_WRITE_ROOTS,
+ memory: process.env.OS_SKILL_MEMORY_STORE,
+};
+process.env.OS_FS_READ_ROOTS = dir;
+process.env.OS_FS_WRITE_ROOTS = dir;
+process.env.OS_SKILL_MEMORY_STORE = path.join(dir, "memory.json");
+const { resetWorkflowStoreCache } = await import("@/lib/workflow");
+const { LEARNING_TOOLS } = await import("./tools-learning");
+
+/** The root-qualified id the catalog assigns, computed the same way it does. */
+describe("workflow_start bootstrap", () => {
+ beforeEach(async () => {
+ await fs.rm(process.env.OS_SKILL_MEMORY_STORE!, { force: true });
+ resetWorkflowStoreCache();
+ });
+ afterAll(async () => {
+ if (previous.read === undefined) delete process.env.OS_FS_READ_ROOTS;
+ else process.env.OS_FS_READ_ROOTS = previous.read;
+ if (previous.write === undefined) delete process.env.OS_FS_WRITE_ROOTS;
+ else process.env.OS_FS_WRITE_ROOTS = previous.write;
+ if (previous.memory === undefined) delete process.env.OS_SKILL_MEMORY_STORE;
+ else process.env.OS_SKILL_MEMORY_STORE = previous.memory;
+ resetWorkflowStoreCache();
+ await fs.rm(dir, { recursive: true, force: true });
+ });
+
+ it("classifies high-risk work, requires evidence, and persists a repo-local receipt plus task memory", async () => {
+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
+ const finish = LEARNING_TOOLS.find((tool) => tool.name === "workflow_finish")!;
+ const context = { actor: "mcp:rasmic-high", scope: "write" as const };
+ const started = await start.run({
+ intent: "update authentication and database schema before production deployment",
+ project,
+ }, context) as {
+ workflow: { id: string; orchestration?: { risk: string; isolation: string } };
+ bootstrap: { orchestration: { classification: { risk: string; isolation: string; verification: string } } };
+ };
+ expect(started.workflow.orchestration).toMatchObject({ risk: "high", isolation: "isolated-worktree" });
+ expect(started.bootstrap.orchestration.classification).toMatchObject({
+ risk: "high", isolation: "isolated-worktree", verification: "full",
+ });
+
+ await expect(finish.run({
+ workflow_id: started.workflow.id, summary: "done", success: true,
+ }, context)).rejects.toThrow(/requires explicit/i);
+ const { activeWorkflowForActor } = await import("@/lib/workflow");
+ await expect(activeWorkflowForActor(context.actor, started.workflow.id)).resolves.toMatchObject({ id: started.workflow.id });
+
+ const done = await finish.run({
+ workflow_id: started.workflow.id,
+ summary: "auth/schema change verified",
+ success: true,
+ evidence: { tests: ["targeted auth/schema regression passed"], manual_verification: ["smoke verification passed"] },
+ }, context) as {
+ evidence: { valid: boolean; path?: string };
+ repoMemory: { taskMemoryId?: string; warnings: string[] };
+ };
+ expect(done.evidence.valid).toBe(true);
+ expect(done.evidence.path).toMatch(/^\.agent\/evidence\//);
+ expect(done.repoMemory.taskMemoryId).toMatch(/^mem_/);
+ expect(done.repoMemory.warnings).toEqual([]);
+ expect((await fs.readdir(path.join(project, ".agent/evidence"))).length).toBeGreaterThan(0);
+ expect((await fs.readdir(path.join(project, ".agent/memory/tasks"))).length).toBeGreaterThan(0);
+ });
+
+ it("records a user manual failed test through the public project memory tool", async () => {
+ const upsert = LEARNING_TOOLS.find((tool) => tool.name === "project_memory_upsert")!;
+ const search = LEARNING_TOOLS.find((tool) => tool.name === "project_memory_search")!;
+ const context = { actor: "mcp:rasmic-manual", scope: "write" as const };
+ const record = await upsert.run({
+ project, kind: "test", title: "Reconnect smoke",
+ summary: "user reports the runtime still freezes after reconnect",
+ observation: "user reports the runtime still freezes after reconnect",
+ source: "user-manual", result: "fail", environment: "mobile PWA",
+ }, context) as { id: string; source: string; result: string; confidence: number };
+ expect(record).toMatchObject({ source: "user-manual", result: "fail", confidence: 1 });
+ const result = await search.run({ project, query: "freezes reconnect", kind: "test" }, context) as {
+ hits: Array<{ record: { id: string; source: string; result: string } }>
+ };
+ expect(result.hits[0].record).toMatchObject({ id: record.id, source: "user-manual", result: "fail" });
+ });
+
+ it("replays a bounded read-only candidate script and promotes it to tested", async () => {
+ const runner = LEARNING_TOOLS.find((tool) => tool.name === "project_script_run")!;
+ const { writeAutomationScript, readAutomationScript } = await import("@/lib/orchestration/repo-memory-artifacts");
+ const now = new Date().toISOString();
+ const script = {
+ schemaVersion: 1 as const, id: "script-test-health", recipeId: "recipe-test-health",
+ status: "candidate" as const, intent: "verify system health", project,
+ steps: [{ tool: "sys_stats" }], output: { format: "structured-json" as const },
+ gates: {
+ repeatedPattern: true, stableSteps: true, clearInputs: true, clearOutputs: true,
+ sideEffectsUnderstood: true, secretSafe: true, tested: false,
+ },
+ createdAt: now, updatedAt: now,
+ };
+ await writeAutomationScript(project, script, script.id, true);
+ const result = await runner.run({ project, script_id: script.id }, { actor: "mcp:script", scope: "write" }) as {
+ status: string; success: boolean; stepsExecuted: number; outputs: Array<{ tool: string; state: string }>; manifestPath?: string;
+ };
+ expect(result).toMatchObject({ status: "tested", success: true, stepsExecuted: 1 });
+ expect(result.outputs).toEqual([expect.objectContaining({ tool: "sys_stats", state: "completed" })]);
+ expect(result.manifestPath).toBe(`.agent/scripts/${script.id}.json`);
+ await expect(readAutomationScript(project, script.id)).resolves.toMatchObject({ status: "tested", gates: { tested: true } });
+ await expect(fs.lstat(path.join(project, `.agent/scripts/${script.id}.candidate.json`))).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("refuses a tampered automation manifest that attempts a write or exec tool", async () => {
+ const runner = LEARNING_TOOLS.find((tool) => tool.name === "project_script_run")!;
+ const { writeAutomationScript } = await import("@/lib/orchestration/repo-memory-artifacts");
+ const now = new Date().toISOString();
+ const script = {
+ schemaVersion: 1 as const, id: "script-tampered", recipeId: "recipe-tampered",
+ status: "candidate" as const, intent: "unsafe replay", project,
+ steps: [{ tool: "exec_run", args: { command: "echo no" } }], output: { format: "structured-json" as const },
+ gates: { repeatedPattern: true, stableSteps: true, clearInputs: true, clearOutputs: true, sideEffectsUnderstood: true, secretSafe: true, tested: false },
+ createdAt: now, updatedAt: now,
+ };
+ await writeAutomationScript(project, script, script.id, true);
+ await expect(runner.run({ project, script_id: script.id }, { actor: "mcp:script", scope: "write" })).rejects.toThrow(/not replay-safe/i);
+ });
+
+ it("keeps a trivial low-risk success memory-light and does not create .agent", async () => {
+ const lightProject = path.join(dir, `light-${Date.now()}`);
+ await fs.mkdir(lightProject);
+ await fs.writeFile(path.join(lightProject, "package.json"), JSON.stringify({ name: "light-fixture" }));
+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
+ const finish = LEARNING_TOOLS.find((tool) => tool.name === "workflow_finish")!;
+ const context = { actor: "mcp:rasmic-light", scope: "write" as const };
+ const started = await start.run({ intent: "fix a typo in docs only", project: lightProject }, context) as {
+ workflow: { id: string; orchestration?: { risk: string; memoryRelevance: string } };
+ };
+ expect(started.workflow.orchestration).toMatchObject({ risk: "low", memoryRelevance: "low" });
+ const done = await finish.run({
+ workflow_id: started.workflow.id, summary: "typo fixed and targeted check passed", success: true,
+ }, context) as { evidence: { path?: string }; repoMemory: { taskMemoryId?: string } };
+ expect(done.evidence.path).toBeUndefined();
+ expect(done.repoMemory.taskMemoryId).toBeUndefined();
+ await expect(fs.lstat(path.join(lightProject, ".agent"))).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+});
diff --git a/lib/mcp/tools-learning.test.ts b/lib/mcp/tools-learning.test.ts
index 20de4e3a..e946dd95 100644
--- a/lib/mcp/tools-learning.test.ts
+++ b/lib/mcp/tools-learning.test.ts
@@ -1,9 +1,9 @@
-import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
-
-vi.mock("server-only", () => ({}));
import { promises as fs } from "fs";
import os from "os";
import path from "path";
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-workflow-bootstrap-"));
const project = path.join(dir, "mso");
@@ -153,119 +153,4 @@ describe("workflow_start bootstrap", () => {
await expect(activeWorkflowForActor(context.actor)).resolves.toBeNull();
});
- it("classifies high-risk work, requires evidence, and persists a repo-local receipt plus task memory", async () => {
- const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
- const finish = LEARNING_TOOLS.find((tool) => tool.name === "workflow_finish")!;
- const context = { actor: "mcp:rasmic-high", scope: "write" as const };
- const started = await start.run({
- intent: "update authentication and database schema before production deployment",
- project,
- }, context) as {
- workflow: { id: string; orchestration?: { risk: string; isolation: string } };
- bootstrap: { orchestration: { classification: { risk: string; isolation: string; verification: string } } };
- };
- expect(started.workflow.orchestration).toMatchObject({ risk: "high", isolation: "isolated-worktree" });
- expect(started.bootstrap.orchestration.classification).toMatchObject({
- risk: "high", isolation: "isolated-worktree", verification: "full",
- });
-
- await expect(finish.run({
- workflow_id: started.workflow.id, summary: "done", success: true,
- }, context)).rejects.toThrow(/requires explicit/i);
- const { activeWorkflowForActor } = await import("@/lib/workflow");
- await expect(activeWorkflowForActor(context.actor, started.workflow.id)).resolves.toMatchObject({ id: started.workflow.id });
-
- const done = await finish.run({
- workflow_id: started.workflow.id,
- summary: "auth/schema change verified",
- success: true,
- evidence: { tests: ["targeted auth/schema regression passed"], manual_verification: ["smoke verification passed"] },
- }, context) as {
- evidence: { valid: boolean; path?: string };
- repoMemory: { taskMemoryId?: string; warnings: string[] };
- };
- expect(done.evidence.valid).toBe(true);
- expect(done.evidence.path).toMatch(/^\.agent\/evidence\//);
- expect(done.repoMemory.taskMemoryId).toMatch(/^mem_/);
- expect(done.repoMemory.warnings).toEqual([]);
- expect((await fs.readdir(path.join(project, ".agent/evidence"))).length).toBeGreaterThan(0);
- expect((await fs.readdir(path.join(project, ".agent/memory/tasks"))).length).toBeGreaterThan(0);
- });
-
- it("records a user manual failed test through the public project memory tool", async () => {
- const upsert = LEARNING_TOOLS.find((tool) => tool.name === "project_memory_upsert")!;
- const search = LEARNING_TOOLS.find((tool) => tool.name === "project_memory_search")!;
- const context = { actor: "mcp:rasmic-manual", scope: "write" as const };
- const record = await upsert.run({
- project, kind: "test", title: "Reconnect smoke",
- summary: "user reports the runtime still freezes after reconnect",
- observation: "user reports the runtime still freezes after reconnect",
- source: "user-manual", result: "fail", environment: "mobile PWA",
- }, context) as { id: string; source: string; result: string; confidence: number };
- expect(record).toMatchObject({ source: "user-manual", result: "fail", confidence: 1 });
- const result = await search.run({ project, query: "freezes reconnect", kind: "test" }, context) as {
- hits: Array<{ record: { id: string; source: string; result: string } }>
- };
- expect(result.hits[0].record).toMatchObject({ id: record.id, source: "user-manual", result: "fail" });
- });
-
- it("replays a bounded read-only candidate script and promotes it to tested", async () => {
- const runner = LEARNING_TOOLS.find((tool) => tool.name === "project_script_run")!;
- const { writeAutomationScript, readAutomationScript } = await import("@/lib/orchestration/repo-memory-artifacts");
- const now = new Date().toISOString();
- const script = {
- schemaVersion: 1 as const, id: "script-test-health", recipeId: "recipe-test-health",
- status: "candidate" as const, intent: "verify system health", project,
- steps: [{ tool: "sys_stats" }], output: { format: "structured-json" as const },
- gates: {
- repeatedPattern: true, stableSteps: true, clearInputs: true, clearOutputs: true,
- sideEffectsUnderstood: true, secretSafe: true, tested: false,
- },
- createdAt: now, updatedAt: now,
- };
- await writeAutomationScript(project, script, script.id, true);
- const result = await runner.run({ project, script_id: script.id }, { actor: "mcp:script", scope: "write" }) as {
- status: string; success: boolean; stepsExecuted: number; outputs: Array<{ tool: string; state: string }>; manifestPath?: string;
- };
- expect(result).toMatchObject({ status: "tested", success: true, stepsExecuted: 1 });
- expect(result.outputs).toEqual([expect.objectContaining({ tool: "sys_stats", state: "completed" })]);
- expect(result.manifestPath).toBe(`.agent/scripts/${script.id}.json`);
- await expect(readAutomationScript(project, script.id)).resolves.toMatchObject({ status: "tested", gates: { tested: true } });
- await expect(fs.lstat(path.join(project, `.agent/scripts/${script.id}.candidate.json`))).rejects.toMatchObject({ code: "ENOENT" });
- });
-
- it("refuses a tampered automation manifest that attempts a write or exec tool", async () => {
- const runner = LEARNING_TOOLS.find((tool) => tool.name === "project_script_run")!;
- const { writeAutomationScript } = await import("@/lib/orchestration/repo-memory-artifacts");
- const now = new Date().toISOString();
- const script = {
- schemaVersion: 1 as const, id: "script-tampered", recipeId: "recipe-tampered",
- status: "candidate" as const, intent: "unsafe replay", project,
- steps: [{ tool: "exec_run", args: { command: "echo no" } }], output: { format: "structured-json" as const },
- gates: { repeatedPattern: true, stableSteps: true, clearInputs: true, clearOutputs: true, sideEffectsUnderstood: true, secretSafe: true, tested: false },
- createdAt: now, updatedAt: now,
- };
- await writeAutomationScript(project, script, script.id, true);
- await expect(runner.run({ project, script_id: script.id }, { actor: "mcp:script", scope: "write" })).rejects.toThrow(/not replay-safe/i);
- });
-
- it("keeps a trivial low-risk success memory-light and does not create .agent", async () => {
- const lightProject = path.join(dir, `light-${Date.now()}`);
- await fs.mkdir(lightProject);
- await fs.writeFile(path.join(lightProject, "package.json"), JSON.stringify({ name: "light-fixture" }));
- const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
- const finish = LEARNING_TOOLS.find((tool) => tool.name === "workflow_finish")!;
- const context = { actor: "mcp:rasmic-light", scope: "write" as const };
- const started = await start.run({ intent: "fix a typo in docs only", project: lightProject }, context) as {
- workflow: { id: string; orchestration?: { risk: string; memoryRelevance: string } };
- };
- expect(started.workflow.orchestration).toMatchObject({ risk: "low", memoryRelevance: "low" });
- const done = await finish.run({
- workflow_id: started.workflow.id, summary: "typo fixed and targeted check passed", success: true,
- }, context) as { evidence: { path?: string }; repoMemory: { taskMemoryId?: string } };
- expect(done.evidence.path).toBeUndefined();
- expect(done.repoMemory.taskMemoryId).toBeUndefined();
- await expect(fs.lstat(path.join(lightProject, ".agent"))).rejects.toMatchObject({ code: "ENOENT" });
- });
-
});
diff --git a/lib/mcp/tools-mutate.ts b/lib/mcp/tools-mutate.ts
new file mode 100644
index 00000000..88a7bec8
--- /dev/null
+++ b/lib/mcp/tools-mutate.ts
@@ -0,0 +1,215 @@
+import { sessionArtifactEnvironment } from "@/lib/agent/artifact-session";
+import { cancelExecJob, getExecJob, runCommand, startExecJob } from "@/lib/host/exec-api";
+import { copy, makeDir, move, remove, writeFileGuarded } from "@/lib/host/fs-api";
+import { resolveProjectHint, runProjectFunction } from "@/lib/host/projects-api";
+import { importOpenAiProvidedFile } from "./openai-file-upload";
+import { type McpTool, opt, PATH_P, S, str } from "./tool-kit";
+
+// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,
+// not the tool, writes the trail, because these call lib/host directly and so
+// never pass the route-layer audit that covers /api/v1.
+export const MUTATE_TOOLS: McpTool[] = [
+ {
+ name: "fs_write",
+ limit: { key: "fs.write", max: 120, windowMs: 60_000 },
+ audit: { action: "fs.write" as const, targetArg: "path" },
+ description:
+ "Create or overwrite a text file on the VPS. Inspect with fs_read first and pass its SHA-256 as expected_sha256 " +
+ "to refuse a stale overwrite when another process changed the file. Omitting the hash keeps legacy overwrite behaviour. " +
+ "Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",
+ scope: "write",
+ annotations: { idempotentHint: true },
+ inputSchema: S({
+ ...PATH_P,
+ content: { type: "string" },
+ expected_sha256: { type: "string", description: "Optional SHA-256 returned by fs_read; refuse if the current file no longer matches." },
+ }, ["path", "content"]),
+ run: async (a) => ({ ok: true, ...(await writeFileGuarded({
+ path: str(a, "path"),
+ content: typeof a.content === "string" ? a.content : "",
+ expectedSha256: opt(a, "expected_sha256"),
+ })) }),
+ },
+ {
+ name: "fs_upload_file",
+ limit: { key: "fs.upload", max: 20, windowMs: 60_000 },
+ audit: { action: "fs.upload" as const, targetArg: "dest" },
+ description:
+ "Import one ChatGPT conversation/generated file into an existing VPS directory. " +
+ "ChatGPT binds the top-level file parameter through openai/fileParams, MSO downloads the temporary OpenAI URL immediately, validates the host/type/size, writes within OS_FS_WRITE_ROOTS, and returns byte count plus SHA-256. Existing same-name files may be replaced.",
+ scope: "write",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ meta: { "openai/fileParams": ["file"] },
+ inputSchema: S({
+ file: {
+ type: "object",
+ description: "ChatGPT-provided file reference. Select or attach exactly one generated/uploaded image.",
+ properties: {
+ download_url: { type: "string" },
+ file_id: { type: "string" },
+ mime_type: { type: "string" },
+ file_name: { type: "string" },
+ name: { type: "string" },
+ size: { type: "number" },
+ },
+ required: ["download_url", "file_id"],
+ additionalProperties: true,
+ },
+ dest: { type: "string", description: "Existing destination directory on the VPS, within OS_FS_WRITE_ROOTS." },
+ filename: { type: "string", description: "Optional safe destination basename; defaults to the ChatGPT filename." },
+ }, ["file", "dest"]),
+ run: async (a) => importOpenAiProvidedFile({
+ file: a.file,
+ dest: str(a, "dest"),
+ filename: opt(a, "filename"),
+ }),
+ },
+ {
+ name: "fs_mkdir",
+ limit: { key: "fs.mkdir", max: 120, windowMs: 60_000 },
+ audit: { action: "fs.mkdir" as const, targetArg: "path" },
+ description: "Create a directory (and any missing parents) on the VPS.",
+ scope: "write",
+ annotations: { idempotentHint: true },
+ inputSchema: S(PATH_P, ["path"]),
+ run: async (a) => { await makeDir(str(a, "path")); return { ok: true, path: a.path }; },
+ },
+ {
+ name: "fs_move",
+ limit: { key: "fs.move", max: 120, windowMs: 60_000 },
+ audit: { action: "fs.move" as const, targetArg: "from" },
+ description: "Move or rename a file or directory. Refuses when the source holds credential paths.",
+ scope: "write",
+ inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
+ run: async (a) => { await move(str(a, "from"), str(a, "to")); return { ok: true }; },
+ },
+ {
+ name: "fs_copy",
+ limit: { key: "fs.copy", max: 60, windowMs: 60_000 },
+ audit: { action: "fs.copy" as const, targetArg: "from" },
+ description: "Copy a file or directory. The cockpit's own secrets are skipped rather than duplicated.",
+ scope: "write",
+ inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
+ run: async (a) => { await copy(str(a, "from"), str(a, "to")); return { ok: true }; },
+ },
+ {
+ name: "fs_delete",
+ limit: { key: "fs.delete", max: 60, windowMs: 60_000 },
+ audit: { action: "fs.delete" as const, targetArg: "path" },
+ description:
+ "Delete a file or directory on the VPS. PERMANENT — there is no trash and no undo. " +
+ "Confirm with the user before calling this on anything you did not create in this conversation.",
+ scope: "write",
+ annotations: { destructiveHint: true },
+ inputSchema: S(PATH_P, ["path"]),
+ run: async (a) => { await remove(str(a, "path")); return { ok: true, path: a.path }; },
+ },
+
+ {
+ name: "project_function_call",
+ limit: { key: "projects.function", max: 60, windowMs: 60_000 },
+ audit: {
+ action: "exec.run" as const,
+ targetArg: "project",
+ outcome: (r) => {
+ const { code } = r as { code: number };
+ return { ok: code === 0, action: "exec.run", detail: `project function exit ${code}` };
+ },
+ },
+ description:
+ "Execute ONE function explicitly declared by a validated project's .mso/functions.json. " +
+ "This is project code execution and therefore requires exec scope. The manifest supplies fixed argv; model/user input is passed only as JSON on stdin and is NEVER interpolated into a shell command. " +
+ "Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing. A function may return a validated bounded direct-image envelope for visual debugging; invalid envelopes remain ordinary text output.",
+ scope: "exec",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ inputSchema: S({
+ project: { type: "string", description: "Exact project id from projects_list, absolute path, name or alias." },
+ name: { type: "string", description: "Function name returned by project_capabilities." },
+ input: { type: "object", description: "JSON object passed to the project function on stdin.", additionalProperties: true },
+ }, ["project", "name", "input"]),
+ run: async (a) => {
+ const project = await resolveProjectHint(str(a, "project"));
+ if (!project) throw new Error(`project not found: ${String(a.project)}`);
+ return (await import("./project-function-content")).projectFunctionContent(await runProjectFunction(project.path, str(a, "name"), a.input));
+ },
+ },
+ {
+ name: "exec_job_start",
+ limit: { key: "exec.job.start", max: 12, windowMs: 60_000 },
+ audit: {
+ action: "exec.job.start" as const,
+ targetArg: "command",
+ outcome: (r) => {
+ const row = r as { state: string };
+ const refused = row.state === "refused";
+ return { ok: !refused, action: refused ? "exec.blocked" : "exec.job.start", detail: refused ? "refused" : "started" };
+ },
+ },
+ description:
+ "Start one bounded asynchronous shell job for legitimate test/build pipelines that exceed exec_run's 30s request budget. " +
+ "The job is client/workflow-bound, capped at 20 minutes and 1 MiB per output stream, limited to four concurrent jobs per client, and uses the same cwd jail and catastrophic-command filter as exec_run. Use exec_job_status to read it and exec_job_cancel to stop it.",
+ scope: "exec",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ inputSchema: S({
+ command: { type: "string", description: "The shell command line to run asynchronously." },
+ cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
+ }, ["command"]),
+ run: async (a, context) => startExecJob({
+ artifactEnv: await sessionArtifactEnvironment(context),
+ command: str(a, "command"), cwd: opt(a, "cwd"), actor: context.workflowActor ?? context.actor, workflowId: context.workflowId,
+ }),
+ },
+ {
+ name: "exec_job_status",
+ limit: { key: "exec.job.status", max: 120, windowMs: 60_000 },
+ description:
+ "Read one asynchronous exec job owned by this MCP client. Returns state, bounded stdout/stderr, exit code when finished, and whether output was truncated.",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ result: { maxTextBytes: 64 * 1024, overflowHint: "The job output is larger than the model context budget; rerun a focused grep/tail after completion if more detail is needed." },
+ inputSchema: S({ job_id: { type: "string", description: "Exact id returned by exec_job_start." } }, ["job_id"]),
+ run: (a, context) => Promise.resolve(getExecJob(str(a, "job_id"), context.workflowActor ?? context.actor, context.workflowId)),
+ },
+ {
+ name: "exec_job_cancel",
+ limit: { key: "exec.job.cancel", max: 30, windowMs: 60_000 },
+ audit: { action: "exec.job.cancel" as const, targetArg: "job_id" },
+ description:
+ "Cancel one still-running asynchronous exec job owned by this MCP client. Repeated cancellation is idempotent.",
+ scope: "exec",
+ annotations: { destructiveHint: true, idempotentHint: true },
+ inputSchema: S({ job_id: { type: "string", description: "Exact id returned by exec_job_start." } }, ["job_id"]),
+ run: (a, context) => Promise.resolve(cancelExecJob(str(a, "job_id"), context.workflowActor ?? context.actor, context.workflowId)),
+ },
+ {
+ name: "exec_run",
+ limit: { key: "exec", max: 60, windowMs: 60_000 },
+ audit: {
+ action: "exec.run" as const,
+ targetArg: "command",
+ // runCommand REFUSES by returning {code:126, stderr:"refused: …"}, it does not
+ // throw — so "the handler did not throw" is not success here. Mirrors
+ // app/api/v1/exec/run/route.ts:39-45 exactly; the two must not disagree about
+ // what the same command did.
+ outcome: (r) => {
+ const { code, stderr } = r as { code: number; stderr: string };
+ const blocked = code === 126 && stderr.startsWith("refused:");
+ return { ok: !blocked && code === 0, action: blocked ? "exec.blocked" : "exec.run", detail: `exit ${code}` };
+ },
+ },
+ description:
+ "Run a shell command on the VPS as the owner and return stdout, stderr and exit code. " +
+ "FULL HOST POWER — prefer fs_* and sys_* tools whenever they cover the task; they are bounded and " +
+ "this is not. Catastrophic patterns (rm -rf /, fork bombs, disk wipes) are refused by the server. " +
+ "Long-running or interactive commands will time out: this is not a terminal session.",
+ scope: "exec",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ result: { maxTextBytes: 48 * 1024, overflowHint: "Command output was compacted; rerun a narrower command (grep/head/tail) for the omitted evidence." },
+ inputSchema: S({
+ command: { type: "string", description: "The shell command line to run." },
+ cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
+ }, ["command"]),
+ run: async (a, context) => runCommand(str(a, "command"), opt(a, "cwd"), await sessionArtifactEnvironment(context)),
+ },
+];
+
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index aa65b2a6..bac51c44 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -1,234 +1,23 @@
-import { INTEGRATION_TOOLS } from "./tools-integrations";
-import { SESSION_ARTIFACT_TOOLS } from "./tools-session-artifacts";
-import { sessionArtifactEnvironment } from "@/lib/agent/artifact-session";
-import { writeFileGuarded, makeDir, remove, move, copy } from "@/lib/host/fs-api";
-import { runCommand, startExecJob, getExecJob, cancelExecJob } from "@/lib/host/exec-api";
-import { resolveProjectHint, runProjectFunction } from "@/lib/host/projects-api";
-import { type McpTool, str, opt, S, PATH_P } from "./tool-kit";
-import { importOpenAiProvidedFile } from "./openai-file-upload";
-import { READ_TOOLS } from "./tools-read";
+import { withWorkflowContext } from "./tool-context";
+import { A2A_TOOLS } from "./tools-a2a";
+import { AGENT_TOOLS } from "./tools-agent";
import { DISCOVERY_TOOLS } from "./tools-discovery";
-import { LEARNING_TOOLS } from "./tools-learning";
-import { POWER_TOOLS } from "./tools-power";
+import { FORGE_TOOLS } from "./tools-forge";
import { INFRA_TOOLS } from "./tools-infra";
-import { AGENT_TOOLS } from "./tools-agent";
-import { A2A_TOOLS } from "./tools-a2a";
+import { INTEGRATION_TOOLS } from "./tools-integrations";
+import { LEARNING_TOOLS } from "./tools-learning";
import { LOCAL_AGENT_TOOLS } from "./tools-local-agents";
-import { SUBAGENT_TOOLS } from "./tools-subagents";
-import { FORGE_TOOLS } from "./tools-forge";
-import { READ_PIPELINE_TOOLS } from "./tools-read-pipeline";
-import { PROJECT_MCP_TOOLS } from "./tools-project-mcp";
-import { PROJECT_EXPERIENCE_TOOLS } from "./tools-project-experience";
import { OPERATOR_DASHBOARD_TOOLS } from "./tools-operator-dashboard";
+import { POWER_TOOLS } from "./tools-power";
+import { PROJECT_EXPERIENCE_TOOLS } from "./tools-project-experience";
+import { PROJECT_MCP_TOOLS } from "./tools-project-mcp";
+import { READ_TOOLS } from "./tools-read";
+import { READ_PIPELINE_TOOLS } from "./tools-read-pipeline";
+import { SESSION_ARTIFACT_TOOLS } from "./tools-session-artifacts";
+import { SUBAGENT_TOOLS } from "./tools-subagents";
import { BLOCK_TOOLS, SURFACE_TOOLS } from "./tools-ui";
-import { withWorkflowContext } from "./tool-context";
-
-// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,
-// not the tool, writes the trail, because these call lib/host directly and so
-// never pass the route-layer audit that covers /api/v1.
-const MUTATE_TOOLS: McpTool[] = [
- {
- name: "fs_write",
- limit: { key: "fs.write", max: 120, windowMs: 60_000 },
- audit: { action: "fs.write" as const, targetArg: "path" },
- description:
- "Create or overwrite a text file on the VPS. Inspect with fs_read first and pass its SHA-256 as expected_sha256 " +
- "to refuse a stale overwrite when another process changed the file. Omitting the hash keeps legacy overwrite behaviour. " +
- "Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",
- scope: "write",
- annotations: { idempotentHint: true },
- inputSchema: S({
- ...PATH_P,
- content: { type: "string" },
- expected_sha256: { type: "string", description: "Optional SHA-256 returned by fs_read; refuse if the current file no longer matches." },
- }, ["path", "content"]),
- run: async (a) => ({ ok: true, ...(await writeFileGuarded({
- path: str(a, "path"),
- content: typeof a.content === "string" ? a.content : "",
- expectedSha256: opt(a, "expected_sha256"),
- })) }),
- },
- {
- name: "fs_upload_file",
- limit: { key: "fs.upload", max: 20, windowMs: 60_000 },
- audit: { action: "fs.upload" as const, targetArg: "dest" },
- description:
- "Import one ChatGPT conversation/generated file into an existing VPS directory. " +
- "ChatGPT binds the top-level file parameter through openai/fileParams, MSO downloads the temporary OpenAI URL immediately, validates the host/type/size, writes within OS_FS_WRITE_ROOTS, and returns byte count plus SHA-256. Existing same-name files may be replaced.",
- scope: "write",
- annotations: { destructiveHint: true, openWorldHint: true },
- meta: { "openai/fileParams": ["file"] },
- inputSchema: S({
- file: {
- type: "object",
- description: "ChatGPT-provided file reference. Select or attach exactly one generated/uploaded image.",
- properties: {
- download_url: { type: "string" },
- file_id: { type: "string" },
- mime_type: { type: "string" },
- file_name: { type: "string" },
- name: { type: "string" },
- size: { type: "number" },
- },
- required: ["download_url", "file_id"],
- additionalProperties: true,
- },
- dest: { type: "string", description: "Existing destination directory on the VPS, within OS_FS_WRITE_ROOTS." },
- filename: { type: "string", description: "Optional safe destination basename; defaults to the ChatGPT filename." },
- }, ["file", "dest"]),
- run: async (a) => importOpenAiProvidedFile({
- file: a.file,
- dest: str(a, "dest"),
- filename: opt(a, "filename"),
- }),
- },
- {
- name: "fs_mkdir",
- limit: { key: "fs.mkdir", max: 120, windowMs: 60_000 },
- audit: { action: "fs.mkdir" as const, targetArg: "path" },
- description: "Create a directory (and any missing parents) on the VPS.",
- scope: "write",
- annotations: { idempotentHint: true },
- inputSchema: S(PATH_P, ["path"]),
- run: async (a) => { await makeDir(str(a, "path")); return { ok: true, path: a.path }; },
- },
- {
- name: "fs_move",
- limit: { key: "fs.move", max: 120, windowMs: 60_000 },
- audit: { action: "fs.move" as const, targetArg: "from" },
- description: "Move or rename a file or directory. Refuses when the source holds credential paths.",
- scope: "write",
- inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
- run: async (a) => { await move(str(a, "from"), str(a, "to")); return { ok: true }; },
- },
- {
- name: "fs_copy",
- limit: { key: "fs.copy", max: 60, windowMs: 60_000 },
- audit: { action: "fs.copy" as const, targetArg: "from" },
- description: "Copy a file or directory. The cockpit's own secrets are skipped rather than duplicated.",
- scope: "write",
- inputSchema: S({ from: { type: "string" }, to: { type: "string" } }, ["from", "to"]),
- run: async (a) => { await copy(str(a, "from"), str(a, "to")); return { ok: true }; },
- },
- {
- name: "fs_delete",
- limit: { key: "fs.delete", max: 60, windowMs: 60_000 },
- audit: { action: "fs.delete" as const, targetArg: "path" },
- description:
- "Delete a file or directory on the VPS. PERMANENT — there is no trash and no undo. " +
- "Confirm with the user before calling this on anything you did not create in this conversation.",
- scope: "write",
- annotations: { destructiveHint: true },
- inputSchema: S(PATH_P, ["path"]),
- run: async (a) => { await remove(str(a, "path")); return { ok: true, path: a.path }; },
- },
- {
- name: "project_function_call",
- limit: { key: "projects.function", max: 60, windowMs: 60_000 },
- audit: {
- action: "exec.run" as const,
- targetArg: "project",
- outcome: (r) => {
- const { code } = r as { code: number };
- return { ok: code === 0, action: "exec.run", detail: `project function exit ${code}` };
- },
- },
- description:
- "Execute ONE function explicitly declared by a validated project's .mso/functions.json. " +
- "This is project code execution and therefore requires exec scope. The manifest supplies fixed argv; model/user input is passed only as JSON on stdin and is NEVER interpolated into a shell command. " +
- "Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing. A function may return a validated bounded direct-image envelope for visual debugging; invalid envelopes remain ordinary text output.",
- scope: "exec",
- annotations: { destructiveHint: true, openWorldHint: true },
- inputSchema: S({
- project: { type: "string", description: "Exact project id from projects_list, absolute path, name or alias." },
- name: { type: "string", description: "Function name returned by project_capabilities." },
- input: { type: "object", description: "JSON object passed to the project function on stdin.", additionalProperties: true },
- }, ["project", "name", "input"]),
- run: async (a) => {
- const project = await resolveProjectHint(str(a, "project"));
- if (!project) throw new Error(`project not found: ${String(a.project)}`);
- return (await import("./project-function-content")).projectFunctionContent(await runProjectFunction(project.path, str(a, "name"), a.input));
- },
- },
- {
- name: "exec_job_start",
- limit: { key: "exec.job.start", max: 12, windowMs: 60_000 },
- audit: {
- action: "exec.job.start" as const,
- targetArg: "command",
- outcome: (r) => {
- const row = r as { state: string };
- const refused = row.state === "refused";
- return { ok: !refused, action: refused ? "exec.blocked" : "exec.job.start", detail: refused ? "refused" : "started" };
- },
- },
- description:
- "Start one bounded asynchronous shell job for legitimate test/build pipelines that exceed exec_run's 30s request budget. " +
- "The job is client/workflow-bound, capped at 20 minutes and 1 MiB per output stream, limited to four concurrent jobs per client, and uses the same cwd jail and catastrophic-command filter as exec_run. Use exec_job_status to read it and exec_job_cancel to stop it.",
- scope: "exec",
- annotations: { destructiveHint: true, openWorldHint: true },
- inputSchema: S({
- command: { type: "string", description: "The shell command line to run asynchronously." },
- cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
- }, ["command"]),
- run: async (a, context) => startExecJob({
- artifactEnv: await sessionArtifactEnvironment(context),
- command: str(a, "command"), cwd: opt(a, "cwd"), actor: context.workflowActor ?? context.actor, workflowId: context.workflowId,
- }),
- },
- {
- name: "exec_job_status",
- limit: { key: "exec.job.status", max: 120, windowMs: 60_000 },
- description:
- "Read one asynchronous exec job owned by this MCP client. Returns state, bounded stdout/stderr, exit code when finished, and whether output was truncated.",
- scope: "read",
- annotations: { readOnlyHint: true, idempotentHint: true },
- result: { maxTextBytes: 64 * 1024, overflowHint: "The job output is larger than the model context budget; rerun a focused grep/tail after completion if more detail is needed." },
- inputSchema: S({ job_id: { type: "string", description: "Exact id returned by exec_job_start." } }, ["job_id"]),
- run: (a, context) => Promise.resolve(getExecJob(str(a, "job_id"), context.workflowActor ?? context.actor, context.workflowId)),
- },
- {
- name: "exec_job_cancel",
- limit: { key: "exec.job.cancel", max: 30, windowMs: 60_000 },
- audit: { action: "exec.job.cancel" as const, targetArg: "job_id" },
- description:
- "Cancel one still-running asynchronous exec job owned by this MCP client. Repeated cancellation is idempotent.",
- scope: "exec",
- annotations: { destructiveHint: true, idempotentHint: true },
- inputSchema: S({ job_id: { type: "string", description: "Exact id returned by exec_job_start." } }, ["job_id"]),
- run: (a, context) => Promise.resolve(cancelExecJob(str(a, "job_id"), context.workflowActor ?? context.actor, context.workflowId)),
- },
- {
- name: "exec_run",
- limit: { key: "exec", max: 60, windowMs: 60_000 },
- audit: {
- action: "exec.run" as const,
- targetArg: "command",
- // runCommand REFUSES by returning {code:126, stderr:"refused: …"}, it does not
- // throw — so "the handler did not throw" is not success here. Mirrors
- // app/api/v1/exec/run/route.ts:39-45 exactly; the two must not disagree about
- // what the same command did.
- outcome: (r) => {
- const { code, stderr } = r as { code: number; stderr: string };
- const blocked = code === 126 && stderr.startsWith("refused:");
- return { ok: !blocked && code === 0, action: blocked ? "exec.blocked" : "exec.run", detail: `exit ${code}` };
- },
- },
- description:
- "Run a shell command on the VPS as the owner and return stdout, stderr and exit code. " +
- "FULL HOST POWER — prefer fs_* and sys_* tools whenever they cover the task; they are bounded and " +
- "this is not. Catastrophic patterns (rm -rf /, fork bombs, disk wipes) are refused by the server. " +
- "Long-running or interactive commands will time out: this is not a terminal session.",
- scope: "exec",
- annotations: { destructiveHint: true, openWorldHint: true },
- result: { maxTextBytes: 48 * 1024, overflowHint: "Command output was compacted; rerun a narrower command (grep/head/tail) for the omitted evidence." },
- inputSchema: S({
- command: { type: "string", description: "The shell command line to run." },
- cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
- }, ["command"]),
- run: async (a, context) => runCommand(str(a, "command"), opt(a, "cwd"), await sessionArtifactEnvironment(context)),
- },
-];
+import type { McpTool } from "./tool-kit";
+import { MUTATE_TOOLS } from "./tools-mutate";
export const TOOLS: McpTool[] = [...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/lib/mcp/ui-resource-state.test.ts b/lib/mcp/ui-resource-state.test.ts
new file mode 100644
index 00000000..38a04410
--- /dev/null
+++ b/lib/mcp/ui-resource-state.test.ts
@@ -0,0 +1,117 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");
+vi.stubEnv("OS_MCP_UI_ORIGIN", "");
+vi.stubEnv("MSO_SURFACE_APPS_JSON", "");
+afterAll(() => vi.unstubAllEnvs());
+
+const { dispatch } = await import("./dispatch");
+const {
+ MSO_BLOCK_URI,
+ MSO_PAGE_URI,
+ LEGACY_BLOCK_V1_URI,
+ LEGACY_PAGE_V1_URI,
+ LEGACY_WORKFLOW_PROGRESS_URI,
+ LEGACY_SURFACE_URI,
+ readUiResource,
+} = await import("./ui-resources");
+const { activeWorkflowForActor } = await import("@/lib/workflow");
+
+const call = (name: string, args: Record<string, unknown> = {}) =>
+ ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
+
+describe("MCP Apps Block and Page contract", () => {
+ it("returns only redacted structured workflow state and keeps status polling out of workflow memory", async () => {
+ const actor = `mcp:ui-status-${Date.now()}`;
+ const projectHint = "/private/operator/projects/mso";
+ const started = await dispatch(call("workflow_start", {
+ intent: "verify the headless workflow contract",
+ project: projectHint,
+ constraints: "never expose secret-token=example in structured output",
+ }), "write", actor);
+ const startResult = started.result as {
+ structuredContent?: {
+ active: boolean;
+ workflowId?: string;
+ project?: string;
+ stepCount: number;
+ steps: Array<{ tool: string }>;
+ [key: string]: unknown;
+ };
+ content: Array<{ text: string }>;
+ };
+ const workflowId = startResult.structuredContent?.workflowId;
+ expect(workflowId).toBeTruthy();
+ expect(startResult.structuredContent).toMatchObject({ active: true, workflowId, project: "mso" });
+ expect(startResult.structuredContent).not.toHaveProperty("bootstrap");
+ expect(startResult.structuredContent).not.toHaveProperty("search");
+ expect(JSON.stringify(startResult.structuredContent)).not.toContain(projectHint);
+ expect(JSON.stringify(startResult.structuredContent)).not.toContain("secret-token");
+ expect(JSON.parse(startResult.content[0].text).workflow.id).toBe(workflowId);
+
+ const before = await activeWorkflowForActor(actor, workflowId!);
+ expect(before).not.toBeNull();
+
+ const statusCall = await dispatch(call("workflow_status", { workflow_id: workflowId }), "write", actor);
+ const status = statusCall.result as {
+ structuredContent?: { active: boolean; workflowId: string; project?: string; stepCount: number; steps: Array<{ tool: string }> };
+ };
+ expect(status.structuredContent).toMatchObject({ active: true, workflowId, project: "mso" });
+ expect(status.structuredContent?.steps.some((step) => step.tool === "workflow_status")).toBe(false);
+ expect(JSON.stringify(status.structuredContent)).not.toContain(projectHint);
+
+ const after = await activeWorkflowForActor(actor, workflowId!);
+ expect(after?.steps).toHaveLength(before!.steps.length);
+
+ await dispatch(call("workflow_cancel", { workflow_id: workflowId, reason: "test cleanup" }), "write", actor);
+ const closed = await dispatch(call("workflow_status", { workflow_id: workflowId }), "write", actor);
+ expect((closed.result as { structuredContent?: { active: boolean } }).structuredContent?.active).toBe(false);
+ });
+
+ it("keeps latest cached workflow/surface URIs as non-advertised Block/Page aliases", async () => {
+ const canonicalBlock = readUiResource(MSO_BLOCK_URI);
+ const canonicalPage = readUiResource(MSO_PAGE_URI);
+ const blockV1 = readUiResource(LEGACY_BLOCK_V1_URI);
+ const pageV1 = readUiResource(LEGACY_PAGE_V1_URI);
+ const legacyBlock = readUiResource(LEGACY_WORKFLOW_PROGRESS_URI);
+ const legacyPage = readUiResource(LEGACY_SURFACE_URI);
+ expect(blockV1).toMatchObject({ uri: LEGACY_BLOCK_V1_URI, text: canonicalBlock?.text });
+ expect(pageV1).toMatchObject({ uri: LEGACY_PAGE_V1_URI, text: canonicalPage?.text });
+ expect(legacyBlock).toMatchObject({ uri: LEGACY_WORKFLOW_PROGRESS_URI, text: canonicalBlock?.text });
+ expect(legacyPage).toMatchObject({ uri: LEGACY_SURFACE_URI, text: canonicalPage?.text });
+
+ const listed = await dispatch({ id: 31, method: "resources/list" }, "read", "mcp:ui-alias");
+ const serialized = JSON.stringify(listed.result);
+ expect(serialized).not.toContain(LEGACY_BLOCK_V1_URI);
+ expect(serialized).not.toContain(LEGACY_PAGE_V1_URI);
+ expect(serialized).not.toContain(LEGACY_WORKFLOW_PROGRESS_URI);
+ expect(serialized).not.toContain(LEGACY_SURFACE_URI);
+ });
+
+ it("retires specialized operator resources in favor of the Page", async () => {
+ for (const uri of [
+ "ui://mso/project-status-v2.html",
+ "ui://mso/project-diff-v2.html",
+ "ui://mso/vps-status-v2.html",
+ ]) {
+ expect(readUiResource(uri)).toBeUndefined();
+ const read = await dispatch({ id: 20, method: "resources/read", params: { uri } }, "read", "mcp:ui-retired");
+ expect(read.error).toMatchObject({ code: -32602 });
+ }
+ });
+
+ it("keeps native Page routes and portable tools/call refreshes", () => {
+ const page = readUiResource(MSO_PAGE_URI)?.text ?? "";
+ expect(page).toContain('route:"/monitor"');
+ expect(page).toContain('route:"/project"');
+ expect(page).toContain('route:"/diff"');
+ expect(page).toContain('route:"/browser"');
+ expect(page).toContain('rpcRequest("tools/call"');
+ });
+
+ it("rejects unknown UI resource URIs", async () => {
+ const result = await dispatch({ id: 1, method: "resources/read", params: { uri: "ui://mso/not-real.html" } }, "read");
+ expect(result.error).toMatchObject({ code: -32602 });
+ });
+});
diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.ts
index 0049e5db..8ff74a44 100644
--- a/lib/mcp/ui-resources.test.ts
+++ b/lib/mcp/ui-resources.test.ts
@@ -1,5 +1,5 @@
-import { inlineScripts } from "../../scripts/test-support/inline-scripts";
import { afterAll, describe, expect, it, vi } from "vitest";
+import { inlineScripts } from "../../scripts/test-support/inline-scripts";
vi.mock("server-only", () => ({}));
vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");
@@ -12,17 +12,8 @@ const {
MCP_APP_MIME_TYPE,
MSO_BLOCK_URI,
MSO_PAGE_URI,
- LEGACY_BLOCK_V1_URI,
- LEGACY_PAGE_V1_URI,
- LEGACY_WORKFLOW_PROGRESS_URI,
- LEGACY_SURFACE_URI,
- readUiResource,
} = await import("./ui-resources");
const { MCP_UI_DOMAIN, MSO_ORIGIN } = await import("./ui-config");
-const { activeWorkflowForActor } = await import("@/lib/workflow");
-
-const call = (name: string, args: Record<string, unknown> = {}) =>
- ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
describe("MCP Apps Block and Page contract", () => {
it("keeps workflow_start headless and binds only explicit Block/Page render tools", async () => {
@@ -164,96 +155,4 @@ describe("MCP Apps Block and Page contract", () => {
expect(MSO_PAGE_URI).toContain("page-v11.html");
});
- it("returns only redacted structured workflow state and keeps status polling out of workflow memory", async () => {
- const actor = `mcp:ui-status-${Date.now()}`;
- const projectHint = "/private/operator/projects/mso";
- const started = await dispatch(call("workflow_start", {
- intent: "verify the headless workflow contract",
- project: projectHint,
- constraints: "never expose secret-token=example in structured output",
- }), "write", actor);
- const startResult = started.result as {
- structuredContent?: {
- active: boolean;
- workflowId?: string;
- project?: string;
- stepCount: number;
- steps: Array<{ tool: string }>;
- [key: string]: unknown;
- };
- content: Array<{ text: string }>;
- };
- const workflowId = startResult.structuredContent?.workflowId;
- expect(workflowId).toBeTruthy();
- expect(startResult.structuredContent).toMatchObject({ active: true, workflowId, project: "mso" });
- expect(startResult.structuredContent).not.toHaveProperty("bootstrap");
- expect(startResult.structuredContent).not.toHaveProperty("search");
- expect(JSON.stringify(startResult.structuredContent)).not.toContain(projectHint);
- expect(JSON.stringify(startResult.structuredContent)).not.toContain("secret-token");
- expect(JSON.parse(startResult.content[0].text).workflow.id).toBe(workflowId);
-
- const before = await activeWorkflowForActor(actor, workflowId!);
- expect(before).not.toBeNull();
-
- const statusCall = await dispatch(call("workflow_status", { workflow_id: workflowId }), "write", actor);
- const status = statusCall.result as {
- structuredContent?: { active: boolean; workflowId: string; project?: string; stepCount: number; steps: Array<{ tool: string }> };
- };
- expect(status.structuredContent).toMatchObject({ active: true, workflowId, project: "mso" });
- expect(status.structuredContent?.steps.some((step) => step.tool === "workflow_status")).toBe(false);
- expect(JSON.stringify(status.structuredContent)).not.toContain(projectHint);
-
- const after = await activeWorkflowForActor(actor, workflowId!);
- expect(after?.steps).toHaveLength(before!.steps.length);
-
- await dispatch(call("workflow_cancel", { workflow_id: workflowId, reason: "test cleanup" }), "write", actor);
- const closed = await dispatch(call("workflow_status", { workflow_id: workflowId }), "write", actor);
- expect((closed.result as { structuredContent?: { active: boolean } }).structuredContent?.active).toBe(false);
- });
-
- it("keeps latest cached workflow/surface URIs as non-advertised Block/Page aliases", async () => {
- const canonicalBlock = readUiResource(MSO_BLOCK_URI);
- const canonicalPage = readUiResource(MSO_PAGE_URI);
- const blockV1 = readUiResource(LEGACY_BLOCK_V1_URI);
- const pageV1 = readUiResource(LEGACY_PAGE_V1_URI);
- const legacyBlock = readUiResource(LEGACY_WORKFLOW_PROGRESS_URI);
- const legacyPage = readUiResource(LEGACY_SURFACE_URI);
- expect(blockV1).toMatchObject({ uri: LEGACY_BLOCK_V1_URI, text: canonicalBlock?.text });
- expect(pageV1).toMatchObject({ uri: LEGACY_PAGE_V1_URI, text: canonicalPage?.text });
- expect(legacyBlock).toMatchObject({ uri: LEGACY_WORKFLOW_PROGRESS_URI, text: canonicalBlock?.text });
- expect(legacyPage).toMatchObject({ uri: LEGACY_SURFACE_URI, text: canonicalPage?.text });
-
- const listed = await dispatch({ id: 31, method: "resources/list" }, "read", "mcp:ui-alias");
- const serialized = JSON.stringify(listed.result);
- expect(serialized).not.toContain(LEGACY_BLOCK_V1_URI);
- expect(serialized).not.toContain(LEGACY_PAGE_V1_URI);
- expect(serialized).not.toContain(LEGACY_WORKFLOW_PROGRESS_URI);
- expect(serialized).not.toContain(LEGACY_SURFACE_URI);
- });
-
- it("retires specialized operator resources in favor of the Page", async () => {
- for (const uri of [
- "ui://mso/project-status-v2.html",
- "ui://mso/project-diff-v2.html",
- "ui://mso/vps-status-v2.html",
- ]) {
- expect(readUiResource(uri)).toBeUndefined();
- const read = await dispatch({ id: 20, method: "resources/read", params: { uri } }, "read", "mcp:ui-retired");
- expect(read.error).toMatchObject({ code: -32602 });
- }
- });
-
- it("keeps native Page routes and portable tools/call refreshes", () => {
- const page = readUiResource(MSO_PAGE_URI)?.text ?? "";
- expect(page).toContain('route:"/monitor"');
- expect(page).toContain('route:"/project"');
- expect(page).toContain('route:"/diff"');
- expect(page).toContain('route:"/browser"');
- expect(page).toContain('rpcRequest("tools/call"');
- });
-
- it("rejects unknown UI resource URIs", async () => {
- const result = await dispatch({ id: 1, method: "resources/read", params: { uri: "ui://mso/not-real.html" } }, "read");
- expect(result.error).toMatchObject({ code: -32602 });
- });
});
diff --git a/package.json b/package.json
index a86901b0..75757216 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "mso",
- "version": "0.2.5",
+ "version": "0.2.6",
"private": true,
"engines": {
"node": ">=20.9",
@@ -10,7 +10,7 @@
"dev": "next dev --hostname 0.0.0.0 --port 3000",
"build": "bash scripts/build-safe.sh",
"start": "next start",
- "lint": "eslint .",
+ "lint": "eslint . --max-warnings=0",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"coverage": "vitest run --coverage",
@@ -22,7 +22,7 @@
"e2e:preview": "node scripts/e2e/preview.mjs",
"changelog": "node scripts/gen-changelog.mjs",
"ship": "bash scripts/ship.sh",
- "smoke": "E2E_BASE_URL=http://localhost:4005 vitest run scripts/e2e/smoke.test.ts",
+ "smoke": "vitest run --config scripts/e2e/vitest.config.mts",
"icons:app": "node scripts/gen-app-icons.mjs && python3 scripts/gen-remaining-platform-icons.py",
"skill:new": "node scripts/create-skill-flow.mjs",
"skill:check": "node scripts/check-skill-flows.mjs",
diff --git a/scripts/approve-device-lock.test.ts b/scripts/approve-device-lock.test.ts
index a70f303a..8bf5f289 100644
--- a/scripts/approve-device-lock.test.ts
+++ b/scripts/approve-device-lock.test.ts
@@ -1,5 +1,5 @@
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
@@ -8,8 +8,8 @@ const SCRIPT = path.join(process.cwd(), "scripts/approve-device.js");
describe("approve-device cross-process lock protocol", () => {
it("publishes the primary lock only while holding the shared recovery gate", () => {
- const source = readFileSync(SCRIPT, "utf8");
- const acquire = source.slice(source.indexOf("function acquireLock()"), source.indexOf("function withMutation"));
+ const source = readFileSync(path.join(process.cwd(), "scripts/lib/device-cli-lock.js"), "utf8");
+ const acquire = source.slice(source.indexOf("function acquireLock()"), source.indexOf("return { acquireLock"));
const gate = acquire.indexOf("openExclusive(RECOVERY");
const primary = acquire.indexOf("openExclusive(LOCK");
expect(gate).toBeGreaterThanOrEqual(0);
diff --git a/scripts/approve-device.js b/scripts/approve-device.js
index 47eb65f4..32c28e54 100755
--- a/scripts/approve-device.js
+++ b/scripts/approve-device.js
@@ -35,92 +35,7 @@ function write(store) {
// Serialize the full read-modify-write shared with the web process; lock-owner
// metadata lets a crashed writer be recovered without losing a revocation.
-const LOCK = `${STORE}.lock`;
-const RECOVERY = `${LOCK}.recovery`;
-const LOCK_WAIT_MS = 25;
-const LOCK_TIMEOUT_MS = 3000;
-const LOCK_STALE_MS = 30000;
-const sleeper = new Int32Array(new SharedArrayBuffer(4));
-function sleep(ms) { Atomics.wait(sleeper, 0, 0, ms); }
-function pidIsGone(pid) {
- try { process.kill(pid, 0); return false; }
- catch (error) { return error && error.code === "ESRCH"; }
-}
-function abandonedLock() {
- let fd;
- try {
- fd = fs.openSync(LOCK, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
- const st = fs.fstatSync(fd);
- if (!st.isFile()) return false;
- const owner = fs.readFileSync(fd, "utf8");
- const pid = Number(owner.split(":", 1)[0]);
- if (Number.isInteger(pid) && pid > 1) return pidIsGone(pid);
- return Date.now() - st.mtimeMs > LOCK_STALE_MS;
- } catch (error) {
- if (error && error.code === "ENOENT") return true;
- return false;
- } finally {
- if (fd !== undefined) try { fs.closeSync(fd); } catch {}
- }
-}
-function openExclusive(file, token) {
- // Publish only a fully-written owner record; linkSync is the atomic create point.
- const candidate = `${file}.${randomUUID()}.candidate`;
- let fd;
- try {
- fd = fs.openSync(candidate, "wx", 0o600);
- fs.writeFileSync(fd, token, "utf8");
- fs.fsyncSync(fd);
- } finally {
- if (fd !== undefined) try { fs.closeSync(fd); } catch {}
- }
- try { fs.linkSync(candidate, file); }
- finally { try { fs.unlinkSync(candidate); } catch {} }
- return { token };
-}
-function releaseLock(file, held) {
- let owner = "";
- try { owner = fs.readFileSync(file, "utf8"); } catch {}
- if (owner === held.token) { try { fs.unlinkSync(file); } catch {} }
-}
-function acquireLock() {
- fs.mkdirSync(path.dirname(STORE), { recursive: true, mode: 0o700 });
- const token = `${process.pid}:${randomUUID()}`;
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
- while (true) {
- // Every process takes the recovery gate before inspecting or publishing LOCK.
- // This closes the stat/read/unlink ABA race where a stale recoverer could delete
- // a newly-created live lock at the same pathname.
- let gate;
- try { gate = openExclusive(RECOVERY, `${process.pid}:${randomUUID()}`); }
- catch (error) {
- if (!error || error.code !== "EEXIST") throw error;
- }
-
- if (gate) {
- try {
- try { return openExclusive(LOCK, token); }
- catch (error) { if (!error || error.code !== "EEXIST") throw error; }
-
- if (abandonedLock()) {
- try { fs.unlinkSync(LOCK); }
- catch (error) { if (!error || error.code !== "ENOENT") throw error; }
- // Publish our owner record while the recovery gate is still held. Every
- // supported writer obeys this gate, so no contender can occupy the gap.
- try { return openExclusive(LOCK, token); }
- catch (error) { if (!error || error.code !== "EEXIST") throw error; }
- }
- } finally {
- // Never auto-break a recovery guard. A crash fails closed until manual
- // cleanup rather than risking a revocation-losing concurrent write.
- releaseLock(RECOVERY, gate);
- }
- }
-
- if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
- sleep(LOCK_WAIT_MS);
- }
-}
+const { acquireLock, releaseLock, LOCK } = require("./lib/device-cli-lock").deviceMutationLock(STORE);
function withMutation(fn) {
const held = acquireLock();
diff --git a/scripts/e2e/mcp-settings.mjs b/scripts/e2e/mcp-settings.mjs
new file mode 100644
index 00000000..4afe16af
--- /dev/null
+++ b/scripts/e2e/mcp-settings.mjs
@@ -0,0 +1,81 @@
+// Real production Settings routes, with synthetic owner state and bounded fault injection.
+import path from "node:path";
+import { chmod } from "node:fs/promises";
+import { expect } from "@playwright/test";
+import AxeBuilder from "@axe-core/playwright";
+
+async function capture(page, name) {
+ if (!process.env.MSO_SCREENSHOT_DIR) return;
+ const file = path.join(process.env.MSO_SCREENSHOT_DIR, name + ".png");
+ await page.screenshot({ path: file });
+ await chmod(file, 0o600);
+}
+async function openMcp(page) {
+ const sections = page.getByRole("button", { name: "Settings sections", exact: true });
+ await expect.poll(async () => await sections.isVisible() || await page.getByRole("button", { name: "MCP", exact: true }).isVisible()).toBe(true);
+ if (await sections.isVisible()) await sections.click();
+ await page.getByRole("button", { name: "MCP", exact: true }).click();
+}
+export async function mcpPublicJourney(page) {
+ let privateRequests = 0;
+ const listener = request => { if (/\/api\/mcp\/tokens|\/api\/v1\/sys\/audit/.test(request.url())) privateRequests++; };
+ page.on("request", listener);
+ await openMcp(page);
+ await expect(page.getByRole("link", { name: "Sign in to manage MCP" })).toBeVisible();
+ expect(privateRequests).toBe(0);
+ page.off("request", listener);
+}
+export async function mcpOwnerJourneys(page, fixture) {
+ const errors = [];
+ page.on("pageerror", error => errors.push(error.message));
+ for (const viewport of [{ width: 1363, height: 936 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {
+ await fixture.seedMcp();
+ await page.setViewportSize(viewport);
+ await page.goto(fixture.base + "/settings");
+ await openMcp(page);
+ const nav = page.getByRole("navigation", { name: "MCP navigation" });
+ await expect(nav.getByRole("button", { name: /^Connected apps/ })).toBeVisible();
+ await capture(page, `mcp-overview-${viewport.width}`);
+ await nav.getByRole("button", { name: /^Connect an app/ }).click();
+ await expect(page.getByRole("heading", { name: "Which app do you want to connect?" })).toBeVisible();
+ await capture(page, `mcp-client-picker-${viewport.width}`);
+ await page.getByRole("button", { name: /^ChatGPT Apps/ }).click();
+ await expect(page.getByText("Connect ChatGPT", { exact: true })).toBeVisible();
+ await expect(page.getByText("Manual OAuth configuration", { exact: true })).toHaveCount(0);
+ await capture(page, `mcp-guide-${viewport.width}`);
+ await page.getByRole("button", { name: "Choose another app", exact: true }).click();
+ await page.getByRole("button", { name: /^Cursor Remote/ }).click();
+ await expect(page.getByText("Connect Cursor", { exact: true })).toBeVisible();
+ await nav.getByRole("button", { name: "MCP overview", exact: true }).click();
+ await nav.getByRole("button", { name: /^Connected apps/ }).click();
+ await page.getByRole("button", { name: "Disconnect Fixture client", exact: true }).click();
+ await page.getByRole("button", { name: "Cancel", exact: true }).click();
+ await expect(page.getByRole("button", { name: "Disconnect Fixture client", exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Disconnect Fixture client", exact: true }).click();
+ await page.getByRole("button", { name: "Confirm disconnect", exact: true }).click();
+ await expect(page.getByText("0 active connections", { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Show expired & disconnected", exact: true }).click();
+ await expect(page.getByText("Read data · revoked", { exact: true })).toBeVisible();
+ await nav.getByRole("button", { name: "MCP overview", exact: true }).click();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ const result = await new AxeBuilder({ page }).include('[data-slot="mcp-page"]').withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ expect(result.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ console.log(`PASS MCP owner hierarchy, app guides, cancel/revoke and accessibility ${viewport.width}x${viewport.height}`);
+ }
+ // Server faults show a recoverable error, never an endless skeleton or false empty audit.
+ await page.route("**/api/mcp/tokens", route => route.fulfill({ status: 503, body: '{}' }));
+ await page.reload(); await openMcp(page);
+ await expect(page.getByRole("alert").filter({ hasText: "MCP settings could not be loaded" })).toBeVisible();
+ await page.unroute("**/api/mcp/tokens");
+ await page.getByRole("button", { name: "Try again", exact: true }).click();
+ const nav = page.getByRole("navigation", { name: "MCP navigation" });
+ await expect(nav.getByRole("button", { name: /^Connect an app/ })).toBeVisible();
+ await page.route("**/api/v1/sys/audit?*", route => route.fulfill({ status: 503, body: '{}' }));
+ await nav.getByRole("button", { name: /^Recent activity/ }).click();
+ await expect(page.getByRole("alert").filter({ hasText: "Activity could not be loaded" })).toBeVisible();
+ await page.unroute("**/api/v1/sys/audit?*");
+ await page.getByRole("button", { name: "Try again", exact: true }).click();
+ await expect(page.getByText("Privileged MCP log", { exact: true })).toBeVisible();
+ expect(errors).toEqual([]);
+ console.log("PASS MCP failed-load recovery and activity error states");
+}
diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjs
index eb612c92..400d23dc 100644
--- a/scripts/e2e/release-fixture.mjs
+++ b/scripts/e2e/release-fixture.mjs
@@ -39,8 +39,14 @@ export async function releaseFixture({ live = false } = {}) {
OS_CONFIG_STORE: path.join(dir, "config.json"), OS_PREFS_PATH: path.join(dir, "prefs.json"),
OS_AUDIT_LOG: path.join(dir, "audit.jsonl"), OS_LOGIN_PASSWORD: password,
OS_SESSION_SECRET: randomBytes(32).toString("hex"), OS_FS_READ_ROOTS: dir, OS_FS_WRITE_ROOTS: dir,
- OS_MCP_ENABLED: "0", NEXT_PUBLIC_OS_DEMO: "0", NEXT_TELEMETRY_DISABLED: "1",
+ OS_MCP_ENABLED: "1", NEXT_PUBLIC_OS_DEMO: "0", NEXT_TELEMETRY_DISABLED: "1",
});
+ const seedMcp = async () => {
+ await writeFile(env.OS_MCP_STORE, JSON.stringify({ clients: {}, codes: {}, refreshTokens: {}, tokens: {
+ ["a".repeat(64)]: { label: "Fixture client", clientId: "fixture-client", scope: "read", createdAt: Date.now(), expiresAt: Date.now() + 3600_000 },
+ } }), { mode: 0o600 });
+ };
+ await seedMcp();
const reservation = createServer();
await new Promise(resolve => reservation.listen(0, "127.0.0.1", resolve));
const port = reservation.address().port;
@@ -67,6 +73,6 @@ export async function releaseFixture({ live = false } = {}) {
await new Promise(resolve => setTimeout(resolve, 250));
}
if (!ready) throw new Error("Fixture server did not become ready: " + logs);
- return { dir, base, device, password, setRole, revokeProvider: () => { providerStatus = 401; }, close };
+ return { dir, base, device, password, setRole, seedMcp, revokeProvider: () => { providerStatus = 401; }, close };
} catch (error) { await close(); throw error; }
}
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 7b36b242..9ef2c66f 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -1,12 +1,15 @@
#!/usr/bin/env node
// Required release journeys against a built app with synthetic stores and a local provider.
+import { execFileSync } from "node:child_process";
import { chromium, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";
+import { mcpOwnerJourneys, mcpPublicJourney } from "./mcp-settings.mjs";
import { releaseFixture } from "./release-fixture.mjs";
const fixture = await releaseFixture();
let browser;
try {
+ execFileSync(process.execPath, ["node_modules/vitest/vitest.mjs", "run", "--config", "scripts/e2e/vitest.config.mts"], { env: { ...process.env, E2E_BASE_URL: fixture.base }, stdio: "inherit" });
browser = await chromium.launch({ headless: true });
for (const viewport of [{ width: 1363, height: 936 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {
const context = await browser.newContext({ viewport });
@@ -49,6 +52,7 @@ try {
return badge && heading ? badge.y + badge.height <= heading.y : false;
}).toBe(true);
}
+ await mcpPublicJourney(page);
expect(errors).toEqual([]);
await context.close();
console.log(`PASS public guides, login entry, launcher and reflow ${viewport.width}x${viewport.height}`);
@@ -82,6 +86,7 @@ try {
expect(exec.status).toBe(200); expect(exec.body.cwd).toBe(fixture.dir);
expect((await call("/api/v1/exec/run", { cmd: "exit 0", cwd: fixture.dir + "/missing" })).status).not.toBe(200);
expect((await call("/api/v1/fs/list?path=" + encodeURIComponent(fixture.dir))).status).toBe(200);
+ await mcpOwnerJourneys(page, fixture);
await fixture.setRole("viewer");
expect((await call("/api/v1/integrations")).status).toBe(403);
// Legacy privileged shell routes return 401 for a non-owner session.
diff --git a/scripts/e2e/smoke.test.ts b/scripts/e2e/smoke.production.ts
similarity index 61%
rename from scripts/e2e/smoke.test.ts
rename to scripts/e2e/smoke.production.ts
index f609ec2f..c513e0b1 100644
--- a/scripts/e2e/smoke.test.ts
+++ b/scripts/e2e/smoke.production.ts
@@ -1,20 +1,7 @@
-// Pre-deploy smoke test — vitest, not Playwright. Hits the most critical
-// HTTP surface of a running production server to catch the classes of bugs
-// the CLAUDE.md deploy notes call out: stale chunk MIME, version pipeline,
-// auth gate, basic API liveness.
-//
-// HOW TO RUN
-// bun run vitest run scripts/e2e/smoke.test.ts
-// requires:
-// E2E_BASE_URL=http://localhost:4005 (or wherever the prod build serves)
-//
-// `describe.skipIf` makes this a no-op in `bun run test` unless E2E_BASE_URL is
-// set. The CI hook (scripts/ci.sh) opts in post-deploy.
-
import { describe, expect, it } from "vitest";
const BASE = process.env.E2E_BASE_URL ?? "";
-const skip = !BASE;
+if (!BASE) throw new Error("E2E_BASE_URL is required; run the release suite against a built fixture");
async function get(path: string, init?: RequestInit): Promise<Response> {
const ctrl = new AbortController();
@@ -26,15 +13,8 @@ async function get(path: string, init?: RequestInit): Promise<Response> {
}
}
-// The describe label is the skip reason the user sees in the vitest report when
-// E2E_BASE_URL is unset — it tells them WHY the suite is skipped + how to opt
-// in, instead of a silent "(skipped)" with no breadcrumb.
-describe.skipIf(skip)(
- skip
- ? "[smoke] SKIPPED — set E2E_BASE_URL=http://host:port to enable live deploy probe"
- : `[smoke] live deploy probe @ ${BASE}`,
- () => {
- it.skipIf(skip)("GET /api/auth/me returns 200 or 401 — never crashes", async () => {
+describe("live deploy probe", () => {
+ it("GET /api/auth/me returns 200 or 401 — never crashes", async () => {
const res = await get("/api/auth/me");
expect([200, 401]).toContain(res.status);
// Body should be JSON-parseable regardless of auth state.
@@ -46,7 +26,7 @@ describe.skipIf(skip)(
// Neither of those two ever existed in this repo (no git history for either path),
// so half of this deploy gate had been asserting 404 == 200 since it was written:
// it reported failure on every run, which is exactly how a gate stops being run.
- it.skipIf(skip)("GET /api/health returns JSON with buildId", async () => {
+ it("GET /api/health returns JSON with buildId", async () => {
const res = await get("/api/health");
expect(res.status).toBe(200);
const body = (await res.json()) as { buildId?: unknown };
@@ -54,14 +34,14 @@ describe.skipIf(skip)(
expect((body.buildId as string).length).toBeGreaterThan(0);
});
- it.skipIf(skip)("GET /api/v1/sys/stats without auth returns 401 (gate working)", async () => {
+ it("GET /api/v1/sys/stats without auth returns 401 (gate working)", async () => {
const res = await get("/api/v1/sys/stats");
// Auth gate is healthy when an unauthenticated probe returns 401.
// Accept 403 too in case the gate evolves to "forbidden".
expect([401, 403]).toContain(res.status);
});
- it.skipIf(skip)("every root-referenced _next/static JS/CSS asset serves with correct MIME", async () => {
+ it("every root-referenced _next/static JS/CSS asset serves with correct MIME", async () => {
const homeRes = await get("/");
expect(homeRes.status).toBe(200);
const html = await homeRes.text();
diff --git a/scripts/e2e/vitest.config.mts b/scripts/e2e/vitest.config.mts
new file mode 100644
index 00000000..0f528457
--- /dev/null
+++ b/scripts/e2e/vitest.config.mts
@@ -0,0 +1,3 @@
+import base from "../../vitest.config.mts";
+const config = { ...base, test: { ...base.test, include: ["scripts/e2e/smoke.production.ts"] } };
+export default config;
diff --git a/scripts/gateway-lifecycle-fixture.ts b/scripts/gateway-lifecycle-fixture.ts
new file mode 100644
index 00000000..e2a6e826
--- /dev/null
+++ b/scripts/gateway-lifecycle-fixture.ts
@@ -0,0 +1,90 @@
+import { execFileSync, spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach } from "vitest";
+
+const ROOT = path.resolve(__dirname, "..");
+const GATEWAY = path.join(__dirname, "mso-gateway");
+const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version as string;
+const roots: string[] = [];
+const pids = new Set<number>();
+
+function fixture() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-gateway-life-")); roots.push(dir);
+ const bin = path.join(dir, "bin"), state = path.join(dir, "state"), envFile = path.join(dir, ".env.local");
+ fs.mkdirSync(bin, { mode: 0o700 }); fs.mkdirSync(state, { mode: 0o700 });
+ fs.writeFileSync(envFile, "OS_SESSION_SECRET=fixture\n", { mode: 0o600 });
+ const curl = path.join(bin, "curl");
+ fs.writeFileSync(curl, `#!/bin/sh\nprintf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}'\n`, { mode: 0o700 });
+ const cloudflared = path.join(bin, "cloudflared");
+ fs.writeFileSync(cloudflared, `#!/usr/bin/env node
+const fs=require('fs');
+if(process.argv.includes('--version')){console.log('cloudflared fixture');process.exit(0)}
+fs.appendFileSync(process.env.HOME + '/gateway-fake-starts', process.pid+'\\n');
+if(process.argv.includes('--url'))console.error('INF https://life-fixture.trycloudflare.com');
+process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000);
+`, { mode: 0o700 });
+ const procTcp = path.join(dir, "proc-tcp"), procTcp6 = path.join(dir, "proc-tcp6");
+ fs.writeFileSync(procTcp, " sl local_address rem_address st\n"); fs.writeFileSync(procTcp6, " sl local_address rem_address st\n");
+ const env = { ...process.env, HOME: dir, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: ROOT, MSO_GATEWAY_ENV: envFile,
+ MSO_GATEWAY_STATE_DIR: state, MSO_GATEWAY_CURL: curl, MSO_GATEWAY_CLOUDFLARED: cloudflared,
+ MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005", MSO_GATEWAY_SKIP_PUBLIC_PROBE: "1",
+ MSO_GATEWAY_PROC_NET_TCP: procTcp, MSO_GATEWAY_PROC_NET_TCP6: procTcp6 };
+ return { dir, state, curl, cloudflared, startFile: path.join(dir, "gateway-fake-starts"), env };
+}
+
+function run(args: string[], env: NodeJS.ProcessEnv) { return execFileSync(GATEWAY, args, { encoding: "utf8", env }); }
+function identity(pid: number) {
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
+ const rest = stat.slice(stat.lastIndexOf(") ") + 2).trim().split(/\s+/);
+ return { pid, startTicks: rest[19], exe: fs.realpathSync(`/proc/${pid}/exe`),
+ cmdHash: createHash("sha256").update(fs.readFileSync(`/proc/${pid}/cmdline`)).digest("hex") };
+}
+function writeState(dir: string, value: Record<string, unknown>) {
+ const localUrl = String(value.localUrl ?? "http://127.0.0.1:4005");
+ const root = fs.realpathSync(ROOT);
+ const scopeId = createHash("sha256").update(`${root}\n${localUrl}`).digest("hex");
+ fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ scopeId, root, ...value }), { mode: 0o600 });
+}
+function readRegularSnapshot(file: string) {
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ try {
+ const stat = fs.fstatSync(fd);
+ if (!stat.isFile()) throw new Error(`expected regular file: ${file}`);
+ return { mode: stat.mode & 0o777, text: fs.readFileSync(fd, "utf8") };
+ } finally { fs.closeSync(fd); }
+}
+function alive(pid: number) {
+ try {
+ process.kill(pid, 0);
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
+ const rest = stat.slice(stat.lastIndexOf(") ") + 2);
+ return rest[0] !== "Z";
+ } catch { return false; }
+}
+function asyncStart(env: NodeJS.ProcessEnv) {
+ return new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {
+ const child = spawn(GATEWAY, ["start"], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let stdout = "", stderr = ""; child.stdout.on("data", (v) => stdout += v); child.stderr.on("data", (v) => stderr += v);
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
+ });
+}
+
+async function waitUntil(predicate: () => boolean, timeoutMs = 8_000, intervalMs = 25): Promise<boolean> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return true;
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ }
+ return predicate();
+}
+
+afterEach(() => {
+ for (const pid of pids) if (alive(pid)) try { process.kill(pid, "SIGTERM"); } catch {}
+ pids.clear(); for (const dir of roots.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+
+export { VERSION, alive, asyncStart, fixture, GATEWAY, identity, pids, readRegularSnapshot, ROOT, run, waitUntil, writeState };
diff --git a/scripts/lib/device-cli-lock.js b/scripts/lib/device-cli-lock.js
new file mode 100644
index 00000000..4ed54978
--- /dev/null
+++ b/scripts/lib/device-cli-lock.js
@@ -0,0 +1,96 @@
+const path = require("path");
+const fs = require("fs");
+const { randomUUID } = require("crypto");
+
+// Process ownership and stale-lock recovery shared by device mutations.
+exports.deviceMutationLock = function deviceMutationLock(storePath) {
+const LOCK = `${storePath}.lock`;
+const RECOVERY = `${LOCK}.recovery`;
+const LOCK_WAIT_MS = 25;
+const LOCK_TIMEOUT_MS = 3000;
+const LOCK_STALE_MS = 30000;
+const sleeper = new Int32Array(new SharedArrayBuffer(4));
+function sleep(ms) { Atomics.wait(sleeper, 0, 0, ms); }
+function pidIsGone(pid) {
+ try { process.kill(pid, 0); return false; }
+ catch (error) { return error && error.code === "ESRCH"; }
+}
+function abandonedLock() {
+ let fd;
+ try {
+ fd = fs.openSync(LOCK, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ const st = fs.fstatSync(fd);
+ if (!st.isFile()) return false;
+ const owner = fs.readFileSync(fd, "utf8");
+ const pid = Number(owner.split(":", 1)[0]);
+ if (Number.isInteger(pid) && pid > 1) return pidIsGone(pid);
+ return Date.now() - st.mtimeMs > LOCK_STALE_MS;
+ } catch (error) {
+ if (error && error.code === "ENOENT") return true;
+ return false;
+ } finally {
+ if (fd !== undefined) try { fs.closeSync(fd); } catch {}
+ }
+}
+function openExclusive(file, token) {
+ // Publish only a fully-written owner record; linkSync is the atomic create point.
+ const candidate = `${file}.${randomUUID()}.candidate`;
+ let fd;
+ try {
+ fd = fs.openSync(candidate, "wx", 0o600);
+ fs.writeFileSync(fd, token, "utf8");
+ fs.fsyncSync(fd);
+ } finally {
+ if (fd !== undefined) try { fs.closeSync(fd); } catch {}
+ }
+ try { fs.linkSync(candidate, file); }
+ finally { try { fs.unlinkSync(candidate); } catch {} }
+ return { token };
+}
+function releaseLock(file, held) {
+ let owner = "";
+ try { owner = fs.readFileSync(file, "utf8"); } catch {}
+ if (owner === held.token) { try { fs.unlinkSync(file); } catch {} }
+}
+function acquireLock() {
+ fs.mkdirSync(path.dirname(storePath), { recursive: true, mode: 0o700 });
+ const token = `${process.pid}:${randomUUID()}`;
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
+ while (true) {
+ // Every process takes the recovery gate before inspecting or publishing LOCK.
+ // This closes the stat/read/unlink ABA race where a stale recoverer could delete
+ // a newly-created live lock at the same pathname.
+ let gate;
+ try { gate = openExclusive(RECOVERY, `${process.pid}:${randomUUID()}`); }
+ catch (error) {
+ if (!error || error.code !== "EEXIST") throw error;
+ }
+
+ if (gate) {
+ try {
+ try { return openExclusive(LOCK, token); }
+ catch (error) { if (!error || error.code !== "EEXIST") throw error; }
+
+ if (abandonedLock()) {
+ try { fs.unlinkSync(LOCK); }
+ catch (error) { if (!error || error.code !== "ENOENT") throw error; }
+ // Publish our owner record while the recovery gate is still held. Every
+ // supported writer obeys this gate, so no contender can occupy the gap.
+ try { return openExclusive(LOCK, token); }
+ catch (error) { if (!error || error.code !== "EEXIST") throw error; }
+ }
+ } finally {
+ // Never auto-break a recovery guard. A crash fails closed until manual
+ // cleanup rather than risking a revocation-losing concurrent write.
+ releaseLock(RECOVERY, gate);
+ }
+ }
+
+ if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
+ sleep(LOCK_WAIT_MS);
+ }
+}
+
+
+return { acquireLock, releaseLock, LOCK };
+};
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 11a81b63..6d2b061d 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -21,8 +21,8 @@ import {
permissionCompletionItems,
permissionMode,
} from "./mso-agent-permissions.mjs";
-import { parseSubagentArgs, SUBAGENT_USAGE } from "./mso-agent-subagent.mjs";
-import { sectionBlock, printSection } from "./mso-agent-layout.mjs";
+import { handleLocalCommand } from "./mso-agent-local-commands.mjs";
+import { printHelp } from "./mso-agent-help.mjs";
function runCli(args) {
const result = spawnSync(CLI, args, {
@@ -33,39 +33,6 @@ function runCli(args) {
return result.status ?? 1;
}
-function localAgentLine(row) {
- const status = String(row?.status || "unknown");
- const cwd = row?.cwd ? ` · ${row.cwd}` : "";
- return ` ${String(row?.label || row?.alias || row?.id || "agent").padEnd(24)} ${status}${cwd}`;
-}
-
-async function listLocalAgents(session, includeOffline = false) {
- const query = new URLSearchParams({ session: session.agentSession.id });
- if (includeOffline) query.set("includeOffline", "1");
- const out = await api(`/api/v1/local-agents?${query}`);
- const rows = Array.isArray(out?.agents) ? out.agents : [];
- if (!rows.length) console.log(" no other live local session agents");
- else for (const row of rows) console.log(localAgentLine(row));
- return rows;
-}
-
-async function sendLocalAgent(session, target, message, kind = "message", options = {}) {
- return api("/api/v1/local-agents", {
- method: "POST",
- body: JSON.stringify({ action: "send", sessionId: session.agentSession.id, target, message, kind, ...options }),
- });
-}
-
-async function trackLocalRequest(session, out, text) {
- if (!out?.message?.id || !out?.message?.correlationId) return;
- session.history.push({
- role: "local_request", messageId: out.message.id, correlationId: out.message.correlationId,
- targetSessionId: out.target.id, targetLabel: out.target.label, text, status: out.status,
- createdAt: out.message.createdAt, requiresUserRelay: true,
- });
- await persistSession(session);
-}
-
async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
const resolved = resolveSlashSkill(
session.state.skills,
@@ -98,52 +65,10 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
return "handled";
}
-function printHelp() {
- console.log(
- [
- " /new [title] create and switch to a fresh durable session",
- " /restart soft-reload Agent runtime; keep this session",
- " /session [query] open picker or resume latest/index/id/@name/title",
- " /resume [query] alias-style resume command; bare opens same picker",
- " /rename <name> rename the short @agent handle",
- " /title <text> rename the session title/description",
- " /status model/auth/context/token/session details",
- " /permission [mode] choose ask | auto-write | yolo",
- " /context alias for /status",
- " /statusbar [on|off] toggle compact dynamic status line",
- " /models [args] configure AI providers/auth",
- " /model [ref] select active model from connected providers",
- " /setup full MSO onboarding",
- " /integrations [args] manage users, providers, connections, source/auth",
- " /doctor run mso doctor",
- " /tools list agent tools",
- " /agents list live local session agents + remote A2A peers",
- " @milo <prompt> message an active local agent by its short @name",
- " /message <target> <msg> send notify-only local agent data",
- " /delegate <target> <job> correlated local task; else remote A2A peer",
- " /spawn [--name N] [--scope S] <job> run foreground isolated subagent in this session",
- " /inbox show native local agent messages for this session",
- " /skills [query] browse available slash skills",
- " /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
- " /<skill> [prompt] select for next message, or run prompt now",
- " /clear clear this session conversation",
- " /exit, /quit quit",
- "",
- "Keyboard",
- " Ctrl+C clear input; empty prompt exits; active turn interrupts",
- " Ctrl+D delete right; empty prompt exits",
- " Ctrl+L clear/repaint terminal",
- " Ctrl+W · Ctrl+U/K delete word · delete to line start/end",
- " ↑/↓ or Ctrl+P/N prompt history (durable after resume)",
- " Ctrl+A/E · Ctrl+B/F line start/end · left/right",
- " Alt+B/F · Ctrl+←/→ move by word",
- " Tab (empty prompt) cycle permission in place: ask → auto → yolo",
- ].join("\n"),
- );
-}
-
export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
const [cmd, ...args] = line.trim().split(/\s+/);
+ const local = await handleLocalCommand(cmd, args, session, { runCli, runSubagent });
+ if (local) return local;
switch (cmd) {
case "/help":
printHelp();
@@ -250,71 +175,6 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
for (const tool of session.state.tools)
console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`);
return "handled";
- case "/agents":
- console.log(`${C.bold}Local session agents${C.reset}`);
- await listLocalAgents(session);
- console.log(`${C.bold}Remote A2A v1 peers${C.reset}`);
- runCli(["a2a", "list"]);
- return "handled";
- case "/message": {
- if (!args[0] || args.length < 2) {
- console.log("usage: /message <local-agent> <message>");
- return "handled";
- }
- const target = args[0];
- const message = args.slice(1).join(" ");
- const out = await sendLocalAgent(session, target, message, "message");
- console.log(sectionBlock("local", `${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"}`, {
- columns: process.stdout.columns, detail: out?.target?.label || target, colors: C,
- }));
- return "handled";
- }
- case "/delegate": {
- if (!args[0] || args.length < 2) {
- console.log(
- "usage: /delegate <session-name|session-id|cwd|peer> <objective>",
- );
- return "handled";
- }
- const target = args[0];
- const objective = args.slice(1).join(" ");
- try {
- const out = await sendLocalAgent(session, target, objective, "task", { intent: "request", requiresUserRelay: true });
- await trackLocalRequest(session, out, objective);
- console.log(sectionBlock("local", `${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"} · correlated reply will relay here`, {
- columns: process.stdout.columns, detail: out?.target?.label || target, colors: C,
- }));
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- if (/local agent target not found/i.test(message))
- runCli(["a2a", "handoff", target, objective]);
- else throw error;
- }
- return "handled";
- }
- case "/spawn": {
- if (typeof runSubagent !== "function") throw new Error("subagent runtime unavailable");
- try { await runSubagent(parseSubagentArgs(args)); }
- catch (error) {
- if (String(error?.message || error).startsWith("usage:")) console.log(`usage: ${SUBAGENT_USAGE}`);
- else throw error;
- }
- return "handled";
- }
- case "/inbox": {
- const out = await api(`/api/v1/local-agents?inbox=1&session=${encodeURIComponent(session.agentSession.id)}&limit=100`);
- const rows = Array.isArray(out?.messages) ? out.messages : [];
- if (!rows.length) console.log("local agent inbox is empty");
- else {
- printSection("local", { detail: "inbox", colors: C });
- for (const row of rows) {
- const label = String(row.senderLabel || "[agent]");
- const prefix = label.startsWith("[agent-") ? label : `[agent-${label.replace(/^\[|\]$/g, "")}]`;
- console.log(`${C.c}${prefix}${row.kind === "task" ? " task" : ""}${C.reset} ${row.text}`);
- }
- }
- return "handled";
- }
case "/skills":
printSkills(session, C, args.join(" "));
return "handled";
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
new file mode 100644
index 00000000..3422611f
--- /dev/null
+++ b/scripts/mso-agent-help.mjs
@@ -0,0 +1,44 @@
+export function printHelp() {
+ console.log(
+ [
+ " /new [title] create and switch to a fresh durable session",
+ " /restart soft-reload Agent runtime; keep this session",
+ " /session [query] open picker or resume latest/index/id/@name/title",
+ " /resume [query] alias-style resume command; bare opens same picker",
+ " /rename <name> rename the short @agent handle",
+ " /title <text> rename the session title/description",
+ " /status model/auth/context/token/session details",
+ " /permission [mode] choose ask | auto-write | yolo",
+ " /context alias for /status",
+ " /statusbar [on|off] toggle compact dynamic status line",
+ " /models [args] configure AI providers/auth",
+ " /model [ref] select active model from connected providers",
+ " /setup full MSO onboarding",
+ " /integrations [args] manage users, providers, connections, source/auth",
+ " /doctor run mso doctor",
+ " /tools list agent tools",
+ " /agents list live local session agents + remote A2A peers",
+ " @milo <prompt> message an active local agent by its short @name",
+ " /message <target> <msg> send notify-only local agent data",
+ " /delegate <target> <job> correlated local task; else remote A2A peer",
+ " /spawn [--name N] [--scope S] <job> run foreground isolated subagent in this session",
+ " /inbox show native local agent messages for this session",
+ " /skills [query] browse available slash skills",
+ " /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
+ " /<skill> [prompt] select for next message, or run prompt now",
+ " /clear clear this session conversation",
+ " /exit, /quit quit",
+ "",
+ "Keyboard",
+ " Ctrl+C clear input; empty prompt exits; active turn interrupts",
+ " Ctrl+D delete right; empty prompt exits",
+ " Ctrl+L clear/repaint terminal",
+ " Ctrl+W · Ctrl+U/K delete word · delete to line start/end",
+ " ↑/↓ or Ctrl+P/N prompt history (durable after resume)",
+ " Ctrl+A/E · Ctrl+B/F line start/end · left/right",
+ " Alt+B/F · Ctrl+←/→ move by word",
+ " Tab (empty prompt) cycle permission in place: ask → auto → yolo",
+ ].join("\n"),
+ );
+}
+
diff --git a/scripts/mso-agent-local-commands.mjs b/scripts/mso-agent-local-commands.mjs
new file mode 100644
index 00000000..9a126d49
--- /dev/null
+++ b/scripts/mso-agent-local-commands.mjs
@@ -0,0 +1,110 @@
+import process from "node:process";
+import { C } from "./mso-agent-runtime.mjs";
+import { api } from "./mso-agent-api.mjs";
+import { persistSession } from "./mso-agent-session-ui.mjs";
+import { sectionBlock, printSection } from "./mso-agent-layout.mjs";
+import { parseSubagentArgs, SUBAGENT_USAGE } from "./mso-agent-subagent.mjs";
+
+function localAgentLine(row) {
+ const status = String(row?.status || "unknown");
+ const cwd = row?.cwd ? ` · ${row.cwd}` : "";
+ return ` ${String(row?.label || row?.alias || row?.id || "agent").padEnd(24)} ${status}${cwd}`;
+}
+
+async function listLocalAgents(session, includeOffline = false) {
+ const query = new URLSearchParams({ session: session.agentSession.id });
+ if (includeOffline) query.set("includeOffline", "1");
+ const out = await api(`/api/v1/local-agents?${query}`);
+ const rows = Array.isArray(out?.agents) ? out.agents : [];
+ if (!rows.length) console.log(" no other live local session agents");
+ else for (const row of rows) console.log(localAgentLine(row));
+ return rows;
+}
+
+async function sendLocalAgent(session, target, message, kind = "message", options = {}) {
+ return api("/api/v1/local-agents", {
+ method: "POST",
+ body: JSON.stringify({ action: "send", sessionId: session.agentSession.id, target, message, kind, ...options }),
+ });
+}
+
+async function trackLocalRequest(session, out, text) {
+ if (!out?.message?.id || !out?.message?.correlationId) return;
+ session.history.push({
+ role: "local_request", messageId: out.message.id, correlationId: out.message.correlationId,
+ targetSessionId: out.target.id, targetLabel: out.target.label, text, status: out.status,
+ createdAt: out.message.createdAt, requiresUserRelay: true,
+ });
+ await persistSession(session);
+}
+
+export async function handleLocalCommand(cmd, args, session, { runCli, runSubagent }) {
+ switch (cmd) {
+ case "/agents":
+ console.log(`${C.bold}Local session agents${C.reset}`);
+ await listLocalAgents(session);
+ console.log(`${C.bold}Remote A2A v1 peers${C.reset}`);
+ runCli(["a2a", "list"]);
+ return "handled";
+ case "/message": {
+ if (!args[0] || args.length < 2) {
+ console.log("usage: /message <local-agent> <message>");
+ return "handled";
+ }
+ const target = args[0];
+ const message = args.slice(1).join(" ");
+ const out = await sendLocalAgent(session, target, message, "message");
+ console.log(sectionBlock("local", `${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"}`, {
+ columns: process.stdout.columns, detail: out?.target?.label || target, colors: C,
+ }));
+ return "handled";
+ }
+ case "/delegate": {
+ if (!args[0] || args.length < 2) {
+ console.log(
+ "usage: /delegate <session-name|session-id|cwd|peer> <objective>",
+ );
+ return "handled";
+ }
+ const target = args[0];
+ const objective = args.slice(1).join(" ");
+ try {
+ const out = await sendLocalAgent(session, target, objective, "task", { intent: "request", requiresUserRelay: true });
+ await trackLocalRequest(session, out, objective);
+ console.log(sectionBlock("local", `${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"} · correlated reply will relay here`, {
+ columns: process.stdout.columns, detail: out?.target?.label || target, colors: C,
+ }));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (/local agent target not found/i.test(message))
+ runCli(["a2a", "handoff", target, objective]);
+ else throw error;
+ }
+ return "handled";
+ }
+ case "/spawn": {
+ if (typeof runSubagent !== "function") throw new Error("subagent runtime unavailable");
+ try { await runSubagent(parseSubagentArgs(args)); }
+ catch (error) {
+ if (String(error?.message || error).startsWith("usage:")) console.log(`usage: ${SUBAGENT_USAGE}`);
+ else throw error;
+ }
+ return "handled";
+ }
+ case "/inbox": {
+ const out = await api(`/api/v1/local-agents?inbox=1&session=${encodeURIComponent(session.agentSession.id)}&limit=100`);
+ const rows = Array.isArray(out?.messages) ? out.messages : [];
+ if (!rows.length) console.log("local agent inbox is empty");
+ else {
+ printSection("local", { detail: "inbox", colors: C });
+ for (const row of rows) {
+ const label = String(row.senderLabel || "[agent]");
+ const prefix = label.startsWith("[agent-") ? label : `[agent-${label.replace(/^\[|\]$/g, "")}]`;
+ console.log(`${C.c}${prefix}${row.kind === "task" ? " task" : ""}${C.reset} ${row.text}`);
+ }
+ }
+ return "handled";
+ }
+ default: return null;
+ }
+}
diff --git a/scripts/mso-gateway-lifecycle.test.ts b/scripts/mso-gateway-lifecycle.test.ts
index 1af0e447..a1906fe5 100644
--- a/scripts/mso-gateway-lifecycle.test.ts
+++ b/scripts/mso-gateway-lifecycle.test.ts
@@ -1,90 +1,8 @@
-import { createHash } from "node:crypto";
-import { execFileSync, spawn, spawnSync } from "node:child_process";
+import { spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
-import os from "node:os";
import path from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
-
-const ROOT = path.resolve(__dirname, "..");
-const GATEWAY = path.join(__dirname, "mso-gateway");
-const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version as string;
-const roots: string[] = [];
-const pids = new Set<number>();
-
-function fixture() {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-gateway-life-")); roots.push(dir);
- const bin = path.join(dir, "bin"), state = path.join(dir, "state"), envFile = path.join(dir, ".env.local");
- fs.mkdirSync(bin, { mode: 0o700 }); fs.mkdirSync(state, { mode: 0o700 });
- fs.writeFileSync(envFile, "OS_SESSION_SECRET=fixture\n", { mode: 0o600 });
- const curl = path.join(bin, "curl");
- fs.writeFileSync(curl, `#!/bin/sh\nprintf '%s\\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}'\n`, { mode: 0o700 });
- const cloudflared = path.join(bin, "cloudflared");
- fs.writeFileSync(cloudflared, `#!/usr/bin/env node
-const fs=require('fs');
-if(process.argv.includes('--version')){console.log('cloudflared fixture');process.exit(0)}
-fs.appendFileSync(process.env.HOME + '/gateway-fake-starts', process.pid+'\\n');
-if(process.argv.includes('--url'))console.error('INF https://life-fixture.trycloudflare.com');
-process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000);
-`, { mode: 0o700 });
- const procTcp = path.join(dir, "proc-tcp"), procTcp6 = path.join(dir, "proc-tcp6");
- fs.writeFileSync(procTcp, " sl local_address rem_address st\n"); fs.writeFileSync(procTcp6, " sl local_address rem_address st\n");
- const env = { ...process.env, HOME: dir, PATH: `${bin}:${process.env.PATH}`, MSO_GATEWAY_ROOT: ROOT, MSO_GATEWAY_ENV: envFile,
- MSO_GATEWAY_STATE_DIR: state, MSO_GATEWAY_CURL: curl, MSO_GATEWAY_CLOUDFLARED: cloudflared,
- MSO_GATEWAY_LOCAL_URL: "http://127.0.0.1:4005", MSO_GATEWAY_SKIP_PUBLIC_PROBE: "1",
- MSO_GATEWAY_PROC_NET_TCP: procTcp, MSO_GATEWAY_PROC_NET_TCP6: procTcp6 };
- return { dir, state, curl, cloudflared, startFile: path.join(dir, "gateway-fake-starts"), env };
-}
-
-function run(args: string[], env: NodeJS.ProcessEnv) { return execFileSync(GATEWAY, args, { encoding: "utf8", env }); }
-function identity(pid: number) {
- const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
- const rest = stat.slice(stat.lastIndexOf(") ") + 2).trim().split(/\s+/);
- return { pid, startTicks: rest[19], exe: fs.realpathSync(`/proc/${pid}/exe`),
- cmdHash: createHash("sha256").update(fs.readFileSync(`/proc/${pid}/cmdline`)).digest("hex") };
-}
-function writeState(dir: string, value: Record<string, unknown>) {
- const localUrl = String(value.localUrl ?? "http://127.0.0.1:4005");
- const root = fs.realpathSync(ROOT);
- const scopeId = createHash("sha256").update(`${root}\n${localUrl}`).digest("hex");
- fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ scopeId, root, ...value }), { mode: 0o600 });
-}
-function readRegularSnapshot(file: string) {
- const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
- try {
- const stat = fs.fstatSync(fd);
- if (!stat.isFile()) throw new Error(`expected regular file: ${file}`);
- return { mode: stat.mode & 0o777, text: fs.readFileSync(fd, "utf8") };
- } finally { fs.closeSync(fd); }
-}
-function alive(pid: number) {
- try {
- process.kill(pid, 0);
- const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
- const rest = stat.slice(stat.lastIndexOf(") ") + 2);
- return rest[0] !== "Z";
- } catch { return false; }
-}
-function asyncStart(env: NodeJS.ProcessEnv) {
- return new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve) => {
- const child = spawn(GATEWAY, ["start"], { env, stdio: ["ignore", "pipe", "pipe"] });
- let stdout = "", stderr = ""; child.stdout.on("data", (v) => stdout += v); child.stderr.on("data", (v) => stderr += v);
- child.on("close", (code) => resolve({ code, stdout, stderr }));
- });
-}
-
-async function waitUntil(predicate: () => boolean, timeoutMs = 8_000, intervalMs = 25): Promise<boolean> {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- if (predicate()) return true;
- await new Promise((resolve) => setTimeout(resolve, intervalMs));
- }
- return predicate();
-}
-
-afterEach(() => {
- for (const pid of pids) if (alive(pid)) try { process.kill(pid, "SIGTERM"); } catch {}
- pids.clear(); for (const dir of roots.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
-});
+import { describe, expect, it } from "vitest";
+import { VERSION, GATEWAY, alive, fixture, identity, pids, run, waitUntil, writeState } from "./gateway-lifecycle-fixture";
describe("mso gateway lifecycle hardening", () => {
it("rolls back a tunnel when durable state persistence fails", () => {
@@ -190,85 +108,4 @@ esac
expect(alive(tunnel.pid!)).toBe(false); expect(alive(runtime.pid!)).toBe(false);
});
- it("persists recovery intent before stopping and reconciles stale ownership after a state-write failure", async () => {
- const f = fixture();
- const runtime = spawn(process.execPath, ["-e", "process.title='next-server (fixture)';process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"], { stdio: "ignore" });
- const pid = runtime.pid!;
- pids.add(pid);
- await new Promise((r) => setTimeout(r, 120));
- const rid = { ...identity(pid), cmdHash: null, instanceId: "fixture" };
- writeState(f.state, { provider: "cloudflare-quick", mode: "temporary", url: "https://life-fixture.trycloudflare.com",
- localUrl: "http://127.0.0.1:4005", tunnelIdentity: null, runtimeIdentity: rid, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
- const recoveryDir = path.join(f.dir, "update-recovery");
- fs.mkdirSync(recoveryDir, { mode: 0o700 });
- const markerPath = path.join(recoveryDir, "restart-runtime");
- const mv = path.join(f.dir, "bin", "mv");
- fs.writeFileSync(mv, `#!/bin/sh
-case "$*" in *mso-private-write*state.json*) exit 1;; esac
-exec /bin/mv "$@"
-`, { mode: 0o700 });
- const env = { ...f.env, MSO_GATEWAY_RECOVERY_MARKER: markerPath };
- const first = spawnSync(GATEWAY, ["runtime-stop"], { encoding: "utf8", env });
- expect(first.status).not.toBe(0);
- expect(first.stderr).toContain("recovery marker preserved");
- for (let i = 0; i < 80 && alive(pid); i++) await new Promise((r) => setTimeout(r, 20));
- expect(alive(pid)).toBe(false);
- const recoveryMarker = readRegularSnapshot(markerPath);
- expect(recoveryMarker.mode).toBe(0o600);
- expect(recoveryMarker.text.trim()).toBe("1");
- expect(JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8")).runtimeOwned).toBe(true);
-
- fs.unlinkSync(mv);
- fs.writeFileSync(f.curl, "#!/bin/sh\nexit 7\n", { mode: 0o700 });
- const second = run(["runtime-stop"], env);
- expect(second).toContain("runtime: recovered-stale-owned");
- const reconciled = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
- expect(reconciled.runtimeOwned).toBe(false);
- expect(reconciled.runtimeIdentity).toBeNull();
- expect(readRegularSnapshot(markerPath).text.trim()).toBe("1");
- });
-
- it.each(["direct", "interpreter exec"])("serializes concurrent starts so only one tunnel remains live and tracked (%s)", async mode => {
- const f = fixture(), startFile = f.startFile, env = f.env;
- if (mode === "interpreter exec") {
- fs.renameSync(f.cloudflared, f.cloudflared + ".cjs");
- // Preserve PID/start ticks while startup changes executable and argv.
- fs.writeFileSync(f.cloudflared, `#!/bin/bash
-sleep 0.3
-exec node -e 'require(process.argv[1] + ".cjs")' "$0" "$@"
-`, { mode: 0o700 });
- }
- const [a, b] = await Promise.all([asyncStart(env), asyncStart(env)]);
- expect(a.code).toBe(0); expect(b.code).toBe(0);
- const spawned = fs.readFileSync(startFile, "utf8").trim().split(/\n+/).filter(Boolean).map(Number);
- for (const pid of spawned) pids.add(pid);
- expect(spawned).toHaveLength(1);
- const live = spawned.filter(alive);
- expect(live).toHaveLength(1);
- const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
- expect(state.tunnelIdentity.pid).toBe(live[0]);
- expect(state.tunnelIdentity).toMatchObject(identity(live[0]));
- run(["stop"], f.env);
- for (let i = 0; i < 50 && spawned.some(alive); i++) await new Promise((r) => setTimeout(r, 20));
- expect(spawned.filter(alive)).toEqual([]);
- });
-
- it("preserves owned runtime identity when only the old tunnel died", async () => {
- const f = fixture();
- const runtime = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"]);
- await new Promise((r) => setTimeout(r, 100)); pids.add(runtime.pid!);
- const rid = { ...identity(runtime.pid!), cmdHash: null, instanceId: "fixture" };
- writeState(f.state, { provider: "fixture", mode: "temporary", url: "https://dead.example", localUrl: "http://127.0.0.1:4005",
- tunnelIdentity: null, runtimeIdentity: rid, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
- run(["start"], f.env); const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
- expect(state.runtimeOwned).toBe(true); expect(state.runtimeIdentity).toEqual(rid);
- const closed = new Promise<void>((resolve) => runtime.once("close", () => resolve()));
- run(["stop"], f.env); await Promise.race([closed, new Promise((r) => setTimeout(r, 500))]);
- expect(alive(runtime.pid!)).toBe(false);
- });
-
- it("does not accept an arbitrary 2xx /api/health body as MSO", () => {
- const f = fixture(); fs.writeFileSync(f.curl, "#!/bin/sh\nprintf '{}\\n'\n", { mode: 0o700 });
- const out = run(["doctor"], f.env); expect(out).toContain("no verified MSO runtime");
- });
});
diff --git a/scripts/mso-gateway-recovery.test.ts b/scripts/mso-gateway-recovery.test.ts
new file mode 100644
index 00000000..60282fdd
--- /dev/null
+++ b/scripts/mso-gateway-recovery.test.ts
@@ -0,0 +1,89 @@
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { GATEWAY, alive, asyncStart, fixture, identity, pids, readRegularSnapshot, run, writeState } from "./gateway-lifecycle-fixture";
+
+describe("mso gateway lifecycle hardening", () => {
+ it("persists recovery intent before stopping and reconciles stale ownership after a state-write failure", async () => {
+ const f = fixture();
+ const runtime = spawn(process.execPath, ["-e", "process.title='next-server (fixture)';process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"], { stdio: "ignore" });
+ const pid = runtime.pid!;
+ pids.add(pid);
+ await new Promise((r) => setTimeout(r, 120));
+ const rid = { ...identity(pid), cmdHash: null, instanceId: "fixture" };
+ writeState(f.state, { provider: "cloudflare-quick", mode: "temporary", url: "https://life-fixture.trycloudflare.com",
+ localUrl: "http://127.0.0.1:4005", tunnelIdentity: null, runtimeIdentity: rid, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
+ const recoveryDir = path.join(f.dir, "update-recovery");
+ fs.mkdirSync(recoveryDir, { mode: 0o700 });
+ const markerPath = path.join(recoveryDir, "restart-runtime");
+ const mv = path.join(f.dir, "bin", "mv");
+ fs.writeFileSync(mv, `#!/bin/sh
+case "$*" in *mso-private-write*state.json*) exit 1;; esac
+exec /bin/mv "$@"
+`, { mode: 0o700 });
+ const env = { ...f.env, MSO_GATEWAY_RECOVERY_MARKER: markerPath };
+ const first = spawnSync(GATEWAY, ["runtime-stop"], { encoding: "utf8", env });
+ expect(first.status).not.toBe(0);
+ expect(first.stderr).toContain("recovery marker preserved");
+ for (let i = 0; i < 80 && alive(pid); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(alive(pid)).toBe(false);
+ const recoveryMarker = readRegularSnapshot(markerPath);
+ expect(recoveryMarker.mode).toBe(0o600);
+ expect(recoveryMarker.text.trim()).toBe("1");
+ expect(JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8")).runtimeOwned).toBe(true);
+
+ fs.unlinkSync(mv);
+ fs.writeFileSync(f.curl, "#!/bin/sh\nexit 7\n", { mode: 0o700 });
+ const second = run(["runtime-stop"], env);
+ expect(second).toContain("runtime: recovered-stale-owned");
+ const reconciled = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
+ expect(reconciled.runtimeOwned).toBe(false);
+ expect(reconciled.runtimeIdentity).toBeNull();
+ expect(readRegularSnapshot(markerPath).text.trim()).toBe("1");
+ });
+
+ it.each(["direct", "interpreter exec"])("serializes concurrent starts so only one tunnel remains live and tracked (%s)", async mode => {
+ const f = fixture(), startFile = f.startFile, env = f.env;
+ if (mode === "interpreter exec") {
+ fs.renameSync(f.cloudflared, f.cloudflared + ".cjs");
+ // Preserve PID/start ticks while startup changes executable and argv.
+ fs.writeFileSync(f.cloudflared, `#!/bin/bash
+sleep 0.3
+exec node -e 'require(process.argv[1] + ".cjs")' "$0" "$@"
+`, { mode: 0o700 });
+ }
+ const [a, b] = await Promise.all([asyncStart(env), asyncStart(env)]);
+ expect(a.code).toBe(0); expect(b.code).toBe(0);
+ const spawned = fs.readFileSync(startFile, "utf8").trim().split(/\n+/).filter(Boolean).map(Number);
+ for (const pid of spawned) pids.add(pid);
+ expect(spawned).toHaveLength(1);
+ const live = spawned.filter(alive);
+ expect(live).toHaveLength(1);
+ const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
+ expect(state.tunnelIdentity.pid).toBe(live[0]);
+ expect(state.tunnelIdentity).toMatchObject(identity(live[0]));
+ run(["stop"], f.env);
+ for (let i = 0; i < 50 && spawned.some(alive); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(spawned.filter(alive)).toEqual([]);
+ });
+
+ it("preserves owned runtime identity when only the old tunnel died", async () => {
+ const f = fixture();
+ const runtime = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"]);
+ await new Promise((r) => setTimeout(r, 100)); pids.add(runtime.pid!);
+ const rid = { ...identity(runtime.pid!), cmdHash: null, instanceId: "fixture" };
+ writeState(f.state, { provider: "fixture", mode: "temporary", url: "https://dead.example", localUrl: "http://127.0.0.1:4005",
+ tunnelIdentity: null, runtimeIdentity: rid, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
+ run(["start"], f.env); const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
+ expect(state.runtimeOwned).toBe(true); expect(state.runtimeIdentity).toEqual(rid);
+ const closed = new Promise<void>((resolve) => runtime.once("close", () => resolve()));
+ run(["stop"], f.env); await Promise.race([closed, new Promise((r) => setTimeout(r, 500))]);
+ expect(alive(runtime.pid!)).toBe(false);
+ });
+
+ it("does not accept an arbitrary 2xx /api/health body as MSO", () => {
+ const f = fixture(); fs.writeFileSync(f.curl, "#!/bin/sh\nprintf '{}\\n'\n", { mode: 0o700 });
+ const out = run(["doctor"], f.env); expect(out).toContain("no verified MSO runtime");
+ });
+});