Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(cli): add MSO agent and infrastructure providers

Rahmancc637831101c
diff --git a/.env.example b/.env.example
index 9052d54f..d60a5471 100644
--- a/.env.example
+++ b/.env.example
@@ -203,6 +203,9 @@ OS_SESSION_SECRET=
# OS_PREFS_PATH=~/.mso/prefs.json # synced UI prefs (theme, layout)
# OS_MEMORY_STORE=~/.mso/memory.json # assistant long-term memory
# OS_THREADS_DIR=~/.mso/threads # assistant chat threads (one file each)
+# Owner-private Dokploy/Cloudflare/Hostinger connection state. Defaults to the path
+# below; normally leave it there so the 0700 directory + 0600 file policy applies.
+# OS_INFRA_STORE=~/.mso/private/infra-providers.json
# CLI-only override for `mso skills install`; default ~/.mso/skills. The target is
# the explicit operator-trust root, so point this only at a private directory you own.
# MSO_SKILL_INSTALL_ROOT=~/.mso/skills
diff --git a/README.md b/README.md
index 48724c50..68138bac 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,8 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
**Extend** — Alfa AI, modular slices, and custom apps.
-- **Use BYOK AI** — Alfa uses credentials stored on your server, not committed to the repo.
+- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` now opens the interactive setup/operations agent; `mso model` connects or changes its provider first.
+- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
@@ -124,6 +125,8 @@ The flow lets you choose:
- **Alfa response preset** — normal, Caveman or Ponytail;
- optional **Hermes / OpenClaw / 9Router** installation (their provider settings remain separate
from Alfa's credentials);
+- optional **Dokploy** plus **Cloudflare or Hostinger** infrastructure connection. Provider secrets
+ are entered with hidden prompts and stay server-side;
- reviewed **installable skills** such as Ponytail, Caveman and the MSO-safe RTK wrapper.
Immediately after checkout, the installer installs and validates the CLI **before dependency
@@ -160,9 +163,12 @@ After installation, the installer prints whether the current shell can already r
On the normal Ubuntu/WSL PATH (which includes `/usr/local/bin`) these work immediately:
```bash
+mso # interactive MSO setup/operations agent
mso -h
+mso model # connect/change the AI provider used by MSO Agent / Alfa
mso doctor
mso onboard # run/re-run guided setup; starts the built loopback runtime on WSL when needed
+mso provider list # Dokploy/Cloudflare/Hostinger status (secrets masked)
mso web # open local UI; starts the built loopback runtime if no service is active
mso update # fetch/verify/build safely; does not require :4005 to be alive
mso skills available # reviewed installable skill list
@@ -273,10 +279,14 @@ The browser UI is one frontend, not the product. The installer puts `mso` on you
covers anything without one.
```bash
+mso # interactive setup/operations agent with MSO ASCII terminal UI
mso -h # grouped command list; `mso <command> --help` per command
+mso model # connect/change AI provider before/while using the agent
mso doctor # includes HTTPS/login-origin diagnosis
mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
-mso onboard # guided AI/app/skill setup
+mso onboard # guided AI/app/infrastructure/skill setup
+mso provider list # masked Dokploy/Cloudflare/Hostinger state
+mso provider set cloudflare # hidden credential prompts + live verification
mso skills available # curated installable skills
mso skills install ponytail caveman rtk -y
mso device pending # who typed the password and is waiting
@@ -312,7 +322,8 @@ An authenticated **Owner** session can read allowed files and run commands as th
- Approve only trusted devices; use Viewer by default, Operator only for bounded operational work, and Owner only where full host authority is intended. Device approval is an allowlist, not standards-based MFA or a named-user directory.
- Keep write roots narrow with `OS_FS_WRITE_ROOTS`.
- Service inventory is read-only by default. Lifecycle buttons require Operator/Owner **and** an exact `OS_SERVICE_CONTROL_UNITS` entry; wildcards are rejected. Package visibility reads only the existing local cache and never upgrades the host.
-- Never commit `.env.local`, API keys, or data from `~/.mso`.
+- Never commit `.env.local`, API keys, or data from `~/.mso`. Infrastructure provider tokens live in `~/.mso/private/infra-providers.json` with owner-only permissions; the agent receives only credential-free tool schemas and masked provider state.
+- Dokploy/Cloudflare/Hostinger automation is intentionally bounded. Cloudflare changes one exact record and never bulk-writes a zone; proxying defaults off. Hostinger updates one exact name/type RR-set with `overwrite:true`; unrelated zone rows are never sent in the mutation payload, while ambiguity/conflicts are still refused and writes require approval.
- Managed-app dashboards are not embedded by default. 9Router is loopback-only by default; a direct public-IP bind requires `NINE_ROUTER_EXPOSE_PUBLIC=1`, while a configured application hostname remains its preferred in-shell UI. Give each vendor UI a separate explicit hostname such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.
- Camoufox/noVNC is also never served on the cockpit origin. It uses the reserved split-origin host such as `camoufox.mso.example.com`; the legacy `/camoufox-vnc/*` path is permanently closed.
- That boundary is browser-only: a plugin installed into Hermes or OpenClaw runs inside that daemon and can run host commands according to the daemon's own trust model.
@@ -428,6 +439,7 @@ Not currently supported:
| [docs/COMPARISON.md](./docs/COMPARISON.md) | Generated comparison methodology, evidence and per-cell notes |
| [docs/COMPETITIVE-ROADMAP.md](./docs/COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate boundaries and next measurable investments |
| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, update, backup/restore and origins |
+| [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md) | MSO terminal agent and Dokploy/Cloudflare/Hostinger deployment-provider contract |
| [docs/HERMES-INTEGRATION.md](./docs/HERMES-INTEGRATION.md) | Hermes-specific managed-app behaviour |
| [docs/OPENCLAW-INTEGRATION.md](./docs/OPENCLAW-INTEGRATION.md) | OpenClaw-specific managed-app behaviour |
| [docs/9ROUTER-INTEGRATION.md](./docs/9ROUTER-INTEGRATION.md) | 9Router immutable-image ownership, loopback default and explicit dashboard exposure |
diff --git a/app/api/v1/agent-tools/route.test.ts b/app/api/v1/agent-tools/route.test.ts
new file mode 100644
index 00000000..af451ac1
--- /dev/null
+++ b/app/api/v1/agent-tools/route.test.ts
@@ -0,0 +1,111 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { canonicalAgentApproval } from "@/lib/agent/approval.js";
+
+const contextRef: { current: null | { role: string; session: { device_id: string } } } = {
+ current: { role: "owner", session: { device_id: "dev-owner" } },
+};
+const dispatchMock = vi.fn();
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: vi.fn(async () => contextRef.current),
+}));
+vi.mock("@/lib/mcp/dispatch", () => ({
+ dispatch: (...args: unknown[]) => dispatchMock(...args),
+}));
+vi.mock("@/lib/mcp/scope", () => ({
+ maxScope: () => "exec",
+ allows: (held: string, needed: string) => {
+ const rank: Record<string, number> = { read: 0, write: 1, exec: 2 };
+ return (rank[held] ?? -1) >= (rank[needed] ?? 99);
+ },
+}));
+vi.mock("@/lib/mcp/tools", () => ({
+ TOOLS: [
+ { name: "read_tool", scope: "read" },
+ { name: "write_tool", scope: "write" },
+ ],
+}));
+
+const postReq = (body: unknown) => new Request("http://localhost/api/v1/agent-tools", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+}) as never;
+
+describe("/api/v1/agent-tools", () => {
+ beforeEach(() => {
+ contextRef.current = { role: "owner", session: { device_id: "dev-owner" } };
+ dispatchMock.mockReset();
+ dispatchMock.mockResolvedValue({
+ result: {
+ tools: [
+ { name: "read_tool", description: "read", inputSchema: { type: "object", properties: {} } },
+ { name: "write_tool", description: "write", inputSchema: { type: "object", properties: {} } },
+ ],
+ _meta: { version: "test" },
+ },
+ });
+ });
+
+ it("requires an owner session even for tool discovery", async () => {
+ contextRef.current = { role: "operator", session: { device_id: "dev-op" } };
+ const { GET } = await import("./route");
+ const res = await GET();
+ expect(res.status).toBe(403);
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it("returns the canonical MCP list with explicit scope and approval metadata", async () => {
+ const { GET } = await import("./route");
+ const res = await GET();
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.scope).toBe("exec");
+ expect(body.tools).toEqual([
+ expect.objectContaining({ name: "read_tool", scope: "read", approvalRequired: false }),
+ expect.objectContaining({ name: "write_tool", scope: "write", approvalRequired: true }),
+ ]);
+ expect(dispatchMock).toHaveBeenCalledWith(
+ expect.objectContaining({ method: "tools/list" }),
+ "exec",
+ "cli:dev-owner",
+ );
+ });
+
+ it("refuses a mutation unless the terminal explicitly approved it", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(postReq({ name: "write_tool", input: { name: "x" } }));
+ expect(res.status).toBe(409);
+ await expect(res.json()).resolves.toMatchObject({ error: "explicit_agent_approval_required", scope: "write" });
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it("binds approval to the exact canonical mutation payload", async () => {
+ const { POST } = await import("./route");
+ const approved = canonicalAgentApproval("write_tool", { name: "x", nested: { safe: true } });
+ const res = await POST(postReq({
+ name: "write_tool",
+ input: { name: "x", nested: { safe: false } },
+ approved: true,
+ approvalDigest: approved.digest,
+ }));
+ expect(res.status).toBe(409);
+ await expect(res.json()).resolves.toMatchObject({ error: "agent_approval_payload_mismatch", scope: "write" });
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it("dispatches an approved mutation with the same owner-device actor", async () => {
+ dispatchMock.mockResolvedValueOnce({ result: { content: [{ type: "text", text: "done" }] } });
+ const input = { name: "x" };
+ const approvalDigest = canonicalAgentApproval("write_tool", input).digest;
+ const { POST } = await import("./route");
+ const res = await POST(postReq({ name: "write_tool", input, approved: true, approvalDigest }));
+ expect(res.status).toBe(200);
+ await expect(res.json()).resolves.toMatchObject({ ok: true, result: "done" });
+ expect(dispatchMock).toHaveBeenCalledWith(
+ expect.objectContaining({ method: "tools/call", params: { name: "write_tool", arguments: { name: "x" } } }),
+ "exec",
+ "cli:dev-owner",
+ );
+ });
+});
diff --git a/app/api/v1/agent-tools/route.ts b/app/api/v1/agent-tools/route.ts
new file mode 100644
index 00000000..1a20b19f
--- /dev/null
+++ b/app/api/v1/agent-tools/route.ts
@@ -0,0 +1,51 @@
+import { NextRequest, NextResponse } from "next/server";
+import { matchesAgentApproval } from "@/lib/agent/approval.js";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { dispatch } from "@/lib/mcp/dispatch";
+import { maxScope, allows } from "@/lib/mcp/scope";
+import { TOOLS } from "@/lib/mcp/tools";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+async function ownerContext() {
+ const context = await getSessionContext();
+ return context?.role === "owner" ? context : null;
+}
+
+export async function GET() {
+ const context = await ownerContext();
+ if (!context) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
+ const scope = maxScope();
+ const listed = await dispatch({ id: "cli-list", method: "tools/list" }, scope, `cli:${context.session.device_id}`);
+ const result = (listed.result ?? {}) as { tools?: Array<Record<string, unknown>>; _meta?: unknown };
+ const tools = (result.tools ?? []).map((tool) => {
+ const name = String(tool.name ?? "");
+ const def = TOOLS.find((entry) => entry.name === name);
+ return { ...tool, scope: def?.scope ?? "read", approvalRequired: def ? def.scope !== "read" : false };
+ });
+ return NextResponse.json({ scope, tools, _meta: result._meta });
+}
+
+export async function POST(req: NextRequest) {
+ const context = await ownerContext();
+ if (!context) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
+ let body: { name?: string; input?: Record<string, unknown>; approved?: boolean; approvalDigest?: string };
+ try { body = await req.json(); } catch { return NextResponse.json({ error: "invalid_request" }, { status: 400 }); }
+ const name = String(body.name ?? "");
+ const tool = TOOLS.find((entry) => entry.name === name);
+ if (!tool) return NextResponse.json({ error: `unknown tool: ${name}` }, { status: 404 });
+ const scope = maxScope();
+ if (!allows(scope, tool.scope)) return NextResponse.json({ error: `deployment scope ${scope} does not allow ${tool.scope}` }, { status: 403 });
+ if (tool.scope !== "read") {
+ if (body.approved !== true) return NextResponse.json({ error: "explicit_agent_approval_required", tool: name, scope: tool.scope }, { status: 409 });
+ if (!matchesAgentApproval(name, body.input ?? {}, body.approvalDigest)) {
+ return NextResponse.json({ error: "agent_approval_payload_mismatch", tool: name, scope: tool.scope }, { status: 409 });
+ }
+ }
+ const rpc = await dispatch({ id: "cli-call", method: "tools/call", params: { name, arguments: body.input ?? {} } }, scope, `cli:${context.session.device_id}`);
+ const result = (rpc.result ?? {}) as { content?: Array<{ type?: string; text?: string }>; isError?: boolean };
+ if ((rpc as { error?: unknown }).error) return NextResponse.json(rpc, { status: 400 });
+ const text = (result.content ?? []).filter((row) => row.type === "text").map((row) => row.text ?? "").join("\n");
+ return NextResponse.json({ ok: !result.isError, result: text || JSON.stringify(result.content ?? []), isError: Boolean(result.isError) });
+}
diff --git a/app/api/v1/infra/cloudflare/zones/route.ts b/app/api/v1/infra/cloudflare/zones/route.ts
new file mode 100644
index 00000000..79741500
--- /dev/null
+++ b/app/api/v1/infra/cloudflare/zones/route.ts
@@ -0,0 +1,12 @@
+import { NextResponse } from "next/server";
+import { requireSession } from "@/lib/auth/require-session";
+import { listCloudflareZones } from "@/lib/infra";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function GET() {
+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ try { return NextResponse.json({ zones: await listCloudflareZones() }); }
+ catch (error) { return NextResponse.json({ error: (error as Error).message }, { status: 503 }); }
+}
diff --git a/app/api/v1/infra/dokploy/projects/route.ts b/app/api/v1/infra/dokploy/projects/route.ts
new file mode 100644
index 00000000..df8939c5
--- /dev/null
+++ b/app/api/v1/infra/dokploy/projects/route.ts
@@ -0,0 +1,12 @@
+import { NextResponse } from "next/server";
+import { requireSession } from "@/lib/auth/require-session";
+import { listDokployProjects } from "@/lib/infra";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function GET() {
+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ try { return NextResponse.json({ projects: await listDokployProjects() }); }
+ catch (error) { return NextResponse.json({ error: (error as Error).message }, { status: 503 }); }
+}
diff --git a/app/api/v1/infra/providers/doctor/route.ts b/app/api/v1/infra/providers/doctor/route.ts
new file mode 100644
index 00000000..09446f7e
--- /dev/null
+++ b/app/api/v1/infra/providers/doctor/route.ts
@@ -0,0 +1,16 @@
+import { NextRequest, NextResponse } from "next/server";
+import { requireSession } from "@/lib/auth/require-session";
+import { INFRA_PROVIDER_IDS, doctorInfraProvider, isInfraProviderId } from "@/lib/infra";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function POST(req: NextRequest) {
+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ let body: { id?: string } = {};
+ try { body = await req.json(); } catch { /* empty means all */ }
+ const ids = body.id ? [body.id] : [...INFRA_PROVIDER_IDS];
+ if (ids.some((id) => !isInfraProviderId(id))) return NextResponse.json({ error: "unknown infrastructure provider" }, { status: 404 });
+ const results = await Promise.all(ids.map((id) => doctorInfraProvider(id as (typeof INFRA_PROVIDER_IDS)[number])));
+ return NextResponse.json({ results });
+}
diff --git a/app/api/v1/infra/providers/route.test.ts b/app/api/v1/infra/providers/route.test.ts
new file mode 100644
index 00000000..55719c82
--- /dev/null
+++ b/app/api/v1/infra/providers/route.test.ts
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const contextRef: { current: null | { role: string; session: { device_id: string } } } = {
+ current: { role: "owner", session: { device_id: "dev-owner" } },
+};
+const setMock = vi.fn();
+const removeMock = vi.fn();
+const auditMock = vi.fn();
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: vi.fn(async () => contextRef.current),
+}));
+vi.mock("@/lib/host", () => ({ audit: (...args: unknown[]) => auditMock(...args) }));
+vi.mock("@/lib/infra", () => ({
+ INFRA_PROVIDER_IDS: ["dokploy", "cloudflare", "hostinger"],
+ isInfraProviderId: (id: string) => ["dokploy", "cloudflare", "hostinger"].includes(id),
+ readInfraProvider: vi.fn(async () => ({})),
+ removeInfraProvider: (...args: unknown[]) => removeMock(...args),
+ setInfraProvider: (...args: unknown[]) => setMock(...args),
+ summarizeInfraProvider: (id: string, values: Record<string, string>) => ({ id, configured: Boolean(Object.keys(values).length), values }),
+}));
+
+const postReq = (body: unknown) => new Request("http://localhost/api/v1/infra/providers", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+}) as never;
+
+describe("/api/v1/infra/providers", () => {
+ beforeEach(() => {
+ contextRef.current = { role: "owner", session: { device_id: "dev-owner" } };
+ setMock.mockReset(); removeMock.mockReset(); auditMock.mockReset();
+ setMock.mockResolvedValue({ apiUrl: "https://panel.example.com/api", apiKey: "masked-by-summary" });
+ removeMock.mockResolvedValue(undefined);
+ });
+
+ it("rejects non-owner configuration", async () => {
+ contextRef.current = { role: "operator", session: { device_id: "dev-op" } };
+ const { POST } = await import("./route");
+ const res = await POST(postReq({ id: "dokploy", values: {} }));
+ expect(res.status).toBe(401);
+ expect(setMock).not.toHaveBeenCalled();
+ });
+
+ it("stores only a known provider and writes an actor-attributed audit event", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(postReq({ id: "dokploy", values: { apiUrl: "https://panel.example.com" } }));
+ expect(res.status).toBe(200);
+ expect(setMock).toHaveBeenCalledWith("dokploy", { apiUrl: "https://panel.example.com" });
+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ action: "infra.write", actor: "dev-owner", target: "dokploy", detail: "provider.configure" }));
+ });
+
+ it("fails closed on unknown providers", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(postReq({ id: "random-cloud", values: { token: "x" } }));
+ expect(res.status).toBe(404);
+ expect(setMock).not.toHaveBeenCalled();
+ });
+
+ it("audits failed provider configuration without returning a secret", async () => {
+ setMock.mockRejectedValueOnce(new Error("Cloudflare API token is invalid"));
+ const { POST } = await import("./route");
+ const res = await POST(postReq({ id: "cloudflare", values: { apiToken: "not-shown" } }));
+ expect(res.status).toBe(400);
+ expect(JSON.stringify(await res.json())).not.toContain("not-shown");
+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ action: "infra.write", target: "cloudflare", ok: false }));
+ });
+});
diff --git a/app/api/v1/infra/providers/route.ts b/app/api/v1/infra/providers/route.ts
new file mode 100644
index 00000000..31f6d680
--- /dev/null
+++ b/app/api/v1/infra/providers/route.ts
@@ -0,0 +1,45 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { audit } from "@/lib/host";
+import { INFRA_PROVIDER_IDS, isInfraProviderId, readInfraProvider, removeInfraProvider, setInfraProvider, summarizeInfraProvider } from "@/lib/infra";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+async function ownerContext() {
+ const context = await getSessionContext();
+ return context?.role === "owner" ? context : null;
+}
+
+export async function GET() {
+ if (!(await ownerContext())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ const providers = await Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id))));
+ return NextResponse.json({ providers });
+}
+
+export async function POST(req: NextRequest) {
+ const context = await ownerContext();
+ if (!context) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ let body: { id?: string; values?: Record<string, unknown> };
+ try { body = await req.json(); } catch { return NextResponse.json({ error: "Invalid request body" }, { status: 400 }); }
+ const id = String(body.id ?? "");
+ if (!isInfraProviderId(id)) return NextResponse.json({ error: "unknown infrastructure provider" }, { status: 404 });
+ try {
+ const values = await setInfraProvider(id, body.values ?? {});
+ void audit({ action: "infra.write", actor: context.session.device_id, target: id, detail: "provider.configure" });
+ return NextResponse.json({ ok: true, provider: summarizeInfraProvider(id, values) });
+ } catch (error) {
+ void audit({ action: "infra.write", actor: context.session.device_id, target: id, ok: false, detail: `provider.configure: ${(error as Error).message}` });
+ return NextResponse.json({ error: (error as Error).message }, { status: 400 });
+ }
+}
+
+export async function DELETE(req: NextRequest) {
+ const context = await ownerContext();
+ if (!context) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ const id = new URL(req.url).searchParams.get("id") ?? "";
+ if (!isInfraProviderId(id)) return NextResponse.json({ error: "unknown infrastructure provider" }, { status: 404 });
+ await removeInfraProvider(id);
+ void audit({ action: "infra.write", actor: context.session.device_id, target: id, detail: "provider.remove" });
+ return NextResponse.json({ ok: true });
+}
diff --git a/bin/mso b/bin/mso
index 7b4c86b1..1452e2cd 100755
--- a/bin/mso
+++ b/bin/mso
@@ -42,7 +42,13 @@
# status Public service status (no session needed)
# health Is this CLI's session valid?
# doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
-# onboard [-y] Guided first-run setup: AI, response style, managed apps, skills
+# agent Interactive MSO setup/ops agent (bare `mso` opens this)
+# chat Alias for agent
+# model Connect or change the AI provider used by MSO Agent / Alfa
+# onboard [-y] Guided setup: AI, apps, infrastructure, skills
+# setup Alias for onboard
+# provider * Infrastructure credentials: list | set | rm | doctor
+# providers * Alias for provider
# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
# web Open the MSO browser UI (active gateway first, else loopback)
#
@@ -119,7 +125,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.4.0"
+VERSION="1.5.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
@@ -523,7 +529,7 @@ onboard_ai() {
echo " $provider uses an API key here (not OAuth). The key is never placed in argv."
tty_secret "Paste $provider API key: "; key="$REPLY"
[ -n "$key" ] || { echo " -- empty key; skipped"; return; }
- body=$(jq -nc --arg p "$provider" --arg k "$key" '{provider:$p,apiKey:$k}')
+ body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
secret_post "/api/config" "$body" >/dev/null
unset key body REPLY
echo " ✓ $provider configured for Alfa"
@@ -625,6 +631,7 @@ run_onboard() {
onboard_ai "$yes"
onboard_style "$yes"
onboard_apps "$yes"
+ onboard_infra "$yes"
onboard_skills "$yes"
echo
echo "Onboarding complete."
@@ -632,9 +639,16 @@ run_onboard() {
echo " mso doctor verify this install"
echo " mso skills available installable skills"
echo " mso config show Alfa provider/style"
+ echo " mso provider list Dokploy/Cloudflare/Hostinger state"
+ echo " mso launch the interactive MSO Agent"
echo " mso mapp list Hermes/OpenClaw state"
}
+# Terminal agent + infrastructure-provider CLI slice. Sourced only after the
+# generic HTTP/auth/onboarding helpers above exist, so it reuses those SSOT seams.
+# shellcheck source=../scripts/mso-cli-agent.sh
+source "$ROOT/scripts/mso-cli-agent.sh"
+
# Print the header block verbatim — stops at the first non-comment line, so the
# help can never drift out of sync with the comment above.
usage() { awk 'NR>1 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "$0"; }
@@ -654,6 +668,7 @@ verbs() {
U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
U_doctor="doctor [--fix]"
+U_provider="provider list|show <id>|set <dokploy|cloudflare|hostinger>|rm <id>|doctor [id]|projects|zones"
U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
@@ -685,7 +700,7 @@ if [ $# -ge 2 ]; then
esac
fi
-cmd="${1:-help}"; maybe_update_notice "$cmd"; shift || true
+cmd="${1:-agent}"; maybe_update_notice "$cmd"; shift || true
case "$cmd" in
version|--version|-V|-v) echo "mso $VERSION (base $B, root $ROOT)"; exit 0 ;;
@@ -843,7 +858,11 @@ case "$cmd" in
[ "$fails" -eq 0 ] && echo "all good." || echo "$fails check(s) failed."
exit $(( fails > 0 ? 1 : 0 )) ;;
+ agent|chat) run_agent ;;
+ model) run_model_setup ;;
+ setup) run_onboard "${1-}" ;;
onboard) run_onboard "${1-}" ;;
+ provider|providers) run_provider "$@" ;;
# ── local/public gateway + browser launcher ───────────────────────────────
gateway) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" "$@" ;;
@@ -925,7 +944,7 @@ case "$cmd" in
*) die "API-key provider must be one of: anthropic openai openrouter google groq xai deepseek mistral" ;; esac
tty_secret "Paste $provider API key: "; key="$REPLY"
[ -n "$key" ] || die "empty API key"
- body=$(jq -nc --arg p "$provider" --arg k "$key" '{provider:$p,apiKey:$k}')
+ body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
secret_post "/api/config" "$body"; unset key body REPLY ;;
style) style="${2:?off|caveman|ponytail}"
case "$style" in off|caveman|ponytail) ;; *) die "style must be off, caveman or ponytail" ;; esac
diff --git a/bin/mso-service-lifecycle.test.ts b/bin/mso-service-lifecycle.test.ts
index 5ded515b..e122be67 100644
--- a/bin/mso-service-lifecycle.test.ts
+++ b/bin/mso-service-lifecycle.test.ts
@@ -41,15 +41,26 @@ afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursiv
describe("mso service/deploy runtime exclusion", () => {
it.each(["start", "restart"])("refuses service %s while an offline build owns the checkout", async (verb) => {
const f = fixture(), lock = lockPath(f.exclusion), held = path.join(f.root, "lock-held");
- const holder = spawn("flock", ["-x", lock, "-c", `touch ${JSON.stringify(held)}; sleep 0.8`], { stdio: "ignore" });
- for (let i = 0; i < 50 && !fs.existsSync(held); i++) await new Promise((r) => setTimeout(r, 20));
- expect(fs.existsSync(held)).toBe(true);
- const out = spawnSync(CLI, ["service", verb], {
- env: { ...f.env, MSO_RUNTIME_EXCLUSION_TIMEOUT_SECONDS: "0.1" }, encoding: "utf8",
+ // Keep the lock holder alive on stdin rather than sleeping for a fixed interval.
+ // Under a busy parallel test run, the old 800 ms sleep could expire after the
+ // ready marker was observed but before spawnSync reached the CLI, creating a
+ // false success. Closing stdin below releases the lock deterministically.
+ const holder = spawn("flock", ["-x", lock, "-c", 'touch "$MSO_TEST_LOCK_HELD"; cat >/dev/null'], {
+ env: { ...process.env, MSO_TEST_LOCK_HELD: held },
+ stdio: ["pipe", "ignore", "ignore"],
});
- expect(out.status).not.toBe(0);
- expect(out.stderr).toContain("offline update/deploy is mutating this checkout");
- await new Promise<void>((resolve) => holder.once("close", () => resolve()));
+ try {
+ for (let i = 0; i < 100 && !fs.existsSync(held); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(fs.existsSync(held)).toBe(true);
+ const out = spawnSync(CLI, ["service", verb], {
+ env: { ...f.env, MSO_RUNTIME_EXCLUSION_TIMEOUT_SECONDS: "0.1" }, encoding: "utf8",
+ });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("offline update/deploy is mutating this checkout");
+ } finally {
+ holder.stdin?.end();
+ if (holder.exitCode === null) await new Promise<void>((resolve) => holder.once("close", () => resolve()));
+ }
});
it("routes deploy through the outer service-update lifecycle", () => {
diff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.ts
index 066297bc..2cf6278c 100644
--- a/bin/mso-update-offline.test.ts
+++ b/bin/mso-update-offline.test.ts
@@ -30,6 +30,7 @@ function fixture() {
for (const rel of [
"bin/mso",
"scripts/mso-update",
+ "scripts/mso-cli-agent.sh",
"scripts/lib/private-state.sh",
"scripts/lib/update-state.sh",
"scripts/lib/runtime-exclusion.sh",
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index 828abbeb..b5f06170 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -22,7 +22,7 @@ describe("bin/mso", () => {
it("documents every verb the dispatch table implements", () => {
const src = require("node:fs").readFileSync(CLI, "utf8") as string;
- const body = src.slice(src.indexOf('cmd="${1:-help}"'));
+ const body = src.slice(src.indexOf('cmd="${1:-agent}"'));
// Case arms look like ` ls)` / ` camoufox)` / ` devices|device)`. Aliases
// are split out too — an alias absent from the help is just as unfindable.
const verbs = [...body.matchAll(/^ {2}([a-z][a-z|-]*)\)/gm)].flatMap((m) => m[1].split("|"));
@@ -74,7 +74,10 @@ describe("bin/mso", () => {
(m) => `${m[1]} ${route}`,
);
});
- const cli = fs.readFileSync(CLI, "utf8");
+ const cli = [
+ fs.readFileSync(CLI, "utf8"),
+ fs.readFileSync(path.join(repo, "scripts/mso-cli-agent.sh"), "utf8"),
+ ].join("\n");
// Not reachable from a shell, each for its own reason:
// • /api/sw is fetched by the browser to install the service worker.
@@ -87,6 +90,9 @@ describe("bin/mso", () => {
"GET /api/sw",
"/api/v1/managed-apps/[id]/proxy/[[...path]]",
"/api/auth/devices",
+ // Internal transport between scripts/mso-agent.mjs and the authenticated
+ // server-side MCP catalog. It is not a user-facing CLI verb by design.
+ "/api/v1/agent-tools",
];
// The CLI writes each call as `jget "/path"` / `jpost "/path"` / `jdel "/path"`,
diff --git a/claude-skills/mso-project-deploy/SKILL.md b/claude-skills/mso-project-deploy/SKILL.md
new file mode 100644
index 00000000..43ea8bec
--- /dev/null
+++ b/claude-skills/mso-project-deploy/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: mso-project-deploy
+description: Deploy through MSO with bounded Dokploy setup, project-owned deployment functions, and approval-gated Cloudflare or Hostinger DNS; never request provider secrets in chat.
+metadata:
+ mso:
+ risk: high
+ policy: inspect-plan-approve-verify
+---
+
+# /mso-project-deploy — provider-aware project deployment
+
+Use this flow when the owner asks MSO Agent to publish, redeploy, attach a domain, or finish infrastructure setup for an application. It is adapted from the proven provider separation in `rahmanef63/si-coder-agent`, but the MSO implementation uses its own private provider store and MCP approval boundary.
+
+## Credential boundary
+
+Never ask the user to paste a Dokploy, Cloudflare, Hostinger, GitHub, Convex, or Vercel credential into chat or a command string. Call `infra_providers_list` first. If a required provider is missing, tell the user exactly which interactive command to run, e.g. `mso provider set dokploy` or `mso provider set cloudflare`, then re-check with `infra_provider_doctor`.
+
+Provider secrets live under MSO's owner-only private state and are loaded server-side. They must not appear in tool arguments, shell argv, logs, git remotes, build args, or generated documentation.
+
+## Deployment flow
+
+1. Start one workflow with `workflow_start` for any multi-step deployment and preserve its id.
+2. Resolve the target project with `projects_list`, then inspect its package/build/runtime contract and `project_capabilities` before changing infrastructure. Do not guess framework, port, build output, or environment variables.
+3. Check providers with `infra_providers_list`, followed by a live `infra_provider_doctor` for every provider you will use.
+4. Prefer bounded infrastructure tools. `dokploy_projects_list` and `dokploy_project_ensure` are preferred over raw API curl or `exec_run`. The current generic Dokploy surface intentionally stops at project setup; application/compose-specific deployment must use a validated project `.mso/functions.json` via `project_function_call`, or an explicitly approved host operation when no bounded project function exists.
+5. DNS is always a separate phase after the application target exists and its intended origin is known. For Cloudflare, use `cloudflare_dns_upsert`: it performs only exact per-record POST/PATCH and refuses bulk writes or ambiguous records. Proxying defaults off and must be explicitly requested. For Hostinger, use `hostinger_dns_upsert` only after approval. MSO verifies the current zone for ambiguity/conflicts, then sends exactly one requested name/type RR-set with provider-scoped overwrite semantics; unrelated zone rows never enter the mutation payload.
+6. Never derive a public DNS A target from a loopback/local Dokploy API URL. Use an explicit verified public origin/IP from the deployment context.
+7. Verify the application directly at its origin before and after DNS, then verify the final HTTPS hostname. Check redirects, health, and the expected app identity rather than treating a generic HTTP 200 as proof.
+8. If any step fails, preserve the first concrete error and repair the smallest failing layer. Do not delete/recreate projects, DNS records, or provider state as a first response.
+9. Finish the workflow only after runtime and domain verification pass. Cancel the workflow if the deployment is abandoned.
+
+## Extending providers
+
+The provider registry is intentionally modular. New providers must define validated fields, secret classification, a live doctor probe, bounded clients, and tests before they are exposed to the agent. A new provider is not complete merely because a token can be stored.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4eea085c..da1cf3ef 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -12,11 +12,17 @@ bounded host layer rather than each implementing filesystem or process access.
flowchart LR
B[Browser / phone] -->|HTTPS + live device role| N[MSO Next.js :4005]
C[CLI `mso`] -->|local HTTP + approved device role| N
+ T[Terminal MSO Agent] -->|SSE chat| N
+ T -->|owner-only agent-tools bridge| M[/mcp dispatcher]
A[Alfa] -->|HostTool catalog + per-call approvals| H[lib/host]
X[ChatGPT / Claude / Cursor] -->|OAuth bearer + MCP| M[/mcp dispatcher]
N --> API[/api/v1/*]
API --> H
M --> H
+ M --> I[lib/infra]
+ I --> DP[Dokploy]
+ I --> CFAPI[Cloudflare]
+ I --> HA[Hostinger]
M --> D[project + skill discovery]
H --> F[filesystem jail]
H --> P[PTY / exec / metrics / services / packages]
@@ -33,7 +39,9 @@ flowchart LR
| Browser device session | `lib/auth/*`, `/api/auth/*` | Password + approved device + HMAC-signed cookie; live Viewer/Operator/Owner role. |
| Host operations | `lib/host/*` | Filesystem roots, credential denylist, process/system operations, audit. |
| Web host API | `/api/v1/*` | Live-role-gated routes; unknown mutations fail up to Owner and routes delegate into `lib/host`. |
-| CLI | `bin/mso` | Another frontend over the same web API; `docs/CLI.md` is generated from it. |
+| CLI | `bin/mso` | Another frontend over the same web API; bare `mso` starts the interactive agent and `docs/CLI.md` is generated from the help contract. |
+| Terminal MSO Agent | `scripts/mso-agent.mjs`, `/api/v1/agent-tools` | Streams through `/api/assistant`, discovers the canonical MCP catalog, and requires terminal approval before write/exec calls. |
+| Infrastructure providers | `lib/infra/*`, `/api/v1/infra/*` | Owner-private Dokploy/Cloudflare/Hostinger state and bounded provider clients; secrets never enter model tool arguments. |
| Alfa | `frontend/slices/assistant/host-tools/*` | Stable tool catalog; reads run immediately, mutations require human approval. |
| MCP | `lib/mcp/*`, `/mcp`, `/oauth/*` | OAuth 2.1 + PKCE; `read < write < exec` token scope. |
| Managed apps | `lib/managed-apps/*` | Hermes/OpenClaw remain separate runtimes and state trees. |
@@ -52,12 +60,14 @@ frontend/slices/ vertical application slices
appshell/ generic shell framework
features/ shell features
os-shell/ MSO manifest + capability adapters
+ infrastructure/ Dokploy and Cloudflare default feature apps
lib/auth/ login/session/device approval + live roles
lib/host/ bounded host capability implementation
lib/mcp/ OAuth/MCP tool catalog and dispatcher
lib/managed-apps/ Hermes/OpenClaw/9Router lifecycle/update/backup/proxy
+lib/infra/ Dokploy/Cloudflare/Hostinger provider registry, private store and bounded clients
lib/skills/ trusted skill discovery and semantic search
-scripts/ install, release, checks and service helpers
+scripts/ install, release, checks, terminal agent and service helpers
claude-skills/ official trusted operational playbooks
docs/ current references + clearly marked historical docs
```
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 5b502d51..9164468a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `cli` add MSO agent and infrastructure providers
- `mcp` add guided client setup
**Fixed**
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index 2df424e5..8040bfb8 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -12,10 +12,10 @@
> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>
> and <https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex>.
-<!-- mcp-toolset: server=1.6.0 version=2026.08.28.1 tools=31 read=16 write=10 exec=5 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.08.31.1 tools=38 read=20 write=13 exec=5 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.08.28.1**: **31 tools**
-(16 read, 10 write, 5 exec). Use `GET /mcp` or Settings → MCP as the live authority if
+MSO currently exposes MCP server **1.6.0**, toolset **2026.08.31.1**: **38 tools**
+(20 read, 13 write, 5 exec). Use `GET /mcp` or Settings → MCP as the live authority if
this document and a deployed instance ever disagree.
## 1. What this connection does
@@ -34,6 +34,7 @@ flowchart LR
D --> H[lib/host]
D --> PR[project discovery/functions]
D --> SK[skills + workflow memory]
+ D --> INF[Dokploy / Cloudflare / Hostinger]
H --> FS[filesystem roots]
H --> SYS[system / PTY / exec]
H --> AP[Hermes / OpenClaw]
@@ -140,7 +141,7 @@ A token sees a scope prefix; there is no per-project or per-agent hidden tool fi
`tools/list` filters the catalog and `tools/call` independently re-checks the required
scope.
-### `read` — 16 tools
+### `read` — 20 tools
- `fs_list`
- `fs_read`
@@ -158,8 +159,12 @@ scope.
- `skills_search`
- `screen_capture`
- `exec_job_status`
+- `infra_providers_list`
+- `infra_provider_doctor`
+- `dokploy_projects_list`
+- `cloudflare_zones_list`
-### `write` — read + 10 tools
+### `write` — read + 13 tools
- `fs_write`
- `fs_upload_file`
@@ -171,6 +176,9 @@ scope.
- `workflow_start`
- `workflow_cancel`
- `workflow_finish`
+- `dokploy_project_ensure`
+- `cloudflare_dns_upsert`
+- `hostinger_dns_upsert`
### `exec` — write + 5 tools
@@ -184,6 +192,17 @@ scope.
accident tripwire, not a sandbox. Grant `exec` only to a ChatGPT app/workspace you trust
with the same care as a remote shell.
+
+### Infrastructure-provider actions
+
+The infrastructure tools never accept API tokens as arguments. ChatGPT sees masked provider
+status, then MSO loads Dokploy/Cloudflare/Hostinger credentials server-side for the approved
+call. `cloudflare_dns_upsert` changes one exact record and defaults proxying off.
+`hostinger_dns_upsert` uses Hostinger's scoped overwrite semantics: MSO sends one exact name/type RR-set rather than a full-zone
+snapshot; unrelated rows are never included in the mutation payload and ambiguous/conflicting records are refused, but the action
+still deserves the same scrutiny as any external infrastructure mutation. Configure providers
+locally with `mso provider set <id>` rather than pasting credentials into a ChatGPT message.
+
## 6. Tool-snapshot refresh: the part most often missed
ChatGPT scans and caches the MCP action definitions. If MSO adds/removes/changes tools, a
@@ -195,7 +214,7 @@ Settings → MCP:
```text
server: 1.6.0
-toolset: 2026.08.28.1
+toolset: 2026.08.31.1
hash: <live schema hash>
count: 31
```
diff --git a/docs/CLI.md b/docs/CLI.md
index 6ac1ed5d..4dd1f8ca 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -82,7 +82,13 @@ Commands:
status Public service status (no session needed)
health Is this CLI's session valid?
doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
- onboard [-y] Guided first-run setup: AI, response style, managed apps, skills
+ agent Interactive MSO setup/ops agent (bare `mso` opens this)
+ chat Alias for agent
+ model Connect or change the AI provider used by MSO Agent / Alfa
+ onboard [-y] Guided setup: AI, apps, infrastructure, skills
+ setup Alias for onboard
+ provider * Infrastructure credentials: list | set | rm | doctor
+ providers * Alias for provider
gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
web Open the MSO browser UI (active gateway first, else loopback)
diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
index 55b33208..7af3018a 100644
--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md
+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
@@ -4,10 +4,10 @@
> can evolve independently, so do not claim its mapping count is current without checking
> that repository at the time of the change.
-<!-- mcp-toolset: server=1.6.0 version=2026.08.28.1 tools=31 read=16 write=10 exec=5 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.08.31.1 tools=38 read=20 write=13 exec=5 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.08.28.1**: **31 tools**
-(16 read, 10 write, 5 exec). `GET /mcp` exposes the live names, version/hash and scoped
+MSO currently exposes MCP server **1.6.0**, toolset **2026.08.31.1**: **38 tools**
+(20 read, 13 write, 5 exec). `GET /mcp` exposes the live names, version/hash and scoped
manifest and is the machine-readable parity source.
## Why this contract matters
@@ -33,20 +33,22 @@ Before changing an MCP tool name:
## Current MSO catalog
-### Read (15)
+### Read (20)
`fs_list`, `fs_read`, `fs_search`, `fs_usage`, `sys_stats`, `sys_processes`,
`apps_list`, `apps_logs`, `browser_status`, `projects_list`, `project_capabilities`,
-`skills_list`, `skills_read`, `skills_search`, `screen_capture`.
+`skills_list`, `skills_read`, `skills_search`, `screen_capture`, `exec_job_status`,
+`infra_providers_list`, `infra_provider_doctor`, `dokploy_projects_list`, `cloudflare_zones_list`.
-### Write (10 beyond read)
+### Write (13 beyond read)
`fs_write`, `fs_upload_file`, `fs_mkdir`, `fs_move`, `fs_copy`, `fs_delete`,
-`apps_power`, `workflow_start`, `workflow_cancel`, `workflow_finish`.
+`apps_power`, `workflow_start`, `workflow_cancel`, `workflow_finish`,
+`dokploy_project_ensure`, `cloudflare_dns_upsert`, `hostinger_dns_upsert`.
-### Exec (3 beyond write)
+### Exec (5 beyond write)
-`exec_run`, `browser_power`, `project_function_call`.
+`exec_run`, `browser_power`, `project_function_call`, `exec_job_start`, `exec_job_cancel`.
## Scope and workflow compatibility
@@ -84,7 +86,8 @@ Treat these as particularly important in any external approval layer:
- `apps_power` — bounded daemon control and state backup;
- `exec_run` — host shell as the MSO user;
- `browser_power` — starts a browser profile with live logged-in sessions;
-- `project_function_call` — executes project-owned fixed argv and is always exec-scope.
+- `project_function_call` — executes project-owned fixed argv and is always exec-scope;
+- `dokploy_project_ensure` / `cloudflare_dns_upsert` / `hostinger_dns_upsert` — mutate external infrastructure with provider credentials kept server-side; Hostinger receives only the requested name/type RR-set (`overwrite:true`), never an MSO-generated full-zone snapshot.
External policy supplements MSO's own scope/path/audit/rate-limit checks; it does not replace
them.
diff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.md
new file mode 100644
index 00000000..c216b05a
--- /dev/null
+++ b/docs/INFRASTRUCTURE-PROVIDERS.md
@@ -0,0 +1,175 @@
+# Infrastructure providers and MSO Agent
+
+> **Current reference.** This is the contract for the interactive `mso` agent and the
+> provider-backed deployment layer. Provider credentials are owner-local state; they are
+> never part of the model prompt or MCP tool arguments.
+
+MSO now owns the deployment-assistance pattern that previously lived separately in
+`rahmanef63/si-coder-agent`: provider discovery, live API verification, bounded Dokploy
+operations, and DNS automation. The implementation is native MSO code rather than a nested
+`si-coder-agent` runtime, so the browser features, CLI, terminal agent and MCP surface share
+one catalog and one security/audit model.
+
+## 1. Terminal entry points
+
+Bare `mso` is the interactive setup/operations agent:
+
+```bash
+mso # launch MSO Agent
+mso agent # explicit alias
+mso model # connect/change the AI provider
+mso setup # guided setup (alias of `mso onboard`)
+mso provider list # masked infrastructure status
+mso provider set dokploy # hidden terminal prompts
+mso provider set cloudflare
+mso provider set hostinger
+mso provider doctor # live-check every configured provider
+mso provider projects # Dokploy projects
+mso provider zones # Cloudflare zones
+```
+
+When no AI provider is connected, `mso` runs the same interactive provider flow as
+`mso model` before the agent starts. The current model connection choices are OpenAI
+ChatGPT/Codex device OAuth plus the built-in API-key providers documented in
+[`INSTALL.md`](./INSTALL.md).
+
+The terminal UI intentionally follows the useful *shape* of mature agent CLIs such as
+Hermes — large identity banner, selected model, tool/skill/provider summary, then an
+interactive prompt — but uses original MSO ASCII artwork and MSO's own tool/runtime stack.
+
+Agent slash commands are:
+
+```text
+/model /setup /providers /provider <id> /doctor
+/tools /skills /clear /exit
+```
+
+## 2. One tool catalog, two transports
+
+`scripts/mso-agent.mjs` does not invent a second host-tool implementation. It asks the
+owner-only `/api/v1/agent-tools` bridge for the canonical `lib/mcp/*` catalog and sends those
+schemas to `/api/assistant`. Tool execution comes back through the same MCP dispatcher.
+
+```mermaid
+flowchart LR
+ T[bare `mso` terminal] --> A[/api/assistant]
+ T --> G[/api/v1/agent-tools]
+ G --> M[canonical MCP dispatcher]
+ M --> H[bounded host/project tools]
+ M --> I[lib/infra provider clients]
+ I --> D[Dokploy]
+ I --> C[Cloudflare]
+ I --> HS[Hostinger]
+```
+
+Read tools may run immediately. Every `write` or `exec` request from the terminal pauses on
+an exact-call approval prompt; there is no session-wide mutation allowlist. MSO renders the
+complete canonical tool name + nested input before approval, shows its SHA-256, and the server
+recomputes that digest before dispatch so changing any field invalidates approval. Calls larger
+than 32 KiB are refused by the terminal agent rather than approved from a truncated preview.
+The server independently requires an Owner session, applies the deployment's MCP scope ceiling,
+re-checks the tool scope, rate-limits the operation and writes its normal audit trail. Terminal
+approval is therefore an additional interaction guard, not a replacement for server authorization.
+
+## 3. Credential boundary
+
+Provider state defaults to:
+
+```text
+~/.mso/private/infra-providers.json
+```
+
+The directory is `0700`; the file is `0600`, owner-checked, regular-file checked, size-bounded
+and opened with `O_NOFOLLOW`. Writes are serialized through the security-store lock and
+published atomically.
+
+Secret fields are entered with terminal echo disabled or through password inputs in the
+Dokploy/Cloudflare feature apps. API-key JSON is posted from stdin; the key is not placed in
+`jq`, Node, or curl argv. API reads expose only the word `configured` for secret fields; no token prefix/suffix leaves the server. Agent/MCP schemas do
+not contain credential parameters at all: the server-side provider client loads the secret
+only when the approved operation actually runs.
+
+Do **not** paste an API token into an MSO Agent conversation. If an agent says a provider is
+missing, run `mso provider set <id>` in the terminal and then ask it to re-check.
+
+## 4. Dokploy
+
+Dokploy is a default MSO feature app and an agent provider. Configuration fields are:
+
+- `apiUrl` — required. Remote endpoints must use HTTPS; loopback development/runtime URLs may
+ use HTTP. `/api` is normalized automatically.
+- `apiKey` — required secret.
+- `publicIp` — optional explicit public IPv4 used by deployment workflows. MSO never derives a
+ public DNS target from a loopback Dokploy URL.
+
+Remote Dokploy requests use the existing DNS-pinned safe-provider transport: private,
+link-local and metadata resolutions are refused and redirects are not followed. Literal
+loopback is the only local exception. The first bounded operations are project listing and
+idempotent project creation/ensure, with retry/backoff on transient upstream failures.
+
+The provider is intentionally narrower than the old standalone deployment scripts. Add each
+new Dokploy mutation as a typed, validated, tested tool rather than turning the API key into a
+generic arbitrary-request primitive.
+
+## 5. Cloudflare
+
+Cloudflare is a default MSO feature app. The provider stores an API token plus optional zone
+and account pins. Use the smallest token scope that covers the zones MSO must manage.
+
+DNS automation is deliberately per-record:
+
+- supported types: `A`, `AAAA`, `CNAME`, `TXT`;
+- exact zone containment and exact record lookup;
+- ambiguous duplicates are refused rather than guessed;
+- conflicting `CNAME` versus address records are refused rather than deleted/replaced;
+- existing records use `PATCH`; new records use `POST`;
+- no bulk zone `PUT` exists;
+- Cloudflare proxying defaults **off** and is enabled only when `proxied=true` was explicitly
+ requested.
+
+This preserves the safest part of the `si-coder-agent` Cloudflare pattern while putting it
+behind MSO scope, approval, audit and workflow controls.
+
+## 6. Hostinger
+
+Hostinger is available as an infrastructure provider because many MSO deployments use hPanel
+for their domain. It is not a default shell app; Dokploy and Cloudflare are the two default
+infrastructure apps requested for the MSO workspace.
+
+Hostinger's zone update API supports scoped RR-set replacement: with `overwrite:true`, only records matching the supplied `name + type` are replaced. MSO therefore verifies portfolio ownership, reads the zone only for ambiguity/conflict checks, and PUTs **one** requested RR-set. Unrelated rows are never included in the mutation payload, so a concurrent update elsewhere in the zone cannot be lost through MSO. The write remains approval-gated because changing DNS is externally visible state.
+
+## 7. Current infrastructure tools
+
+| Tool | Scope | Purpose |
+|---|---|---|
+| `infra_providers_list` | read | masked provider/configuration inventory |
+| `infra_provider_doctor` | read | live provider API check |
+| `dokploy_projects_list` | read | bounded Dokploy project discovery |
+| `dokploy_project_ensure` | write | idempotently create a missing project |
+| `cloudflare_zones_list` | read | bounded accessible-zone discovery |
+| `cloudflare_dns_upsert` | write | exact one-record Cloudflare create/update |
+| `hostinger_dns_upsert` | write | replace one exact Hostinger name/type RR-set |
+
+For multi-step project deployment, the official
+[`mso-project-deploy`](../claude-skills/mso-project-deploy/SKILL.md) skill requires
+`workflow_start` → inspect/plan → provider doctor → bounded operations → runtime/domain
+verification → `workflow_finish`. A provider credential is never an excuse to skip project
+inspection or verification.
+
+## 8. Adding another provider
+
+A provider is not complete merely because MSO can store its token. A new integration must add:
+
+1. a registry definition with required/optional and secret fields;
+2. strict normalization/validation;
+3. private-store tests, including secret non-disclosure;
+4. a live read-only doctor probe;
+5. bounded provider-client operations with timeout/retry and SSRF/redirect policy appropriate
+ to configurable endpoints;
+6. scoped MCP tools with rate limits and audit classification;
+7. an explicit Alfa/MCP parity exemption or corresponding in-app capability;
+8. CLI/UI exposure only after those contracts pass;
+9. docs plus the normal repository/security gates.
+
+Prefer provider-native exact operations over generic `curl`/shell automation. Generic shell
+remains the escape hatch, not the product API.
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 55eb83b9..f1e5804b 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -103,6 +103,18 @@ Their model/provider configuration belongs to those applications and is not impl
filled from Alfa's credential. Selected app installs stream their job transcript until a
terminal status.
+The same onboarding can optionally connect **Dokploy** and one DNS provider (**Cloudflare**
+or **Hostinger**). These credentials are a separate infrastructure store, not AI-provider
+configuration. Secret prompts have terminal echo disabled and are posted from stdin; the
+model sees only masked configuration state and credential-free tool schemas. `-y` skips all
+external infrastructure credentials. Reconfigure later with `mso provider set <id>` and
+verify with `mso provider doctor`.
+
+After an AI provider is connected, bare `mso` launches the interactive MSO Agent. The agent
+uses the canonical MCP tool catalog internally: reads run directly, while write/exec calls
+pause for terminal approval. See [`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md)
+for the deployment/provider boundary.
+
### WSL2
WSL can contain `systemctl` while still running a non-systemd PID 1. MSO treats those as two
diff --git a/docs/MCP.md b/docs/MCP.md
index a1aede02..53ed3fd2 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -75,15 +75,19 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe
| Scope | Tools |
|---|---|
-| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` `exec_job_status` |
-| `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` |
+| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` `exec_job_status` `infra_providers_list` `infra_provider_doctor` `dokploy_projects_list` `cloudflare_zones_list` |
+| `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` `dokploy_project_ensure` `cloudflare_dns_upsert` `hostinger_dns_upsert` |
| `exec` | + `project_function_call` `exec_run` `exec_job_start` `exec_job_cancel` `browser_power` |
-Alfa — the in-app assistant — has the same host capabilities under dot.case names,
+Alfa — the in-app assistant — overlaps the same host capabilities under dot.case names,
and `lib/mcp/parity.test.ts` fails if one surface gains a tool the other lacks
-without a written reason. `skills_search` maps to Alfa's `skills.search`.
-`screen_capture`, `projects_list`, `project_capabilities`, `project_function_call`, `fs_upload_file`, `workflow_start`, `workflow_cancel` and
-`workflow_finish` are explicitly MCP-only: the external connector needs visual proof,
+without a written reason. `skills_search` maps to Alfa's `skills.search`. The infrastructure
+provider tools are intentionally MCP-only: the terminal MSO Agent consumes this canonical
+catalog through the owner-only agent-tools bridge, while in-shell Alfa has dedicated
+Dokploy/Cloudflare feature surfaces instead of receiving public-DNS credentials/capabilities.
+`screen_capture`, `projects_list`, `project_capabilities`, `project_function_call`, `fs_upload_file`, `workflow_start`, `workflow_cancel`,
+`workflow_finish`, the async `exec_job_*` lifecycle and the `infra_*` / Dokploy / Cloudflare /
+Hostinger provider tools are explicitly MCP-only: the external connector needs visual proof,
an explicit project enumeration and an actor-scoped task boundary, while Alfa already
runs inside the rendered shell, has the Files window and owns an in-app run boundary.
`skills_list` and `skills_read` now exist on BOTH surfaces — capability discovery is
@@ -120,7 +124,7 @@ The catalog has a stable server version plus a schema-derived toolset signature.
Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.
-<!-- mcp-toolset: server=1.6.0 version=2026.08.28.1 tools=31 read=16 write=10 exec=5 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.08.31.1 tools=38 read=20 write=13 exec=5 -->
Current catalog: **31 tools** (16 read, 10 write, 5 exec), server `1.6.0` / toolset
`2026.08.28.1`. `project_capabilities` and `project_function_call` add one stable
@@ -547,7 +551,8 @@ failure mode for an endpoint whose top scope is a shell.
Those are per TOKEN and say nothing about which tool ran, so each mutating tool
also carries the **per-operation** limit its route already applies, on the SAME
bucket key — MCP and the browser share one allowance rather than getting one each.
-`exec_run` 60/min, fs writes 120/min, fs copy/delete 60/min, `apps_power` and
+`exec_run` 60/min, fs writes 120/min, fs copy/delete 60/min, Dokploy/Cloudflare
+infrastructure writes 20/min, Hostinger DNS writes 10/min, `apps_power` and
`browser_power` 12/min per app. MCP-native expensive/stateful operations are
stricter: `screen_capture` 10/min, `projects_list` and `skills_list` 30/min,
`skills_read` 60/min, and workflow-memory writes 30/min.
@@ -563,6 +568,7 @@ lib/mcp/tools-read.ts bounded reads + skills_search + screen_capture
lib/mcp/tools-discovery.ts projects_list / skills_list / skills_read — global discovery
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/activity.ts workflow-correlated live activity
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 26aa4f74..52103fe6 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,26 @@
Running log of what shipped each phase. Newest at top.
+## 2026-08-31 — MSO terminal agent + provider-backed deployment setup — DONE IN SOURCE
+
+**Source milestone — ship only after the exact commit passes the repository/security gates and the live health SHA matches.** The standalone deployment-assistance pattern from `rahmanef63/si-coder-agent` is now absorbed into MSO's own architecture instead of spawning a second agent runtime. Installed Hermes and its public CLI were used as interaction references only; MSO has original terminal artwork, its own tool catalog, and its existing auth/audit model.
+
+What changed:
+
+- bare `mso` now launches **MSO Agent**; `mso agent`/`mso chat` are explicit aliases and `mso model` connects or changes the AI provider before the agent starts;
+- the terminal presents original MSO ASCII, selected model, Available Tools, Available Skills and infrastructure readiness, then streams through the existing `/api/assistant` backend;
+- the terminal discovers the canonical MCP catalog through an Owner-only `/api/v1/agent-tools` bridge. Read tools may execute directly; every individual write/exec call pauses for an exact-call terminal approval (never a cached session-wide mutation grant) while server role/scope/rate-limit/audit checks remain authoritative;
+- MCP toolset is **2026.08.31.1: 38 tools = 20 read + 13 write + 5 exec**. New provider tools cover redacted provider discovery/doctor, Dokploy project list/ensure, exact per-record Cloudflare DNS upsert, and exact Hostinger name/type RR-set replacement;
+- provider credentials are stored separately in `~/.mso/private/infra-providers.json`: 0700 parent, 0600 file, `O_NOFOLLOW`, regular-file/owner/size checks, atomic locked writes, API summaries expose only the word `configured` for secret fields, and no raw secret enters model/MCP arguments;
+- `mso provider set dokploy|cloudflare|hostinger` uses hidden terminal input. AI API-key setup was hardened at the same time so provider keys are built from stdin rather than being exposed through helper-process argv;
+- **Dokploy** and **Cloudflare** are built-in default shell/App Store features with secure configuration, Verify, and live project/zone inventory. Hostinger remains a provider rather than a default app;
+- configurable remote Dokploy endpoints use the existing DNS-pinned safe-provider transport; remote HTTP is refused, redirects are refused, and private/link-local/metadata resolution is blocked. Literal loopback remains the explicit same-host exception;
+- Cloudflare automation never performs a bulk zone PUT, refuses duplicate/conflicting rows, PATCHes one existing record or POSTs one new record, and defaults proxying off. Hostinger DNS now uses the provider's scoped RR-set replacement semantics (`overwrite:true` with one `name + type` row), so unrelated zone rows never enter the PUT payload; ambiguity/conflicts remain refused and the mutation stays approval-gated;
+- official `mso-project-deploy` skill documents workflow start → inspect → provider doctor → bounded deployment/DNS operations → runtime/HTTPS verification → finish/cancel;
+- CLI version for this interaction milestone is **1.5.0**. `docs/INFRASTRUCTURE-PROVIDERS.md`, architecture/install/MCP/ChatGPT connector docs, generated CLI reference and slice catalog are synchronized.
+
+Verification added specifically for this slice covers provider-store symlink/permission/secret behavior, Cloudflare one-record semantics, Hostinger exact RR-set payloads, Owner-only agent/provider routes, exact-payload terminal approval, CLI onboarding/update fixtures, MCP parity/rate limits, and documentation/toolset markers. The final full repository gate passes with **249 test files / 1,901 passing tests** (1 expected fail, 4 skipped), typecheck and dependency audit green, zero value cycles, and zero lint errors (three pre-existing max-lines warnings remain). A targeted Codex Security pass first found two Medium issues in the new infrastructure surface — whole-response buffering before its nominal 1 MiB cap and a stale full-zone Hostinger PUT. Both were fixed; the final infrastructure re-scan completed **1/1 component with 0 findings**. A separate terminal-agent scan found one Medium issue where a truncated approval preview could conceal mutation fields. The terminal now renders the complete canonical tool name + nested input, refuses approval payloads above 32 KiB, removes session-wide mutation grants, and binds the approval SHA-256 to the exact payload that the server independently re-hashes before dispatch; the final terminal-agent re-scan completed **1/1 component with 0 findings**. A parallel-suite-only lifecycle harness race was also removed by holding the fixture lock until the assertion explicitly releases it; the lifecycle file then passed 5 consecutive runs (40/40 checks). Live Dokploy/Cloudflare/Hostinger API success is intentionally not claimed until an owner supplies credentials and `mso provider doctor` checks that provider.
+
## 2026-08-31 — Login-origin diagnosis + `mso doctor --fix` + runtime hardening (SHIPPED)
A real install report confirmed the confusing post-approval login case was transport, not a broken
diff --git a/docs/README.md b/docs/README.md
index ce86ef9f..6b40db0a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -24,6 +24,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`COMPARISON.md`](./COMPARISON.md) | Generated product comparison methodology, evidence and notes |
| [`COMPETITIVE-ROADMAP.md`](./COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate specialist boundaries and next investments |
| [`INSTALL.md`](./INSTALL.md) | Owner installation, TLS, updates, backup and uninstall |
+| [`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md) | Interactive MSO Agent, Dokploy/Cloudflare/Hostinger credentials, tools and deployment boundary |
| [`DEVELOPMENT.md`](./DEVELOPMENT.md) | Development and release workflow |
| [`SECURITY-ASSURANCE.md`](./SECURITY-ASSURANCE.md) | Repeatable security verification lanes, public evidence, and claim boundaries |
| [`CLI.md`](./CLI.md) | Generated `mso` CLI contract |
diff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.md
index 5680a219..fa09f3d9 100644
--- a/docs/SLICE-CATALOG.md
+++ b/docs/SLICE-CATALOG.md
@@ -3,12 +3,12 @@
> **Current reference.** Counts are checked against the directory tree by
> `scripts/check-docs.mjs`; the directory remains the final authority.
-<!-- slice-catalog: slices=21 appshell-features=10 -->
+<!-- slice-catalog: slices=22 appshell-features=10 -->
Every application is a vertical slice under `frontend/slices/`. Host-facing slices use the
shared API/host seam rather than reaching arbitrary Node host APIs from client code.
-## Slices (21)
+## Slices (22)
| Slug | Purpose |
|---|---|
@@ -23,6 +23,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c
| `files-manager` | VPS Files manager |
| `image-editor` | Layered raster image editor |
| `image-picker` | Reusable image/wallpaper picker |
+| `infrastructure` | Dokploy/Cloudflare provider configuration and live inventory apps |
| `managed-apps` | Hermes/OpenClaw install/lifecycle/update/backup/proxy |
| `media-studio` | Image/media studio surface |
| `media-viewer` | Preview/Quick Look-style media viewer |
diff --git a/frontend/slices/app-store/lib/system-catalog.ts b/frontend/slices/app-store/lib/system-catalog.ts
index 9fe122ed..2e0a4c95 100644
--- a/frontend/slices/app-store/lib/system-catalog.ts
+++ b/frontend/slices/app-store/lib/system-catalog.ts
@@ -16,6 +16,8 @@ import {
Bell,
SlidersHorizontal,
LayoutGrid,
+ Cloud,
+ ServerCog,
type LucideIcon,
} from "lucide-react";
@@ -50,6 +52,8 @@ export const SYSTEM_CATALOG: SystemEntry[] = [
{ id: "create-app", title: "Create App", kind: "app", icon: PlusSquare, gradient: "linear-gradient(160deg,#16c2c2,#0a8a8a)", desc: "Author a custom runtime app." },
{ id: "system-monitor", title: "System Monitor", kind: "app", icon: Gauge, gradient: "linear-gradient(160deg,#f25f5c,#c0392b)", desc: "Live CPU, memory, and disk telemetry." },
{ id: "assistant", title: "Alfa", kind: "app", icon: Sparkles, gradient: "linear-gradient(160deg,#7a5cff,#3aa0ff)", desc: "AI copilot for your VPS." },
+ { id: "dokploy", title: "Dokploy", kind: "app", icon: ServerCog, gradient: "linear-gradient(160deg,#111827,#2563eb)", desc: "Deploy and manage projects through the Dokploy API." },
+ { id: "cloudflare", title: "Cloudflare", kind: "app", icon: Cloud, gradient: "linear-gradient(160deg,#f59e0b,#ea580c)", desc: "Verify Cloudflare access and inspect DNS zones." },
{ id: "os-settings", title: "Settings", kind: "app", icon: Settings, gradient: "linear-gradient(160deg,#5b6070,#2b2f3a)", desc: "Appearance, server mode, devices." },
{ id: "app-store", title: "App Store", kind: "app", icon: Store, gradient: "linear-gradient(160deg,#9b5cff,#5b2fe0)", desc: "Install apps and toggle features.", required: true },
// ── Shell features ────────────────────────────────────────────────────────
diff --git a/frontend/slices/infrastructure/app.tsx b/frontend/slices/infrastructure/app.tsx
new file mode 100644
index 00000000..348300a1
--- /dev/null
+++ b/frontend/slices/infrastructure/app.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { CheckCircle2, Cloud, Loader2, RefreshCw, Save, ServerCog, ShieldCheck, TriangleAlert } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import type { InfrastructureFeatureId } from "./index";
+
+type Field = { key: string; label: string; secret: boolean; required: boolean; placeholder?: string; description: string };
+type Provider = { id: string; title: string; description: string; configured: boolean; missing: string[]; values: Record<string, string>; fields: Field[] };
+type Doctor = { id: string; ok: boolean | null; detail: string };
+
+type RemoteItem = { id: string; name: string };
+
+async function json<T>(url: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(url, { ...init, headers: { "content-type": "application/json", ...(init?.headers ?? {}) } });
+ const body = await res.json().catch(() => ({})) as T & { error?: string };
+ if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`);
+ return body;
+}
+
+export function InfrastructureProviderApp({ provider }: { provider: InfrastructureFeatureId }) {
+ const [meta, setMeta] = useState<Provider | null>(null);
+ const [form, setForm] = useState<Record<string, string>>({});
+ const [doctor, setDoctor] = useState<Doctor | null>(null);
+ const [items, setItems] = useState<RemoteItem[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+
+ const refresh = useCallback(async () => {
+ try {
+ const data = await json<{ providers: Provider[] }>("/api/v1/infra/providers");
+ setError("");
+ const row = data.providers.find((entry) => entry.id === provider) ?? null;
+ setMeta(row);
+ if (row) setForm((current) => Object.fromEntries(row.fields.map((field) => [field.key, current[field.key] ?? (field.secret ? "" : row.values[field.key] ?? "")])))
+ if (row?.configured) {
+ const resource = provider === "dokploy"
+ ? await json<{ projects: Array<{ projectId: string; name: string }> }>("/api/v1/infra/dokploy/projects").then((r) => r.projects.map((p) => ({ id: p.projectId, name: p.name })))
+ : await json<{ zones: RemoteItem[] }>("/api/v1/infra/cloudflare/zones").then((r) => r.zones);
+ setItems(resource);
+ } else setItems([]);
+ } catch (e) { setError(e instanceof Error ? e.message : "Failed to read provider"); }
+ }, [provider]);
+
+ useEffect(() => {
+ const timer = window.setTimeout(() => { void refresh(); }, 0);
+ return () => window.clearTimeout(timer);
+ }, [refresh]);
+
+ const save = async () => {
+ if (!meta) return;
+ setBusy(true); setError("");
+ try {
+ const values = Object.fromEntries(Object.entries(form).filter(([, value]) => value.trim()));
+ await json("/api/v1/infra/providers", { method: "POST", body: JSON.stringify({ id: provider, values }) });
+ const checked = await json<{ results: Doctor[] }>("/api/v1/infra/providers/doctor", { method: "POST", body: JSON.stringify({ id: provider }) });
+ setDoctor(checked.results[0] ?? null);
+ setForm((current) => ({ ...current, ...(meta.fields.filter((field) => field.secret).reduce((acc, field) => ({ ...acc, [field.key]: "" }), {}) as Record<string, string>) }));
+ await refresh();
+ } catch (e) { setError(e instanceof Error ? e.message : "Failed to save provider"); }
+ finally { setBusy(false); }
+ };
+
+ const verify = async () => {
+ setBusy(true); setError("");
+ try {
+ const checked = await json<{ results: Doctor[] }>("/api/v1/infra/providers/doctor", { method: "POST", body: JSON.stringify({ id: provider }) });
+ setDoctor(checked.results[0] ?? null);
+ await refresh();
+ } catch (e) { setError(e instanceof Error ? e.message : "Provider verification failed"); }
+ finally { setBusy(false); }
+ };
+
+ const Icon = provider === "dokploy" ? ServerCog : Cloud;
+ const remoteLabel = provider === "dokploy" ? "Projects" : "Zones";
+ const summary = useMemo(() => meta?.configured ? "Configured" : meta ? `Missing ${meta.missing.join(", ")}` : "Loading", [meta]);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col bg-[color:var(--window-bg)] text-[color:var(--text)]">
+ <header className="flex flex-wrap items-center justify-between gap-2 border-b border-[color:var(--separator)] px-4 py-3">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <div className="grid size-8 place-items-center rounded-lg bg-[color:var(--inset)]"><Icon className="size-4.5" /></div>
+ <div className="min-w-0"><h2 className="truncate text-sm font-semibold">{meta?.title ?? (provider === "dokploy" ? "Dokploy" : "Cloudflare")}</h2><p className="truncate text-[11px] text-[color:var(--text-dim)]">{summary}</p></div>
+ </div>
+ <div className="flex items-center gap-2"><Button size="sm" variant="outline" onClick={() => void verify()} disabled={busy || !meta?.configured}><ShieldCheck className="size-3.5" /> Verify</Button><Button size="sm" onClick={() => void save()} disabled={busy || !meta}>{busy ? <Loader2 className="size-3.5 animate-spin" /> : <Save className="size-3.5" />} Save</Button></div>
+ </header>
+
+ <div className="min-h-0 flex-1 overflow-y-auto p-4">
+ <div className="mx-auto grid w-full max-w-5xl gap-4 lg:grid-cols-[minmax(0,1.05fr)_minmax(280px,.95fr)]">
+ <section className="rounded-xl border border-[color:var(--separator)] bg-[color:var(--surface)] p-4">
+ <div className="mb-4"><h3 className="text-xs font-semibold uppercase tracking-[0.12em] text-[color:var(--text-dim)]">Connection</h3><p className="mt-1 text-xs text-[color:var(--text-dim)]">{meta?.description}</p></div>
+ <div className="space-y-3">
+ {meta?.fields.map((field) => <label key={field.key} className="block"><span className="mb-1 flex items-center justify-between text-xs font-medium"><span>{field.label}{field.required ? " *" : ""}</span>{meta.values[field.key] && <span className="text-[10px] font-normal text-[color:var(--text-dim)]">current: {meta.values[field.key]}</span>}</span><input type={field.secret ? "password" : "text"} autoComplete="off" value={form[field.key] ?? ""} placeholder={field.secret && meta.values[field.key] ? "Leave blank to keep current secret" : field.placeholder ?? ""} onChange={(e) => setForm((current) => ({ ...current, [field.key]: e.target.value }))} className="h-9 w-full rounded-lg border border-[color:var(--separator)] bg-[color:var(--inset)] px-3 text-xs outline-none focus:border-[color:var(--accent)]" /><span className="mt-1 block text-[10px] leading-4 text-[color:var(--text-faint)]">{field.description}</span></label>)}
+ </div>
+ {doctor && <div className={`mt-4 flex items-start gap-2 rounded-lg border p-3 text-xs ${doctor.ok ? "border-emerald-500/30 bg-emerald-500/5" : "border-amber-500/30 bg-amber-500/5"}`}>{doctor.ok ? <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-500" /> : <TriangleAlert className="mt-0.5 size-4 shrink-0 text-amber-500" />}<span>{doctor.detail}</span></div>}
+ {error && <div className="mt-4 flex items-start gap-2 rounded-lg border border-red-500/30 bg-red-500/5 p-3 text-xs"><TriangleAlert className="mt-0.5 size-4 shrink-0 text-red-500" /><span>{error}</span></div>}
+ </section>
+
+ <section className="rounded-xl border border-[color:var(--separator)] bg-[color:var(--surface)] p-4">
+ <div className="mb-3 flex items-center justify-between"><div><h3 className="text-xs font-semibold uppercase tracking-[0.12em] text-[color:var(--text-dim)]">{remoteLabel}</h3><p className="mt-1 text-[10px] text-[color:var(--text-faint)]">Live read from the configured provider.</p></div><Button size="sm" variant="ghost" onClick={() => void refresh()}><RefreshCw className="size-3.5" /></Button></div>
+ {!meta?.configured ? <p className="rounded-lg bg-[color:var(--inset)] p-3 text-xs text-[color:var(--text-dim)]">Configure the required fields first.</p> : items.length ? <div className="space-y-1.5">{items.map((item) => <div key={item.id} className="flex items-center justify-between gap-3 rounded-lg bg-[color:var(--inset)] px-3 py-2"><span className="truncate text-xs font-medium">{item.name}</span><code className="max-w-[45%] truncate text-[10px] text-[color:var(--text-faint)]">{item.id}</code></div>)}</div> : <p className="rounded-lg bg-[color:var(--inset)] p-3 text-xs text-[color:var(--text-dim)]">No {remoteLabel.toLowerCase()} returned.</p>}
+ <div className="mt-4 rounded-lg border border-[color:var(--separator)] p-3 text-[10px] leading-4 text-[color:var(--text-dim)]">MSO Agent uses the same provider state through bounded tools. Secrets stay server-side and are never included in model tool arguments.</div>
+ </section>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/slices/infrastructure/index.tsx b/frontend/slices/infrastructure/index.tsx
new file mode 100644
index 00000000..db3dd5fb
--- /dev/null
+++ b/frontend/slices/infrastructure/index.tsx
@@ -0,0 +1,22 @@
+import { Cloud, ServerCog } from "lucide-react";
+import type { AppDescriptor } from "@/features/os-shell";
+
+export type InfrastructureFeatureId = "dokploy" | "cloudflare";
+
+function descriptor(id: InfrastructureFeatureId): AppDescriptor {
+ const isDokploy = id === "dokploy";
+ return {
+ id,
+ title: isDokploy ? "Dokploy" : "Cloudflare",
+ icon: isDokploy ? ServerCog : Cloud,
+ gradient: isDokploy ? "linear-gradient(160deg,#111827,#2563eb)" : "linear-gradient(160deg,#f59e0b,#ea580c)",
+ load: async () => {
+ const { InfrastructureProviderApp } = await import("./app");
+ return { default: () => <InfrastructureProviderApp provider={id} /> };
+ },
+ defaultSize: { w: 960, h: 680 },
+ };
+}
+
+export const dokployApp = descriptor("dokploy");
+export const cloudflareApp = descriptor("cloudflare");
diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.ts
index 2992244d..2fe94ebf 100644
--- a/frontend/slices/os-shell/shell.manifest.ts
+++ b/frontend/slices/os-shell/shell.manifest.ts
@@ -19,6 +19,7 @@ import { hermesApp, nineRouterApp, openclawApp } from "@/features/managed-apps";
import { osSettingsApp } from "@/features/os-settings";
import { quicklinksApp } from "@/features/quicklinks";
import { docsApp } from "@/features/docs";
+import { cloudflareApp, dokployApp } from "@/features/infrastructure";
import { themeQuickPickerFeature } from "./theme-quick-picker";
import { APP_MARKS } from "./brand-marks";
@@ -62,6 +63,8 @@ export const BUILTIN_APPS: AppDescriptor[] = [
withSlug(withArtwork(hermesApp), "hermes"),
withSlug(withArtwork(openclawApp), "openclaw"),
withSlug(withArtwork(nineRouterApp), "9router"),
+ withSlug(withArtwork(dokployApp), "dokploy"),
+ withSlug(withArtwork(cloudflareApp), "cloudflare"),
withSlug(withArtwork(quicklinksApp), "links"),
// Docs is deliberately dockable, not noDock: for a signed-out visitor it is the
// only app that explains what they are looking at and how to get their own.
diff --git a/lib/agent/approval.js b/lib/agent/approval.js
new file mode 100644
index 00000000..bdd182c9
--- /dev/null
+++ b/lib/agent/approval.js
@@ -0,0 +1,43 @@
+import { createHash } from "node:crypto";
+
+export const MAX_AGENT_APPROVAL_BYTES = 32 * 1024;
+
+function canonicalize(value) {
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
+ if (typeof value === "number") {
+ if (!Number.isFinite(value)) throw new Error("agent approval payload contains a non-finite number");
+ return value;
+ }
+ if (Array.isArray(value)) return value.map(canonicalize);
+ if (value && typeof value === "object") {
+ const out = Object.create(null);
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key]);
+ return out;
+ }
+ throw new Error(`agent approval payload is not JSON-safe: ${typeof value}`);
+}
+
+export function canonicalAgentApproval(name, input) {
+ const payload = canonicalize({ name: String(name), input: input ?? {} });
+ const canonical = JSON.stringify(payload);
+ const bytes = Buffer.byteLength(canonical, "utf8");
+ if (bytes > MAX_AGENT_APPROVAL_BYTES) {
+ throw new Error(`tool call is ${bytes} bytes; safe terminal approval is limited to ${MAX_AGENT_APPROVAL_BYTES} bytes`);
+ }
+ return {
+ payload,
+ canonical,
+ display: JSON.stringify(payload, null, 2),
+ digest: createHash("sha256").update(canonical).digest("hex"),
+ bytes,
+ };
+}
+
+export function matchesAgentApproval(name, input, digest) {
+ if (typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) return false;
+ try {
+ return canonicalAgentApproval(name, input).digest === digest;
+ } catch {
+ return false;
+ }
+}
diff --git a/lib/agent/approval.test.ts b/lib/agent/approval.test.ts
new file mode 100644
index 00000000..42e30206
--- /dev/null
+++ b/lib/agent/approval.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { canonicalAgentApproval, matchesAgentApproval, MAX_AGENT_APPROVAL_BYTES } from "./approval.js";
+
+describe("agent approval binding", () => {
+ it("renders every nested field losslessly in a stable canonical order", () => {
+ const a = canonicalAgentApproval("write_tool", { z: "tail", nested: { b: 2, a: "x" }, a: "head" });
+ const b = canonicalAgentApproval("write_tool", { a: "head", nested: { a: "x", b: 2 }, z: "tail" });
+ expect(a.canonical).toBe(b.canonical);
+ expect(a.digest).toBe(b.digest);
+ expect(a.display).toContain('"z": "tail"');
+ expect(a.display).toContain('"nested"');
+ expect(a.display).toContain('"b": 2');
+ });
+
+ it("rejects a digest when any approved input field changes", () => {
+ const approved = canonicalAgentApproval("write_tool", { command: "deploy --safe", nested: { value: 1 } });
+ expect(matchesAgentApproval("write_tool", { command: "deploy --safe", nested: { value: 1 } }, approved.digest)).toBe(true);
+ expect(matchesAgentApproval("write_tool", { command: "deploy --safe", nested: { value: 2 } }, approved.digest)).toBe(false);
+ expect(matchesAgentApproval("other_tool", { command: "deploy --safe", nested: { value: 1 } }, approved.digest)).toBe(false);
+ });
+
+ it("refuses payloads too large to review safely in the terminal", () => {
+ expect(() => canonicalAgentApproval("write_tool", { text: "x".repeat(MAX_AGENT_APPROVAL_BYTES) })).toThrow("safe terminal approval is limited");
+ });
+});
diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.ts
index b70cbcf8..bda1bcb9 100644
--- a/lib/config/env-example.test.ts
+++ b/lib/config/env-example.test.ts
@@ -22,6 +22,15 @@ const NOT_A_KNOB: Record<string, string> = {
NEXT_RUNTIME: "set by Next itself",
NEXT_PUBLIC_BUILD_ID: "injected by next.config.mjs at build time",
MSO_RUNTIME_INSTANCE_ID: "injected by the installer-managed service to prove restart readiness",
+ // Private launcher-to-agent handoff. scripts/mso-cli-agent.sh owns these; users
+ // should configure the public CLI knobs instead of persisting these in .env.local.
+ MSO_AGENT_BASE: "internal mso-cli-agent launcher handoff for the selected loopback API base",
+ MSO_AGENT_CLI: "internal mso-cli-agent launcher handoff for the canonical CLI path",
+ MSO_AGENT_JAR: "internal mso-cli-agent launcher handoff for the authenticated cookie jar",
+ MSO_AGENT_ORIGIN: "internal mso-cli-agent launcher handoff for the request Origin header",
+ MSO_AGENT_VERSION: "internal mso-cli-agent launcher handoff for banner metadata",
+ // Standard terminal convention inherited from the invoking shell, not MSO config.
+ NO_COLOR: "standard terminal color convention inherited from the caller",
VITEST: "set by the test runner",
// The OS gives these to every process.
SHELL: "the OS's",
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index 97c1741c..21156177 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -28,6 +28,7 @@ export type AuditAction =
/** The cockpit replacing its own code (Settings → About, or `mso update run`). */
| "sys.update"
| "managed-app.action"
+ | "infra.write"
| "camoufox.power"
| "workflow.start"
| "workflow.cancel"
diff --git a/lib/infra/catalog.ts b/lib/infra/catalog.ts
new file mode 100644
index 00000000..26f3bf2a
--- /dev/null
+++ b/lib/infra/catalog.ts
@@ -0,0 +1,78 @@
+import { INFRA_PROVIDER_IDS, type InfraProviderDefinition, type InfraProviderId, type InfraProviderValues } from "./types";
+
+const definitions: Record<InfraProviderId, InfraProviderDefinition> = {
+ dokploy: {
+ id: "dokploy",
+ title: "Dokploy",
+ description: "Connect Dokploy and expose bounded project operations through its API.",
+ feature: true,
+ fields: [
+ { key: "apiUrl", label: "API URL", secret: false, required: true, placeholder: "https://panel.example.com/api", description: "Dokploy panel URL. /api is appended when omitted." },
+ { key: "apiKey", label: "API key", secret: true, required: true, description: "Dokploy API key. Stored only in MSO's owner-only infra store." },
+ { key: "publicIp", label: "Public IPv4", secret: false, required: false, placeholder: "203.0.113.10", description: "Optional public VPS IPv4 used when creating DNS A records. Never derived from a loopback Dokploy URL." },
+ ],
+ },
+ cloudflare: {
+ id: "cloudflare",
+ title: "Cloudflare",
+ description: "Inspect zones and perform bounded per-record DNS changes; bulk zone writes are intentionally unavailable.",
+ feature: true,
+ fields: [
+ { key: "apiToken", label: "API token", secret: true, required: true, description: "Cloudflare token scoped to Zone:Read + DNS:Edit for the intended zones." },
+ { key: "zoneId", label: "Zone ID", secret: false, required: false, description: "Optional zone pin. MSO verifies the pinned zone still contains the requested hostname before writing." },
+ { key: "accountId", label: "Account ID", secret: false, required: false, description: "Optional account identifier for future account-scoped operations." },
+ ],
+ },
+ hostinger: {
+ id: "hostinger",
+ title: "Hostinger",
+ description: "Hostinger portfolio/VPS verification and DNS record automation for domains hosted in hPanel.",
+ feature: false,
+ fields: [
+ { key: "apiToken", label: "API token", secret: true, required: true, description: "Hostinger API token. DNS writes replace only the requested name/type RR-set." },
+ ],
+ },
+};
+
+export const isInfraProviderId = (value: string): value is InfraProviderId =>
+ (INFRA_PROVIDER_IDS as readonly string[]).includes(value);
+
+export const getInfraProviderDefinition = (id: InfraProviderId): InfraProviderDefinition => definitions[id];
+export const listInfraProviderDefinitions = (): InfraProviderDefinition[] => INFRA_PROVIDER_IDS.map((id) => definitions[id]);
+
+const IPV4_RE = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
+const HEX32_RE = /^[0-9a-f]{32}$/i;
+
+export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, unknown>): InfraProviderValues {
+ const def = definitions[id];
+ const allowed = new Set(def.fields.map((field) => field.key));
+ const out: InfraProviderValues = {};
+ for (const [key, value] of Object.entries(raw)) {
+ if (!allowed.has(key) || typeof value !== "string") continue;
+ const clean = value.trim();
+ if (clean) out[key] = clean;
+ }
+ if (id === "dokploy" && out.apiUrl) {
+ let parsed: URL;
+ try { parsed = new URL(out.apiUrl); } catch { throw new Error("Dokploy API URL must be an absolute http(s) URL"); }
+ if (parsed.username || parsed.password) throw new Error("Dokploy API URL must not contain credentials");
+ if (parsed.hash) throw new Error("Dokploy API URL must not contain a fragment");
+ const loopback = ["127.0.0.1", "localhost", "::1", "[::1]"].includes(parsed.hostname);
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) {
+ throw new Error("Dokploy API URL must use HTTPS, except loopback development URLs");
+ }
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "") || "/";
+ if (!parsed.pathname.endsWith("/api")) parsed.pathname = `${parsed.pathname === "/" ? "" : parsed.pathname}/api`;
+ parsed.search = ""; parsed.hash = "";
+ out.apiUrl = parsed.toString().replace(/\/$/, "");
+ if (out.apiKey && out.apiKey.length < 20) throw new Error("Dokploy API key is too short");
+ if (out.publicIp && !IPV4_RE.test(out.publicIp)) throw new Error("Dokploy publicIp must be a valid IPv4 address");
+ }
+ if (id === "cloudflare") {
+ if (out.apiToken && out.apiToken.length < 24) throw new Error("Cloudflare API token is too short");
+ if (out.zoneId && !HEX32_RE.test(out.zoneId)) throw new Error("Cloudflare zoneId must be 32 hexadecimal characters");
+ if (out.accountId && out.accountId.length < 16) throw new Error("Cloudflare accountId is too short");
+ }
+ if (id === "hostinger" && out.apiToken && out.apiToken.length < 24) throw new Error("Hostinger API token is too short");
+ return out;
+}
diff --git a/lib/infra/clients.test.ts b/lib/infra/clients.test.ts
new file mode 100644
index 00000000..036415b7
--- /dev/null
+++ b/lib/infra/clients.test.ts
@@ -0,0 +1,85 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let root = "";
+const response = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-infra-client-"));
+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");
+ vi.resetModules();
+});
+
+afterEach(async () => {
+ vi.unstubAllGlobals();
+ delete process.env.OS_INFRA_STORE;
+ await fs.rm(root, { recursive: true, force: true });
+ vi.resetModules();
+});
+
+describe("infrastructure clients", () => {
+ it("uses only exact per-record Cloudflare writes and defaults proxying off", async () => {
+ const store = await import("./store");
+ await store.setInfraProvider("cloudflare", { apiToken: "c".repeat(32) });
+ const seen: Array<{ url: string; method: string; body: string }> = [];
+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input); const method = init?.method ?? "GET"; seen.push({ url, method, body: String(init?.body ?? "") });
+ if (url.includes("/zones?")) return response({ success: true, result: [{ id: "z1", name: "example.com" }], result_info: { total_pages: 1 } });
+ if (method === "GET" && url.includes("dns_records?type=A")) return response({ success: true, result: [] });
+ if (method === "GET" && url.includes("dns_records?type=CNAME")) return response({ success: true, result: [] });
+ if (method === "POST") return response({ success: true, result: { id: "r1" } });
+ throw new Error(`unexpected ${method} ${url}`);
+ }));
+ const client = await import("./clients");
+ const result = await client.upsertCloudflareDns({ name: "app.example.com", type: "A", content: "203.0.113.7" });
+ expect(result.action).toBe("created");
+ expect(seen.some((call) => call.method === "PUT")).toBe(false);
+ const write = seen.find((call) => call.method === "POST");
+ expect(write?.url).toMatch(/\/zones\/z1\/dns_records$/);
+ expect(JSON.parse(write?.body ?? "{}").proxied).toBe(false);
+ expect(seen.some((call) => call.url.includes("name.exact=app.example.com"))).toBe(true);
+ });
+
+ it("refuses an ambiguous Cloudflare record instead of guessing which record to patch", async () => {
+ const store = await import("./store");
+ await store.setInfraProvider("cloudflare", { apiToken: "c".repeat(32) });
+ const fetchMock = vi.fn(async (input: string | URL | Request, _init?: RequestInit) => {
+ const url = String(input);
+ if (url.includes("/zones?")) return response({ success: true, result: [{ id: "z1", name: "example.com" }], result_info: { total_pages: 1 } });
+ return response({ success: true, result: [
+ { id: "a", name: "app.example.com", type: "A", content: "203.0.113.1" },
+ { id: "b", name: "app.example.com", type: "A", content: "203.0.113.2" },
+ ] });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const client = await import("./clients");
+ await expect(client.upsertCloudflareDns({ name: "app.example.com", type: "A", content: "203.0.113.7" })).rejects.toThrow("ambiguous");
+ expect(fetchMock.mock.calls.every(([, init]) => !init || (init as RequestInit).method == null || (init as RequestInit).method === "GET")).toBe(true);
+ });
+
+ it("sends only the requested Hostinger RR-set so unrelated zone rows cannot be overwritten", async () => {
+ const store = await import("./store");
+ await store.setInfraProvider("hostinger", { apiToken: "h".repeat(32) });
+ let putBody: unknown = null;
+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input); const method = init?.method ?? "GET";
+ if (url.includes("/domains/v1/portfolio")) return response([{ domain: "example.com" }]);
+ if (url.includes("/dns/v1/zones/example.com") && method === "GET") return response([
+ { name: "@", type: "MX", ttl: 14400, records: [{ content: "mail.example.com", is_disabled: false }] },
+ { name: "app", type: "A", ttl: 14400, records: [{ content: "203.0.113.1", is_disabled: false }] },
+ ]);
+ if (url.includes("/dns/v1/zones/example.com") && method === "PUT") { putBody = JSON.parse(String(init?.body)); return response({ ok: true }); }
+ throw new Error(`unexpected ${method} ${url}`);
+ }));
+ const client = await import("./clients");
+ const result = await client.upsertHostingerDns({ name: "app.example.com", type: "A", content: "203.0.113.7" });
+ expect(result.action).toBe("updated");
+ const payload = putBody as { overwrite: boolean; zone: Array<{ name: string; type: string; records: Array<{ content: string }> }> };
+ expect(payload.overwrite).toBe(true);
+ expect(payload.zone).toHaveLength(1);
+ expect(payload.zone[0]).toMatchObject({ name: "app", type: "A" });
+ expect(payload.zone[0].records[0].content).toBe("203.0.113.7");
+ });
+});
diff --git a/lib/infra/clients.ts b/lib/infra/clients.ts
new file mode 100644
index 00000000..72240285
--- /dev/null
+++ b/lib/infra/clients.ts
@@ -0,0 +1,21 @@
+import type { InfraDoctorResult, InfraProviderId } from "./types";
+import { doctorCloudflare } from "./cloudflare";
+import { doctorDokploy } from "./dokploy";
+import { doctorHostinger } from "./hostinger";
+
+export { listCloudflareZones, upsertCloudflareDns } from "./cloudflare";
+export { ensureDokployProject, listDokployProjects } from "./dokploy";
+export { upsertHostingerDns } from "./hostinger";
+
+export async function doctorInfraProvider(id: InfraProviderId): Promise<InfraDoctorResult> {
+ try {
+ const detail = id === "dokploy"
+ ? await doctorDokploy()
+ : id === "cloudflare"
+ ? await doctorCloudflare()
+ : await doctorHostinger();
+ return detail === null ? { id, ok: null, detail: "not configured" } : { id, ok: true, detail };
+ } catch (error) {
+ return { id, ok: false, detail: (error as Error).message.slice(0, 300) };
+ }
+}
diff --git a/lib/infra/cloudflare.ts b/lib/infra/cloudflare.ts
new file mode 100644
index 00000000..001aa802
--- /dev/null
+++ b/lib/infra/cloudflare.ts
@@ -0,0 +1,96 @@
+import { readInfraProvider } from "./store";
+import { HOST_RE, IPV4_RE, obj, request } from "./http";
+
+const API = "https://api.cloudflare.com/client/v4";
+const MAX_PAGE = 20;
+const headers = (token: string) => ({ authorization: `Bearer ${token}`, accept: "application/json", "content-type": "application/json" });
+const parsed = (body: unknown): { success: boolean; result: unknown } => {
+ const value = obj(body);
+ return { success: value.success === true, result: value.result };
+};
+
+export async function listCloudflareZones(): Promise<Array<{ id: string; name: string }>> {
+ const values = await readInfraProvider("cloudflare");
+ if (!values.apiToken) throw new Error("Cloudflare is not configured; run `mso provider set cloudflare`");
+ const out: Array<{ id: string; name: string }> = [];
+ for (let page = 1; page <= MAX_PAGE; page++) {
+ const res = await request(`${API}/zones?per_page=50&page=${page}`, { headers: headers(values.apiToken) });
+ const body = parsed(res.body);
+ if (!res.ok || !body.success || !Array.isArray(body.result)) throw new Error(`Cloudflare zones HTTP ${res.status}`);
+ for (const row of body.result) {
+ const item = obj(row); const id = String(item.id ?? ""); const name = String(item.name ?? "");
+ if (id && name) out.push({ id, name });
+ }
+ const info = obj(obj(res.body).result_info);
+ const totalPages = Number(info.total_pages ?? page);
+ if (!Number.isFinite(totalPages) || page >= totalPages || body.result.length < 50) break;
+ }
+ return out;
+}
+
+export async function doctorCloudflare(): Promise<string | null> {
+ const values = await readInfraProvider("cloudflare");
+ if (!values.apiToken) return null;
+ const verify = await request(`${API}/user/tokens/verify`, { headers: headers(values.apiToken) });
+ if (!verify.ok || obj(verify.body).success !== true) throw new Error(`token verification HTTP ${verify.status}`);
+ const zones = await listCloudflareZones();
+ return `active token; ${zones.length} accessible zone(s)${zones.length ? `: ${zones.slice(0, 5).map((z) => z.name).join(", ")}` : ""}`;
+}
+
+async function zoneFor(fqdn: string): Promise<{ id: string; name: string; token: string }> {
+ const values = await readInfraProvider("cloudflare");
+ if (!values.apiToken) throw new Error("Cloudflare is not configured; run `mso provider set cloudflare`");
+ const zones = await listCloudflareZones();
+ const zone = values.zoneId
+ ? zones.find((row) => row.id === values.zoneId)
+ : zones.filter((row) => fqdn === row.name || fqdn.endsWith(`.${row.name}`)).sort((a, b) => b.name.length - a.name.length)[0];
+ if (values.zoneId && !zone) throw new Error("configured Cloudflare zoneId is not accessible to this token");
+ if (!zone || !(fqdn === zone.name || fqdn.endsWith(`.${zone.name}`))) throw new Error(`no accessible Cloudflare zone contains ${fqdn}`);
+ return { ...zone, token: values.apiToken };
+}
+
+function validateDns(name: string, type: string, content: string): void {
+ if (!HOST_RE.test(name)) throw new Error("invalid DNS hostname");
+ if (!["A", "AAAA", "CNAME", "TXT"].includes(type)) throw new Error("DNS type must be A, AAAA, CNAME, or TXT");
+ if (type === "A" && !IPV4_RE.test(content)) throw new Error("A record content must be an IPv4 address");
+ if (type === "AAAA" && (!content.includes(":") || !/^[0-9a-f:]+$/i.test(content))) throw new Error("AAAA record content must be an IPv6 address");
+ if (type === "CNAME" && !HOST_RE.test(content.replace(/\.$/, ""))) throw new Error("CNAME content must be a hostname");
+}
+
+export async function upsertCloudflareDns(input: { name: string; type: string; content: string; proxied?: boolean; ttl?: number }): Promise<{ action: string; id: string; name: string; type: string }> {
+ const name = input.name.trim().replace(/\.$/, "").toLowerCase();
+ const type = input.type.trim().toUpperCase();
+ const content = input.content.trim();
+ validateDns(name, type, content);
+ const zone = await zoneFor(name);
+ const base = `${API}/zones/${encodeURIComponent(zone.id)}/dns_records`;
+ const find = await request(`${base}?type=${encodeURIComponent(type)}&name.exact=${encodeURIComponent(name)}`, { headers: headers(zone.token) });
+ const found = parsed(find.body);
+ if (!find.ok || !found.success || !Array.isArray(found.result)) throw new Error(`Cloudflare record lookup HTTP ${find.status}`);
+ const exact = found.result.map(obj).filter((r) => String(r.name ?? "").toLowerCase() === name && String(r.type ?? "").toUpperCase() === type);
+ if (exact.length > 1) throw new Error(`refusing ambiguous DNS change: ${exact.length} ${type} records already exist for ${name}`);
+ const proxied = ["A", "AAAA", "CNAME"].includes(type) ? input.proxied === true : undefined;
+ const payload = { type, name, content, ttl: input.ttl && input.ttl >= 60 ? input.ttl : 1, ...(proxied === undefined ? {} : { proxied }) };
+ if (exact.length === 1) {
+ const current = exact[0];
+ const same = String(current.content ?? "").replace(/\.$/, "") === content.replace(/\.$/, "") && (proxied === undefined || Boolean(current.proxied) === proxied);
+ if (same) return { action: "unchanged", id: String(current.id), name, type };
+ const id = String(current.id ?? "");
+ if (!id) throw new Error("Cloudflare returned a DNS record without an id");
+ const changed = await request(`${base}/${encodeURIComponent(id)}`, { method: "PATCH", headers: headers(zone.token), body: JSON.stringify(payload) });
+ if (!changed.ok || !parsed(changed.body).success) throw new Error(`Cloudflare DNS PATCH HTTP ${changed.status}`);
+ return { action: "updated", id, name, type };
+ }
+ const clashes = type === "CNAME" ? ["A", "AAAA"] : (["A", "AAAA"].includes(type) ? ["CNAME"] : []);
+ for (const clash of clashes) {
+ const check = await request(`${base}?type=${clash}&name.exact=${encodeURIComponent(name)}`, { headers: headers(zone.token) });
+ const body = parsed(check.body);
+ if (check.ok && body.success && Array.isArray(body.result) && body.result.some((r) => String(obj(r).name ?? "").toLowerCase() === name)) {
+ throw new Error(`refusing DNS type replacement: ${name} already has ${clash}; remove it explicitly before creating ${type}`);
+ }
+ }
+ const created = await request(base, { method: "POST", headers: headers(zone.token), body: JSON.stringify(payload) });
+ const body = parsed(created.body); const row = obj(body.result);
+ if (!created.ok || !body.success) throw new Error(`Cloudflare DNS POST HTTP ${created.status}`);
+ return { action: "created", id: String(row.id ?? ""), name, type };
+}
diff --git a/lib/infra/dokploy.ts b/lib/infra/dokploy.ts
new file mode 100644
index 00000000..1beb3e48
--- /dev/null
+++ b/lib/infra/dokploy.ts
@@ -0,0 +1,64 @@
+import { safeProviderFetch } from "@/lib/host/ssrf";
+import { readInfraProvider } from "./store";
+import { obj, request, TIMEOUT_MS } from "./http";
+
+function dokployFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const requestInput = new Request(input, { ...init, redirect: "error" });
+ const host = new URL(requestInput.url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
+ // Loopback is an explicit same-host Dokploy case. All remote endpoints use the
+ // DNS-pinned safe transport so DNS rebinding/private metadata routes are refused.
+ if (["127.0.0.1", "localhost", "::1"].includes(host)) return fetch(requestInput);
+ return safeProviderFetch(requestInput);
+}
+
+async function call(endpoint: string, method = "GET", body?: unknown): Promise<unknown> {
+ const values = await readInfraProvider("dokploy");
+ if (!values.apiUrl || !values.apiKey) throw new Error("Dokploy is not configured; run `mso provider set dokploy`");
+ let last: Error | null = null;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ const res = await request(`${values.apiUrl}${endpoint}`, {
+ method,
+ headers: { "x-api-key": values.apiKey, accept: "application/json", "content-type": "application/json" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ }, TIMEOUT_MS, dokployFetch);
+ if (res.ok) return res.body;
+ if (res.status !== 429 && res.status < 500) throw new Error(`Dokploy HTTP ${res.status}: ${res.text.slice(0, 300)}`);
+ last = new Error(`Dokploy HTTP ${res.status}`);
+ } catch (error) {
+ last = error as Error;
+ }
+ if (attempt < 2) await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
+ }
+ throw last ?? new Error("Dokploy request failed");
+}
+
+export async function doctorDokploy(): Promise<string | null> {
+ const values = await readInfraProvider("dokploy");
+ if (!values.apiUrl || !values.apiKey) return null;
+ const res = await request(`${values.apiUrl}/project.all`, {
+ headers: { "x-api-key": values.apiKey, accept: "application/json" },
+ }, TIMEOUT_MS, dokployFetch);
+ if (!res.ok) throw new Error(`Dokploy HTTP ${res.status}`);
+ return `reachable; ${Array.isArray(res.body) ? res.body.length : 0} project(s)`;
+}
+
+export async function listDokployProjects(): Promise<Array<{ projectId: string; name: string }>> {
+ const rows = await call("/project.all");
+ if (!Array.isArray(rows)) throw new Error("Dokploy project.all returned an unexpected response");
+ return rows
+ .map((row) => obj(row))
+ .map((row) => ({ projectId: String(row.projectId ?? row.id ?? ""), name: String(row.name ?? "") }))
+ .filter((row) => row.projectId && row.name);
+}
+
+export async function ensureDokployProject(name: string): Promise<{ projectId: string; name: string; created: boolean }> {
+ const clean = name.trim();
+ if (!/^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$/.test(clean)) throw new Error("invalid Dokploy project name");
+ const existing = (await listDokployProjects()).find((row) => row.name === clean);
+ if (existing) return { ...existing, created: false };
+ await call("/project.create", "POST", { name: clean });
+ const created = (await listDokployProjects()).find((row) => row.name === clean);
+ if (!created) throw new Error("Dokploy project create returned success but the project is still absent");
+ return { ...created, created: true };
+}
diff --git a/lib/infra/hostinger.ts b/lib/infra/hostinger.ts
new file mode 100644
index 00000000..ac1c5752
--- /dev/null
+++ b/lib/infra/hostinger.ts
@@ -0,0 +1,57 @@
+import { readInfraProvider } from "./store";
+import { HOST_RE, IPV4_RE, obj, request } from "./http";
+
+const API = "https://developers.hostinger.com/api";
+const headers = (token: string) => ({ authorization: `Bearer ${token}`, accept: "application/json", "content-type": "application/json" });
+
+export async function doctorHostinger(): Promise<string | null> {
+ const values = await readInfraProvider("hostinger");
+ if (!values.apiToken) return null;
+ const res = await request(`${API}/vps/v1/virtual-machines`, { headers: headers(values.apiToken) });
+ if (!res.ok) throw new Error(`Hostinger HTTP ${res.status}`);
+ return `token valid; ${Array.isArray(res.body) ? res.body.length : 0} VPS visible`;
+}
+
+async function rootFor(fullDomain: string, token: string): Promise<{ root: string; name: string }> {
+ const res = await request(`${API}/domains/v1/portfolio`, { headers: headers(token) });
+ if (!res.ok || !Array.isArray(res.body)) throw new Error(`Hostinger portfolio HTTP ${res.status}`);
+ const roots = res.body
+ .map(obj).map((row) => String(row.domain ?? "")).filter(Boolean)
+ .filter((root) => fullDomain === root || fullDomain.endsWith(`.${root}`))
+ .sort((a, b) => b.length - a.length);
+ if (!roots[0]) throw new Error(`${fullDomain} is not in the Hostinger domain portfolio`);
+ return { root: roots[0], name: fullDomain === roots[0] ? "@" : fullDomain.slice(0, -(roots[0].length + 1)) };
+}
+
+export async function upsertHostingerDns(input: { name: string; type: string; content: string; ttl?: number }): Promise<{ action: string; name: string; type: string }> {
+ const values = await readInfraProvider("hostinger");
+ if (!values.apiToken) throw new Error("Hostinger is not configured; run `mso provider set hostinger`");
+ const fullDomain = input.name.trim().replace(/\.$/, "").toLowerCase();
+ const type = input.type.trim().toUpperCase(); const content = input.content.trim();
+ if (!HOST_RE.test(fullDomain)) throw new Error("invalid DNS hostname");
+ if (!["A", "CNAME", "TXT"].includes(type)) throw new Error("Hostinger DNS type must be A, CNAME, or TXT");
+ if (type === "A" && !IPV4_RE.test(content)) throw new Error("A record content must be an IPv4 address");
+ if (type === "CNAME" && !HOST_RE.test(content.replace(/\.$/, ""))) throw new Error("CNAME content must be a hostname");
+ const { root, name } = await rootFor(fullDomain, values.apiToken);
+ const url = `${API}/dns/v1/zones/${encodeURIComponent(root)}`;
+ const auth = headers(values.apiToken);
+ const zone = await request(url, { headers: auth });
+ if (!zone.ok || !Array.isArray(zone.body)) throw new Error(`Hostinger zone HTTP ${zone.status}`);
+ const rows = zone.body.map((row) => ({ ...obj(row) }));
+ const exact = rows.filter((row) => String(row.name ?? "") === name && String(row.type ?? "").toUpperCase() === type);
+ if (exact.length > 1) throw new Error(`refusing ambiguous Hostinger DNS change: ${exact.length} ${type} rows exist for ${fullDomain}`);
+ const conflicts = rows.filter((row) => String(row.name ?? "") === name && ((type === "CNAME" && ["A", "AAAA"].includes(String(row.type ?? "").toUpperCase())) || (["A", "AAAA"].includes(type) && String(row.type ?? "").toUpperCase() === "CNAME")));
+ if (!exact.length && conflicts.length) throw new Error(`refusing DNS type replacement for ${fullDomain}; remove the conflicting record explicitly first`);
+ const normalized = content.replace(/\.$/, "");
+ if (exact.length === 1) {
+ const targets = Array.isArray(exact[0].records) ? exact[0].records.map(obj).map((r) => String(r.content ?? "").replace(/\.$/, "")) : [];
+ if (targets.length === 1 && targets[0] === normalized) return { action: "unchanged", name: fullDomain, type };
+ }
+ const record = { name, type, ttl: input.ttl && input.ttl >= 60 ? input.ttl : 14400, records: [{ content, is_disabled: false }] };
+ // Hostinger's overwrite flag replaces only RRsets matching the supplied name+type.
+ // Sending one RRset avoids a stale full-zone read/modify/write and cannot erase
+ // an unrelated concurrent DNS change.
+ const put = await request(url, { method: "PUT", headers: auth, body: JSON.stringify({ overwrite: true, zone: [record] }) });
+ if (!put.ok) throw new Error(`Hostinger DNS PUT HTTP ${put.status}`);
+ return { action: exact.length ? "updated" : "created", name: fullDomain, type };
+}
diff --git a/lib/infra/http.test.ts b/lib/infra/http.test.ts
new file mode 100644
index 00000000..918ab6c1
--- /dev/null
+++ b/lib/infra/http.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from "vitest";
+import { MAX_RESPONSE_BYTES, request } from "./http";
+
+describe("infrastructure HTTP response bounds", () => {
+ it("cancels an oversized streaming response before reading another chunk", async () => {
+ let cancelled = false;
+ let pulls = 0;
+ const first = new Uint8Array(MAX_RESPONSE_BYTES - 8);
+ const second = new Uint8Array(16);
+ const body = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ pulls += 1;
+ if (pulls === 1) controller.enqueue(first);
+ else if (pulls === 2) controller.enqueue(second);
+ else throw new Error("oversized response reader consumed an extra chunk");
+ },
+ cancel() { cancelled = true; },
+ }, { highWaterMark: 0 });
+ const fetchImpl = vi.fn(async () => new Response(body, { status: 200 }));
+
+ await expect(request("https://provider.example/api", {}, 1_000, fetchImpl)).rejects.toThrow(
+ `provider response exceeds ${MAX_RESPONSE_BYTES} bytes`,
+ );
+ expect(pulls).toBe(2);
+ expect(cancelled).toBe(true);
+ });
+
+ it("rejects an oversized declared content length without pulling the body", async () => {
+ let pulled = false;
+ let cancelled = false;
+ const body = new ReadableStream<Uint8Array>({
+ pull(controller) { pulled = true; controller.enqueue(new Uint8Array([1])); },
+ cancel() { cancelled = true; },
+ }, { highWaterMark: 0 });
+ const fetchImpl = vi.fn(async () => new Response(body, {
+ status: 200,
+ headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) },
+ }));
+
+ await expect(request("https://provider.example/api", {}, 1_000, fetchImpl)).rejects.toThrow(
+ `provider response exceeds ${MAX_RESPONSE_BYTES} bytes`,
+ );
+ expect(cancelled).toBe(true);
+ expect(pulled).toBe(false);
+ });
+});
diff --git a/lib/infra/http.ts b/lib/infra/http.ts
new file mode 100644
index 00000000..1a362246
--- /dev/null
+++ b/lib/infra/http.ts
@@ -0,0 +1,64 @@
+export const TIMEOUT_MS = 15_000;
+export const MAX_RESPONSE_BYTES = 1024 * 1024;
+export const IPV4_RE = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
+export const HOST_RE = /^(?=.{1,253}$)[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?(?:\.[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?)+\.?$/;
+
+type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+
+export type InfraResponse = { status: number; ok: boolean; body: unknown; text: string };
+
+async function boundedText(res: Response): Promise<string> {
+ const length = Number(res.headers.get("content-length"));
+ if (Number.isFinite(length) && length > MAX_RESPONSE_BYTES) {
+ await res.body?.cancel().catch(() => undefined);
+ throw new Error(`provider response exceeds ${MAX_RESPONSE_BYTES} bytes`);
+ }
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value?.byteLength) continue;
+ total += value.byteLength;
+ if (total > MAX_RESPONSE_BYTES) {
+ await reader.cancel("provider response too large").catch(() => undefined);
+ throw new Error(`provider response exceeds ${MAX_RESPONSE_BYTES} bytes`);
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
+ return new TextDecoder().decode(bytes);
+}
+
+export async function request(
+ url: string,
+ init: RequestInit = {},
+ timeoutMs = TIMEOUT_MS,
+ fetchImpl: FetchLike = fetch,
+): Promise<InfraResponse> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetchImpl(url, { ...init, redirect: "error", signal: controller.signal });
+ const text = await boundedText(res);
+ let body: unknown = null;
+ try { body = text ? JSON.parse(text) : null; } catch { body = text; }
+ return { status: res.status, ok: res.ok, body, text };
+ } catch (error) {
+ if ((error as Error).name === "AbortError") throw new Error(`request timed out after ${timeoutMs}ms`);
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export const obj = (value: unknown): Record<string, unknown> =>
+ value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
diff --git a/lib/infra/index.ts b/lib/infra/index.ts
new file mode 100644
index 00000000..74f5b9bb
--- /dev/null
+++ b/lib/infra/index.ts
@@ -0,0 +1,4 @@
+export * from "./types";
+export * from "./catalog";
+export * from "./store";
+export * from "./clients";
diff --git a/lib/infra/store.test.ts b/lib/infra/store.test.ts
new file mode 100644
index 00000000..a1ba1d0f
--- /dev/null
+++ b/lib/infra/store.test.ts
@@ -0,0 +1,64 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let root = "";
+let file = "";
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-infra-"));
+ file = path.join(root, "private", "infra.json");
+ process.env.OS_INFRA_STORE = file;
+ vi.resetModules();
+});
+
+afterEach(async () => {
+ delete process.env.OS_INFRA_STORE;
+ await fs.rm(root, { recursive: true, force: true });
+ vi.resetModules();
+});
+
+describe("infra provider store", () => {
+ it("normalizes Dokploy, persists owner-only state, and never returns a raw secret in summaries", async () => {
+ const store = await import("./store");
+ const values = await store.setInfraProvider("dokploy", {
+ apiUrl: "https://panel.example.com/",
+ apiKey: "d".repeat(32),
+ publicIp: "203.0.113.10",
+ });
+ expect(values.apiUrl).toBe("https://panel.example.com/api");
+ const stat = await fs.stat(file);
+ expect(stat.mode & 0o777).toBe(0o600);
+ const summary = store.summarizeInfraProvider("dokploy", values);
+ expect(summary.configured).toBe(true);
+ expect(summary.values.apiKey).not.toBe(values.apiKey);
+ expect(summary.values.apiKey).toBe("configured");
+ });
+
+ it("merges rotations under the security-store lock instead of erasing unrelated provider fields", async () => {
+ const store = await import("./store");
+ await store.setInfraProvider("cloudflare", { apiToken: "a".repeat(32), accountId: "account-1234567890" });
+ await store.setInfraProvider("cloudflare", { zoneId: "f".repeat(32) });
+ const values = await store.readInfraProvider("cloudflare");
+ expect(values.apiToken).toBe("a".repeat(32));
+ expect(values.accountId).toBe("account-1234567890");
+ expect(values.zoneId).toBe("f".repeat(32));
+ });
+
+ it("refuses a symlinked provider store instead of following it into another file", async () => {
+ const target = path.join(root, "target.json");
+ await fs.writeFile(target, JSON.stringify({ providers: {} }), { mode: 0o600 });
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
+ await fs.symlink(target, file);
+ const store = await import("./store");
+ await expect(store.readInfraProvider("dokploy")).rejects.toThrow();
+ });
+
+ it("refuses an insecure remote Dokploy endpoint and malformed IPs before persisting", async () => {
+ const store = await import("./store");
+ await expect(store.setInfraProvider("dokploy", { apiUrl: "http://panel.example.com", apiKey: "x".repeat(32) })).rejects.toThrow("HTTPS");
+ await expect(store.setInfraProvider("dokploy", { apiUrl: "https://panel.example.com", apiKey: "x".repeat(32), publicIp: "999.1.1.1" })).rejects.toThrow("IPv4");
+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
diff --git a/lib/infra/store.ts b/lib/infra/store.ts
new file mode 100644
index 00000000..0bd33c13
--- /dev/null
+++ b/lib/infra/store.ts
@@ -0,0 +1,83 @@
+import { randomUUID } from "node:crypto";
+import { constants as fsConstants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";
+import type { InfraProviderId, InfraProviderSummary, InfraProviderValues, InfraStore } from "./types";
+
+export const INFRA_STORE_PATH = process.env.OS_INFRA_STORE ?? path.join(os.homedir(), ".mso", "private", "infra-providers.json");
+const SECRET_KEYS = new Set(["apiKey", "apiToken"]);
+const MAX_STORE_BYTES = 256 * 1024;
+
+function mask(value: string): string {
+ return value ? "configured" : "";
+}
+
+async function readUnlocked(): Promise<InfraStore> {
+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
+ try {
+ handle = await fs.open(INFRA_STORE_PATH, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile()) throw new Error("infrastructure provider store must be a regular file");
+ if (stat.size <= 0 || stat.size > MAX_STORE_BYTES) throw new Error("infrastructure provider store has an invalid size");
+ if ((stat.mode & 0o077) !== 0) throw new Error("infrastructure provider store permissions are too broad; expected 0600");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("infrastructure provider store is not owned by the MSO user");
+ const raw = JSON.parse(await handle.readFile("utf8")) as InfraStore;
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("infrastructure provider store has an invalid shape");
+ return raw;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
+ throw error;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
+async function writeUnlocked(store: InfraStore): Promise<void> {
+ const dir = path.dirname(INFRA_STORE_PATH);
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ await fs.chmod(dir, 0o700).catch(() => undefined);
+ const tmp = `${INFRA_STORE_PATH}.${randomUUID()}.tmp`;
+ await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
+ await fs.chmod(tmp, 0o600);
+ await fs.rename(tmp, INFRA_STORE_PATH);
+ await fs.chmod(INFRA_STORE_PATH, 0o600);
+}
+
+export async function readInfraProvider(id: InfraProviderId): Promise<InfraProviderValues> {
+ const store = await readUnlocked();
+ return { ...(store.providers?.[id] ?? {}) };
+}
+
+export async function setInfraProvider(id: InfraProviderId, raw: Record<string, unknown>): Promise<InfraProviderValues> {
+ return withSecurityStoreLock(INFRA_STORE_PATH, async () => {
+ const store = await readUnlocked();
+ const current = store.providers?.[id] ?? {};
+ const normalized = normalizeInfraValues(id, raw);
+ const values = { ...current, ...normalized };
+ const def = getInfraProviderDefinition(id);
+ const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
+ if (missing.length) throw new Error(`${id} is missing required value(s): ${missing.join(", ")}`);
+ await writeUnlocked({ ...store, providers: { ...(store.providers ?? {}), [id]: values } });
+ return values;
+ });
+}
+
+export async function removeInfraProvider(id: InfraProviderId): Promise<void> {
+ await withSecurityStoreLock(INFRA_STORE_PATH, async () => {
+ const store = await readUnlocked();
+ const providers = { ...(store.providers ?? {}) };
+ delete providers[id];
+ await writeUnlocked({ ...store, providers });
+ });
+}
+
+export function summarizeInfraProvider(id: InfraProviderId, values: InfraProviderValues): InfraProviderSummary {
+ const def = getInfraProviderDefinition(id);
+ const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
+ const safeValues = Object.fromEntries(def.fields
+ .filter((field) => values[field.key])
+ .map((field) => [field.key, SECRET_KEYS.has(field.key) ? mask(values[field.key]) : values[field.key]]));
+ return { id, title: def.title, description: def.description, feature: def.feature, configured: missing.length === 0, missing, values: safeValues, fields: def.fields };
+}
diff --git a/lib/infra/types.ts b/lib/infra/types.ts
new file mode 100644
index 00000000..a58132cb
--- /dev/null
+++ b/lib/infra/types.ts
@@ -0,0 +1,41 @@
+export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger"] as const;
+export type InfraProviderId = (typeof INFRA_PROVIDER_IDS)[number];
+
+export type InfraProviderValues = Record<string, string>;
+export type InfraStore = {
+ providers?: Partial<Record<InfraProviderId, InfraProviderValues>>;
+};
+
+export type InfraField = {
+ key: string;
+ label: string;
+ secret: boolean;
+ required: boolean;
+ placeholder?: string;
+ description: string;
+};
+
+export type InfraProviderDefinition = {
+ id: InfraProviderId;
+ title: string;
+ description: string;
+ feature: boolean;
+ fields: InfraField[];
+};
+
+export type InfraProviderSummary = {
+ id: InfraProviderId;
+ title: string;
+ description: string;
+ feature: boolean;
+ configured: boolean;
+ missing: string[];
+ values: Record<string, string>;
+ fields: InfraField[];
+};
+
+export type InfraDoctorResult = {
+ id: InfraProviderId;
+ ok: boolean | null;
+ detail: string;
+};
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 329da6dd..fd66ef08 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -44,6 +44,13 @@ const MCP_ONLY: Record<string, string> = {
"exec.job.start": "external MCP requests have a hard request-time budget and need a bounded resumable shell job; in-shell Alfa can keep using its interactive Terminal/approved exec.run surfaces",
"exec.job.status": "status exists only to resume an MCP async exec job; Alfa has no corresponding external request timeout to recover from",
"exec.job.cancel": "cancellation is paired with the MCP-only async exec lifecycle and remains actor/workflow-bound",
+ "infra.providers.list": "MSO Agent and external connectors need a credential-free infrastructure capability inventory; in-shell Alfa has dedicated Dokploy/Cloudflare feature apps instead",
+ "infra.provider.doctor": "provider credentials stay server-side and the terminal/external agent needs a bounded live verification tool; Alfa has no reason to receive infrastructure secrets or duplicate these clients",
+ "dokploy.projects.list": "MSO Agent deploy workflows need a bounded Dokploy discovery seam; in-shell Alfa can delegate deployment through the dedicated infrastructure feature instead of duplicating this provider catalog",
+ "dokploy.project.ensure": "terminal/external deployment workflows need one idempotent Dokploy mutation with scope/approval; in-shell Alfa does not own infrastructure deployment credentials",
+ "cloudflare.zones.list": "terminal/external deployment workflows need bounded zone discovery while credentials stay server-side; in-shell Alfa has the Cloudflare feature app",
+ "cloudflare.dns.upsert": "DNS automation is intentionally MCP/terminal-agent-only so it inherits scope, approval, audit and workflow semantics without teaching generic in-shell Alfa to mutate public DNS",
+ "hostinger.dns.upsert": "external DNS mutation remains an explicitly approved deployment-agent capability; MSO sends one exact Hostinger name/type RR-set and keeps credentials server-side rather than adding a generic Alfa provider primitive",
};
describe("Alfa ↔ MCP capability parity", () => {
@@ -114,6 +121,9 @@ describe("MCP rate limits mirror the routes", () => {
"projects.function": 60,
"skills.list": 30,
"skills.read": 60,
+ "infra.dokploy": 20,
+ "infra.cloudflare": 20,
+ "infra.hostinger": 10,
};
for (const t of TOOLS) {
if (!t.limit) continue;
diff --git a/lib/mcp/tools-infra.ts b/lib/mcp/tools-infra.ts
new file mode 100644
index 00000000..6556a9b3
--- /dev/null
+++ b/lib/mcp/tools-infra.ts
@@ -0,0 +1,78 @@
+import { doctorInfraProvider, ensureDokployProject, INFRA_PROVIDER_IDS, isInfraProviderId, listCloudflareZones, listDokployProjects, readInfraProvider, summarizeInfraProvider, upsertCloudflareDns, upsertHostingerDns } from "@/lib/infra";
+import { type McpTool, opt, S, str } from "./tool-kit";
+
+const dnsSchema = {
+ name: { type: "string", description: "Fully-qualified DNS hostname, e.g. app.example.com" },
+ type: { type: "string", enum: ["A", "AAAA", "CNAME", "TXT"], description: "DNS record type" },
+ content: { type: "string", description: "DNS record value/target" },
+ ttl: { type: "number", description: "Optional TTL seconds. Cloudflare defaults to automatic." },
+};
+
+export const INFRA_TOOLS: McpTool[] = [
+ {
+ name: "infra_providers_list",
+ description: "List MSO infrastructure providers (Dokploy, Cloudflare, Hostinger), showing masked configuration state and missing required fields. Raw credentials are never returned.",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ inputSchema: S({}),
+ run: async () => Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id)))),
+ },
+ {
+ name: "infra_provider_doctor",
+ description: "Live-check one configured infrastructure provider against its real API. Use infra_providers_list first. Tokens are read from MSO private state and never passed in tool arguments.",
+ scope: "read",
+ annotations: { readOnlyHint: true, openWorldHint: true },
+ inputSchema: S({ id: { type: "string", enum: [...INFRA_PROVIDER_IDS] } }, ["id"]),
+ run: async (a) => {
+ const id = str(a, "id");
+ if (!isInfraProviderId(id)) throw new Error(`unknown infrastructure provider: ${id}`);
+ return doctorInfraProvider(id);
+ },
+ },
+ {
+ name: "dokploy_projects_list",
+ description: "List projects from the configured Dokploy API. Credentials stay in the private provider store.",
+ scope: "read",
+ annotations: { readOnlyHint: true, openWorldHint: true },
+ inputSchema: S({}),
+ run: async () => listDokployProjects(),
+ },
+ {
+ name: "dokploy_project_ensure",
+ description: "Idempotently ensure a Dokploy project exists by exact name. Creates it only when absent.",
+ scope: "write",
+ annotations: { idempotentHint: true, openWorldHint: true },
+ audit: { action: "infra.write", targetArg: "name" },
+ limit: { key: "infra.dokploy", max: 20, windowMs: 60_000 },
+ inputSchema: S({ name: { type: "string", description: "Dokploy project name" } }, ["name"]),
+ run: async (a) => ensureDokployProject(str(a, "name")),
+ },
+ {
+ name: "cloudflare_zones_list",
+ description: "List zones accessible to the configured Cloudflare token. Read-only and paginated with a hard cap.",
+ scope: "read",
+ annotations: { readOnlyHint: true, openWorldHint: true },
+ inputSchema: S({}),
+ run: async () => listCloudflareZones(),
+ },
+ {
+ name: "cloudflare_dns_upsert",
+ description: "Create or PATCH exactly one Cloudflare DNS record. Never performs bulk zone writes, never uses PUT, refuses ambiguous or conflicting record sets, and defaults Cloudflare proxying off unless proxied=true is explicit.",
+ scope: "write",
+ annotations: { idempotentHint: true, openWorldHint: true },
+ audit: { action: "infra.write", targetArg: "name" },
+ limit: { key: "infra.cloudflare", max: 20, windowMs: 60_000 },
+ inputSchema: S({ ...dnsSchema, proxied: { type: "boolean", description: "Explicit opt-in to Cloudflare proxy for A/AAAA/CNAME. Defaults false." } }, ["name", "type", "content"]),
+ run: async (a) => upsertCloudflareDns({ name: str(a, "name"), type: str(a, "type"), content: str(a, "content"), proxied: a.proxied === true, ttl: typeof a.ttl === "number" ? a.ttl : undefined }),
+ },
+ {
+ name: "hostinger_dns_upsert",
+ description: "Idempotently replace one exact Hostinger DNS name/type RR-set. The provider request contains only that RR-set, so unrelated zone records are never part of the mutation payload; ambiguity/conflicts are refused.",
+ scope: "write",
+ annotations: { idempotentHint: true, openWorldHint: true, destructiveHint: true },
+ audit: { action: "infra.write", targetArg: "name" },
+ limit: { key: "infra.hostinger", max: 10, windowMs: 60_000 },
+ inputSchema: S({ name: dnsSchema.name, type: { type: "string", enum: ["A", "CNAME", "TXT"] }, content: dnsSchema.content, ttl: dnsSchema.ttl }, ["name", "type", "content"]),
+ run: async (a) => upsertHostingerDns({ name: str(a, "name"), type: str(a, "type"), content: str(a, "content"), ttl: typeof a.ttl === "number" ? a.ttl : undefined }),
+ },
+];
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 013068e1..1d2de650 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -5,6 +5,7 @@ import { READ_TOOLS } from "./tools-read";
import { DISCOVERY_TOOLS } from "./tools-discovery";
import { LEARNING_TOOLS } from "./tools-learning";
import { POWER_TOOLS } from "./tools-power";
+import { INFRA_TOOLS } from "./tools-infra";
// 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
@@ -227,6 +228,4 @@ const withWorkflowContext = (tool: McpTool): McpTool => WORKFLOW_CONTEXT_EXEMPT.
},
});
-export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext);
-export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
-export type { McpTool } from "./tool-kit";
+export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 657eca91..c8f94474 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -3,8 +3,8 @@ import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
export const MCP_SERVER_VERSION = "1.6.0";
-export const MCP_TOOLSET_VERSION = "2026.08.28.1";
-export const MCP_TOOLSET_CHANGED_AT = "2026-08-28T07:02:00Z";
+export const MCP_TOOLSET_VERSION = "2026.08.31.1";
+export const MCP_TOOLSET_CHANGED_AT = "2026-08-31T16:36:00Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/security/codex-component-results.test.ts b/lib/security/codex-component-results.test.ts
index 0ef91a31..f000bd2a 100644
--- a/lib/security/codex-component-results.test.ts
+++ b/lib/security/codex-component-results.test.ts
@@ -19,6 +19,15 @@ function findings(...levels: string[]) {
}
describe("Codex Security component result gate", () => {
+ test("covers the infrastructure control plane in the committed component plan", () => {
+ const fs = require("node:fs") as typeof import("node:fs");
+ const path = require("node:path") as typeof import("node:path");
+ const plan = JSON.parse(fs.readFileSync(path.join(process.cwd(), "security/codex-components.json"), "utf8")) as { components: Array<{ name: string; paths: string[] }> };
+ const assigned = new Set(plan.components.flatMap((component) => component.paths));
+ expect(assigned).toContain("lib/infra");
+ expect(assigned).toContain("frontend/slices/infrastructure");
+ });
+
test("passes complete coverage with no high-or-critical findings", () => {
expect(evaluateComponentResults(completeSummary, findings("medium", "low"))).toMatchObject({ exitCode: 0 });
});
diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs
index 144144d1..7ee2c459 100755
--- a/scripts/check-docs.mjs
+++ b/scripts/check-docs.mjs
@@ -19,6 +19,7 @@ const toolFiles = [
"lib/mcp/tools-read.ts",
"lib/mcp/tools-discovery.ts",
"lib/mcp/tools-learning.ts",
+ "lib/mcp/tools-infra.ts",
"lib/mcp/tools-power.ts",
];
const tools = new Map();
diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.ts
new file mode 100644
index 00000000..7be9c119
--- /dev/null
+++ b/scripts/mso-agent-contract.test.ts
@@ -0,0 +1,30 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const files = ["mso-agent.mjs", "mso-agent-runtime.mjs"].map((name) => path.join(__dirname, name));
+const src = files.map((file) => fs.readFileSync(file, "utf8")).join("\n");
+
+describe("MSO terminal agent contract", () => {
+ it("renders original MSO terminal branding and exposes setup shortcuts", () => {
+ expect(src).toContain("███╗ ███╗ ███████╗ ██████╗");
+ for (const command of ["/model", "/setup", "/providers", "/provider", "/doctor", "/tools", "/skills", "/clear", "/exit"]) expect(src).toContain(command);
+ });
+
+ it("keeps infrastructure secrets out of model messages and binds write/exec approval to the exact full payload", () => {
+ expect(src).toContain("never ask the user to paste API tokens into chat");
+ expect(src).toContain('tool.scope === "read"');
+ expect(src).toContain("exact tool call");
+ expect(src).toContain("allow this exact call? [y/N]");
+ expect(src).toContain("canonicalAgentApproval");
+ expect(src).toContain("approvalDigest");
+ expect(src).not.toContain("redactedPreview");
+ expect(src).not.toContain("allowedForSession");
+ expect(src).toContain("approved: true");
+ });
+
+ it("reads the authenticated cookie jar instead of accepting a bearer/token argument", () => {
+ expect(src).toContain("MSO_AGENT_JAR");
+ expect(src).not.toMatch(/process\.argv.*(?:token|secret|password|apiKey)/i);
+ });
+});
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
new file mode 100644
index 00000000..2ad413ca
--- /dev/null
+++ b/scripts/mso-agent-runtime.mjs
@@ -0,0 +1,148 @@
+import fs from "node:fs";
+import process from "node:process";
+
+export const BASE = String(process.env.MSO_AGENT_BASE || "http://127.0.0.1:4005").replace(/\/$/, "");
+const ORIGIN = String(process.env.MSO_AGENT_ORIGIN || BASE);
+const JAR = String(process.env.MSO_AGENT_JAR || "");
+export const CLI = String(process.env.MSO_AGENT_CLI || "mso");
+const VERSION = String(process.env.MSO_AGENT_VERSION || "");
+const color = process.stdout.isTTY && !process.env.NO_COLOR;
+export const C = {
+ reset: color ? "\x1b[0m" : "", bold: color ? "\x1b[1m" : "", dim: color ? "\x1b[2m" : "",
+ a: color ? "\x1b[38;2;124;92;255m" : "", b: color ? "\x1b[38;2;58;160;255m" : "", c: color ? "\x1b[38;2;52;211;153m" : "",
+ warn: color ? "\x1b[38;2;245;158;11m" : "", err: color ? "\x1b[38;2;239;68;68m" : "",
+};
+
+function cookieHeader() {
+ if (!JAR) return "";
+ let raw = "";
+ try { raw = fs.readFileSync(JAR, "utf8"); } catch { return ""; }
+ const pairs = [];
+ for (let line of raw.split(/\r?\n/)) {
+ if (line.startsWith("#HttpOnly_")) line = line.slice("#HttpOnly_".length);
+ else if (!line || line.startsWith("#")) continue;
+ const cols = line.split("\t");
+ if (cols.length >= 7 && cols[5] === "session") pairs.push(`session=${cols[6] ?? ""}`);
+ }
+ return pairs.join("; ");
+}
+
+export async function api(path, init = {}) {
+ const headers = new Headers(init.headers || {});
+ headers.set("origin", ORIGIN);
+ const cookie = cookieHeader();
+ if (cookie) headers.set("cookie", cookie);
+ if (init.body && !headers.has("content-type")) headers.set("content-type", "application/json");
+ const res = await fetch(`${BASE}${path}`, { ...init, headers });
+ const text = await res.text();
+ let body = null;
+ try { body = text ? JSON.parse(text) : null; } catch { body = text; }
+ if (!res.ok) throw new Error(typeof body === "object" && body?.error ? String(body.error) : `HTTP ${res.status}`);
+ return body;
+}
+
+function logo() {
+ const lines = [
+ "███╗ ███╗ ███████╗ ██████╗ ",
+ "████╗ ████║ ██╔════╝ ██╔═══██╗",
+ "██╔████╔██║ ███████╗ ██║ ██║",
+ "██║╚██╔╝██║ ╚════██║ ██║ ██║",
+ "██║ ╚═╝ ██║ ███████║ ╚██████╔╝",
+ "╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ",
+ ];
+ return lines.map((line, i) => `${i < 2 ? C.a : i < 4 ? C.b : C.c}${C.bold}${line}${C.reset}`).join("\n");
+}
+
+function countSkills(data) { return Array.isArray(data?.skills) ? data.skills.length : 0; }
+function summarizeInfra(data) {
+ const rows = Array.isArray(data?.providers) ? data.providers : [];
+ const ready = rows.filter((row) => row.configured).map((row) => row.id);
+ return { ready, total: rows.length };
+}
+
+export async function state() {
+ const [config, toolsData, skills, infra] = await Promise.all([
+ api("/api/config"), api("/api/v1/agent-tools"), api("/api/skills").catch(() => ({ skills: [] })), api("/api/v1/infra/providers").catch(() => ({ providers: [] })),
+ ]);
+ const tools = Array.isArray(toolsData?.tools) ? toolsData.tools : [];
+ return { config, toolsData, tools, skills, infra };
+}
+
+function compactNames(rows, max = 7) {
+ const names = rows.map((row) => String(row.id ?? row.name ?? "")).filter(Boolean);
+ return `${names.slice(0, max).join(", ")}${names.length > max ? `, +${names.length - max} more` : ""}` || "none";
+}
+
+export function printBanner(s) {
+ const byScope = { read: 0, write: 0, exec: 0 };
+ for (const tool of s.tools) byScope[tool.scope] = (byScope[tool.scope] || 0) + 1;
+ const infra = summarizeInfra(s.infra);
+ const readTools = s.tools.filter((tool) => tool.scope === "read");
+ const gatedTools = s.tools.filter((tool) => tool.scope !== "read");
+ const skills = Array.isArray(s.skills?.skills) ? s.skills.skills : [];
+ console.log(logo());
+ console.log();
+ console.log(`${C.bold}╭─ MSO Agent${C.reset} ${C.dim}${VERSION ? `v${VERSION} · ` : ""}${BASE}${C.reset}`);
+ console.log(`│ model ${C.a}${s.config?.provider ?? "—"}/${s.config?.model ?? "—"}${C.reset}`);
+ console.log(`│ capabilities ${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec ${C.dim}(write/exec approval-gated)${C.reset}`);
+ console.log(`├─ ${C.bold}Available Tools${C.reset}`);
+ console.log(`│ read ${compactNames(readTools)}`);
+ console.log(`│ approval ${compactNames(gatedTools, 6)}`);
+ console.log(`├─ ${C.bold}Available Skills${C.reset}`);
+ console.log(`│ ${countSkills(s.skills)} loaded ${compactNames(skills, 8)}`);
+ console.log(`├─ ${C.bold}Infrastructure${C.reset}`);
+ console.log(`│ ${infra.ready.length}/${infra.total} ready ${infra.ready.length ? infra.ready.join(", ") : "run /providers to connect Dokploy/Cloudflare/Hostinger"}`);
+ console.log(`╰─ ${C.dim}Ask MSO to inspect, configure, deploy, or debug this server. /help shows commands.${C.reset}`);
+}
+
+const SYSTEM = [
+ "You are MSO Agent, the interactive terminal setup and operations agent for Manef Shell OS on the user's own server.",
+ "Use the provided tools to do real work instead of only describing commands. Prefer bounded tools over exec_run.",
+ "For setup, first inspect infrastructure with infra_providers_list and live-check configured providers with infra_provider_doctor.",
+ "Dokploy, Cloudflare, and Hostinger credentials are entered interactively with `mso provider set <id>` and are never exposed to you; never ask the user to paste API tokens into chat or shell commands.",
+ "Use dokploy_* and cloudflare_*/hostinger_* tools after the user has configured those providers. Cloudflare DNS must remain per-record and DNS-only unless the user explicitly asks for proxying.",
+ "If multiple operational calls are needed, use workflow_start, pass its workflow_id to later calls, verify, then workflow_finish. If the task is abandoned, workflow_cancel.",
+ "Write and exec tools may be denied by the user's approval prompt. Never retry a denied call unchanged.",
+ "Be concise. Explain only decisions the user needs to make or concrete results/errors.",
+].join(" ");
+
+function toolForModel(tool) {
+ return { name: tool.name, description: tool.description, input_schema: tool.inputSchema || { type: "object", properties: {} } };
+}
+
+export async function streamTurn(messages, tools) {
+ const res = await fetch(`${BASE}/api/assistant`, {
+ method: "POST",
+ headers: { origin: ORIGIN, cookie: cookieHeader(), "content-type": "application/json" },
+ body: JSON.stringify({ messages, tools: tools.map(toolForModel), system: SYSTEM }),
+ });
+ if (!res.ok || !res.body) {
+ let body = {}; try { body = await res.json(); } catch {}
+ throw new Error(body?.error || `assistant HTTP ${res.status}`);
+ }
+ const reader = res.body.getReader();
+ const dec = new TextDecoder();
+ let buf = "", text = "", stopReason = null;
+ const toolUses = [];
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += dec.decode(value, { stream: true });
+ const blocks = buf.split("\n\n"); buf = blocks.pop() || "";
+ for (const block of blocks) {
+ let event = "message", data = "";
+ for (const line of block.split("\n")) {
+ if (line.startsWith("event:")) event = line.slice(6).trim();
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
+ }
+ if (!data) continue;
+ if (event === "delta") {
+ const chunk = JSON.parse(data); text += chunk; process.stdout.write(chunk);
+ } else if (event === "tool_use") toolUses.push(JSON.parse(data));
+ else if (event === "done") stopReason = JSON.parse(data)?.stopReason ?? null;
+ else if (event === "error") throw new Error(JSON.parse(data));
+ }
+ }
+ if (text && !text.endsWith("\n")) process.stdout.write("\n");
+ return { text, toolUses, stopReason };
+}
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
new file mode 100644
index 00000000..dc6e502a
--- /dev/null
+++ b/scripts/mso-agent.mjs
@@ -0,0 +1,115 @@
+#!/usr/bin/env node
+import { spawnSync } from "node:child_process";
+import readline from "node:readline/promises";
+import process from "node:process";
+import { canonicalAgentApproval } from "../lib/agent/approval.js";
+import { BASE, CLI, C, api, printBanner, state, streamTurn } from "./mso-agent-runtime.mjs";
+
+async function executeTool(rl, tool, call) {
+ if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };
+ let approved = tool.scope === "read";
+ let approval = null;
+ if (!approved) {
+ try {
+ approval = canonicalAgentApproval(tool.name, call.input || {});
+ } catch (error) {
+ return { ok: false, result: `cannot safely approve tool call: ${error instanceof Error ? error.message : String(error)}` };
+ }
+ console.log(`${C.warn}${C.bold}[${tool.scope.toUpperCase()}] exact tool call${C.reset}`);
+ console.log(approval.display);
+ console.log(`${C.dim}sha256 ${approval.digest} · ${approval.bytes} bytes${C.reset}`);
+ const answer = (await rl.question(" allow this exact call? [y/N]: ")).trim().toLowerCase();
+ if (answer === "y" || answer === "yes") approved = true;
+ }
+ if (!approved) return { ok: false, result: "denied by user" };
+ process.stdout.write(`${C.dim} ↳ ${tool.name}…${C.reset}`);
+ try {
+ const input = approval ? approval.payload.input : (call.input || {});
+ const out = await api("/api/v1/agent-tools", {
+ method: "POST",
+ body: JSON.stringify({
+ name: tool.name,
+ input,
+ ...(tool.scope === "read" ? {} : { approved: true, approvalDigest: approval.digest }),
+ }),
+ });
+ process.stdout.write(`\r${C.c} ✓ ${tool.name}${C.reset}\n`);
+ if (!out.ok) return { ok: false, result: out.result || "tool failed" };
+ return { ok: true, result: String(out.result ?? "ok") };
+ } catch (error) {
+ process.stdout.write(`\r${C.err} ✗ ${tool.name}${C.reset}\n`);
+ return { ok: false, result: (error instanceof Error ? error.message : String(error)).slice(0, 2000) };
+ }
+}
+
+async function agentRound(rl, history, tools) {
+ for (let turn = 0; turn < 10; turn++) {
+ const result = await streamTurn(history, tools);
+ history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });
+ if (!result.toolUses.length) return;
+ const results = [];
+ for (const call of result.toolUses) {
+ const tool = tools.find((row) => row.name === call.name);
+ const outcome = await executeTool(rl, tool, call);
+ results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });
+ }
+ history.push({ role: "tool", results });
+ }
+ console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);
+}
+
+function runCli(args) {
+ const r = spawnSync(CLI, args, { stdio: "inherit", env: { ...process.env, MSO_BASE: BASE } });
+ if (r.error) console.error(`${C.err}${r.error.message}${C.reset}`);
+ return r.status ?? 1;
+}
+
+async function slash(line, rl, session) {
+ const [cmd, ...args] = line.trim().split(/\s+/);
+ switch (cmd) {
+ case "/help":
+ console.log(" /model connect/change AI provider\n /setup full MSO onboarding\n /providers infrastructure provider status\n /provider <id> configure dokploy|cloudflare|hostinger\n /doctor run mso doctor\n /tools list agent tools\n /skills list available skills\n /clear clear this conversation\n /exit quit"); return "handled";
+ case "/model": runCli(["model"]); session.state = await state(); return "refresh";
+ case "/setup": runCli(["onboard"]); session.state = await state(); return "refresh";
+ case "/providers": runCli(["provider", "list"]); session.state = await state(); return "refresh";
+ case "/provider": if (!args[0]) console.log("usage: /provider dokploy|cloudflare|hostinger"); else runCli(["provider", "set", args[0]]); session.state = await state(); return "refresh";
+ case "/doctor": runCli(["doctor"]); return "handled";
+ case "/tools": for (const tool of session.state.tools) console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`); return "handled";
+ case "/skills": for (const skill of session.state.skills?.skills ?? []) console.log(` ${skill.id}${skill.description ? ` — ${skill.description}` : ""}`); return "handled";
+ case "/clear": session.history.length = 0; console.log("conversation cleared."); return "handled";
+ case "/exit": return "exit";
+ default: return "unknown";
+ }
+}
+
+async function main() {
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
+ console.error("mso agent needs an interactive terminal. For one-shot automation use: mso ai <prompt>");
+ process.exit(2);
+ }
+ let s = await state();
+ printBanner(s);
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true, historySize: 100 });
+ const session = { state: s, history: [] };
+ process.on("SIGINT", () => { console.log("\nUse /exit to quit."); });
+ try {
+ while (true) {
+ let line = "";
+ try { line = (await rl.question(`\n${C.a}${C.bold}›${C.reset} `)).trim(); }
+ catch { break; }
+ if (!line) continue;
+ if (line.startsWith("/")) {
+ const result = await slash(line, rl, session);
+ if (result === "exit") break;
+ if (result === "unknown") console.log("unknown command; /help lists commands.");
+ continue;
+ }
+ session.history.push({ role: "user", text: line });
+ if (session.history.length > 36) session.history.splice(0, session.history.length - 36);
+ try { await agentRound(rl, session.history, session.state.tools); }
+ catch (error) { console.error(`${C.err}agent error: ${error instanceof Error ? error.message : String(error)}${C.reset}`); }
+ }
+ } finally { rl.close(); }
+}
+
+main().catch((error) => { console.error(`${C.err}mso agent: ${error instanceof Error ? error.message : String(error)}${C.reset}`); process.exit(1); });
diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.sh
new file mode 100755
index 00000000..d2d2bbec
--- /dev/null
+++ b/scripts/mso-cli-agent.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env bash
+# MSO terminal-agent / infrastructure-provider CLI slice.
+# This file is sourced by bin/mso after generic auth/HTTP/TTY helpers are defined.
+# It deliberately owns no standalone entrypoint and no duplicate transport logic.
+
+# Build the provider/key request from stdin so the secret never appears in jq/node argv.
+provider_key_body() {
+ node -e 'const fs=require("fs"); const a=fs.readFileSync(0).toString("utf8").split("\0"); process.stdout.write(JSON.stringify({provider:a[0]||"",apiKey:a[1]||""}));'
+}
+
+onboard_infra() {
+ local yes="$1" choice
+ if [ "$yes" = 1 ]; then
+ echo " -- infrastructure providers skipped (-y never stores external credentials)"
+ return
+ fi
+ echo
+ echo "Infrastructure providers"
+ echo " MSO Agent can use these after you connect them. Secrets stay server-side and never enter model tool arguments."
+ tty_line "Configure Dokploy now? [y/N]: " "n"; choice="${REPLY,,}"
+ case "$choice" in y|yes) run_provider set dokploy ;; esac
+ echo
+ echo "DNS provider"
+ echo " 0) Skip"
+ echo " 1) Cloudflare (per-record writes only)"
+ echo " 2) Hostinger (exact name/type RR-set updates; agent approval required)"
+ tty_line "Choose [0]: " 0; choice="$REPLY"
+ case "$choice" in 1) run_provider set cloudflare ;; 2) run_provider set hostinger ;; *) echo " -- DNS provider skipped" ;; esac
+}
+
+ai_config_ready() {
+ jq -e '. as $c | ($c.hasApiKey == true or any($c.providers[]?; .id == $c.provider and .kind == "oauth"))' >/dev/null 2>&1
+}
+
+run_model_setup() {
+ ensure_local_cli_device
+ ensure_onboard_runtime
+ jget "/api/auth/me" >/dev/null
+ tty_ok || die "mso model needs an interactive terminal"
+ onboard_ai 0
+}
+
+provider_metadata() { jget "/api/v1/infra/providers"; }
+
+run_provider() {
+ local sub="${1:-list}" id="${2-}" data row fields key label secret required description existing value body
+ local -a pairs=()
+ case "$sub" in
+ list)
+ provider_metadata | jq -r '.providers[] | "\(if .configured then "✓" else "·" end) \(.id)\t\(if .configured then "configured" else "missing: " + (.missing|join(", ")) end)\t\(.description)"' ;;
+ show)
+ [ -n "$id" ] || die "usage: mso $U_provider"
+ provider_metadata | jq --arg id "$id" '.providers[] | select(.id==$id)' ;;
+ projects|dokploy-projects)
+ jget "/api/v1/infra/dokploy/projects" | jq -r '.projects[] | "\(.projectId)\t\(.name)"' ;;
+ zones|cloudflare-zones)
+ jget "/api/v1/infra/cloudflare/zones" | jq -r '.zones[] | "\(.id)\t\(.name)"' ;;
+ doctor)
+ id="${2-}"
+ if [ -n "$id" ]; then body=$(jq -nc --arg id "$id" '{id:$id}'); else body='{}'; fi
+ jpost "/api/v1/infra/providers/doctor" "$body" | jq -r '.results[] | "\(if .ok == true then "✓" elif .ok == false then "✗" else "·" end) \(.id) — \(.detail)"' ;;
+ rm|remove)
+ [ -n "$id" ] || die "usage: mso $U_provider"
+ jdel "/api/v1/infra/providers?id=$(enc "$id")" >/dev/null
+ echo "removed infrastructure provider: $id" ;;
+ set)
+ [ -n "$id" ] || die "usage: mso $U_provider"
+ tty_ok || die "provider setup needs a terminal because API tokens are entered with hidden input"
+ data=$(provider_metadata)
+ row=$(jq -c --arg id "$id" '.providers[] | select(.id==$id)' <<<"$data")
+ [ -n "$row" ] || die "unknown provider '$id' (expected dokploy, cloudflare, hostinger)"
+ echo "$(jq -r '.title + " — " + .description' <<<"$row")"
+ pairs=()
+ while IFS=$'\t' read -r key label secret required description existing; do
+ [ -n "$key" ] || continue
+ echo
+ if [ "$required" = true ]; then echo " $label (required)"; else echo " $label (optional)"; fi
+ [ -z "$description" ] || echo " $description"
+ if [ "$secret" = true ]; then
+ if [ -n "$existing" ]; then tty_secret " new value (blank = keep ${existing}): "; value="$REPLY"
+ else tty_secret " value: "; value="$REPLY"; fi
+ else
+ tty_line " value${existing:+ [$existing]}: " "$existing"; value="$REPLY"
+ fi
+ if [ -z "$value" ] && [ "$required" = true ] && [ -z "$existing" ]; then die "$key is required"; fi
+ [ -z "$value" ] || pairs+=("$key" "$value")
+ unset value REPLY
+ done < <(jq -r '.fields[] as $f | [$f.key,$f.label,($f.secret|tostring),($f.required|tostring),($f.description // ""),(.values[$f.key] // "")] | @tsv' <<<"$row")
+ # Values stay in this shell's memory and flow to Node over stdin; they never
+ # appear in process argv, environment variables, or a temporary credential file.
+ body=$(printf '%s\0' "${pairs[@]}" | node -e '
+const fs = require("fs");
+const id = process.argv[1];
+const parts = fs.readFileSync(0).toString("utf8").split("\0");
+const values = {};
+for (let i = 0; i + 1 < parts.length; i += 2) if (parts[i]) values[parts[i]] = parts[i + 1];
+process.stdout.write(JSON.stringify({ id, values }));
+' "$id")
+ secret_post "/api/v1/infra/providers" "$body" >/dev/null
+ unset body
+ echo " ✓ $id configured"
+ jpost "/api/v1/infra/providers/doctor" "$(jq -nc --arg id "$id" '{id:$id}')" | jq -r '.results[] | " \(if .ok == true then "✓" elif .ok == false then "✗" else "·" end) \(.detail)"' ;;
+ *) die "usage: mso $U_provider" ;;
+ esac
+}
+
+run_agent() {
+ local cfg
+ tty_ok || die "interactive agent needs a terminal; use: mso ai <prompt> for a one-shot request"
+ ensure_local_cli_device
+ ensure_onboard_runtime
+ jget "/api/auth/me" >/dev/null
+ cfg=$(jget "/api/config")
+ if ! printf '%s' "$cfg" | ai_config_ready; then
+ echo "MSO Agent needs an AI provider first."
+ onboard_ai 0
+ cfg=$(jget "/api/config")
+ printf '%s' "$cfg" | ai_config_ready || die "no AI provider connected; run `mso model` when ready"
+ fi
+ MSO_AGENT_BASE="$B" MSO_AGENT_ORIGIN="$B" MSO_AGENT_JAR="$JAR" \
+ MSO_AGENT_CLI="$ROOT/bin/mso" MSO_AGENT_VERSION="$VERSION" \
+ node "$ROOT/scripts/mso-agent.mjs"
+}
diff --git a/security/codex-components.json b/security/codex-components.json
index 9f6c1dcc..cd1d1d48 100644
--- a/security/codex-components.json
+++ b/security/codex-components.json
@@ -26,7 +26,8 @@
"lib/config",
"lib/security-store-lock.ts",
"lib/path.ts",
- "lib/path.test.ts"
+ "lib/path.test.ts",
+ "lib/infra"
]
},
{
@@ -92,7 +93,8 @@
"frontend/slices/os-settings",
"frontend/slices/shell-settings",
"frontend/slices/system-monitor",
- "frontend/slices/quicklinks"
+ "frontend/slices/quicklinks",
+ "frontend/slices/infrastructure"
]
},
{