Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
docs: refresh architecture and ChatGPT MCP guide
Rahmanec910ebbbad4
diff --git a/.env.example b/.env.exampleindex e4eecf98..592796ba 100644--- a/.env.example+++ b/.env.example@@ -68,18 +68,17 @@ OS_SESSION_SECRET=# OS_CODEX_BUILTIN_TOOLS=# --- Managed apps: Hermes / OpenClaw (optional) ----# The OS lists an upstream app's own dashboard pages by reading that app's built-# SPA off disk plus its ONE public (unauthenticated) JSON endpoint. No credentials-# are used or stored for discovery — if the paths below don't resolve, the OS lists-# nothing rather than guessing at routes.-# Upstream dashboards the feature proxy targets.+# MSO detects these two known apps through bounded service/package probes and can+# install/control/log/update/back up/restore them. It does NOT scrape vendor SPA routes+# into MSO features. The URLs below are only the known loopback dashboards used by the+# optional split-origin proxy.# HERMES_DASHBOARD_URL=http://127.0.0.1:9119# OPENCLAW_DASHBOARD_URL=http://127.0.0.1:18789# Hermes install home. Default ~/.hermes. Absolute, or "~/…" for the home of the# user running mso. This is the tree the managed-app backup action copies.# HERMES_HOME=/home/you/.hermes-# Public origin the BROWSER uses, e.g. https://mso.rahmanef.com. Only the scheme+# Public origin the BROWSER uses, e.g. https://mso.example.com. Only the scheme# + host + port are read. The managed-app proxy scopes its Content-Security-Policy# to this origin; without it the origin is inferred from the Host header and then# from X-Forwarded-Host, and the latter is client-settable — set this whenever the@@ -87,16 +86,15 @@ OS_SESSION_SECRET=# In split-origin mode (below) this is also the origin the app hosts name in# `frame-ancestors`, so it decides whether the cockpit may frame the dashboard at# all. Unset, it falls back to the parent name of the host template-# (`{id}.mso.rahmanef.com` → `https://mso.rahmanef.com`); if THAT yields nothing+# (`{id}.mso.example.com` → `https://mso.example.com`); if THAT yields nothing# usable the policy emits `frame-ancestors 'none'` and the window stays blank —# closed, on purpose, rather than naming a guessed origin as a permitted framer.-# OS_PUBLIC_ORIGIN=https://mso.rahmanef.com+# OS_PUBLIC_ORIGIN=https://mso.example.com# --- Managed-app dashboards: ONE decision, TWO variables ----# Unset (default) = MSO does not serve the Hermes/OpenClaw web UI at all. Feature-# windows open on the CLI view, and the dashboards stay reachable the way they-# always were: at their own address, from a browser of your own. Nothing is lost-# but the embedded frame.+# Unset (default) = MSO does not serve the Hermes/OpenClaw vendor web UI. Their+# MSO Details management surface (install/start/log/update/backup/restore) remains+# available; only the embedded vendor dashboard is absent.## There is no fallback to serving them under a path on the cockpit's origin. That# mode existed and was removed: those SPAs need allow-same-origin to run at all,@@ -108,7 +106,7 @@ OS_SESSION_SECRET=# process, cross-origin — so `window.top` is opaque:## 1. NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE — `{id}` is the app id, so this-# yields hermes.mso.rahmanef.com and openclaw.mso.rahmanef.com. Each host+# yields hermes.mso.example.com and openclaw.mso.example.com. Each host# needs its own DNS record + TLS pointing at this app. On such a host the# middleware rewrites EVERY path into that app's proxy and 404s the rest, so# the cockpit API does not exist there.@@ -119,7 +117,7 @@ OS_SESSION_SECRET=## THE CONSEQUENCE OF SETTING (2) WITHOUT (1): the session cookie is handed to# every host under that domain, and each one still serves the whole cockpit —-# /api/v1/exec/run included. Anything that can answer on a *.mso.rahmanef.com name+# /api/v1/exec/run included. Anything that can answer on a *.mso.example.com name# (a future subdomain, a stale DNS record someone else points here, a wildcard# certificate reused by another service) receives the credential. Only the# middleware host gating makes the widened cookie safe. Set both, or neither.@@ -146,8 +144,8 @@ OS_SESSION_SECRET=# Cookie header carries no Domain, so a cookie that was never sent looks exactly# like one that never existed. Turning this on is a three-step change — set, build,# re-login — and skipping the third is the one that wastes an afternoon.-# NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.rahmanef.com-# OS_SESSION_COOKIE_DOMAIN=mso.rahmanef.com+# NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com+# OS_SESSION_COOKIE_DOMAIN=mso.example.com# --- Storage paths (optional overrides) ---# OS_DEVICE_STORE=~/.mso/auth-devices.json # approved-device allowlistdiff --git a/CLAUDE.md b/CLAUDE.mdindex fa7d66d9..d51db59d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -28,16 +28,17 @@ agent — it runs AS a host process and controls its own machine.`WATCHDOG_USEC`), the OS's (`PATH`, `SHELL`), test-only ones (`E2E_BASE_URL`,`OPENCLAW_HOME`), and `OS_BROWSER_*`, which belong to the retired `os-browser/`sidecar and not to this app. Still grep `process.env` before adding a new one.-- **The code wins over any doc.** `docs/ARCHITECTURE.md` is HISTORY, not current — it- still describes a retired Playwright browser sidecar, a managed-app "single-origin- mode" that was removed for security, and workspace modes that were reversed. It is- kept for the reasoning it records, not as a description of today.+- **The code wins over any doc.** `docs/README.md` classifies the doc set. Current+ reference docs (including `docs/ARCHITECTURE.md`) must track `main`; dated audits/plans+ are explicitly historical and may preserve obsolete implementation details only inside+ that historical context.- `frontend/slices/assistant/CONTRACT.md` — current, and authoritative for what anAgent / Tool / Skill / Playbook is and what reaches the model.-**The doc set, and the one rule.** `docs/PROGRESS.md` is the SSOT; everything else is-history, a live plan, or reference. Append to PROGRESS when you ship — do not start a-second HAND-WRITTEN log. (`docs/CHANGELOG.md` was exactly that once and was merged+**The doc set, and the one rule.** `docs/README.md` is the map. `docs/PROGRESS.md` is+the SSOT for historical WHY; current reference docs describe today's contracts; dated+plans/audits are historical. Append to PROGRESS when you ship — do not start a second+HAND-WRITTEN log. (`docs/CHANGELOG.md` was exactly that once and was mergedback in; the root `progress.md` is gitignored local scratch and claims authority itdoes not have.) `docs/CHANGELOG.md` exists again as of 2026-08-11 but is **generatedfrom git subjects** by `scripts/gen-changelog.mjs` and gated stale-by-`gates.sh`, so@@ -108,15 +109,12 @@ to `resources/` (rr) and drive any project from one manifest:(toast/activity/inspector), and `<AppShell manifest>` (the one entry point). Itimports NO brand/feature and NO mso `@/lib/*` — only the universal `@/lib/utils`(`cn`). Everything project-specific arrives via `manifest.capabilities`.-- `appshell/features/{search,inspector,notifications,control-center,widgets,quick-look,- clipboard,share,shortcut-help,lock-screen}` — each shell **feature** lives NESTED inside- the appshell slice (converged to the rr-canonical shape; they were flat top-level- `shell-*` slices before). Each mounts into a named `<Slot>` via `defineFeature({ id,- slots, provider? })` and is consumer-free (data via capabilities, not `@/lib`).- `appshell/defaults.ts` bundles all 10 as `DEFAULT_FEATURES` (one-line install:- `features: DEFAULT_FEATURES`); the barrel re-exports it LAST so the `defineFeature`- ES-cycle resolves. Buses live in core so apps fire them without depending on a feature- slice. (`shell-settings` stays a flat UI-primitives slice — not a feature unit.)+- `appshell/features/` currently contains 10 directories: `clipboard`,+ `control-center`, `desktop-icons`, `force-quit`, `inspector`, `lock-screen`,+ `notifications`, `search`, `shortcut-help`, `widgets`. `desktop-icons` and+ `force-quit` are shell infrastructure rather than normal slot features. Keep+ `docs/SLICE-CATALOG.md` and the machine-checked count in sync with the directory tree.+ (`shell-settings` stays a flat UI-primitives slice — not an AppShell feature directory.)- `os-shell` — the thin mso **consumer**: `shell.manifest.ts` (MSO brand + applist + slugs + features) + `capabilities.ts` (adapts `@/lib/appearance`+`os-api`+`ai/stream` to `ShellCapabilities`) + a re-export barrel (`@/features/os-shell`@@ -178,13 +176,12 @@ to `resources/` (rr) and drive any project from one manifest:explicitly if you want it public. The checkout is a shallow clone of this repo with`node_modules` copied in; rebuild it with the flag (`NEXT_PUBLIC_OS_DEMO=1` is inlinedat BUILD time) whenever you re-deploy it.-- **Deploy prod:** `bun run build` **THEN** `sudo systemctl restart mso.service`. ALWAYS- build-then-restart, never the reverse, and never rebuild again after restarting- without restarting once more — `next start` loads the build manifest at boot, so if- the on-disk `.next/static` chunks don't match the running process's HTML refs, every- CSS/JS chunk 404s → unstyled/broken UI. On any chunk mismatch: `rm -rf .next && bun run- build && restart` (clean rebuild). Verify with- `curl -sI :4005/_next/static/chunks/<the-css-the-HTML-refs> | grep content-type` → must be `text/css`.+- **Deploy prod:** use `bun run ship "<conventional commit>"`. It regenerates the+ derived changelog, runs the committed pre-push gates/out-of-tree build, pushes the exact+ SHA, then finalizes the in-place build/service replacement/chunk verification. Through+ MSO/MCP, finalization runs in `mso-self-update.service`; completion is proven only when+ the log ends `UPDATE OK`. Operator update/recovery is Settings → About or+ `mso update run [--rebuild]`. Do not use a bare in-place build merely to verify code.- **Service worker** is served from `app/api/sw/route.ts` with a **`beforeFiles`rewrite `/sw.js`→`/api/sw`** (in `next.config`): a literal `app/sw.js/route.ts`gets shadowed by the optional catch-all, and routes under `/api` are never caught.@@ -296,9 +293,11 @@ to `resources/` (rr) and drive any project from one manifest:## MCP server (`/mcp`) — optional, OFF by defaultAn MCP endpoint so ChatGPT / Claude.ai / Cursor can drive the host. `lib/mcp/*`-(pkce · scope · store · tool-kit · tools-read · tools · dispatch) + `app/mcp/route.ts` + `app/oauth/*` +-`app/.well-known/oauth-*`. **`OS_MCP_ENABLED=1` or every one of those routes 404s** —-that is the kill switch, and demo mode forces it off. Read `docs/MCP.md` first.+includes OAuth/PKCE/store/scope, read/discovery/learning/power/write tool catalogs,+toolset metadata, workflow activity and dispatch; routes live under `/mcp`, `/oauth/*`+and `/.well-known/oauth-*`. **`OS_MCP_ENABLED=1` or every one of those routes 404s** —+that is the kill switch, and demo mode forces it off. Read `docs/MCP.md`; for ChatGPT+setup/diagrams use `docs/CHATGPT-PLUGIN.md`.- **`/mcp` is deliberately NOT under `/api`.** `proxy.ts` blocks mutating `/api` thatcannot prove same-origin and an MCP client is cross-origin by definition; the beareris the control, not the CSRF gate. `proxy.ts` exempts `/mcp`, `/oauth/token`,@@ -313,8 +312,10 @@ that is the kill switch, and demo mode forces it off. Read `docs/MCP.md` first.permitted tier; set the env to `read` or `write` to opt down. `tools/list` filters byit AND `tools/call` re-checks it — a client can call a name it was never shown.- **Tool names are a cross-repo contract.** `rahmanef63/connectors-gateway` registered- mso as a connector on 2026-08-17 and pins 15 of the 22 names as literal strings- (`x-upstream`), omitting `exec_run`, `browser_power`, and the five skill/workflow/visual tools added later. `GET /mcp` plus `_meta.toolset` now expose a version/hash/name manifest for parity checks. Renaming or removing+ mso as a connector on 2026-08-17 and historically pinned a subset of the MCP names as+ literal `x-upstream` strings. MSO itself currently exposes 28 tools (15 read, 10 write,+ 3 exec); `GET /mcp` plus `_meta.toolset` expose the current version/hash/name manifest.+ Treat the gateway mapping as a separate cross-repo contract and verify it before renaming. Renaming or removinga tool here breaks it with **no error in either repo** — `parity.test.ts` guards theAlfa axis, not this one. Read `docs/CONNECTORS-GATEWAY-INTEGRATION.md` before touchinga tool name.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 90859219..ec9b749d 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,62 +1,86 @@# Contributing-Solo-maintainer project — PRs and issues welcome, scope kept deliberately small.+MSO is a focused, single-owner project. Issues and pull requests are welcome, but changes+should preserve the narrow security and deployment model.## Setup```bashbun install-cp .env.example .env.local # set OS_LOGIN_PASSWORD + OS_SESSION_SECRET-bun run dev # :3000, mock data by default (no host access needed)+cp .env.example .env.local+bun run dev```-Node `>=20.9` (see `.nvmrc`). The mock adapter means you can develop every app-without a VPS or any credentials.--## Before you open a PR--A `pre-push` hook blocks the push on failure, so this checklist mostly describes what-already happens. It runs four guards: typecheck + lint + test (via sc-git's `ci.js`),-`check-cycles.mjs`, `scripts/audit.mjs`, and `scripts/verify-build.sh`. Budget ~70 s-per push. `.github/workflows/ci.yml` is **manual** (`gh workflow run CI`) — run it-before cutting a release or after touching `package.json`, `bun.lock` or-`scripts/install.sh`, because a clean-checkout `bun install --frozen-lockfile` is-the one thing the local hook cannot reproduce.--Two things about that hook are easy to get wrong:--- **The hook is UNTRACKED** (`.git/hooks/pre-push`), so nothing in this repo can carry- it. Re-running an sc-git hook installer overwrites it and silently drops the audit- and build guards. A healthy push prints `audit: clean at high/critical.` and- `build: HEAD compiles (out-of-tree).` — if those two lines are missing, it is gone.-- **`ci.js` is invoked with `--skip build`, on purpose.** It would run the build in- the current directory, which on the VPS *is* `mso.service`'s WorkingDirectory, and- `next build` deletes `distDir` before it compiles. `scripts/verify-build.sh` builds- a throwaway copy of `HEAD` in a temp dir instead. Do not "fix" the skip.--- [ ] `bun run verify` — typecheck + lint + test + check + audit, in one command-- [ ] `bun run build`-- [ ] (optional) `bash scripts/verify-build.sh` — build `HEAD` out-of-tree; safe to- run against the prod checkout, unlike a bare `bun run build`-- [ ] (optional) `bun run smoke` — e2e smoke against a running server--## Conventions (the short version)--Full conventions live in [CLAUDE.md](./CLAUDE.md) and-[docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md). The ones reviewers will hold-you to:--- **Vertical slices**: every app lives in `frontend/slices/<slug>/`; cross-slice- imports go through the barrel `@/features/<slug>` only.-- **Host seam**: each app's only host coupling is its `lib/host.ts`. API routes- never touch `fs`/`child_process` directly — always through `lib/host/*`- (bounds + realpath checks).-- **Max ~200 lines/file**, single responsibility, shadcn/ui primitives only,- theme tokens not raw hex, mobile-first.-- **Routing**: one catch-all route; URL writes via the History API, never- `router.push`; dock/launcher links keep `prefetch={false}`.-- Conventional commits (`feat:`, `fix:`, `docs:`…).+Set `OS_LOGIN_PASSWORD` and `OS_SESSION_SECRET` for live auth. The mock adapters let most UI+work proceed without VPS credentials or host access.++## Before a PR++Run:++```bash+bun run verify+node scripts/check-docs.mjs+bash scripts/verify-build.sh+```++`bun run verify` covers typecheck, lint, the Vitest suite, repository checks and the+high/critical dependency audit. `verify-build.sh` compiles a throwaway copy of `HEAD` so it+is safe even when the checkout is also the production WorkingDirectory.++Do **not** run a bare production build inside a live production checkout merely to prove+that code compiles; replacing `.next` underneath `next start` can create a chunk mismatch+until the service is replaced.++The committed source of truth for pre-push policy is `scripts/gates.sh`. The actual+`.git/hooks/pre-push` file is intentionally a tiny untracked shim. Install/reinstall it with:++```bash+bash scripts/gates.sh --install+```++A healthy push runs the shared typecheck/lint/test path (or in-repo fallback), cycle/docs/+changelog checks, dependency audit and the out-of-tree build. It should end with both:++```text+audit: clean at high/critical.+build: HEAD compiles (out-of-tree).+```++The GitHub CI workflow is still useful for a clean-checkout dependency/install proof,+especially after changes to `package.json`, `bun.lock` or installer/release scripts.++## Conventions++The current architecture is in [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) and the+documentation map is [`docs/README.md`](./docs/README.md). Reviewers will hold changes to+these rules:++- vertical application slices live under `frontend/slices/<slug>/`;+- cross-slice imports use public barrels;+- host operations flow through `lib/host` instead of reimplementing path/process guards in+ routes or components;+- keep files small/single-purpose where practical and use the existing UI primitives/tokens;+- keep responsive/mobile behaviour first-class;+- preserve the single catch-all app routing model;+- use conventional commit subjects.++When you add/remove/rename a current capability, update the relevant current reference doc+in the same change. `scripts/check-docs.mjs` catches selected machine-verifiable drift but+cannot infer every semantic change.++## Releasing maintainer changes++Normal contributor PRs should not deploy production. The maintainer release path after a+verified merge is:++```bash+bun run ship "feat(scope): describe the verified change"+```++A Git push by itself is not deployment. See [`docs/DEVELOPMENT.md`](./docs/DEVELOPMENT.md).## Security issues-Do **not** open a public issue — see [SECURITY.md](./SECURITY.md).+Do not open a public issue containing exploit details or secrets. Follow+[`SECURITY.md`](./SECURITY.md).diff --git a/README.md b/README.mdindex 3596d229..96b203a3 100644--- a/README.md+++ b/README.md@@ -64,7 +64,7 @@ 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.-- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health, every project and every trusted skill across all of them, ChatGPT file import, and, if you grant it, a shell. A token sees the *whole* catalog for its tier: the read/write/exec ladder is the only thing that narrows it, never a per-project or per-agent filter. Off unless you set `OS_MCP_ENABLED=1`, revocable from Settings. See [docs/MCP.md](./docs/MCP.md).+- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health, global project/skill discovery, ChatGPT file import and, at `exec`, a shell. The read/write/exec ladder is the server-side permission boundary. See the [ChatGPT custom MCP app guide](./docs/CHATGPT-PLUGIN.md) for setup/diagrams and [MCP reference](./docs/MCP.md) for internals.- **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.@@ -162,9 +162,9 @@ An authenticated MSO session can read allowed files and run commands as the user- Approve only devices you own; device approval is an allowlist, not standards-based 2FA.- Keep write roots narrow with `OS_FS_WRITE_ROOTS`.- Never commit `.env.local`, API keys, or data from `~/.mso`.-- Serve each managed app's dashboard from its own hostname (`hermes.os.example.com`), because a framed dashboard needs `allow-same-origin` and would otherwise be same-origin with the cockpit and able to call the host API with your session.-- That boundary is browser-only: a plugin installed into Hermes or OpenClaw runs inside that daemon and can run host commands, whatever the browser thinks about origins.-- With an API-key provider set, Alfa is a tool-calling agent, not a chatbot. Twelve tools run with no confirmation (`fs.list`, `fs.read`, `fs.search`, `fs.usage`, `sys.stats`, `sys.processes`, `apps.list`, `app.open`, `skills.list`, `skills.read`, `memory.remember`, `memory.forget`); six park an Approve/Deny card showing the exact call (`fs.write`, `fs.mkdir`, `fs.move`, `fs.copy`, `fs.delete`, `exec.run`).+- Managed-app dashboards are not embedded by default. If enabled, give Hermes/OpenClaw separate explicit hostnames such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.+- 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.+- With a model provider configured, Alfa is a tool-calling agent, not a plain chatbot. Its complete current catalog and human-approval contract are generated from `frontend/slices/assistant/host-tools/*` and documented in `frontend/slices/assistant/CONTRACT.md`; avoid copying a tool count into overview docs because the catalog changes independently of MCP.- Everything Alfa reads — file contents, command output, process lists — is sent to your model provider, and is re-sent on every following turn of the same run. BYOK means you own the key, not that the data stays on the box.- Treat any file Alfa reads as untrusted input. The approval card is the only thing between text hidden inside a file and an `exec.run`. Read the command on the card, not Alfa's summary of it.- Agents and Skills group tools for your own convenience. They are not a permission boundary: every agent can call every tool.@@ -226,8 +226,8 @@ bun run devQuality gates:```bash-bun run verify # typecheck + lint + test + check + audit-bun run build+bun run verify # typecheck + lint + test + checks + audit+node scripts/check-docs.mjs # docs links/toolset/slice driftbash scripts/verify-build.sh # build HEAD out-of-tree — safe on the prod checkoutbash -n scripts/install.sh```@@ -261,18 +261,20 @@ Not currently supported:| Doc | What's in it ||---|---|-| [docs/INSTALL.md](./docs/INSTALL.md) | Server install, credentials, systemd, TLS/VPN, updates, rollback |-| [docs/CLI.md](./docs/CLI.md) | The `mso` command-line reference (generated from `mso --help`) |-| [docs/DEVELOPMENT.md](./docs/DEVELOPMENT.md) | Local dev, quality gates, bun, deploy hazards |-| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | App shell, host layer, slices, routing |-| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Managing Hermes/OpenClaw, per-app origins, workspace modes |-| [docs/MODELS-INTEGRATION.md](./docs/MODELS-INTEGRATION.md) | Alfa AI and BYOK model providers |-| [docs/MCP.md](./docs/MCP.md) | The MCP server: connecting ChatGPT/Claude/Cursor, scopes, revoking |-| [docs/FAQ.md](./docs/FAQ.md) | Security posture, device approval, costs, product boundaries |-| [docs/TROUBLESHOOTING.md](./docs/TROUBLESHOOTING.md) | Common install, build, and deployment failures |-| [SECURITY.md](./SECURITY.md) | Responsible disclosure and deployment warnings |-| [docs/PRODUCT_HUNT.md](./docs/PRODUCT_HUNT.md) | Product Hunt launch copy and feedback prompts |-| [docs/DEMO-SCRIPT.md](./docs/DEMO-SCRIPT.md) | 60-second demo video script |+| [docs/README.md](./docs/README.md) | Documentation map: current reference vs generated vs historical |+| [docs/INSTALL.md](./docs/INSTALL.md) | Server install, credentials, TLS/VPN, update/rebuild, persistence |+| [docs/CLI.md](./docs/CLI.md) | Generated `mso` command-line reference |+| [docs/DEVELOPMENT.md](./docs/DEVELOPMENT.md) | Local dev, gates and exact release flow |+| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Current AppShell/host/MCP/managed-app architecture |+| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Hermes/OpenClaw lifecycle, jobs, update, backup/restore and origins |+| [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/MODELS-INTEGRATION.md](./docs/MODELS-INTEGRATION.md) | Alfa BYOK/custom/Codex model credentials |+| [docs/MCP.md](./docs/MCP.md) | MCP/OAuth tools, discovery, workflow memory and security internals |+| [docs/CHATGPT-PLUGIN.md](./docs/CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup + architecture/OAuth/tool/file diagrams |+| [docs/FAQ.md](./docs/FAQ.md) | Security, product and operator boundaries |+| [docs/TROUBLESHOOTING.md](./docs/TROUBLESHOOTING.md) | Current symptom → cause → supported recovery |+| [SECURITY.md](./SECURITY.md) | Security posture and vulnerability reporting |## Statusdiff --git a/SECURITY.md b/SECURITY.mdindex 8aeb2942..dce56db9 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -1,135 +1,154 @@# Security PolicyManef Shell OS is Public Alpha / Developer Preview software. It has not had a-third-party security audit. Only the latest commit on `main` is supported; there-are no release branches yet.+third-party security audit. Only the latest commit on `main` is supported; there are no+release branches yet.## Reporting a vulnerability-Please do not open a public issue for security vulnerabilities.+Do not open a public issue containing exploit details or secrets. Use GitHub's private+vulnerability-reporting flow for this repository. Include the affected commit, reproduction+steps, impact and sanitized logs. If private reporting is unavailable, open only a minimal+public issue asking the maintainer to enable private advisory intake.-Use GitHub's private vulnerability reporting flow for this repository:--1. Open the repository on GitHub.-2. Go to **Security** → **Report a vulnerability**.-3. Include the affected version or commit, reproduction steps, impact, and any- logs with secrets removed.--If private vulnerability reporting is unavailable, open a minimal public issue-asking the maintainer to enable private advisory intake. Do not include exploit-details, passwords, session secrets, API keys, private file contents, or full-environment files in that public issue.+Never post passwords, session secrets, API keys, bearer tokens, private file contents,+Camoufox profile data or full environment files.## Deployment warning-An authenticated MSO session can run commands and access files as the Linux user+An authenticated MSO owner session can read allowed files and run commands as the Linux userthat owns the process. Treat it like SSH in a browser.- Run MSO as a dedicated non-root user.-- Prefer Tailscale or another VPN for real deployments.-- If using a public domain, put HTTPS, firewall rules, and strict access control- in front of the app.+- Prefer Tailscale/VPN for a real deployment.+- Otherwise use HTTPS plus firewall/allowlist controls in front of the app.- Do not expose the raw app port directly to the public internet.-- Do not commit `.env.local`, API keys, or data from `~/.mso`.-- Use demo mode (`NEXT_PUBLIC_OS_DEMO=1`) for public showcases.+- Keep `OS_FS_WRITE_ROOTS` narrow and review read roots deliberately.+- Do not commit `.env.local`, model credentials or data under `~/.mso`.+- Use `NEXT_PUBLIC_OS_DEMO=1` only in a separate mock-only public demo checkout.++## Authentication and sessions++The owner login is password + device approval. A correct password on a new browser creates a+pending device; an already-approved device or the server must approve it before a normal+session is issued. The browser session cookie is HMAC signed and `Secure`.++Changing `OS_SESSION_SECRET` invalidates existing sessions. Removing a device from the+allowlist revokes that browser. Device approval is an allowlist, not standards-based MFA.++## Filesystem and command boundary++File routes inherit `OS_FS_READ_ROOTS` / `OS_FS_WRITE_ROOTS`, canonical containment checks+and a credential denylist. MSO's own private state, `.env*`, SSH/GPG material and other+sensitive-home paths are hidden/refused unless the supervised sensitive-path escape hatch is+explicitly enabled.++`exec.run` / MCP `exec_run` runs as the MSO Linux user. The destructive-command matcher is a+short accident tripwire, not a sandbox. Interactive Terminal PTYs are even more direct: raw+keystrokes cannot be reliably parsed into commands, so authentication and PTY session+lifecycle—not the one-shot command matcher—are the boundary.++## Alfa model data++Alfa credentials are stored server-side in private host config. BYOK means the owner controls+the credential; it does **not** mean model traffic stays on the VPS. Messages and tool+context included in a model request go to the selected provider.++Alfa's read tools can supply file/process/log data to the model. Host mutations use the+visible Alfa approval-card boundary. Treat file/log contents as untrusted prompt input and+review the actual proposed mutation, not only the model's explanation.++## MCP / ChatGPT / external AI clients++The MCP server is off unless `OS_MCP_ENABLED=1`. External clients authenticate through MSO's+OAuth 2.1 + PKCE flow and receive a bearer with `read`, `write` or `exec` scope, capped by+`OS_MCP_MAX_SCOPE`.++An MCP bearer is a standing credential. At `exec` scope it can execute host commands as the+MSO user. Scope is rechecked on every tool call. Tool inputs and results are also processed+by the connected AI client/provider according to that product's data controls.++Use `read` unless a workflow truly needs more, revoke stale clients in Settings → MCP and+refresh the client tool snapshot when MSO's toolset signature changes. See+[`docs/MCP.md`](./docs/MCP.md) and [`docs/CHATGPT-PLUGIN.md`](./docs/CHATGPT-PLUGIN.md).++`browser_status` deliberately never returns Camoufox's viewer password or profile data.+`screen_capture` is limited to MSO itself, not arbitrary web pages.## Managed applications and per-app origins-MSO can manage separate applications that already run on the box (Hermes, OpenClaw)-and frame each one's own dashboard in a window. Those apps keep their own runtime,-config, data and privileges; MSO talks to them through their CLIs, their HTTP surfaces-and systemd, and writes nothing into their state directories.--The dashboards are framed with `allow-same-origin`, because their SPAs do not boot-without it. On the cockpit's own origin that also made upstream JavaScript same-origin-**with the cockpit**, so it could take `window.top.fetch` and call `/api/v1/exec/run`-with the signed-in session. No Content-Security-Policy can prevent that: a policy binds-a realm, not a reference held across realms. Each dashboard is therefore served from its-own host on the same process (`hermes.os.<domain>`, `openclaw.os.<domain>`), which makes-`window.top` cross-origin and opaque. Middleware enforces the other half: on one of those-hosts **every** path is rewritten into that app's dashboard proxy (and `/_next/*` is refused-outright), so no cockpit route — not `/api/v1/exec/run`, not `/api/auth/*`, not a page — can-be reached there at all.--**This boundary is browser-realm only.** A plugin or extension installed into Hermes or-OpenClaw runs inside that daemon, with that daemon's privileges, and those daemons execute-shell commands on the host. Installing an untrusted plugin into either application is-handing it arbitrary code execution as the user that runs it. Separate origins do not-change that, and neither does anything else MSO can do.--Operational rules for anyone maintaining a split-origin deployment:--- **Never create a `*.os.<domain>` wildcard record, and never point a new- `X.os.<domain>` name at the app port** without deciding what serves it. The session- cookie is widened to that whole namespace. MSO 404s unknown names in the namespace as a- backstop, but DNS is the primary control.-- **`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN` are one- decision.** Set both or neither. The second alone widens the session cookie to every- host under the domain while each of them still serves the full cockpit API.-- **`SameSite=Strict` keeps working only while the app hosts share the cockpit's- registrable domain.** Moving one to a different domain makes those requests cross-site- and the framed dashboard stops authenticating; that is a design change, not a config- tweak.-- Leaving both variables unset is the default and is safe: MSO then serves no upstream- dashboard at all, and the feature windows fall back to their CLI view. The old- single-origin mode (dashboards under a path on the cockpit origin) has been removed —- it handed upstream JS a realm holding your session, and no header could take it back.-- **MSO expects HTTPS** (or `localhost`). The session cookie is `Secure`, so a plain-http- deployment on an IP cannot log in at all — that is deliberate, not a bug to work around.-- A managed-app **backup** copies that application's state directory into- `~/.mso/backups/<app>/<timestamp>/`, including any credentials the application keeps there —- `~/.openclaw/credentials/` and `identity/` are in scope, and so is anything secret in- `openclaw.json` or under `~/.hermes`. Treat those copies exactly like the application's own- config: never publish them, and include them when you rotate that application's secrets. The- copy directory is created `0700` and the manifest `0600`, but nothing encrypts the contents.- Symlinks are skipped rather than followed, so a link inside the state dir cannot pull bytes in- from outside it, and a restore cannot be aimed outside the tree by an absolute link- ([docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) §6).+MSO can manage Hermes and OpenClaw as separate applications. They keep their own runtime,+config, state and host privileges. MSO can install them, control lifecycle, read logs,+update, back up, restore and conservatively uninstall through explicit managed-app paths.+Restore is the intentional exception to the general rule that MSO should not edit another+app's state: it is heavily gated, requires the app stopped, creates a pre-restore safety+snapshot and writes only into the verified state directory.-## In scope+Vendor dashboards require `allow-same-origin` to function. Running that JavaScript on the+cockpit origin would give it the owner's browser realm/session. MSO therefore has no+supported same-origin dashboard mode.-- Auth bypass: session forgery without `OS_SESSION_SECRET`, device-approval- bypass, or rate-limit defeat that enables practical brute force.-- Filesystem jail escape: reading or writing outside `OS_FS_READ_ROOTS` /- `OS_FS_WRITE_ROOTS`, or reaching denied credential material such as `.env*` or- `~/.mso/*` through the file APIs.-- Unauthenticated access to live host routes such as `/api/v1/*`,- `/api/assistant`, `/api/config`, or `/api/auth/devices`.-- CSRF or clickjacking that triggers host actions cross-origin.-- Escape from a managed-app origin: reaching any cockpit route, the cockpit realm, or a- sibling managed app's origin from inside a framed dashboard on `hermes.os.<domain>` /- `openclaw.os.<domain>`, or getting the proxy to fetch something other than its own- loopback upstream.+The safe default is **no embedded vendor dashboard**. To embed dashboards, set both+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN` and give each app a+separate hostname, for example:-## Out of scope+```text+mso.example.com+hermes.mso.example.com+openclaw.mso.example.com+```++On a managed-app hostname every request is routed only into that app's proxy and cockpit+pages/API/static chunks are not served there. Keep DNS explicit; do not point arbitrary+wildcards inside the shared cookie domain at MSO.-- An already-authenticated owner session doing documented owner actions such as- running commands or accessing files within configured roots.-- Bypassing the destructive-command guard with shell tricks. It is an accident- tripwire, not a sandbox.-- Deployments that ignore the minimum posture: non-root user, strong secrets,- Tailscale/VPN or protected HTTPS, and narrow filesystem roots.-- What a plugin installed into Hermes or OpenClaw can do inside that daemon, including- running host commands. That is the application's trust model, not MSO's boundary.-- Single-origin mode (`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` unset) behaving as- documented: a framed dashboard's JavaScript can reach the cockpit realm there. Serving- the dashboards from their own origins is the fix, and it is a deployment choice.+This is a browser-realm boundary only. A plugin installed **inside Hermes or OpenClaw**+runs with that daemon's host privileges. Installing an untrusted daemon plugin is equivalent+to trusting code with that user's capabilities; iframe origin separation does not sandbox+it.-## Key rotation+## Managed-app backups-BYOK AI credentials are stored server-side in `~/.mso/config.json`, never in-the client bundle. To rotate a key, stop MSO, edit the config file or remove the-provider from Settings → AI, then restart/sign in again.+Managed-app snapshots live under `~/.mso/backups/<app>/<timestamp>/` and can contain the+application's own credentials, pairings and history. Treat those copies like the source+state. They are private but not encrypted by MSO.-To rotate auth secrets:+Backups skip symlinks and reinstallable/cache directories. Restore validates the manifest,+app identity, state path and symlink collisions before writing, then creates an additional+`pre-restore` safety snapshot. See [`docs/MANAGED-APPS.md`](./docs/MANAGED-APPS.md).-- Change `OS_SESSION_SECRET` and restart to invalidate sessions.-- Change `OS_LOGIN_PASSWORD` and restart to require the new password.-- Remove entries from `~/.mso/auth-devices.json` to revoke devices.+## In scope-## Audit log retention+- auth/session/device-approval bypass;+- practical login rate-limit defeat;+- filesystem-jail or credential-denylist escape;+- unauthenticated access to live host/config routes;+- CSRF/clickjacking that triggers owner host actions;+- MCP scope/OAuth bypass or bearer validation failure;+- managed-app origin escape into the cockpit or a sibling app;+- managed-app proxy SSRF/target escape;+- backup/restore path escape or symlink-following writes;+- secret leakage through logs, tool descriptors, temporary shares or browser-status APIs.++## Out of scope-The JSONL audit trail defaults to `~/.mso/audit.log` and can grow over time.-Use logrotate or your normal host log retention system. Do not publish audit-logs without checking for private paths, command names, or other sensitive-context.+- an already-authenticated owner intentionally using documented owner capabilities;+- bypassing the one-shot destructive-command regex after the user already granted shell+ execution—it is not presented as a sandbox;+- deployments that ignore the minimum documented posture;+- what trusted/untrusted code installed *inside* Hermes/OpenClaw can do with that daemon's+ own host permissions;+- prompt/model quality issues that do not bypass MSO's server-side permission boundary.++## Rotation and retention++- change `OS_SESSION_SECRET` to invalidate browser sessions;+- change `OS_LOGIN_PASSWORD` to rotate the owner password;+- remove entries from `~/.mso/auth-devices.json` to revoke browsers;+- remove/revoke MCP tokens from Settings → MCP;+- rotate provider credentials from Settings → AI or the corresponding environment source;+- rotate managed-app credentials if a state snapshot containing them was exposed.++`~/.mso/audit.log` is append-oriented local forensic data and can grow. Use normal host log+retention/rotation and inspect it before sharing because paths and command context can be+sensitive.diff --git a/claude-skills/mso-apps/SKILL.md b/claude-skills/mso-apps/SKILL.mdindex 94979c51..b734ec4b 100644--- a/claude-skills/mso-apps/SKILL.md+++ b/claude-skills/mso-apps/SKILL.md@@ -34,7 +34,7 @@ When the current environment exposes bounded MSO tools, use those first. The CLI| Reel Editor | timeline/render | browser/client; shell only for explicit media preprocessing || Settings | devices/provider/theme/server mode | dedicated settings/UI; never expose secrets || Assistant | chat + tools + skills | `/api/assistant`; trusted skills only |-| Managed apps | status/logs/start/stop/restart/backup | bounded managed-app capability |+| Managed apps | detect/install/status/logs/start/stop/restart/backup/update/restore/uninstall/jobs | bounded list/log/power for direct actions; MSO Details/API/CLI for long-running update/install/restore/uninstall workflows || Runtime apps | app-defined actions | use declared app capability; command runtimes are full shell risk |## Important boundariesdiff --git a/claude-skills/mso-deploy/SKILL.md b/claude-skills/mso-deploy/SKILL.mdindex b0788119..47b049cb 100644--- a/claude-skills/mso-deploy/SKILL.md+++ b/claude-skills/mso-deploy/SKILL.md@@ -13,13 +13,13 @@ Call `workflow_start` with the complete change and deployment intent, then carry## Required order-1. Targeted tests and `bun run verify`.-2. `bash scripts/verify-build.sh` for an out-of-tree compile check.-3. Review clean diff and append the shipped reasoning to `docs/PROGRESS.md`.-4. Run `bun run ship "<conventional commit>"`. From MCP, the script automatically returns after handing build/restart to `mso-self-update.service`; that return means **scheduled**, not deployed.-5. Poll `systemctl --user is-active mso-self-update.service` and `~/.mso/self-update.log` until the unit is inactive and the log ends in `UPDATE OK`. Never use fixed `sleep` delays as proof.-6. Verify `mso.service` is active, `/api/health` reports the new build, and CSS/JS chunks referenced by live HTML serve the correct MIME types.-7. Run the live smoke test and `screen_capture` for visual proof.-8. Call `workflow_finish(success=true)` only after all checks pass.+1. Run the smallest targeted tests, then `bun run verify` (which includes documentation/skill checks).+2. Review `git diff --check`, the final diff/stat, and append shipped reasoning to `docs/PROGRESS.md`.+3. Run `bun run ship "<conventional commit>"`. Its pre-push gate performs the authoritative out-of-tree build for the committed SHA; do not run a redundant production build first.+4. From MCP, `ship` hands the in-place build/replacement to `mso-self-update.service`; that handoff means **scheduled**, not deployed.+5. Poll `systemctl --user is-active mso-self-update.service` and `~/.mso/self-update.log` until the unit is inactive and the log ends in `UPDATE OK`. Never use fixed sleeps as proof.+6. Verify `mso.service` is active, `/api/health` reports the new build, and CSS/JS chunks referenced by live HTML have the expected MIME types.+7. Run the live smoke test and `screen_capture` when UI changed.+8. Call `workflow_finish(success=true)` only after all requested runtime proof passes.`git push` alone is not deployment. The production checkout's `.next` is live: build then restart immediately, never restart before build, and never leave an in-place build without the matching restart. `nohup` is not a detach boundary inside `mso.service`; the service manager terminates the whole cgroup. The owner transient user unit is the supported long-running release boundary.diff --git a/claude-skills/mso-list/SKILL.md b/claude-skills/mso-list/SKILL.mdindex 7d2a7cbd..fd051beb 100644--- a/claude-skills/mso-list/SKILL.md+++ b/claude-skills/mso-list/SKILL.md@@ -32,7 +32,7 @@ A route not probed is **UNPROBED**, never green by association. Dynamic app jobs| Terminal / runtime command apps | full host execution; highest-risk fallback || System Monitor | stats/processes; maintenance routes are separate || Browser | Camoufox status/power; secret viewer credential is human-only |-| Managed Apps | list/status/logs/start/stop/restart/backup/update/install/jobs |+| Managed Apps | list/status/logs/start/stop/restart/backup/update/install/restore/uninstall/jobs || Image/Media Studio | shared editor document registry; browser rendering || Settings / Assistant | configuration, devices, models, tools, trusted skills |diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex f1657270..c35173ec 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -1,412 +1,222 @@-# mso (Manef Shell OS) — Architecture--> ## ⚠ HISTORY, NOT CURRENT STATE->-> This file was accurate on **2026-07-25** and has NOT been maintained since. Several-> passages are now false, and at least one was dangerous: it described a managed-app-> "single-origin mode" as a supported fallback after the code had removed it *because-> it was a privilege-escalation hole*. Known-wrong areas: the Browser app (a retired-> Playwright sidecar is described as live), workspace modes (reversed — Hermes and-> OpenClaw are ordinary apps), the upstream feature-discovery pipeline (deleted), the-> slice list, and the `/api/v1` route list.->-> **For what exists today, read `PROGRESS.md` (newest entry at top) and the code.**-> This file is kept for the REASONING it records — why the origin split exists, why-> the CSP is shaped as it is — which remains valuable and is hard to recover.->-> The earlier Convex + Control-Room-agent design was removed: mso runs **as a host-> process** and talks to its own machine directly. No database, no external agent.-> Its reconciliation note was deleted on 2026-08-10 —-> `git show 421ab7f:docs/DESIGN-RECONCILE.md` — because the `mock-os/` tree it compared-> against is gone; the early `PROGRESS.md` phases still record the shape.--## What it is--A single Next.js 16 app that you run on a VPS as a normal (non-root) user. It-serves a desktop/iOS-style web UI and exposes a small host API (`/api/v1`) that-does fs / exec / sys work straight through Node `fs` + `child_process`, bounded-by realpath-checked roots. Auth is a signed-cookie session. Optional Playwright-service powers the Browser app. It also acts as the control plane for separate-applications already on the box (Hermes, OpenClaw) — managing them through their own-CLIs and HTTP surfaces, and framing each one's dashboard from an origin of its own.-+# MSO architecture++> **Current reference.** This document describes `main` as of the current checkout.+> `docs/PROGRESS.md` records why the architecture changed; dated plans and audits are+> historical inputs, not runtime contracts.++MSO is one self-hosted Next.js application running as a non-root Linux user. The+browser UI, CLI, Alfa assistant, and optional MCP connector all converge on the same+bounded host layer rather than each implementing filesystem or process access.++```mermaid+flowchart LR+ B[Browser / phone] -->|HTTPS + signed session| N[MSO Next.js :4005]+ C[CLI `mso`] -->|local HTTP + approved device session| N+ 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 --> D[project + skill discovery]+ H --> F[filesystem jail]+ H --> P[PTY / exec / system metrics]+ H --> MA[managed apps]+ MA --> HE[Hermes]+ MA --> OC[OpenClaw]+ N --> CF[Camoufox viewer proxy]```-phone / browser ──https──> mso.rahmanef.com ─────────┐- signed-cookie auth (lib/auth) │- ├─> mso (Next.js :4005) ──┬── lib/host → Node fs / child_process (host, non-root)- the app iframe ──https──> hermes.mso.rahmanef.com ──┤ ONE process, 3 origins └── os-browser (Playwright :4002, loopback, optional)- the app iframe ──https──> openclaw.mso.rahmanef.com ┘- ▲ proxy.ts rewrites EVERY path on an app host into- /api/v1/managed-apps/<id>/proxy → loopback Hermes :9119 /- OpenClaw :18789. Nothing else is reachable there — the cockpit- API, /api/auth/* and its pages are not routes on those hosts- (and /_next/* is refused outright)++## 1. Runtime boundaries++| Boundary | Authority | Notes |+|---|---|---|+| Browser owner session | `lib/auth/*`, `/api/auth/*` | Password + approved device + HMAC-signed cookie. |+| Host operations | `lib/host/*` | Filesystem roots, credential denylist, process/system operations, audit. |+| Web host API | `/api/v1/*` | Session-gated routes; routes delegate into `lib/host`. |+| CLI | `bin/mso` | Another frontend over the same web API; `docs/CLI.md` is generated from it. |+| 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. |+| Remote browser | `camoufox-vnc.service` + `scripts/camoufox-vnc-service` | Real Camoufox Firefox over noVNC; no legacy Playwright browser service. |++There is no application database. Server-side persistence is small owner-local state+under `~/.mso/` plus the independent state directories owned by managed applications.+Window layout and several shell preferences are browser-local or synchronized through the+existing preference store.++## 2. Repository layout++```text+app/ Next.js routes, OAuth and public install surface+frontend/slices/ vertical application slices+ appshell/ generic shell framework+ features/ shell features+ os-shell/ MSO manifest + capability adapters+lib/auth/ login/session/device approval+lib/host/ bounded host capability implementation+lib/mcp/ OAuth/MCP tool catalog and dispatcher+lib/managed-apps/ Hermes/OpenClaw lifecycle/update/backup/proxy+lib/skills/ trusted skill discovery and semantic search+scripts/ install, release, checks and service helpers+claude-skills/ official trusted operational playbooks+docs/ current references + clearly marked historical docs```-Traefik points all three hosts at the same `172.17.0.1:4005` with `passHostHeader:-true`; the Host header is what picks the branch. See **Managed applications** below-for why the dashboards need origins of their own.+Cross-slice imports go through the public slice barrels. Host-facing code is centralized:+a client slice calls its adapter/API contract, an API route calls `lib/host`, and neither+route nor component reimplements path-jail or process guards.-## Layout (mirrors `resources/` so slices stay lift-ready)+## 3. AppShell-```-mso/-├── app/ Next 16 App Router-│ ├── layout.tsx fonts + theme + providers-│ ├── globals.css Tailwind 4 + glass theme tokens-│ ├── [[...slug]]/page.tsx one catch-all route → os-root → <OsDesktop/> (auth-gated)-│ └── api/-│ ├── v1/ host Cloud API — fs · exec · sys · term · stock · browser ·-│ │ managed-apps (state/actions/logs/features + dashboard proxy)-│ ├── health/ tiny liveness probe (200 OK) for uptime checks-│ ├── auth/ login · logout · me · devices-│ ├── config/ BYOK AI key (read/write ~/.mso/config.json)-│ └── assistant/ Claude SSE stream (BYOK)-├── components/ui/ shadcn (new-york) primitives — app-wide-├── components/shared/ cross-slice primitives (file-tree, …) via @/shared/*-├── lib/-│ ├── host/ THE host facade — every /api/v1 route goes through here-│ │ ├── fs.ts list/read/write/mkdir/move/copy/remove/usage/upload/search-│ │ ├── exec.ts one-shot shell + destructive-command guard-│ │ ├── pty.ts interactive PTY sessions (node-pty) behind /api/v1/term/*-│ │ ├── sys.ts cpu/mem/disk/uptime/processes-│ │ ├── host-error.ts / api-error.ts HostError + apiError + readJson/requireString kit-│ │ ├── paths.ts read/write root jail + realpath bounds check-│ │ ├── audit.ts append-only JSONL audit (~/.mso/audit.log) — writes serialized through a chained promise so bursty callers land in submission order-│ │ ├── rate-limit.ts fixed-window in-memory limiter-│ │ └── index.ts barrel-│ ├── auth/ session.ts (HMAC sign/verify) · require-session.ts ·-│ │ device-store.ts (~/.mso/auth-devices.json)-│ ├── config/ store.ts (~/.mso/config.json — BYOK key + model)-│ ├── managed-apps/ Hermes/OpenClaw control plane: catalog · manager · runner ·-│ │ features + feature-parser · and the dashboard reverse proxy-│ │ (origin · proxy-csp · proxy-headers · proxy-html)-│ ├── agent/ server.ts — server-only client for the os-browser service-│ ├── os-api/ the UI ↔ host boundary: types · MockAdapter · HttpAdapter-│ ├── ai/ Claude stream helper-│ ├── appearance/ theme/accent/dir/wallpaper/server-mode store-│ └── demo.ts IS_DEMO flag (NEXT_PUBLIC_OS_DEMO=1 → force mock)-├── frontend/slices/<slug>/ app slices (UI + types + config + metadata trio), plus:-│ ├── appshell/ generic shell framework — <AppShell manifest>, window-│ │ runtime, desktop+mobile surfaces, registries, ResponsiveProvider,-│ │ primitives (MasterDetail · AppFrame · WindowPreview · useResponsive ·-│ │ useFocusedHotkey · useViewportWindow), pub/sub buses.-│ │ Brand/feature-agnostic → lifts to rr.-│ ├── shell-search / shell-inspector / shell-notifications / shell-control-center /-│ │ shell-widgets pluggable features mounted via <Slot region>-│ ├── managed-apps/ Hermes/OpenClaw surfaces: the manage window, per-feature-│ │ windows (iframe + CLI fallback), icons, workspace app lists-│ └── os-shell/ mso consumer: shell.manifest.ts (brand+apps+features)-│ + re-export barrel (@/features/os-shell)-├── os-browser/ Playwright Chromium service (gitignored, deploy-local)-├── public/demo-media/ real sample media so the mock demo can open files-├── scripts/ approve-device.js · gen-demo-media.mjs · …-└── docs/ proxy.ts next.config.mjs tsconfig.json ...-```+`frontend/slices/appshell/` is the generic shell framework. `os-shell` is the thin MSO+consumer that supplies brand, app manifest, shell choice and capabilities.-Path aliases (tsconfig): `@/*` → root, `@/features/*` → `frontend/slices/*`,-`@/shared/*` → `components/shared` + `lib/shared`. Same shape as `resources/` so-a slice lifts by copy, no rewrite.+Current AppShell feature directories are:-## Runtime — one tier+- `clipboard`+- `control-center`+- `desktop-icons`+- `force-quit`+- `inspector`+- `lock-screen`+- `notifications`+- `search`+- `shortcut-help`+- `widgets`-There is no backend tier. The browser hits same-origin route handlers; the-handlers call `lib/host`; `lib/host` touches the kernel. That's it.+`desktop-icons` and `force-quit` are shell infrastructure rather than ordinary slot+features, but they live under the same feature tree. See `docs/SLICE-CATALOG.md` for the+current slice inventory; its counts are checked by `scripts/check-docs.mjs`.-```-browser- │ React 19 + os-shell window manager (module store, drag/resize 100% client)- ▼-/api/v1/* Next route handlers (server) every route: verifyAuth() first- │ fs · exec · sys · term · stock · browser- ▼-lib/host fs / child_process, root-jailed, realpath-checked, audited, rate-limited- ▼-host kernel (as the unprivileged service user — NOT root)+The shell supports macOS, Windows, iOS, Android and Dashboard presentation layers over the+same app/window state. Phone portrait resolves to a mobile shell; phone landscape can use+the desktop surface according to the responsive policy. App windows themselves remain the+same feature code.++## 4. Addressable routing without page-per-app duplication++MSO uses one catch-all application route, `app/[[...slug]]/page.tsx`. The focused app is+mirrored into the URL while window state remains client-side. App slugs are assigned in+`frontend/slices/os-shell/shell.manifest.ts`.++The shell uses the History API for focus/open URL synchronization instead of treating every+window operation as a server navigation. Reserved framework paths are never allowed to fall+through the app catch-all.++## 5. Host API and filesystem model++`/api/v1/*` is the authenticated host API. Important families include:++- `fs/*` — list/read/search/write/upload/move/copy/delete/zip/usage+- `exec/run` — one-shot captured command execution+- `term/*` — interactive PTY lifecycle and streaming+- `sys/*` — stats, processes, cleanup, audit and self-update+- `camoufox/*` — browser service/session control+- `managed-apps/*` — Hermes/OpenClaw lifecycle, jobs, backups and proxying++`OS_FS_READ_ROOTS` and `OS_FS_WRITE_ROOTS` constrain filesystem access. The implementation+uses canonical path/containment checks and additionally blocks credential material such as+MSO's own state, `.env*`, SSH/GPG material and other sensitive-home paths unless a supervised+operator explicitly enables the documented escape hatch.++Interactive PTYs are intentionally stronger than filtered one-shot exec. A PTY is a real+login shell; raw keystrokes do not have reliable command boundaries. Authentication and+session lifecycle are therefore the boundary, not the one-shot destructive-command regex.++## 6. Alfa versus MCP++Alfa and MCP are two separate model-facing catalogs on purpose.++**Alfa** runs inside the authenticated MSO UI. Its tool catalog lives under+`frontend/slices/assistant/host-tools/`. Read tools execute immediately; host mutations+park a visible Approve/Deny card. The complete semantic contract is+`frontend/slices/assistant/CONTRACT.md`.++**MCP** is for external clients such as ChatGPT, Claude.ai and Cursor. Its catalog lives in+`lib/mcp/`; access is controlled by the OAuth token scope rather than Alfa approval cards.+At the current toolset it exposes 28 tools: 15 read, 10 write and 3 exec. Project-specific+function names remain data behind `project_capabilities` / `project_function_call`, so one+project cannot dynamically rewrite the global MCP tool prefix.++See `docs/MCP.md` for protocol/security internals and `docs/CHATGPT-PLUGIN.md` for the+ChatGPT-facing setup and diagrams.++## 7. Project and skill discovery++MSO can discover projects across configured containers instead of assuming a single+`~/projects` tree. Enumeration and resolution share the same containment/ownership checks,+are bounded, and return truthful truncation + continuation metadata when a scan cannot+finish in one pass.++A project can opt into two additional declarations:++- `.mcp.json` — presence only is reported; MSO never exposes its contents or automatically+ connects to arbitrary project MCP servers.+- `.mso/functions.json` — a bounded version-1 manifest of fixed-argv functions. Public+ schemas are visible at read scope; execution always requires MCP `exec` scope.++Skills are merged from official/operator/bundled roots plus eligible per-project roots.+Trust is derived from provenance, ownership and containment; untrusted instructions are not+fed directly to the model. See `skills/README.md`.++## 8. Managed applications++Hermes and OpenClaw are managed, not embedded into MSO's process model. MSO can detect,+install, start/stop/restart, read logs, update, back up, restore and conservatively uninstall+them. Long-running install/update/uninstall/restore work is represented as jobs with bounded+logs and status.++Their vendor dashboards are optional. The safe default is no embedded dashboard. A+split-origin deployment opts in by setting both `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and+`OS_SESSION_COOKIE_DOMAIN`, giving each dashboard its own hostname while the same MSO+process proxies its loopback upstream. There is no supported same-origin dashboard mode.++There is also no runtime navigation/feature scraping of Hermes/OpenClaw bundles. The old+`/features` route and parser pipeline were removed; current MSO presents the vendor's own+dashboard as one surface plus MSO's Details management surface.++See `docs/MANAGED-APPS.md`, `docs/HERMES-INTEGRATION.md` and+`docs/OPENCLAW-INTEGRATION.md`.++## 9. Camoufox Browser++The Browser app is a real Camoufox Firefox session on a headless X display. It is streamed+through noVNC and proxied under `/camoufox-vnc/*` after normal MSO session verification.+The service is a systemd **user** unit and is deliberately off by default; the UI starts it+when needed. `scripts/camoufox-vnc-service` owns the launch contract.++The logged-in Firefox profile is intentionally outside `~/.mso`, under the user's local+share tree. It can hold live account cookies. Browser status tools never return the VNC+password or profile contents.++## 10. Build and release architecture++Production is a systemd deployment, not a webhook deployment. `git push` alone changes no+running bytes. The supported developer release command is:++```bash+bun run ship "docs: describe the verified change"```-- **Hot path is client-only.** Window drag/resize never re-renders the desktop:- state lives in a module-level store read via `useSyncExternalStore`; only the- dragged window subscribes to its own rect.-- **Persistence is local.** Window layout + installed-app registry → `localStorage`- (the demo also persists its mock FS to `localStorage`, key `mso:demo-fs`).- Device allowlist → `~/.mso/auth-devices.json`; BYOK key/model →- `~/.mso/config.json`; audit trail → `~/.mso/audit.log`.-- **Apps lazy-mount.** A window mounts its app component only when opened.-- **Shared shell primitives.** `MasterDetail` + `AppFrame` + `useResponsive`- back the responsive layout of system-monitor / assistant / os-settings (more- apps to follow). `<WindowPreview>` powers the mobile app switcher without- re-mounting the live app (kills the terminal double-PTY bug).- `useFocusedHotkey()` scopes keystrokes to the focused window so background- apps don't steal shortcuts.--## The host boundary — `lib/host` + `lib/os-api`--`lib/os-api` is the UI-facing contract (os-rr Cloud API shape): one `OsApi`-interface, two adapters —--- **MockAdapter** — in-browser simulation. Default + forced when `IS_DEMO`. The- whole OS is demoable with zero host.-- **HttpAdapter** — `fetch` to same-origin `/api/v1`, used in **Live** mode- (Settings → Server). Sends the session cookie; no token in JS.--Server side, **every `/api/v1` route calls `verifyAuth()` then goes through-`lib/host`** — routes never call `fs`/`child_process` directly. `lib/host`-enforces:--- **FS jail** — `OS_FS_READ_ROOTS` / `OS_FS_WRITE_ROOTS` (default: home + `~/projects`).- Symlinks are realpath-resolved **before** the bounds check; a root dir itself- refuses writes. READ may be widened to `/` (read-only browse) without widening WRITE.-- **Exec guard** — `destructiveReason()` refuses catastrophic commands- (`rm -rf /`, `mkfs`, `dd of=/dev/…`, fork bomb, `chmod/chown -R /`) unless- `OS_EXEC_ALLOW_DESTRUCTIVE=1`. Exec itself stays one-shot — the interactive- shell is the PTY (below).-- **Rate limit** — exec is fixed-window limited per device.-- **Audit** — exec/fs-mutation/term/browser/auth actions append to the JSONL log.--### Terminal PTY — `/api/v1/term/*`--Live Terminal sessions are real PTYs (`node-pty`), managed by `lib/host/pty.ts`:-spawn the owner's login shell, stream output as SSE (`/api/v1/term/stream`,-ring-buffered so a `Last-Event-ID` reconnect resumes exactly where it dropped),-plus `open`/`input`/`resize`/`close` routes. 8 concurrent sessions max, 30-min-idle reap; `term.open`/`term.close` are audited (keystrokes are not — high-volume, and the owner has a full shell by design). The exec destructive filter-does **not** apply here, by design: a pty carries raw keystrokes with no command-boundary to inspect, and an interactive shell composes commands from fragments-anyway — the gate is the same signed session + approved device as every route.-Mock mode never touches it; if the PTY fails the Terminal app falls back to-one-shot exec.--### Stock search — `/api/v1/stock/search`--A thin server-side proxy for the image picker's Stock tab: keyless **Openverse**-by default, **Unsplash** when `OS_UNSPLASH_ACCESS_KEY` is set. The key never-reaches the client.--### API error contract--Every `/api/v1` route returns errors as `{ error: string }` via `apiError()`-(`lib/host/api-error.ts`): curated `HostError` messages pass through as 400-(they're client-safe UX); everything else is masked to "Operation failed" and-logged server-side with the route name, so raw Node errors (ENOENT/EACCES with-absolute paths) never leak. Inputs are validated by a dependency-free-`readJson`/`requireString`/`requireInt` kit — no zod.--## Auth (`lib/auth`)--Signed-cookie sessions — no Convex, no Clerk.--- **Factor 1**: `OS_LOGIN_PASSWORD` (weak/memorable), checked constant-time.-- **Factor 2**: the device must be in the approved allowlist- (`~/.mso/auth-devices.json`). A correct password on a new device registers- it `pending`; **no session is issued until approved**- (`node scripts/approve-device.js <deviceId> "name"`).-- On success: an HMAC-SHA256 cookie signed with `OS_SESSION_SECRET` (≥32 bytes),- `httpOnly` + `Secure` + `SameSite=strict`, default 24h.-- `requireSession()` verifies signature + expiry only (device approval is a- login-time gate, not re-checked per request). `getSessionActor()` → `device_id`- for the audit trail.--## Managed applications — Hermes and OpenClaw (`lib/managed-apps`)--MSO is the shell / control plane. Hermes and OpenClaw stay **separate applications**:-their own runtime, config, data, versions, health, logs and backups. MSO does not copy,-fork or merge their source, does not scrape their DOM, and writes nothing under-`~/.hermes/` or `~/.openclaw/` — reading those trees is how discovery works, but the-only writes are into `~/.mso/`. Everything else goes through the app's own CLI, its-own HTTP surface, or systemd/docker. Full operator guide: `docs/MANAGED-APPS.md`.--- **catalog** (`lib/managed-apps/catalog.ts:13`) — one definition per app: `command`,- candidate `serviceNames`, candidate `containerNames`, the **loopback** dashboard URL,- the state dir name, and env overrides for a non-default install (`HERMES_HOME`,- `HERMES_WEB_DIST`, `OPENCLAW_CONTROL_UI_DIST`, `*_DASHBOARD_URL`).-- **manager** (`lib/managed-apps/manager.ts`) — detect → state → health → version →- actions → backup → logs. Detection asks `systemctl [--user] show -p LoadState -p ActiveState`- per candidate unit, then `docker ps -a`, then `which <command>`; the detected type decides which- actions exist at all (systemd/docker → start·stop·restart·backup, a bare package →- backup only). `show` rather than `is-active` because `is-active` prints `inactive` for a unit- that does not exist, so a phantom name would win detection forever (that was a live defect:- OpenClaw read `stopped` while serving). Health is `GET <dashboardUrl>/health`; version is the- first line of `<command> --version`. One in-flight action per app (`manager.ts:186`), so a- double-click cannot interleave a stop with a restart. Live now: both apps `systemd` / `running`- / `healthy: true` through `listManagedApps()`.-- **backup** (`manager.ts:141`) copies the app's state dir (`HERMES_HOME` honoured) to- `~/.mso/backups/<id>/<timestamp>/` (per-app dir 0700, `manifest.json` 0600), skipping- `node_modules`/`.venv`/`venv`/`__pycache__`/`.git`/`.cache`/`backups` and **skipping symlinks**- rather than following or recreating them — following one copies bytes from outside the app,- recreating an absolute one aims a future restore outside the tree; the manifest records both- counts. It is a read of their state, never a write to it. 366 MB and 237 MB on this host, from- 2.7 GB and 1.7 GB. There is still no restore code (`docs/MANAGED-APPS.md` §6).-- **logs** (`manager.ts:196`) — `journalctl -n 100` (user unit first, then system) or- `docker logs --tail 100`, then redaction (`manager.ts:18`): bearer tokens and- `api_key|token|secret|password|authorization` assignments are replaced, each line- clipped to 8 KB. Another app's log lines are untrusted input, so nothing is echoed raw.-- **runner** (`lib/managed-apps/runner.ts:12`) — `execFile` with `shell: false` and an- argv array, always: no string is ever handed to a shell, output is capped at 128 KB,- every call carries a timeout. This is why an app id or unit name cannot become a- command, and why `lib/host`'s destructive-command guard is not needed here.-- **features** (`lib/managed-apps/features.ts`) — each app's navigation is **discovered- from that app's own installed bundle and plugin API**, never hard-coded. Hermes: the- `{path,label}` nav table inside its built SPA (falling back to its route record, then to- `web/src/App.tsx` for a git install) spliced with `/api/dashboard/plugins` the way- upstream's own `buildNavItems()` does.- OpenClaw: its `app-route-paths-*.js` chunk over HTTP, with the copy on disk as fallback.- Routes the upstream only serves behind a flag or a plugin panel are marked unavailable- rather than shipped as dead tiles; the live counts per app are in- `docs/MANAGED-APPS.md` §4, since they move with every upstream release. Results cache 60 s; a parse- shorter than the guard (`feature-parser.ts:16`) is discarded, so an unreachable or- restructured upstream yields **nothing** rather than routes that 404.--| Route | Method | Notes |-|---|---|---|-| `/api/v1/managed-apps` | GET | every app's view (state, health, version, actions) |-| `/api/v1/managed-apps/[id]` | GET · POST | POST = `start`·`stop`·`restart`·`backup` |-| `/api/v1/managed-apps/[id]/logs` | GET | last 100 lines, redacted |-| `/api/v1/managed-apps/[id]/features` | GET | discovered navigation |--Every one of them calls `verifyAuth()` first. The action POST additionally: refuses in-demo mode, rate-limits to 12/min per app, and audits both outcomes as-`managed-app.action`.--**Workspace modes — REMOVED in `a2c3882`; this describes the old design.** They-(`frontend/slices/os-shell/workspace-mode.ts`, deleted) decided *which* app's-features populate the dock/launchpad: `plain | hermes | openclaw`, stored in-`localStorage` under `mso:workspace-mode` and read through `useSyncExternalStore`.-This is orthogonal to Shell Style (macos/windows/dashboard/ios/android) — a workspace is-which apps exist, a shell is what they look like. Switching writes one key and fires one-event: nothing restarts, no service is touched. Each discovered feature becomes an-ordinary `AppDescriptor` (`frontend/slices/managed-apps/dynamic-features.tsx:25`), so-windowing, URL slugs, Spotlight and the dock pick it up with no surface edits.--### The dashboard proxy and the origin split--Each app's own dashboard is reverse-proxied and rendered in an OS window as an iframe.-The upstream target must be loopback or the route refuses it-(`app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts:114`) — the proxy is not a-general-purpose fetcher. Cookies are namespaced (`mapp_<id>_`) and pinned to that app's-mount, the mso `session` cookie is never forwarded upstream, `authorization` is never-forwarded and `www-authenticate` never returned (together they would make the proxy a-credential relay), off-origin redirects are refused rather than passed on (they are an-open redirect **and** a CSP path-matching bypass), and an upstream service worker is-never handed to the browser (`lib/managed-apps/proxy-headers.ts`). The emitted CSP is-ours, but it is **intersected** with the upstream's own per directive-(`lib/managed-apps/proxy-csp.ts:182`): a-source survives only if both policies allow it, upstream script hashes are carried over-(never nonces), and the external hosts an upstream declares for itself are honoured —-so OpenClaw's sha256-pinned inline scripts and its narrow `connect-src` survive while-its `frame-ancestors 'none'` does not.--**The trust boundary is the browser realm, and it is drawn by giving each app its own-origin.** The iframe needs `allow-same-origin` or these SPAs do not boot at all. On the-cockpit origin that made upstream JS same-origin *with the cockpit*: it could take-`window.top.fetch` and call `/api/v1/exec/run` with the user's session. No CSP closes-that — a policy binds a realm, not a reference across realms. So each dashboard is-served from its **own host on this same process**: `hermes.mso.rahmanef.com`,-`openclaw.mso.rahmanef.com`. `window.top` is then cross-origin and opaque (measured in-Chromium 148; the properties and the same-origin control are listed in-`docs/MANAGED-APPS.md` §5). One host **per app**, not one shared host:-a shared one puts Hermes and OpenClaw back in a single origin where they can script each-other.--Two halves make that real:--| Half | Where | What it does |-|---|---|---|-| Host rewrite | `proxy.ts:123` | on an app host, EVERY path is rewritten into that app's proxy and stamped with `x-os-managed-app-host`; `/_next/*` 404s. The cockpit API does not exist on those origins. |-| Namespace gate | `proxy.ts:121` + `lib/managed-apps/origin.ts:71` | a host inside the app namespace that is not an app (`staging.os.…`, a `*.os` wildcard) 404s. The parent — the cockpit — is never matched, so this cannot lock the operator out. |--Supporting details that are load-bearing rather than incidental: the `Host` header is-authoritative and `x-forwarded-host` is deliberately ignored for this decision-(`proxy.ts:112`); the CSRF check runs **before** the rewrite, or it would stop applying-once the path became `/api/…`; the proxy route only accepts root-mounted mode when-middleware stamped the header, and middleware deletes any inbound copy, so the mode-cannot be claimed from the cockpit origin (`route.ts:92`); `frame-ancestors` names the-cockpit from deployment env only (`lib/managed-apps/origin.ts:101`) — a missing value-emits `'none'`, so a-misconfiguration refuses the frame visibly instead of inviting an unknown framer. Because-the app is root-mounted on its own host, the proxy no longer rewrites the document at-all: no `<base href>`, no URL rebasing, no fetch shim, nothing to pin.--The session cookie gained an optional `Domain` (`lib/auth/session-cookie.ts:68`) so it-reaches those hosts. `SameSite=Strict` is unchanged and still correct: SameSite is-evaluated per **site** (scheme + registrable domain), and the app hosts share-`rahmanef.com` with the cockpit — cross-origin is not cross-site. Logout clears the-cookie with *and* without the Domain (`session-cookie.ts:108`), because those are-distinct jar entries.--**What the split does not do.** It is a browser-realm boundary, nothing more. A plugin-installed into Hermes runs inside the Hermes daemon with Hermes' privileges — and Hermes-executes shell commands on this VPS. Installing an untrusted plugin or extension into-either app is handing that daemon arbitrary code execution on the host, as the service-user, whatever the browser thinks about origins. The split also cannot stop an upstream-from broadening its **own** `connect-src` to a third-party https host it declares (it can-never name the cockpit — `lib/managed-apps/proxy-csp.ts:174` refuses that specifically).--**Single-origin mode is GONE, and this paragraph used to recommend it.** ~~The-dashboards are proxied under `/api/v1/managed-apps/<id>/proxy` on the cockpit's own-origin; that is the dev, demo and rollback path.~~ Removed in `38d010d` ("serve-dashboards from an app host or not at all"). It cannot be made safe: a CSP binds a-realm, not a reference across realms, so upstream JS reaches-`window.top.fetch('/api/v1/exec')` from a frame and a whole cockpit realm from-`window.open('/')`. The route now hard-404s it-(`app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts`: "managed application-dashboards are not served on this origin"). A deployment with no app host simply does-not show upstream dashboards — the windows fall back to the CLI view. **Do not-"restore" this as a convenience.**--**Known gaps.** Backup runs but has no counterpart: there is no restore code, so a rollback is-a manual `cp -a` of a snapshot, and the manifest carries no inventory or checksum to check one-against. No update center yet (check-update, channels, update, rollback, uninstall, install-wizard). The docker and `package` detection branches have no test and no install here to-exercise them. OpenClaw's control UI is WebSocket-driven and this proxy is-fetch-based — a Next route handler cannot service an `Upgrade` — so its panels stay empty-and those features open on a CLI view instead, with the reason stated in the window-(`frontend/slices/managed-apps/feature-cli.ts:41`). No notifications, no resource-aware-behaviour, no start-on-boot. The workspace switcher is reachable from right-click on every-shell and from the Dashboard sidebar, but is not yet a visible control in the macOS /-Windows / iOS / Android chrome. No integration or journey tests — the coverage is unit-tests around the parsers, detection and backup behaviour (`lib/managed-apps/manager.test.ts`),-the policy intersection, the header rules and the host gating.--## Browser app (`os-browser`, optional)--A separate Playwright Chromium service (`os-browser/`, systemd, **loopback**-:4002, gitignored). `lib/agent/server.ts` proxies the `/api/v1/browser/*` routes-to it (secret-gated, server-only). Renders any site, drivable from the UI, with-a persistent profile (`~/.mso/chrome-profile`) so logins stick. Leave-`OS_BROWSER_URL`/`OS_BROWSER_SECRET` unset to disable the app — everything else-still works.--## Deployment--- **prod** — `mso.service` :4005 (systemd, `User=rahman`, WorkingDir- `/home/rahman/projects/mso`).-- **demo** — `mso-demo.service` :4006 (`NEXT_PUBLIC_OS_DEMO=1`, separate- WorkingDir `/home/rahman/projects/mso-demo`, mock-only, no host access).-- **os-browser** — `os-browser.service` :4002 (loopback).-- **managed-app origins** — `hermes.mso.rahmanef.com` and `openclaw.mso.rahmanef.com`, each- its own DNS record and TLS cert, both routed to the same `172.17.0.1:4005` by- `/etc/dokploy/traefik/dynamic/mso-managed-apps.yml` (`passHostHeader: true`, so the- process sees the public name). Adding an app to the catalog means adding a router there and a- DNS record **in the same change**: the host template applies to every catalog id, so a new- app's iframe points at `<newid>.os.…` the moment it exists, and with no record for that name- the window just fails to load — there is no per-app fallback to the single-origin URL.--Ship: commit to `main`, push (pre-push hook runs typecheck + lint CI), then-restart prod + sync/rebuild demo manually.--`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` + `OS_SESSION_COOKIE_DOMAIN` are **one decision-in two variables** — set both or neither (`.env.example` spells out why (2) without (1)-hands the session to every host under the domain). `NEXT_PUBLIC_*` is inlined into the-client bundle, so set them **before `pnpm build`**, not just before the restart: built-without the template, the browser still points the iframe at the old same-origin proxy-URL that the server has already stopped answering, and the app window comes up blank.-`OS_PUBLIC_ORIGIN` is a third, optional variable behind the same decision: it names the-cockpit origin the app hosts allow as their framer and the origin their policy is scoped-to. Unset, it falls back to the template's parent name — correct for-`{id}.os.<domain>`, and worth setting explicitly for anything else.--`package.json` carries a `pnpm.overrides` pin for `postcss` to keep the build-deterministic across transitive resolutions — bump it deliberately, never via-auto-update.+The release path regenerates derived changelog data, runs push gates (including an+out-of-tree production build), pushes the exact commit, then hands the in-place+build/restart/final verification to the owner user manager when launched through MSO/MCP.+A successful finalizer ends `~/.mso/self-update.log` with `UPDATE OK`.++For operator updates use Settings → About or `mso update run`; use `--rebuild` for the+supported recovery rebuild. See `docs/INSTALL.md`, `docs/DEVELOPMENT.md` and+`docs/TROUBLESHOOTING.md`.++## 11. What is authoritative++When sources disagree, use this order:++1. current code + runtime descriptors (`GET /mcp`, `/api/health`);+2. generated contracts (`docs/CLI.md`, `docs/CHANGELOG.md`);+3. current reference docs listed in `docs/README.md`;+4. `docs/PROGRESS.md` for historical reasoning;+5. dated audits/plans for their point-in-time context only.++`node scripts/check-docs.mjs` checks current-reference links and selected machine-verifiable+facts (MCP toolset and slice counts) so common drift becomes a gate failure instead of a+future archaeology task.diff --git a/docs/AUDIT-2026-06-11.md b/docs/AUDIT-2026-06-11.mdindex 8405190c..82742206 100644--- a/docs/AUDIT-2026-06-11.md+++ b/docs/AUDIT-2026-06-11.md@@ -1,5 +1,12 @@# mso Full Audit — 2026-06-11+> **Archived point-in-time audit.** This file preserves findings against HEAD `84e857c`+> on 2026-06-11, including the commands/paths/counts used then. Many findings were fixed or+> structurally superseded. Do **not** use it as today's architecture/runbook; start with+> [`README.md`](./README.md), [`ARCHITECTURE.md`](./ARCHITECTURE.md) and+> [`TROUBLESHOOTING.md`](./TROUBLESHOOTING.md). Source comments may still cite finding+> numbers here, which is why the original body is intentionally retained.+> Method: six parallel audit passes over HEAD `84e857c` (security, shell core,> app slices, shell fidelity inventory, Next/React best-practice with Context7> docs, DX/code-quality), every load-bearing claim verified against the actualdiff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 945e0994..8dd503f8 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -19,6 +19,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.- `ui` separate shell design systems+**Docs**++- refresh architecture and ChatGPT MCP guide+## 2026-08-22**Fixed**diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdnew file mode 100644index 00000000..a7e91f1f--- /dev/null+++ b/docs/CHATGPT-PLUGIN.md@@ -0,0 +1,374 @@+# ChatGPT plugin / custom MCP app for MSO++> **Current reference.** In this project, people often say "the ChatGPT plugin". The+> current ChatGPT product calls this a **custom MCP app/connector** in Developer Mode. It+> is not a legacy ChatGPT Plugin manifest, browser extension, or a plugin installed inside+> Hermes/OpenClaw.+>+> ChatGPT's Developer Mode UI and plan availability are controlled by OpenAI and may change+> while full MCP is in beta. The stable contract on the MSO side is the remote MCP endpoint+> plus OAuth metadata documented here. OpenAI's current overview is:+> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>++<!-- mcp-toolset: server=1.6.0 version=2026.08.21.1 tools=28 read=15 write=10 exec=3 -->++MSO currently exposes MCP server **1.6.0**, toolset **2026.08.21.1**: **28 tools**+(15 read, 10 write, 3 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++The ChatGPT app lets ChatGPT call the MSO tool catalog on your server. OAuth controls which+tier the bearer token can use; MSO then applies the same host path, project, managed-app+and process guards used by its other surfaces.++```mermaid+flowchart LR+ U[Owner in ChatGPT] --> CG[ChatGPT custom MCP app]+ CG -->|OAuth 2.1 + PKCE| OA[MSO /oauth/*]+ OA -->|bearer token: read/write/exec| CG+ CG -->|MCP JSON-RPC| M[MSO /mcp]+ M --> D[scope + rate limit + audit dispatcher]+ D --> H[lib/host]+ D --> PR[project discovery/functions]+ D --> SK[skills + workflow memory]+ H --> FS[filesystem roots]+ H --> SYS[system / PTY / exec]+ H --> AP[Hermes / OpenClaw]+```++The MCP client does **not** get a Linux credential or SSH key. It gets an MSO bearer token+whose scope is re-checked on every tool call.++## 2. Before connecting ChatGPT++You need:++1. a real owner MSO deployment over HTTPS;+2. an approved browser device that can open the MSO OAuth consent page;+3. `OS_MCP_ENABLED=1` on the running MSO service;+4. an intentional server ceiling, `OS_MCP_MAX_SCOPE=read|write|exec` (default is `exec`);+5. a ChatGPT plan/workspace that currently permits the MCP capability you need.++ChatGPT connects to a **remote** MCP server. A private-only MSO endpoint therefore needs a+supported remote path rather than an unreachable `localhost` URL. OpenAI's current docs+name **Secure MCP Tunnel** as the supported option for private/on-prem/developer-machine+servers; use the current OpenAI instructions rather than exposing the MSO shell port merely+to satisfy discovery.++After changing MSO environment configuration, use the normal MSO update/rebuild path; do+not treat a Git push as deployment.++### Current ChatGPT availability (external, as of 2026-08-24)++OpenAI's current Developer Mode documentation says custom MCP apps are a **web** capability+in beta. Full MCP including write/modify actions is available to Business, Enterprise and+Edu workspaces under their workspace controls; Pro can connect custom MCP servers for+read/fetch access. Workspace admins can further restrict or disable the capability. This+availability is an OpenAI product decision and can change independently of MSO—check the+current OpenAI article before treating the table as entitlement:+<https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>.++MSO itself does not special-case ChatGPT plans. It publishes the same scoped MCP server; the+client decides which actions it will expose/allow.++## 3. MSO endpoint values++For an MSO origin such as `https://mso.example.com`:++| Purpose | Value |+|---|---|+| MCP server | `https://mso.example.com/mcp` |+| OAuth authorization | `https://mso.example.com/oauth/authorize` |+| OAuth token | `https://mso.example.com/oauth/token` |+| Dynamic client registration | `https://mso.example.com/oauth/register` |+| Authorization-server metadata | `https://mso.example.com/.well-known/oauth-authorization-server` |+| Protected-resource metadata | `https://mso.example.com/.well-known/oauth-protected-resource` |++MSO supports public OAuth clients with PKCE S256 and token-endpoint authentication method+`none`. ChatGPT can use the predefined public client id `chatgpt-mso`; a client secret is+not required. Other MCP clients can use Dynamic Client Registration where supported.++The exact ChatGPT form labels can change during the beta. In Developer Mode, create a+custom MCP app, provide the remote MCP endpoint, select OAuth, then let ChatGPT scan tools.+When the authorization browser opens, sign into MSO on an approved device, review the+requested scope, and Allow only the tier you intend.++## 4. OAuth lifecycle++```mermaid+sequenceDiagram+ actor Owner+ participant ChatGPT+ participant Auth as MSO OAuth+ participant Store as MSO token store+ participant MCP as MSO /mcp++ Owner->>ChatGPT: Create/enable MSO custom MCP app+ ChatGPT->>Auth: authorization request + PKCE challenge+ Auth->>Owner: signed-in consent page+ Owner->>Auth: choose allowed scope and Allow+ Auth-->>ChatGPT: one-time authorization code+ ChatGPT->>Auth: exchange code + PKCE verifier+ Auth->>Store: store hash of bearer token+ Auth-->>ChatGPT: bearer token+ ChatGPT->>MCP: initialize / tools.list / tools.call+ MCP->>Store: validate token + scope on every call+ MCP-->>ChatGPT: tool results+```++Authorization codes live for 60 seconds and are consumed once. MCP bearer tokens expire+after 90 days unless revoked earlier. MSO stores token/code hashes, not reusable plaintext+bearers. The current authorization metadata advertises only `authorization_code`; MSO does+**not** issue refresh tokens. After a bearer expires (or is revoked), authorize the MCP app+again rather than expecting an offline refresh grant.++## 5. Scope ladder and exact tool catalog++A token sees a scope prefix; there is no per-project or per-agent hidden tool filter.+`tools/list` filters the catalog and `tools/call` independently re-checks the required+scope.++### `read` — 15 tools++- `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`++### `write` — read + 10 tools++- `fs_write`+- `fs_upload_file`+- `fs_mkdir`+- `fs_move`+- `fs_copy`+- `fs_delete`+- `apps_power`+- `workflow_start`+- `workflow_cancel`+- `workflow_finish`++### `exec` — write + 3 tools++- `exec_run`+- `browser_power`+- `project_function_call`++`exec_run` is full host shell power as the MSO service user. The command filter is an+accident tripwire, not a sandbox. Grant `exec` only to a ChatGPT app/workspace you trust+with the same care as a remote shell.++## 6. Tool-snapshot refresh: the part most often missed++ChatGPT scans and caches the MCP action definitions. If MSO adds/removes/changes tools, a+running ChatGPT app may continue using its previous snapshot until you refresh/recreate the+app according to the current ChatGPT workspace controls.++MSO exposes a schema-derived signature in `GET /mcp`, MCP `initialize`, `tools/list`, and+Settings → MCP:++```text+server: 1.6.0+toolset: 2026.08.21.1+hash: 8c3c9092013069de+count: 28+```++Use this sequence after an MSO MCP change:++```mermaid+flowchart LR+ C[Deploy new MSO] --> S[Check Settings → MCP signature]+ S --> R[Refresh/recreate ChatGPT MCP app and Scan Tools]+ R --> V[Verify expected actions in ChatGPT]+ V --> A[Mark ChatGPT refreshed in MSO Settings]+```++**Mark ChatGPT refreshed** is only an operator acknowledgement stored by MSO. It does not+reach into ChatGPT and refresh anything by itself.++OpenAI's current beta controls differ by plan: a published Business custom app must be+recreated/republished to change tools or metadata, while Enterprise/Edu admins can use the+workspace **Refresh** / action-control flow to pull new or changed definitions. New actions+are not automatically enabled. Always follow the current workspace UI if OpenAI changes+this behaviour.++## 7. Multi-step work and `workflow_id`++For a task needing several operational calls, ChatGPT should call `workflow_start` once.+The returned exact `workflow_id` is then included on later operational calls. Missing id =+a standalone call; an unknown id is refused.++```mermaid+flowchart TD+ Q[User task] --> M{More than one operational call?}+ M -->|No| O[Use smallest bounded tool]+ M -->|Yes| W[workflow_start]+ W --> I[carry exact workflow_id]+ I --> T[bounded tools or one scoped exec batch]+ T --> V[verify result independently]+ V --> F{Completed?}+ F -->|Yes| X[workflow_finish]+ F -->|Abandoned/interrupted| C[workflow_cancel]+```++Successful runs can become redacted local recipes. MSO never stores raw file bodies,+`fs_write.content`, bearer tokens, browser credentials or secret-looking command payloads+in workflow memory.++## 8. ChatGPT file/image → VPS bridge++`fs_upload_file` is intentionally ChatGPT-aware through MCP metadata+`openai/fileParams`. The normal flow is:++```mermaid+flowchart LR+ G[ChatGPT creates/receives image or file] --> F[ChatGPT file reference]+ F --> U[fs_upload_file]+ U --> D[download temporary OpenAI HTTPS URL]+ D --> V[revalidate host + redirects + MIME + size]+ V --> J[OS_FS_WRITE_ROOTS + credential/path jail]+ J --> W[write file]+ W --> R[return path + bytes + SHA-256]+```++Current guardrails:++- maximum 20 MiB;+- PNG, WebP, JPEG or generic octet-stream only;+- temporary URL must be from an allowed OpenAI content/storage host;+- up to three redirects, and each redirect target is revalidated;+- destination still has to be inside `OS_FS_WRITE_ROOTS`;+- filename is sanitized;+- an existing same-name file can be replaced, so treat this as a write/destructive action;+- result includes byte count and SHA-256.++MSO does **not** provide a second image generator. Generate with ChatGPT's native image+capability, then use this bridge to move the result into the VPS when needed.++## 9. Visual proof without arbitrary browser access++`screen_capture` captures only the authenticated MSO UI. It cannot be pointed at an+arbitrary URL. It supports macOS, Windows or Dashboard shells, 900–1920 px width and+600–1200 px height.++The call returns the MCP image directly plus a session-gated temporary preview/download+link. The link expires after 15 minutes or 5 authenticated downloads, whichever comes+first. This is intended for visual verification while avoiding a general read-token web+exfiltration primitive.++Camoufox is a separate capability. `browser_status` reveals only installed/running/autostart+state. The VNC password, logged-in profile and cookies are deliberately never returned to+an MCP client.++## 10. Project-aware tools++`projects_list` discovers validated projects across configured containers. Scans are+bounded and may return a continuation cursor; never interpret a truncated scan as "the+project does not exist".++`project_capabilities` can report:++- `.mcp.json` **presence only** — contents may contain credential wiring and are never+ returned; MSO does not auto-connect arbitrary project MCP servers;+- `.mso/functions.json` — public schemas for a version-1 project function manifest.++A function manifest can declare at most 32 functions. Functions use fixed argv (at most 16+strings), a maximum 30-second timeout, and receive caller JSON on stdin. User values are not+interpolated into a shell command. `project_function_call` always requires `exec` scope,+even when a project function is named "read".++## 11. Four credentials people commonly confuse++```mermaid+flowchart TB+ S[MSO browser session cookie] -->|human UI| UI[MSO web app]+ B[MCP bearer token] -->|ChatGPT permission to MSO tools| MCP[/mcp]+ K[BYOK API key] -->|Alfa model inference| API[Model provider API]+ C[Alfa openai-codex OAuth] -->|Alfa model inference| COD[ChatGPT Codex backend]+```++| Credential | Purpose | Does not grant |+|---|---|---|+| MSO session cookie | human browser access | MCP access by itself |+| MCP bearer | external client access to scoped MSO tools | an Alfa model credential |+| BYOK provider API key | Alfa inference | permission for ChatGPT to operate MSO |+| Alfa `openai-codex` OAuth | Alfa inference via ChatGPT subscription backend | MSO MCP scope |++Authorizing the ChatGPT MCP app therefore does **not** automatically configure Alfa, and+"Sign in with OpenAI" under Alfa provider settings is not the ChatGPT plugin setup.++## 12. Security model++- Connect only an MSO server you own and trust.+- Start with `read` unless the workflow actually needs host changes.+- `write` can change/delete files and control bounded managed apps.+- `exec` is effectively a remote shell as the MSO Linux user.+- Prompt injection still matters: data read from files/logs can influence the model. Scope+ is the server-side boundary that prevents a read-only token from turning that influence+ into a write/exec.+- Tool inputs/results used in a ChatGPT conversation are processed by ChatGPT according to+ the user's/workspace's OpenAI data controls; do not assume an MCP call stays on the VPS.+- Revoke old tokens from Settings → MCP. Tokens also expire after 90 days.+- Do not publish the MSO bearer, OAuth store, browser profile or `~/.mso` contents.++OpenAI may additionally ask for confirmation or block some write actions based on the+ChatGPT app/workspace permission model. That is an additional client control; it does not+replace MSO's own scope checks.++## 13. Troubleshooting++### ChatGPT cannot discover the server++- the endpoint must be remote/reachable from ChatGPT;+- use HTTPS;+- verify `OS_MCP_ENABLED=1` is present in the **running** service;+- `GET /mcp` should return the public descriptor instead of 404.++### OAuth page opens but cannot authorize++The authorization page is a real MSO browser page. Log into MSO from an approved device,+then retry the connector authorization. Check the requested scope against+`OS_MCP_MAX_SCOPE`.++### ChatGPT sees old/missing tools after a deploy++Compare the toolset signature in Settings → MCP or `GET /mcp`, then refresh/recreate the+ChatGPT app and run **Scan Tools**. Only after ChatGPT shows the new actions should you mark+it refreshed in MSO Settings.++### A tool is visible but returns a scope error++The token was authorized at a lower tier than that action requires. Reauthorize deliberately+at the needed scope; do not raise the whole server ceiling only to silence the error.++### `fs_upload_file` fails++Check destination write roots, file size/type, and whether ChatGPT supplied a current file+reference. Temporary OpenAI URLs expire; retry from the actual attached/generated file+rather than pasting an arbitrary public URL.++### Project/skill seems missing++Inspect the returned scan report. If `truncated:true`, follow its continuation cursor.+Project and skill discovery are deliberately bounded.++## 14. Deeper reference++- `docs/MCP.md` — protocol, OAuth store, tool internals, project/skill discovery, rate limits+- `docs/ARCHITECTURE.md` — whole-system boundaries+- `docs/CONNECTORS-GATEWAY-INTEGRATION.md` — cross-repo action-name contract+- `docs/MODELS-INTEGRATION.md` — Alfa model credentials and the separate Codex OAuth flow+- `SECURITY.md` — deployment/security posturediff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.mdindex d015f4ee..c64e5c58 100644--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md@@ -1,80 +1,107 @@-# mso → Connectors Gateway+# MSO ↔ Connectors Gateway contract-**Status:** mso is a registered connector in `rahmanef63/connectors-gateway` as of 2026-08-17. MSO is the provider; the gateway is one consumer alongside ChatGPT, Claude.ai and Cursor. Every client reaches `https://mso.rahmanef.com/mcp` through the same OAuth and scope rules documented in [`MCP.md`](./MCP.md).+> **Current MSO-side reference.** This file pins what **MSO** exposes. A gateway repository+> can evolve independently, so do not claim its mapping count is current without checking+> that repository at the time of the change.-## Cross-repo contract+<!-- mcp-toolset: server=1.6.0 version=2026.08.21.1 tools=28 read=15 write=10 exec=3 -->-MSO currently exposes **28 tool names** (server `1.6.0`, toolset `2026.08.21.1`). The gateway manifest still maps **15** of them through literal `x-upstream` strings:+MSO currently exposes MCP server **1.6.0**, toolset **2026.08.21.1**: **28 tools**+(15 read, 10 write, 3 exec). `GET /mcp` exposes the live names, version/hash and scoped+manifest and is the machine-readable parity source.++## Why this contract matters++Connector/gateway manifests commonly bind an action to an MSO tool with a literal upstream+name such as:```json{ "id": "mso.fs.delete", "x-upstream": "fs_delete" }```-Renaming or removing a tool here breaks that action at runtime even when both repositories typecheck. Adding a tool here does not make it appear in the gateway until its manifest is deliberately updated.+Renaming/removing an MSO tool can therefore break a gateway without a TypeScript error in+either repository. `lib/mcp/parity.test.ts` covers MSO MCP ↔ Alfa intent, not an external+gateway's literal strings.-The runtime contract is no longer invisible:+Before changing an MCP tool name:-- unauthenticated `GET /mcp` returns the current toolset version, hash, count and names;-- MCP `initialize` and `tools/list` return `_meta.toolset` for the token's visible scope;-- Settings → MCP shows the same signature and lets the operator mark the ChatGPT action snapshot as refreshed;-- the signature hashes names, descriptions, schemas, scope, annotations and limits, so a schema-only change is visible too.+1. inspect the live `GET /mcp` manifest;+2. search the gateway's connector manifest for the exact upstream string;+3. decide whether the external action is renamed, migrated or intentionally dropped;+4. update both repos in a coordinated release if necessary;+5. refresh/re-scan connected ChatGPT/custom apps because action definitions are cached.-A consumer CI should compare the upstream names it pins against this runtime manifest. Source parsing remains useful for review, but it is no longer the only way to detect drift.+## Current MSO catalog-## What the gateway exposes+### Read (15)-**Removed 2026-08-20 — a gateway that pinned either name must drop it:** `image_generation_status` and `image_generate`. MSO no longer generates images on any surface (a GPT client already carries its own; a second tool for the same job made the model choose wrong). Neither name was in the gateway's 15, so nothing breaks there today. `fs_upload_file` is unchanged and remains how a conversation-generated file reaches the VPS.+`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`.-The gateway has not yet synchronized the tools added or deliberately withheld from its 15-action manifest:+### Write (10 beyond read)-| Not mapped in gateway | Reason/status |-|---|---|-| `exec_run` | deliberately omitted: arbitrary owner-level shell |-| `browser_power` | deliberately omitted: controls a browser profile holding live sessions |-| `skills_search` | added to MSO after the original gateway manifest |-| `screen_capture` | added later; secure MSO-only visual artifact, requires a product decision in the gateway |-| `workflow_start` | added later; starts the actor-scoped task lease |-| `workflow_cancel` | added later; exact-id recovery for an interrupted run |-| `workflow_finish` | added later; exact-id verified recipe boundary |-| `fs_upload_file` | added later; ChatGPT `openai/fileParams` binding the gateway does not model |-| `projects_list` | added 2026-08-20; enumerates every configured project container |-| `project_capabilities` | added 2026-08-21; detects opt-in project MCP/function manifests without exposing secrets |-| `project_function_call` | added 2026-08-21; exec-scope generic runner for functions declared by a project |-| `skills_list` | added 2026-08-20; global + per-project skill catalog with trust |-| `skills_read` | added 2026-08-20; exact-catalog-id SKILL.md read, trusted tiers only |+`fs_write`, `fs_upload_file`, `fs_mkdir`, `fs_move`, `fs_copy`, `fs_delete`,+`apps_power`, `workflow_start`, `workflow_cancel`, `workflow_finish`.-`fs_delete` and `apps_power` remain the gateway's highest-risk mapped actions and should keep its human approval policy. The gateway's policy layer supplements, never replaces, MSO's scope checks, path jail, audit trail and per-operation rate limits.+### Exec (3 beyond write)-## Change procedure+`exec_run`, `browser_power`, `project_function_call`.-Before changing the MCP catalog:+## Scope and workflow compatibility-1. Read `lib/mcp/tools.ts`, `tools-read.ts`, `tools-learning.ts` and `toolset.ts`.-2. Do not rename a public tool unless migration is intentional.-3. Run MSO parity, dispatch and toolset tests.-4. Compare the new `GET /mcp` signature and names with the gateway manifest.-5. Update the gateway mapping or explicitly document why a capability stays absent.-6. Refresh affected custom-app action snapshots after deployment.+The MSO scope ladder (`read < write < exec`) is the server permission boundary. A gateway+may add stricter approvals/policy, but it must not assume that hiding an action changes the+MSO bearer scope.-The Alfa ↔ MCP axis is guarded by `lib/mcp/parity.test.ts`; this document and the runtime toolset signature cover the cross-repo axis until the gateway adds an automated parity check.+Operational MCP tools also accept optional `workflow_id`. A gateway that does not expose+that field can still call the tools, but those calls are standalone and will not join an+MSO learned workflow. For multi-step orchestration, expose the workflow trio and propagate+the exact id returned by `workflow_start`.-## Scope ceiling+## Project functions are data, not dynamic MCP names-The running MSO instance currently allows tokens up to:+A project may publish `.mso/functions.json`. The gateway does not need a new MSO action for+each project function: it calls `project_capabilities` to see validated public schemas and+`project_function_call` to run one at exec scope. This is intentional so switching projects+does not change the global MCP tool prefix.-```text-OS_MCP_MAX_SCOPE=exec-```+`.mcp.json` is different: MSO reports presence only and never returns its contents or+implicitly connects to an arbitrary project's MCP server.++## ChatGPT file parameters++`fs_upload_file` uses OpenAI MCP metadata `openai/fileParams` on its top-level `file`+parameter. A generic gateway that cannot preserve that metadata may still proxy ordinary+MSO JSON actions, but it cannot manufacture the ChatGPT-provided temporary file object from+a string path. Preserve metadata if file import parity is required.++## Security-sensitive mapped actions-The gateway's mapped actions do not require `exec`, so narrowing the gateway token to `write` costs it nothing. The server-wide ceiling remains an owner decision because it also governs separately minted ChatGPT, Claude or Cursor tokens.+Treat these as particularly important in any external approval layer:-## Operator checks+- `fs_delete` / `fs_write` / `fs_upload_file` — host data mutation;+- `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.-```bash-curl -s https://mso.rahmanef.com/mcp | jq '.toolset'-mso mcp list-mso mcp activity 100-mso audit 50 mcp.+External policy supplements MSO's own scope/path/audit/rate-limit checks; it does not replace+them.++## Removed names++Provider-backed MSO image generation was removed on 2026-08-20. Do not map+`image_generation_status` or `image_generate`. A GPT/ChatGPT client should use its native+image capability and, when needed, transfer the resulting file through `fs_upload_file`.++## Verification++For an integration update, compare the gateway's literal upstream names with:++```text+GET https://<mso-origin>/mcp```-The gateway strategy and its user-facing OAuth are maintained in the gateway repository. This file owns only the provider-side contract and drift procedure.+Then run MSO's MCP parity/global-tool tests and the gateway's own connector-contract tests.+Do not infer external-gateway parity merely because MSO's internal tests are green.diff --git a/docs/DEMO-SCRIPT.md b/docs/DEMO-SCRIPT.mdindex 85c1bab7..a9750ab9 100644--- a/docs/DEMO-SCRIPT.md+++ b/docs/DEMO-SCRIPT.md@@ -1,36 +1,38 @@-# Demo Script+# 60-second demo script-## 0-5 sec+> **Marketing/demo collateral, not a runtime contract.** Use a separate+> `NEXT_PUBLIC_OS_DEMO=1` build unless recording a private owner-only walkthrough.-Show MSO opening on a phone.+## 0–6 sec — phone home-## 5-15 sec+Open MSO on a phone and show the iOS/Android shell adapting to the viewport.-Open System Monitor and show server health.+## 6–14 sec — system health-## 15-25 sec+Open System Monitor and show CPU, memory, disk and processes.-Open Files and browse the sample `example-next-app` project.+## 14–24 sec — project files-## 25-35 sec+Open Files and browse a sample project. Show one real file preview without exposing secrets.-Launch Terminal from the project folder and run a harmless mock command.+## 24–34 sec — Code + terminal-## 35-45 sec+Open Code, then reveal its integrated Terminal. Run a harmless mock/read-only command so the+editor and terminal relationship is visible without implying a public demo has host access.-Open Alfa and ask about the mock warning:+## 34–44 sec — Alfa-```text-Why did the background worker restart?-```+Ask Alfa a simple mock diagnosis question and show a read tool/activity row. If demonstrating+a mutation in a private build, show the human Approve/Deny card rather than auto-approving.-## 45-52 sec+## 44–52 sec — Browser / managed app-Switch between mobile and desktop layouts.+Show the Camoufox Browser power surface or a Hermes/OpenClaw Details panel. In a public demo,+do not expose a real logged-in browser profile or vendor credentials.-## 52-60 sec+## 52–60 sec — responsive switch + CTA-Show CTA:+Switch to desktop/landscape, then show:```textOpen source.diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.mdindex a2592e71..b628e0be 100644--- a/docs/DEVELOPMENT.md+++ b/docs/DEVELOPMENT.md@@ -26,18 +26,17 @@ Every feature is a self-contained **vertical slice** under `frontend/slices/<slubun run verify # typecheck + lint + test + check + audit (high/critical only)```-A **pre-push hook** blocks the push on failure. Four guards, ~70 s: sc-git's `ci.js`-(typecheck + lint + test), `check-cycles.mjs`, `scripts/audit.mjs`, and-`scripts/verify-build.sh`. None of them touch this checkout's `.next` — the build-guard compiles a throwaway copy of `HEAD` in a temp dir — so all of it is safe to run-against the prod checkout. A healthy push prints `audit: clean at high/critical.` and+The **committed source of truth** for pre-push policy is `scripts/gates.sh`. The+actual `.git/hooks/pre-push` file is an intentionally tiny untracked shim; reinstall it+idempotently with `bash scripts/gates.sh --install`.++The gate runs typecheck/lint/test (shared sc-git runner when present, otherwise the+in-repo verify path), cycle checks, generated-changelog freshness, documentation/skill+checks, the high/critical dependency audit, and an out-of-tree production build.+`check-contrast.mjs` is informational. None of the build verification touches the live+checkout's `.next`. A healthy push ends with `audit: clean at high/critical.` and`build: HEAD compiles (out-of-tree).`-The hook is **untracked**, so nothing in this repo can carry it: re-running an sc-git-hook installer overwrites the file and silently drops the audit and build guards (and-re-adds a `check-slices.mjs` line for a script that no longer exists, which blocks-every push). If those two lines stop appearing, the wiring is gone.-## Deploy — and the build hazard ⚠️mso deploys via **systemd on the VPS**, not `git push` (no webhook, no Dokploy/@@ -71,7 +70,8 @@ instance** on a different port — e.g. a build with `NEXT_PUBLIC_OS_DEMO=1` (nono host access, forced mock data), served on `:4006` via its own systemd unit. For anon-destructive static check, `bun run typecheck && bun run lint` is the cheap gate.-Recovery if a chunk mismatch is live: `sudo systemctl restart mso.service`.+Recovery if a chunk mismatch is live: wait for any active self-update finalizer to+finish, then run `mso update run --rebuild` and re-run the post-deploy smoke check.## Package manager: bun installs, Node runsdiff --git a/docs/DRAWER-MENU-BYOK-PLAN.md b/docs/DRAWER-MENU-BYOK-PLAN.mdindex b7775397..7eaa608e 100644--- a/docs/DRAWER-MENU-BYOK-PLAN.md+++ b/docs/DRAWER-MENU-BYOK-PLAN.md@@ -1,5 +1,10 @@# Shell Action Contract + BYOK Add-Provider — Plan+> **Historical implementation plan.** Phases A/B/C and OpenAI Codex OAuth D1 shipped in+> 2026; current provider behaviour is documented in [`MODELS-INTEGRATION.md`](./MODELS-INTEGRATION.md).+> D2–D4 below are old design ideas, not current commitments. Paths/test counts/commands in+> the original plan describe their point in time unless a note explicitly says otherwise.+> **Ask (2026-07-16):** (1) mobile **drawer** not applied in-app; (2) feature slices not> refactored to feed the **OS menu / drawer format** like the Apple mock; (3) BYOK not like> the **"add provider"** flow in `../models-rahmanef-com`.@@ -94,7 +99,9 @@ Framework: `OsConfig.oauthTokens` (0600 host file) + in-memory handshake (`lib/a`decodeAccountId` + models) + bespoke Responses streamer `lib/ai/codex-stream.ts` (ChatGPT backend`…/codex/responses`, not `/chat/completions`; bearer + account-id header + `response.output_text.delta` SSE).Public Codex-CLI client id, no secret. UI: `oauth-connect.tsx` "Sign in with OpenAI". Start verified live.- **Caveats:** consumer endpoint (needs ChatGPT Plus/Pro, may break), **chat-only (no Alfa tools)**, tokens plaintext in 0600 file.+ **Current correction:** the consumer endpoint remains more fragile than the public Platform API,+ but current `app/api/assistant/route.ts` can pass Alfa tools through the Codex adapter; the old+ "chat-only" caveat is no longer true. OAuth material remains private host state (0600).- **D2 Claude** (PKCE paste) — TODO. `/v1/messages` with Bearer (not x-api-key) + mandatory betas + a "You are Claude Code" system block.- **D3 Copilot** (device-code) — TODO. gh→copilot token exchange + 5 editor headers; ToS caveat.- **D4 OpenRouter** (PKCE redirect) — TODO, low value (yields a normal `sk-or-` key you can already paste); needs a public callback URL.@@ -104,7 +111,8 @@ Framework: `OsConfig.oauthTokens` (0600 host file) + in-memory handshake (`lib/aFiles-specific menu when Files focused; Android "•••" → drawer. Screenshot each.- BYOK: add a custom OpenAI-compatible endpoint from the UI, key-test returns a badge, provider appears in thelist, assistant streams through the custom baseUrl; delete removes it. Verify SSRF rejects `http://169.254.169.254`.-- Gates: `pnpm verify` (tsc · lint · vitest) green before ship. Never `pnpm build` in prod to verify.+- Historical gate at plan time used pnpm. Current repository policy is `bun run verify` plus+ `bash scripts/verify-build.sh`; never use a bare in-place production build only as verification.## 5. Log- 2026-07-16 — plan written from the 3-probe audit.@@ -119,5 +127,3 @@ Framework: `OsConfig.oauthTokens` (0600 host file) + in-memory handshake (`lib/abespoke ChatGPT-backend Responses streamer + "Sign in with OpenAI" UI. tsc + lint + vitest (301) green;device-flow **start verified against the live OpenAI endpoint** (HTTP 200 + user_code). Full round-tripneeds the owner's ChatGPT auth. Claude/Copilot/OpenRouter (D2–D4) scaffolded, not yet built.-</content>-</invoke>diff --git a/docs/FAQ.md b/docs/FAQ.mdindex cab39784..dfe83872 100644--- a/docs/FAQ.md+++ b/docs/FAQ.md@@ -1,106 +1,136 @@# FAQ-### Is this a real operating system?+### Is MSO a real operating system?-No. It's a single Next.js app with a desktop-style UI metaphor. The value is-utility — terminal, files, monitor, media, a real remote browser — in one-mobile-first pane. See the [README](../README.md) for the current positioning.+No. It is a self-hosted Next.js application with an OS-style workspace metaphor. The value+is practical server control—Files, Terminal, Code, metrics, Browser, AI and managed apps—in+one responsive browser UI.### Is it safe to expose to the public internet?-Treat an authenticated session like an SSH login: the owner can read files-(within roots) and run shell commands. The app ships signed cookies, device-approval as a browser allowlist, rate limits, an FS jail and an audit log —-but it has **not** had a third-party security audit. Recommended posture:-Tailscale/VPN, or a TLS reverse proxy + IP allowlist. Public exposure is for the-[demo build](./INSTALL.md#8-optional-public-demo-mode) (no auth, no host-access), not the real thing.+Treat an authenticated owner session like SSH. MSO has signed sessions, device approval,+filesystem bounds, rate limits and audits, but no third-party security audit. Prefer+Tailscale/VPN or a tightly controlled HTTPS reverse proxy. Public showcases should use a+separate `NEXT_PUBLIC_OS_DEMO=1` mock-only build.-### Why a password AND device approval?+### Why password plus device approval?-The password protects login, and the device allowlist prevents a new browser-from receiving a session until you approve it. A leaked password alone gets an-attacker a *pending* device and nothing else. You approve devices from an-already-approved device, or from the server with `node scripts/approve-device.js-<deviceId> "label"`.+The password proves the owner knows the login secret; device approval prevents a new browser+from receiving an owner session until an existing trusted device or the server approves it.+It is a browser allowlist, not standards-based MFA.-### I lost all my approved devices. How do I get back in?+### I lost all approved devices. How do I get back in?-SSH to the box. Either approve your current device id (shown on the login-screen) with `scripts/approve-device.js`, or inspect-`~/.mso/auth-devices.json` directly. Deleting an entry revokes a device.+Use a trusted host-admin path to approve the device id shown on the login page with+`scripts/approve-device.js`, or inspect the allowlist on the server. Do not expose the+allowlist through the normal Files API.-### Can multiple people use it?+### Can multiple people use one MSO installation?-It's single-owner by design: one password, one trust level, every session is-"the owner". Don't hand out sessions you wouldn't hand a shell.+It is single-owner by design. There is no multi-user RBAC for the cockpit. Do not hand out+sessions you would not hand a shell.-### Why is there no database?+### Why no database?-Nothing needs one. Sessions are stateless signed cookies; the device-allowlist, BYOK key and audit log are small JSON/JSONL files under-`~/.mso/`; window layout lives in the browser's localStorage. One process,-no migrations, nothing to back up except `~/.mso`.+Core state is small: signed sessions are stateless, device/config/MCP/audit state lives in+private owner-local files, and UI/window state is browser-side or in the existing preference+store. Managed applications keep their own independent state.-### Can I run it as root so it can manage the whole box?+### Can I run MSO as root?-Don't. Run as a normal user and widen `OS_FS_READ_ROOTS=/` if you want-read-only browsing of the whole filesystem. Writes and exec stay bounded to-what the process user can do — that's the point.+Do not. Run it as a normal dedicated user. The process user's Unix permissions are another+important boundary beyond MSO's own path checks.-### What are "mock" and "live" modes?+### What are mock and live modes?-Every app works against an in-browser mock by default (zero risk, great for-trying the UI). Settings → Server flips an app to the live host API. The-public demo build is mock-only and does not call live host APIs.+The shell can use mock adapters for safe demos/development and live host adapters for the+real VPS. A public demo build is forced mock-only and does not expose live host operations.-### How do I add my own app? (the modular part)+### How do I add an MSO app?-Each app is a self-contained vertical slice under `frontend/slices/<slug>/`-that exports an `AppDescriptor`. Register it in `os-shell/shell.manifest.ts`-(one entry: id, title, icon, slug, `load`) — dock, launcher, Spotlight, URL-routing and windowing pick it up with **no surface edits**. Shell features-(search, inspector, control-center, widgets…) are their own `shell-*` slices-contributed through the same manifest. See-[ARCHITECTURE.md](./ARCHITECTURE.md) and the slice list in-[SLICE-CATALOG.md](./SLICE-CATALOG.md).+Create a vertical slice under `frontend/slices/<slug>/` and register its descriptor in the+MSO shell manifest. Dock/launcher/search/routing/windowing consume the manifest rather than+requiring per-surface edits. Shell features are nested under `appshell/features/*`; see+`docs/ARCHITECTURE.md` and `docs/SLICE-CATALOG.md`.-### Can I reuse the apps outside mso?+### Can I reuse slices outside MSO?-Yes — that's deliberate. The shell framework (`appshell`) and several apps-(image editor, video editor, file explorer, media viewer, code editor) are-published as copy-in slices in the [Rahman Resources](https://resource.rahmanef.com)-catalog (`npx rr add <slug>`). Each slice's only host coupling is a small-`lib/host.ts` seam with injectable adapters, so the same code runs inside-mso or standalone in any Next.js app.+That is a design goal. AppShell is generic and application slices keep their host coupling+behind small adapters/contracts so they can be lifted into compatible Next.js projects.-### Why is the repo called `mso` but the product is "Manef Shell OS"?+### What does the Browser app actually run?-Three names, three jobs: **`mso`** is the repo/service/deploy slug (stable-for paths, systemd units and the domain); **Manef Shell OS** is the product-name; **MSO** is the short mark shown in the UI chrome. Renaming the slug would-break every deploy path, so it stays.+Camoufox: a real anti-fingerprinting Firefox on a headless X display, streamed through+noVNC. It is optional and off when not needed. The old Playwright browser daemon is retired;+Playwright remaining under `os-browser/` is development/test tooling only.++### Why can Browser status not return the VNC password?++The persistent Camoufox profile can contain live logged-in cookies. Model-facing status APIs+therefore return only installed/running/autostart state. Human viewer credentials stay on+the owner side.++### What are Hermes and OpenClaw inside MSO?++Independent managed applications. MSO can install/control/log/update/back up/restore them and+optionally frame each vendor dashboard from a separate hostname. Their plugins still run+with the daemon's host privileges; MSO's browser origin split does not sandbox daemon code.++### Why is a managed-app dashboard not embedded by default?++Vendor SPAs need `allow-same-origin`. On the cockpit origin that would share the owner's+browser realm/session. The safe default is no embedded dashboard; split-origin embedding is+an explicit two-variable deployment decision. See `docs/MANAGED-APPS.md`.++### Can ChatGPT control MSO?++Yes, through the optional remote MCP server. Enable it deliberately, connect a ChatGPT+custom MCP app/connector over OAuth 2.1 + PKCE, and grant `read`, `write` or `exec` scope.+Full details and diagrams are in `docs/CHATGPT-PLUGIN.md`; protocol/security internals are in+`docs/MCP.md`.++### Is "Sign in with OpenAI" in Alfa the same as the ChatGPT plugin?++No. Alfa's `openai-codex` option is a model-inference credential using a ChatGPT consumer+flow. The ChatGPT MCP app gives ChatGPT a scoped MSO bearer so it can call VPS tools. One+does not grant the other.++### Can ChatGPT send a generated image/file into the VPS?++Yes. `fs_upload_file` accepts a ChatGPT-provided temporary file reference, validates the+OpenAI download host/redirects/type/size, and writes it inside `OS_FS_WRITE_ROOTS`. MSO does+not maintain a second image generator; use ChatGPT's native generation, then transfer the+result.++### Does MCP expose every project automatically?++Project discovery searches configured containers with containment/ownership checks and hard+work bounds. A truncated scan comes with continuation metadata; it must not be interpreted+as a complete "not found" result. Project function calling is opt-in through+`.mso/functions.json` and always exec-scope.### What does it cost to run?-It's a normal Node process. Idle it sits around a few hundred MB RSS; the-systemd unit caps it at 3 GB. The optional headless Chromium (`os-browser`)-adds the usual browser footprint — skip it on tiny boxes.+The MSO Node process is modest compared with a full remote desktop, but exact RSS/build+needs depend on the host and enabled features. A production build needs significantly more+memory than idle runtime. Camoufox adds a real Firefox/X/VNC stack while it is running, so+leave it off on small boxes when not needed.-### How was the codebase audited?+### How is the codebase checked?-The maintainer's initial cross-cutting sweep — security, perf, a11y, slice-boundaries — is `docs/AUDIT-2026-06-11.md`; several source comments still cite its-findings by number. A follow-up pass and its scorecard were deleted on 2026-08-10-once every row had either shipped or gone stale (`git show-421ab7f:docs/AUDIT-2026-06-14.md`). A third pass on 2026-08-03 ran five-adversarially-verified lenses (over-engineering, security, Next 16/React 19,-package-manager migration, repo health) — see the top of `docs/PROGRESS.md`. Quality-gates run on every push via the pre-push hook: typecheck, lint, 1100+ vitest tests,-import-cycle check, a high/critical dependency audit, and an out-of-tree build.+Every normal push is expected to pass typecheck, lint, the full Vitest suite, cycle/doc/skill+checks, high/critical dependency audit and an out-of-tree production build. Dated audits are+historical evidence; current behaviour is validated continuously by the gates and current+reference docs.### Phone support?-Mobile-first is the point: the shell switches to a home-screen/app-switcher-surface on small viewports, apps get sheet-based sidebars, and the whole-thing is comfortable from a phone browser.+Mobile is a first-class surface. Portrait uses iOS/Android-style shells with safe-area and+single-owner navigation rules; phone landscape can resolve to the desktop surface. Current+shell E2E covers desktop, phone portrait and phone landscape.++### Why is the repo called `mso` but product text says MSO / Manef Shell OS?++`mso` is the stable repo/service/deploy slug. **Manef Shell OS** is the product name and+**MSO** is the short UI mark. Keeping the technical slug stable avoids churn in paths,+services and URLs.diff --git a/docs/HERMES-INTEGRATION.md b/docs/HERMES-INTEGRATION.mdindex 10070347..700aa0cf 100644--- a/docs/HERMES-INTEGRATION.md+++ b/docs/HERMES-INTEGRATION.md@@ -1,408 +1,107 @@-# Hermes — integration notes+# Hermes integration-> **⚠ SUPERSEDED IN PART (`a2c3882`, 2026-07-28).** Every passage about *feature-> discovery* — parsing Hermes's built SPA bundle to spawn one MSO window per-> upstream nav route — describes DELETED code (`lib/managed-apps/features.ts`,-> `feature-parser.ts`, `dynamic-features.tsx`, `feature-icons.ts`, the `/features`-> route, `os-shell/workspace-mode.ts`). Hermes is an ordinary app window now,-> opening on its own dashboard, because it already ships its own sidebar. Passages about-> the origin split, the proxy, the CLI fallback and the update centre are still accurate.-> Any mention of managed-app "single-origin mode" is also dead — see MANAGED-APPS.md §7.+> **Current reference.** Hermes is one of MSO's two managed applications. MSO no longer+> scrapes Hermes' SPA routes into launcher items; historical feature-discovery details are+> available in Git history, not in this runtime contract.-> Originally re-checked against the installed source under `~/.hermes` (read-only) and the-> live process on 2026-07-25. Shipped `c411187` → `d880f68`. Where this file and the code-> disagree, the code is what is documented and the divergence is called out.+## Runtime identity-The subsystem itself — contract, lifecycle, proxy internals, CSP intersection, backup,-deploy order, gaps — is [MANAGED-APPS.md](./MANAGED-APPS.md). This file is only what is true-of **Hermes**. Its sibling [OPENCLAW-INTEGRATION.md](./OPENCLAW-INTEGRATION.md) has the same-seven sections in the same order, so the two read side by side.--**Hermes is a separate application.** MSO gives it a window, a status card, a dock and a-switch. Nothing in this repo copies, forks or vendors its source, scrapes its DOM, or writes-a byte under `~/.hermes/`. Read-only inspection of that tree is how discovery works.-------## 1. What it is and where it lives--Hermes Agent — a tool-calling AI agent with a FastAPI/uvicorn web dashboard and a separate-messaging gateway (Telegram / WhatsApp / Discord). MSO uses it for exactly three things:-one status card, its own dashboard pages as MSO app tiles, and a read-only CLI view.--| | Value | Verified by |-|---|---|---|-| Version | `Hermes Agent v0.19.0 (2026.7.20) · upstream a61183b5` | `hermes --version` (line 1) |-| Install method | `git` | `~/.hermes/.install_method` |-| CLI | `/home/rahman/.local/bin/hermes` | `which hermes` |-| Install dir | `~/.hermes/hermes-agent` (1.5 GB — git checkout + its own venv) | `hermes --version`, `du -sh` |-| State dir | `~/.hermes` (2.7 GB — **the install lives inside the state dir**) | `catalog.ts:22`, `du -sh` |-| Dashboard port | `9119`, bound `0.0.0.0` | `ss -tlnp`, unit `--host 0.0.0.0` |-| Public today | **yes** — `ai.rahmanef.com` | `/etc/dokploy/traefik/dynamic/ai-hermes.yml` → `http://172.17.0.1:9119`, `passHostHeader: true` |-| MSO app host | `hermes.mso.rahmanef.com` → mso `:4005` → proxy → `127.0.0.1:9119` | `mso-managed-apps.yml`, `curl` below |--Two **user** systemd units, both in `~/.config/systemd/user/`, both `Restart=always`. There-is no system-scope unit for either.--| Unit | ExecStart | What it is |-|---|---|---|-| `hermes-dashboard.service` | `~/.hermes/hermes-agent/venv/bin/python -m hermes_cli.main dashboard --host 0.0.0.0 --port 9119 --skip-build --no-open` | the web dashboard MSO proxies |-| `hermes-gateway.service` | `… -m hermes_cli.main gateway run` | the messaging gateway — **not in MSO's catalog** |--The dashboard unit also sets `HERMES_HOME=/home/rahman/.hermes` and-`HERMES_DASHBOARD_PUBLIC_URL=https://ai.rahmanef.com`, and `WorkingDirectory=/home/rahman/.hermes`.--**`--host 0.0.0.0` is load-bearing twice over.** It is why Traefik can reach the dashboard-across the docker bridge for `ai.rahmanef.com`, and it is why Hermes runs its *gated* auth-middleware rather than the loopback one (§3). MSO does not depend on it: the proxy targets-`127.0.0.1:9119` and would keep working if the bind were narrowed.-------## 2. How MSO detects and controls it--Catalog entry at `lib/managed-apps/catalog.ts:14`.--| Field | Value |+| Property | Current MSO value ||---|---|-| `command` | `hermes` |-| `serviceNames` | `["hermes-dashboard.service", "hermes.service"]` |-| `containerNames` | `["hermes", "hermes-dashboard"]` |-| `dashboardUrl` | `http://127.0.0.1:9119` (`HERMES_DASHBOARD_URL`) |-| `stateDirName` | `.hermes` |-| overrides | `HERMES_HOME` (discovery **and** the backup source), `HERMES_WEB_DIST` (discovery only) |--**Detection resolves on the first candidate, and now for the right reason.** `systemctl --user show--p LoadState -p ActiveState hermes-dashboard.service` → `loaded` + `active`, so `detect()`-(`manager.ts:42`) accepts it and reports `installationType: "systemd"`. `hermes.service` is-`not-found` here and is skipped rather than accepted — which used to be the bug: `is-active` prints-`inactive` (rc 4) for an unknown unit on systemd 255, so the loop never advanced. OpenClaw is where-that bit — see [OPENCLAW-INTEGRATION.md §2](./OPENCLAW-INTEGRATION.md).--**Actions.** `start`/`stop`/`restart` run `systemctl --user <action> hermes-dashboard.service`, and try-the system scope only if that fails (`manager.ts:121`) — always via `execFile`, never a shell-(`runner.ts:12`). `backup` copies the Hermes home.--- Only the **dashboard** unit is touched. `hermes-gateway.service` keeps running through a dashboard- restart, and MSO offers no control over it at all. The dashboard reports the gateway's state in its- own `/api/status` (`gateway_running`, `gateway_state`, `gateway_platforms`) — look there after one.-- **`backup` follows `HERMES_HOME`** (`manager.ts:142`). It is not set in the *cockpit's* process —- the dashboard unit exports it for itself and that env does not reach mso — so the source falls- back to `~/.hermes`, the same path; a relocated install would now be copied instead of missed.- With the exclusions in [MANAGED-APPS.md §6](./MANAGED-APPS.md) the copy is **366 MB** rather than- 2.7 GB: the venv and `hermes-agent/node_modules` are pruned, and so is `~/.hermes/backups` — 1.1 GB- of Hermes' *own* snapshots. Symlinks are skipped, not refused: `find ~/.hermes -type l | wc -l` →- **58**, 57 inside those pruned trees, the last `lsp/bin/typescript-language-server`. Refusing on the- first symlink is what used to fail this install every time.-- Hermes' own `hermes backup` / `hermes import` still archive and re-import; MSO's copy has no restore side.--**What "healthy" means for Hermes: less than it looks.** `health()` (`manager.ts:65`) does-`GET http://127.0.0.1:9119/health` with `fetch`, which follows redirects, and returns-`response.ok`. `/health` is **not** on Hermes' public-path allowlist, so:--```-GET /health → 302 location: /login?next=%2Fhealth-GET /login → 200 text/html-```--The chain ends 200, so MSO reports `healthy: true`. It proves the dashboard answers HTTP —-nothing about the agent, the gateway, or whether anyone can log in. The real signal is-`GET /api/status`, which *is* public (`hermes_cli/dashboard_auth/public_paths.py:39`) and-returns version, `gateway_state`, per-platform channel state, `active_sessions` and-`can_update_hermes`. MSO does not read it.--**Version** is the first line of `hermes --version`, capped at 160 chars. The command also-prints the install directory and install method on later lines; those are discarded.--**Logs**: `journalctl --user -u hermes-dashboard.service -n 100 --no-pager -o short-iso`,-then redaction (`manager.ts:18`). Six lines today — the dashboard is quiet once up.--Live view from `listManagedApps()` against this host: `installationType: "systemd"`,-`state: "running"`, `healthy: true`, `dashboardAvailable: true`,-`supportedActions: ["start","stop","restart","backup"]`.-------## 3. Auth model, and how the proxy lives with it--Hermes runs **gated** auth because the bind is non-loopback. Its own `/api/status` reports the-shape: `auth_required: true`, `auth_providers: ["basic"]`, `auth_flows: ["cookie"]`. The-`basic` provider's credential belongs to Hermes and lives in Hermes' own state; MSO never reads-it, and no MSO code path reads `~/.hermes/config.yaml`, `auth.json` or `.env` (grep of-`lib/managed-apps/`: the only upstream reads are the built SPA, `web/src/App.tsx`, and the-public plugins endpoint).--**Its five cookies** (`hermes_cli/dashboard_auth/cookies.py:67-82`):+| Managed id | `hermes` |+| Preferred service | `hermes-dashboard.service` |+| Other recognized services | `hermes-gateway.service`, `hermes.service` |+| Dashboard upstream | `http://127.0.0.1:9119` by default |+| State | `HERMES_HOME` when set, otherwise `~/.hermes` |-| Bare name | Contents | `Max-Age` (`cookies.py:96`, `:104`, `:194`) |-|---|---|---|-| `hermes_session_at` | access token | whatever the provider's `expires_in` said |-| `hermes_session_rt` | refresh token (omitted entirely when empty) | 30 days (`_RT_MAX_AGE`) |-| `hermes_session_provider` | which provider minted the session (routing hint, no secret) | 30 days (same constant) |-| `hermes_session_pkce` | PKCE state + CSRF nonce + provider hint | 10 min |-| `hermes_sso_attempt` | one-shot auto-SSO loop guard (boolean breadcrumb) | 60 s |+The dashboard service is intentionally ranked ahead of the messaging gateway because it is+the service that actually answers the framed dashboard port.-All five are `HttpOnly`, `SameSite=Lax`, and their **names change with the request shape**:-`_resolved_name()` (`cookies.py:107`) prepends `__Host-` on HTTPS at `Path=/`, `__Secure-` on-HTTPS behind a path prefix, and nothing over HTTP. The switch is `request.url.scheme ==-"https"` (`cookies.py:338`), and uvicorn runs with `proxy_headers=bool(auth_required)`-(`web_server.py:19860`), so `X-Forwarded-Proto` would decide it.+## What MSO can do-**The proxy never forwards `x-forwarded-proto`** — it is not on the request allowlist-(`proxy-headers.ts:14`) — and it connects over plain `http` to loopback, so Hermes always takes-the bare-name branch for proxied traffic. MSO adds the transport hardening back on the browser-side: `rewriteSetCookie()` (`proxy-headers.ts:112`) renames `hermes_session_at` →-`mapp_hermes_hermes_session_at`, drops `Domain`, forces `SameSite=Lax`, keeps `HttpOnly` and-`Max-Age`, pins `Path` (`/` root-mounted, the proxy prefix otherwise) and appends `Secure` when-the *browser's* hop was HTTPS (`isSecureRequest()`, `:128`).+- detect installation/runtime state and version;+- install Hermes non-interactively;+- start, stop and restart the known service;+- read recent logs;+- create state snapshots;+- check/apply upstream updates;+- restore an MSO snapshot while Hermes is stopped;+- conservatively uninstall Hermes;+- optionally proxy the vendor dashboard from a dedicated managed-app hostname.-Why the namespace matters concretely: the cockpit's own cookie is called `session`, and any of-Hermes' five could as easily have been named that. The rest of the rule — only `mapp_hermes_*`-travels up, no `authorization`, no `www-authenticate` back — is in-[MANAGED-APPS.md §5](./MANAGED-APPS.md).+The generic architecture and backup/restore rules are in `docs/MANAGED-APPS.md`.-**Login flow, as it actually runs in the frame:**+## Install-1. `GET /` → `302 /login?next=%2F`. The `next` is built by `_safe_next_target()`- (`dashboard_auth/middleware.py:244`).-2. `/login` renders a username/password form plus **one inline `<script>`**- (`login_page.py:412`). Hermes ships no CSP, so `'unsafe-inline'` in MSO's own policy is- what keeps that script alive (§5).-3. Submit → `POST /auth/password-login` (JSON, `credentials: 'same-origin'`) → `200- {"ok":true,"next":"<path>"}` + `Set-Cookie`.-4. `window.location.assign((data && data.next) || '/')` (`login_page.py:436`).+The one-click flow runs `scripts/managed-app-install hermes` as a long-running managed-app+job. Hermes may fetch a Python toolchain and other prerequisites first, so several minutes+is normal.-### The upstream quirk MSO works around+A model provider is optional during installation. If supplied, the API key is sent once and+passed to the installer through its environment; MSO does not persist the key in the job+argv or transcript. Installing with no provider is valid—the running Hermes application can+be configured later through its own settings.-Hermes validates the post-login target twice, and **rejects every path under `/api/`**:+## Lifecycle-```python-# ~/.hermes/hermes-agent/hermes_cli/dashboard_auth/routes.py:561-def _validate_post_login_target(raw: str) -> str:- ...- if not decoded.startswith("/") or decoded.startswith("//"):- return ""- ...- if decoded == "/api" or decoded.startswith("/api/"):- return ""- return decoded-```+MSO recognizes the dashboard/gateway systemd units and exposes bounded+start/stop/restart actions rather than asking an AI client to run arbitrary service-manager+commands. When state detection is uncertain because the user bus is unavailable, MSO says+so and refuses install/restore operations that would be unsafe under that uncertainty.-with the same rule at `middleware.py:271` (inside `_safe_next_target`, `:244`) on the way in.-The upstream rationale is sound: a post-login redirect onto an API endpoint renders raw JSON,-and is indistinguishable from someone weaponising the redirect.+## Update semantics-In **single-origin mode** the proxy mount is `/api/v1/managed-apps/hermes/proxy`, so that-rule refuses it: Hermes answers `next: "/"` no matter what the hidden field says, step 4-navigates the frame to the cockpit root, and the cockpit's own `frame-ancestors 'none'`-refuses to display it — an opaque, blank frame. `proxy-html.ts:63` still rebases the hidden-`next` field (correct for an upstream without that rule), and `reentryPath()`-(`feature-cli.ts:84`) is the actual rescue: it re-points the frame back onto the prefix, and-treats a bare `/` as the fallback it is by sending the window to its own route instead of-the dashboard home. Three escapes in a row raises a "stuck" panel rather than looping.+Hermes supports an upstream read-only update check and a real apply operation. It does not+have a true update dry-run equivalent to OpenClaw's `--dry-run`.-In **origin-split mode** — production — the mount is `/` on `hermes.mso.rahmanef.com`, `next`-is a plain path Hermes accepts, and the whole workaround is inert: `reentryTarget()` returns-`null` without touching `frame.contentWindow.location` (`feature-cli.ts:122`), which it must,-because that read throws cross-origin and a throw is the "it escaped" branch.+Before an apply, MSO creates a state snapshot. A failed snapshot aborts the update. MSO+leaves Hermes' own backup preference alone rather than overriding it.----+Hermes has branch switching upstream, but MSO does not use it as an automatic rollback pin.+A restored `~/.hermes` tree can be dirty relative to Hermes' git checkout; immediately+running the branch updater can stash/reapply/reset exactly those restored files. For that+reason rollback restores state first and leaves code-branch movement as a separate explicit+operator decision.-## 4. The dashboard's shape, and what works through the proxy+## Backups and restore-A Vite-built React SPA at `~/.hermes/hermes-agent/hermes_cli/web_dist`, served by uvicorn.-The shell is minimal and **root-absolute**:+MSO snapshots Hermes state under `~/.mso/backups/hermes/<timestamp>/`. The snapshot skips+symlinks and reinstallable/cache directories including `.git`, `.venv`, `node_modules`,+`.cache`, `__pycache__` and nested `backups` trees.-```html-<script type="module" crossorigin src="/assets/index-CEmUNp2y.js"></script>-<link rel="stylesheet" crossorigin href="/assets/index-BbJ3HYO2.css">-```+Restore is available when Hermes is stopped. MSO verifies the backup manifest/path, checks+for symlink collisions, creates a `pre-restore` safety snapshot, then overwrites files from+the selected snapshot. It does not delete files created since that snapshot and does not+recreate directories that were excluded from backups.-- **No inline script in the SPA shell** (the only inline script is on `/login`).-- **No service worker** anywhere in `web_dist` — Hermes is not why the proxy refuses SW- scripts (`route.ts:109`); OpenClaw is.-- Its stylesheet carries 10 root-absolute `url()`s (7 `/assets/*.woff2`, 3- `/fonts-terminal/JetBrainsMono-*.woff2`), which is why `text/css` is rewritten too in- single-origin mode (`proxy-html.ts:11`).+This is separate from Hermes' own backup/import features; each system owns its own snapshot+format.-Root-mounted on `hermes.mso.rahmanef.com` those root-absolute URLs already resolve, so the-proxy rewrites the document **not at all** — no `<base href>`, no rebasing, no fetch shim,-nothing to hash-pin.+## Uninstall-**What does not work:** anything on a socket. Hermes opens six WebSocket routes —-`/api/console` (`web_server.py:17667`), `/api/pty` (`:18017`), `/api/ws` (`:18204`),-`/api/pub` (`:18235`), `/api/events` (`:18263`), `/api/audio/speak-stream` (`:4533`). A Next-route handler cannot service an `Upgrade`, and the proxy is `fetch`-based, so the **Chat**-page loads its chrome and sits dead.+The MSO-managed uninstall uses Hermes' conservative removal path and keeps `~/.hermes`+state by default. The more destructive upstream full removal flag is not exposed by MSO.+MSO creates a snapshot before invoking the uninstall; a failed snapshot means no uninstall.-**Everything else is REST**, and Hermes' asset and cookie shape is fully carried by the proxy,-so the remaining 19 pages are expected to render. That expectation is *not* browser-verified-here: there are no integration tests in this subsystem-([MANAGED-APPS.md §8](./MANAGED-APPS.md)) and this pass verified the transport, not each paint.+## Dashboard-Because only `chat` is socket-bound (`SOCKET_FEATURES.hermes = new Set(["chat"])`,-`feature-cli.ts:43`), Hermes features **default to the UI view** — `defaultView()` switches-to CLI only for an app whose every panel needs the socket. Chat opens on the UI with a-notice explaining why it is empty and a one-click switch to `hermes chat` in a real PTY.--Also inert in the frame, in either mode: new-window links. `allow-popups` is deliberately-absent from the sandbox (`feature-app.tsx:107`), so all six `window.open(` sites in the entry-chunk do nothing, and nothing is lost either way — four are the provider-OAuth hop-(`auth_url` / `verification_url`, across two duplicated code paths) whose callback is the-upstream's own `127.0.0.1` and unreachable from a browser regardless; two are a generic-"open this link in a new tab" helper, a destination for the user's own browser rather than-this frame. (`feature-app.tsx:99` says "2 call sites"; the measured count is six.) The window-says the clicks do nothing rather than letting them look broken.-------## 5. Its own CSP and framing headers, and what the intersection does--Hermes **serves no policy at all**. `curl -sS -D- -o /dev/null http://127.0.0.1:9119/login`-returns exactly `HTTP/1.1 200`, `date`, `server: uvicorn`, `cache-control: no-store, no-cache,-must-revalidate`, `content-length: 10044`, `content-type: text/html; charset=utf-8` — nothing-else; `/` and `/health` answer a bare `302 Found` carrying only `date`, `server`,-`content-length` and `location`. (It has to be a GET: `/login` is `GET`-only and answers `405`-to `curl -sI`.) No `content-security-policy`, no `x-frame-options`, no `permissions-policy`-anywhere, so Hermes is framable as shipped and `contentSecurityPolicy()` (`proxy-csp.ts:214`)-has nothing to intersect — every directive stays as MSO wrote it. What the browser gets on-`hermes.mso.rahmanef.com`, computed from the live headers:--```-default-src H; script-src H 'unsafe-inline' blob:; style-src H 'unsafe-inline';-img-src H data: blob:; font-src H data: https:; media-src H data: blob:;-worker-src blob:; connect-src H data: blob:; frame-src H; form-action H;-base-uri H; frame-ancestors 'self' https://mso.rahmanef.com; object-src 'none'- …where H = https://hermes.mso.rahmanef.com/-```--Three consequences specific to Hermes:--- **`'unsafe-inline'` in `script-src` is what keeps `/login` working.** Root-mounted, MSO- injects nothing and therefore pins nothing (`proxy-csp.ts:233`), so the inline handler at- `login_page.py:412` is covered only by `'unsafe-inline'`. This is safe *because* Hermes- ships no policy; it is also the thing that would break first if it ever started shipping- one (§7).-- **`img-src` loses `https:`** root-mounted. Hermes references no external image host at- all, and the wildcard would have been a credentialed existence oracle over- `OS_FS_READ_ROOTS` (the session cookie is `Domain`-widened to reach this host, so a- `new Image().src = "<cockpit>/api/v1/fs/raw?path=…"` fires with it).-- **`fonts.googleapis.com` is refused.** The bundle references it once- (`web_dist/assets/index-CEmUNp2y.js`), but `style-src` has no `https:` and Hermes declares- no policy for the intersection to honour, so nothing grants it. Not silent: it is the one- Hermes entry in `PROXY_BLOCKED_EXTERNALS` (`proxy-headers.ts:228`) and the window says- *"Theme webfonts (Inter, IBM Plex, …) fall back to system faces."* `font-src` keeps `https:`- — webfont *files* are CORS-anonymous, carry no cookie, and blocking them broke visibly.--`frame-ancestors` is always MSO's (`proxy-csp.ts:104`) — being framed by the cockpit is the-whole point. Live check, unauthenticated, so `401` is the success signal:--```-$ curl -sI https://hermes.mso.rahmanef.com/-HTTP/2 401-content-security-policy: default-src 'none'; frame-ancestors 'self' https://mso.rahmanef.com-x-middleware-rewrite: /api/v1/managed-apps/hermes/proxy-```-------## 6. Feature discovery for Hermes--`discoverHermes()` (`features.ts:49`) reads Hermes' **own nav table** off disk, then splices-in its **own plugin manifests** over HTTP. Nothing is hardcoded as a feature.--1. Read `<dist>/index.html` and follow the `<script src="/assets/…js">` it names; if that- fails, the newest `assets/index-*.js` (`features.ts:42`). `<dist>` is `HERMES_WEB_DIST`,- else `<HERMES_HOME|~/.hermes>/hermes-agent/hermes_cli/web_dist`.-2. Parse the `{ path, labelKey?, label }` nav table (`parseHermesNavBundle`,- `feature-parser.ts:64`). The regex keys on `path:` immediately followed by an optional- `labelKey:` and then `label:` — property names, which survive minification. **18 entries- today.**-3. Empty? Parse the route→component record in the same bundle (`:75`) — titles then come- from the `key=label` table at `feature-parser.ts:7`. **17 entries today**, so this- fallback is live and correct, just label-poorer.-4. Still empty? Parse `~/.hermes/hermes-agent/web/src/App.tsx` — a git install keeps the nav- SSOT in TypeScript and the same shapes match. Present here, `path: "/sessions"` at- line 165.-5. Splice plugin tabs from `GET /api/dashboard/plugins` — **public and unauthenticated**- by upstream's own declaration (`public_paths.py:48`), so no credential is involved —- honouring `position: before:/after:`, `override` and `hidden` exactly the way upstream's- `buildNavItems()` does (`web/src/App.tsx:233` vs `feature-parser.ts:94`, including the- "target not found → append" behaviour).--Live result, reproduced end to end: **18 built-ins + 2 plugin tabs = 20 features**, all-`available`.--- `nav-bundle` (18): `/chat` `/sessions` `/files` `/analytics` `/models` `/logs` `/cron`- `/skills` `/plugins` `/mcp` `/channels` `/webhooks` `/pairing` `/profiles` `/config`- `/env` (titled "Keys") `/system` `/docs` (titled "Documentation").-- `plugin-api` (2): `/achievements` spliced after `/analytics`, `/kanban` after `/skills`.-- Skipped on purpose (`feature-parser.ts:14`): `/` (a redirect) and `/profiles/new` (a form).--**The tripwire.** `checked()` (`feature-parser.ts:58`) accepts a run only if it has **≥ 5-entries and includes `/sessions`**; otherwise it discards the *whole* run. So a bundle-reshuffle that breaks the regex yields **zero** Hermes tiles, never a plausible-looking-partial list.--**Exact symptom when an upgrade breaks it:** the Hermes workspace keeps only the shared apps-(Terminal, Files, Assistant, Monitor, Settings) and every Hermes tile disappears from dock-and Launchpad. `/api/v1/managed-apps/hermes/features` still answers `200 {"features":[]}` —-a `503` only happens if discovery *throws*. The status card, the proxy and the CLI view are-unaffected, so the dashboard is still reachable via the Hermes app window. Results cache 60 s-(`features.ts:15`), so a fix or a new upstream nav entry appears within a minute; nothing-invalidates on upgrade.--**CLI view.** 13 of the 20 keys map to a verified read-only subcommand-(`feature-cli.ts:22`): `chat`, `sessions`, `logs`, `cron`, `skills`, `plugins`, `mcp`,-`pairing`, `kanban`, `config` → `config show`, `models` → `config get model`, `webhooks` →-`webhook`, `profiles` → `profile`. The other seven — `files`, `analytics`, `achievements`,-`channels`, `env`, `system`, `docs` — have **no `hermes` subcommand at all**, so the toggle-is simply absent rather than shelling something bogus. `models` maps to `config get model`-and not `hermes model` on purpose: bare `hermes model` is *"Interactively select your-inference provider and default model"* and saves the pick, so it would write on window open.-------## 7. Upgrade and operational notes--Hermes updates itself: `hermes update` (and `hermes uninstall`). MSO has **no update-centre** — no check-update, channels, update, rollback or install wizard (see-[MANAGED-APPS.md §8](./MANAGED-APPS.md)). Nothing in MSO's action set writes upstream state,-which is why the current surface is safe. Pending on this host right now, per the public-`/api/status`: `can_update_hermes: true`, and `config_version: 28` against-`latest_config_version: 33` — a config migration Hermes wants (`hermes config migrate`).-MSO neither reports nor performs either.--**The dashboard unit never builds.** `--skip-build` means uvicorn serves whatever `web_dist`-the last build left ("Skipping web UI build (--skip-build); using dist at …" in its startup-log), so discovery reflects that dist and not the installed Python version. After a-`hermes update` that ships frontend changes, rebuild with Hermes' own tooling or the tiles-describe the previous release.--Re-check after any Hermes upgrade:--| Check | Why |-|---|---|-| tile count (open the Hermes workspace) | a nav-table reshape trips the tripwire → 0 tiles |-| `systemctl --user list-units '*hermes*'` | if `hermes-dashboard.service` is renamed, no configured unit is `loaded` any more and the card reads `not-installed` with no actions — a rename means a catalog edit |-| sign in inside an app window | see the CSP note below |-| `curl -s 127.0.0.1:9119/api/dashboard/plugins` | a new bundled plugin adds a tile automatically; `override`/`hidden` manifests are skipped |-| `ls …/web_dist/assets` | discovery follows `index.html`, so a new asset hash self-heals; a *missing* `index.html` falls back to the newest `index-*.js` |+Embedding is opt-in. With split-origin configuration, a host such as+`hermes.mso.example.com` routes only to the authenticated MSO Hermes proxy, which forwards+to the loopback dashboard. Without split-origin configuration, MSO does **not** embed the+vendor dashboard and the Details management surface remains available.-**The one upgrade that would actually break the frame: Hermes starting to ship its own-CSP.** Today it ships none, so MSO's `script-src … 'unsafe-inline'` covers the inline login-handler. If a future release sent, say, `script-src 'self'`, the intersection would drop-`'unsafe-inline'` (nothing on the upstream side allows it) and — root-mounted — MSO pins no-hash of its own (`proxy-csp.ts:233`), so Hermes' *own* inline login script would be blocked-and the password form would stop submitting inside the frame. A release that instead ships-hashes for its inline scripts is fine: hashes are copied across (`proxy-csp.ts:190`), nonces-never are. Sign-in through the app window is therefore the smoke test after an upgrade, not-just "does the dashboard render".+Do not install untrusted Hermes plugins because of the iframe origin separation. A Hermes+plugin executes inside Hermes with Hermes' host privileges; browser-origin isolation only+protects the MSO browser realm.-**Known divergences from this integration, all upstream-neutral:**+## Troubleshooting-- `hermes-gateway.service` is invisible to MSO. Messaging channel breakage shows up only in- the dashboard's own Channels page or `hermes status`.-- `backup` runs but has no restore side (§2). To roll back, use `hermes import` or `cp -a`.-- `healthy: true` means "answers HTTP" (§2). For a real answer, read `/api/status`.-- `ManagedAppView.dashboardAvailable` is computed and no UI consumes it.+- **Hermes appears installed but dashboard is absent:** confirm the dashboard service, not+ only the messaging gateway, is actually listening; then check split-origin configuration.+- **Install button refuses because state is uncertain:** repair MSO access to the owner+ systemd user bus before retrying.+- **Update refuses before running:** inspect the mandatory state-snapshot error.+- **Restore refuses:** stop Hermes first and resolve the reported path/symlink mismatch.+- **Need the old branch as well as old state:** restore state in MSO, then move the Hermes+ checkout separately after reviewing the resulting working tree; do not make branch+ switching an automatic continuation of restore.diff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex e35d4414..5cf38c06 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -1,345 +1,299 @@-# Installing mso (Manef Shell OS) on your VPS+# Installing MSO on a Linux server-Step-by-step setup for a server you own. For the short path, see-[Install](../README.md#install). This guide covers credentials, systemd, TLS,-the optional browser service, demo mode, updating, and rollback.+> **Current reference.** The one-command installer is the supported path for a normal+> deployment. Manual commands below explain the model and recovery boundaries; release+> developers should use `bun run ship`, while operators update through Settings → About or+> `mso update run`.## 0. Requirements-- A Linux VPS (any distro with systemd; 1 vCPU / 2 GB RAM works, build wants- ≥2 GB free — see [Troubleshooting](./TROUBLESHOOTING.md)).-- **Node.js 20.9+** (22 recommended) — the RUNTIME — and **bun** as the package manager.-- A **non-root user** that owns the install. Never run mso as root —- an authenticated session can run shell commands as the process user.-- Optional: a domain + reverse proxy (Caddy/nginx/Traefik) **or** Tailscale.+- Linux with systemd;+- Node.js 20.9+ (Node 22 recommended/current production runtime);+- Bun for dependency installation/scripts;+- a non-root user that owns MSO;+- enough memory/swap for a Next production build (build needs more than idle runtime);+- HTTPS through Tailscale Serve or a reverse proxy for normal non-localhost browser use.-## 1. Clone + install+Optional Browser support additionally needs Camoufox, Xvfb, a lightweight X window manager,+x11vnc, noVNC/websockify and a user systemd runtime.++## 1. Recommended one-command install++Run as the normal server user, not root:```bash-# as your normal user (NOT root)-git clone https://github.com/<you>/mso.git ~/mso-cd ~/mso-bun install+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash```-## 2. Credentials — read this section carefully+The installer:++1. resolves/creates the checkout;+2. installs Bun/dependencies as needed;+3. creates private owner auth configuration when missing;+4. runs the production build;+5. installs the `mso.service` system unit when systemd is available;+6. enables the owner's lingering user manager needed by self-update/managed-app user units;+7. installs the `mso` CLI convenience link and official skills;+8. starts/replaces the service only after a successful build.++Useful flags:++```text+--dir PATH installation directory+--ref REF branch/tag/ref (default main)+--port N app port (default 4005)+--bind ADDR listen address (default 127.0.0.1)+--no-service build without installing the system unit+--uninstall remove the system unit; keep code + ~/.mso+```++Re-running the installer updates an existing installation with the same build-before-replace+safety rule.++## 2. Network exposure-mso is single-owner. A password, signed session cookie, and device allowlist-gate owner access. All of it lives in two places:+The installer binds `127.0.0.1` by default. This is intentional: an authenticated MSO owner+session can execute host commands.-| What | Where | Committed? |-|---|---|---|-| Secrets/env | `.env.local` | **NEVER** (gitignored) |-| Device allowlist, BYOK AI key, audit log | `~/.mso/*.json`, `~/.mso/audit.log` | outside the repo |+For an initial connection, use a localhost tunnel:```bash-cp .env.example .env.local+ssh -N -L 4005:127.0.0.1:4005 you@your-server```-Edit `.env.local`:+Then open `http://localhost:4005`. A `Secure` cookie is accepted on localhost, but ordinary+plain-HTTP IP/hostnames will drop it.-```bash-# Owner password (min 6 chars). Use a strong password for any exposed host.-OS_LOGIN_PASSWORD=pick-something-strong+### Tailscale (recommended)-# The HMAC key that signs session cookies. MUST be strong and random:-OS_SESSION_SECRET=$(openssl rand -hex 32) # paste the output, don't keep the $( )-```+Keep MSO on loopback and publish it with Tailscale Serve so the browser reaches an HTTPS+origin.-**Device approval.** The first time a browser logs in with the right password-it does NOT get a session — it lands *pending*. Promote it once, from the-server. This is a local browser allowlist, not standards-based 2FA:+### Caddy/nginx/Traefik-```bash-# the device id is shown on that browser's login screen-node scripts/approve-device.js <deviceId> "rahman's phone"-```+Terminate TLS at the reverse proxy and forward to `127.0.0.1:4005`. Preserve the real host+and client IP headers consistently. Set `OS_PUBLIC_ORIGIN=https://mso.example.com` when a+reverse proxy is the stable public origin; MCP discovery and managed-app CSP use it as+deployment-owned authority.-After you have one approved device, you can approve new ones from the UI-(Settings → Devices) instead of SSH. The allowlist is a plain JSON file at-`~/.mso/auth-devices.json` — deleting an entry revokes that device.+Do not bind `0.0.0.0` merely because a reverse proxy exists. Bind wider only when the host+firewall/network design explicitly requires it.-**Filesystem bounds.** Reads and writes are jailed to configured roots-(default: `~` + `~/projects`, realpath-checked so symlinks can't escape):+## 3. Owner authentication-```bash-# widen reads to the whole box (read-only browsing), keep writes narrow:-OS_FS_READ_ROOTS=/-OS_FS_WRITE_ROOTS=~:~/projects+If installing manually, copy `.env.example` to `.env.local` and set at minimum:-# narrow reads to projects only (hides the rest of $HOME entirely):-OS_FS_READ_ROOTS=~/projects+```dotenv+OS_LOGIN_PASSWORD=choose-a-strong-owner-password+OS_SESSION_SECRET=<stable random 32+ byte secret>```-Even inside legal roots, credential material is always blocked: `~/.mso`,-the app's own `.env*`, and the sensitive-home denylist (`~/.ssh`, `~/.gnupg`,-`~/.secrets`, `~/vault`, `~/.bash_history`, `~/.npmrc`) — those paths are-unreadable AND hidden from listings. Escape hatch for a supervised session:-`OS_FS_ALLOW_SENSITIVE=1`.+The first correct login from a browser creates a **pending device**. Approve the device id+shown on that login screen from the server with `scripts/approve-device.js`. After one+browser is approved, additional devices can be approved in Settings → Devices.-**Rotation.** To rotate the session secret just change `OS_SESSION_SECRET`-and restart — every session is invalidated, approved devices stay approved.-To rotate the password change `OS_LOGIN_PASSWORD`; pending devices reset on-their next attempt.+Changing `OS_SESSION_SECRET` invalidates all existing browser sessions while leaving the+device allowlist intact.-**Checklist before going live** (same as the README security checklist):-strong `OS_SESSION_SECRET`, VPN/TLS in front, tight read roots, non-root-user, `.env.local` never committed, review `~/.mso/audit.log`.+## 4. Filesystem roots-## 3. First run+Defaults allow the owner's home/project area. Override deliberately:-```bash-bun run build-bun run start # serves on :3000, or PORT=4005 bun run start+```dotenv+OS_FS_READ_ROOTS=~:~/projects+OS_FS_WRITE_ROOTS=~:~/projects```-Open it, note the device id on the login screen, approve it (step 2), log in.--## 4. Run as a systemd service--`/etc/systemd/system/mso.service` (adjust user + paths):--```ini-[Unit]-Description=Manef Shell OS — browser-based visual shell for a Linux server-After=network.target--[Service]-Type=simple-User=youruser-WorkingDirectory=/home/youruser/mso-EnvironmentFile=/home/youruser/mso/.env.local-Environment=PORT=4005-Environment=HOSTNAME=127.0.0.1-ExecStart=/usr/bin/npm run start -- --hostname 127.0.0.1 --port 4005-Restart=always-RestartSec=5-MemoryMax=3G-StandardOutput=journal-StandardError=journal-SyslogIdentifier=mso--[Install]-WantedBy=multi-user.target-```+`OS_FS_READ_ROOTS=/` permits broad **read** browsing subject to the process user's Unix+permissions, but write roots should stay narrow. The credential denylist still blocks MSO's+private state, `.env*`, SSH/GPG paths and other sensitive-home material.-```bash-sudo systemctl daemon-reload-sudo systemctl enable --now mso.service-journalctl -u mso -f # watch logs-```+## 5. Service model-That `ExecStart` runs the `start` script from `package.json` (`next start`) — note the-`--` before the flags, which is what forwards them to `next` rather than to npm.+The installed production process is a normal systemd system unit running as the non-root+owner, with its working directory set to the checkout and `.env.local` loaded as the+environment file.-**npm here is deliberate, and is not a typo for bun.** bun is this project's-*installer*; the *runtime* stays Node, because `node-pty` is a native addon compiled-against Node's ABI and `lib/host/index.ts` re-exports it into all 51 `/api/v1` routes.-npm ships with Node, so `/usr/bin/npm` exists on a box where a bun install path may not-— and systemd resolves `ExecStart` with no shell and no user PATH. Verify the binary-really is where the unit says (`command -v npm` → adjust `ExecStart=` accordingly;-`/usr/local/bin/npm` on some distros). Dependencies are still installed with-`bun install --frozen-lockfile` from `bun.lock` — don't substitute npm/yarn/pnpm for-*that* step, or lockfile drift defeats the audit trail.+The installer also sets `XDG_RUNTIME_DIR=/run/user/<uid>` and enables user lingering. This+is required because MSO itself controls systemd **user** units such as Camoufox and managed+applications; without a persistent user manager those calls look like "not installed" even+when the application exists.-**Graceful shutdown**: add to the `[Service]` block:+Production health is:-```ini-KillSignal=SIGTERM-TimeoutStopSec=20+```text+GET /api/health -> {status, buildId, uptime, version}```-This gives 20 s for in-flight requests + PTY sessions to drain on-restart. Without it, systemd waits the default 90 s then SIGKILLs —-fine for normal use, but interactive PTY sessions get cut mid-keystroke.+## 6. Optional Browser app — Camoufox-## 5. Put TLS in front (pick ONE)+The current Browser app is **Camoufox**, not the retired Playwright browser daemon.+`scripts/camoufox-vnc-service` launches:-**Tailscale (recommended for a personal box):** don't expose anything.-`tailscale up`, then `tailscale serve 4005`, and browse the-`https://<machine>.<tailnet>.ts.net` URL it prints.+```text+Xvfb -> matchbox window manager -> Camoufox -> x11vnc -> websockify/noVNC+```-`tailscale serve` is required, not a nicer alternative: reaching-`http://<machine>:4005` directly over the tailnet **cannot log in**. The session-cookie is `Secure` (`lib/auth/session-cookie.ts`), and a browser only keeps a-`Secure` cookie over plain http on `localhost` / `127.0.0.1` / `::1`. A-`100.64.0.0/10` address or a MagicDNS name is neither, so the login returns 200-and the cookie is dropped — an endless login loop with the right password. The-same is true of every `http://<ip>:4005` URL.+The service should be a systemd **user** unit named `camoufox-vnc.service`. It is intended+to stay **disabled at boot**, with `Restart=no` and a finite runtime lease; the Browser UI+powers it on only when needed.-**Caddy (public domain):**+Important paths/defaults:-```caddy-os.example.com {- reverse_proxy 127.0.0.1:4005-}-```+- persistent logged-in profile:+ `~/.local/share/camoufox/profiles/linkedin`;+- VNC password file: `~/.vnc/passwd`;+- rolling login/session safety snapshots:+ `~/.local/state/camoufox/session-backup/`;+- runtime noVNC overlay: under `XDG_RUNTIME_DIR` and recreated each start.-**nginx:** a standard `proxy_pass http://127.0.0.1:4005;` server block with-TLS (certbot). Keep `proxy_set_header Host $host;` and forward-`X-Forwarded-For` (the login rate limiter keys on client IP).+The profile can contain live Google/LinkedIn cookies. Keep the profile and session backups+private (`0700` parent tree) and do **not** add them to an ordinary broad backup without+considering the account-takeover impact of a stolen cookie database.-Either way the app should stay on `127.0.0.1:4005` (the installer's default), so-the proxy is the only thing that can reach it and there is no public port to-firewall in the first place. If you deliberately bind wider with-`--bind 0.0.0.0`, firewall :4005 as well.+The old `os-browser/` directory that remains in this checkout is development/test tooling+because it carries the Playwright dependency. It is not a production browser service and+uses none of the old `OS_BROWSER_*` runtime configuration.-## 6. Optional — the Browser app (Camoufox)+## 7. Optional Alfa AI-The Browser app streams a real anti-fingerprinting Firefox from a headless X-display over noVNC, run by the `camoufox-vnc.service` systemd USER unit whose-ExecStart is `scripts/camoufox-vnc-service` in this repo. Skip it and everything-else still works. See CLAUDE.md for the host-side prerequisites (`enable-linger`,-the `XDG_RUNTIME_DIR` drop-in, and the VNC password file it refuses to start-without).+Settings → AI can store BYOK provider credentials in private host config. Common built-ins+include Anthropic/OpenAI/OpenRouter/Google/Groq/xAI/DeepSeek/Mistral; custom compatible+endpoints are supported and SSRF-checked.-An earlier `os-browser/` Playwright sidecar on :4002 filled this role; it was-stopped, disabled, and finally deleted on 2026-08-10. Only its vendored-Playwright install remains, used by `scripts/gen-readme-media.mjs`.+The optional `openai-codex` provider uses a separate ChatGPT consumer OAuth/device flow for+Alfa inference. It is unrelated to the ChatGPT MCP connector. See+`docs/MODELS-INTEGRATION.md`.-## 7. Optional — AI assistant (BYOK)+## 8. Optional MCP / ChatGPT custom app-Set `ANTHROPIC_API_KEY` in `.env.local`, **or** paste a key in the OS under-Settings → AI (stored in `~/.mso/config.json`, never in the repo). Unset-= the assistant endpoint returns 501 and the rest of the OS is unaffected.+MCP is **off by default**. Enable it only for a deployment that needs external AI clients:-## 8. Optional — public demo mode--```bash-NEXT_PUBLIC_OS_DEMO=1 bun run build && bun run start+```dotenv+OS_MCP_ENABLED=1+OS_MCP_MAX_SCOPE=read # raise to write/exec only when required```-Demo builds have **no real login, no host access, no PTY, no shell command-execution, no live host API, and no API-key storage**. They use mock data only-and show a permanent demo banner. Use a separate checkout/service for the demo;-the flag is baked at build time.+Use `docs/CHATGPT-PLUGIN.md` for ChatGPT setup and diagrams, and `docs/MCP.md` for the+complete protocol/security model. After changing the MCP toolset, refresh/re-scan the+ChatGPT app; MSO's "Mark ChatGPT refreshed" button is only a local acknowledgement.-## 9. Updating+## 9. Optional managed-app dashboards-```bash-cd ~/mso-git status --short # must be clean before updating-git fetch origin main-git merge --ff-only FETCH_HEAD-bun install --frozen-lockfile-bun run build # ALWAYS build before restarting-sudo systemctl restart mso.service-./scripts/post-deploy-smoke.sh # catches the chunk/MIME drift the README warns about-```+Hermes/OpenClaw lifecycle management works without embedding their web dashboards. The safe+default is therefore no vendor dashboard on the MSO origin.-The installer follows the same rule: it shows the old and new commit, refuses-dirty worktrees, exits non-zero if the target ref cannot be fetched, builds only-after a successful update, and restarts only after a successful build.+To opt into split-origin embedding, configure **both**:-Build **then** restart, never the reverse — `next start` loads the build-manifest at boot, and mismatched on-disk chunks cause every CSS/JS request to-404 (see [Troubleshooting](./TROUBLESHOOTING.md#ui-is-unstyledbroken-after-a-deploy)).+```dotenv+NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com+OS_SESSION_COOKIE_DOMAIN=.mso.example.com+OS_PUBLIC_ORIGIN=https://mso.example.com+```-## 9b. Rolling back+Provision DNS/TLS only for the explicit `hermes` and `openclaw` hostnames and sign out/in+after changing the cookie domain. There is no supported same-origin iframe fallback. See+`docs/MANAGED-APPS.md`.-If a deploy breaks production:+## 10. Public demo mode-1. Find the prior good commit: `git log --oneline -10`-2. Check out the known-good commit: `git switch --detach <good-sha>`-3. Rebuild: `bun run build`-4. Restart: `sudo systemctl restart mso.service`-5. Verify: `curl -s http://localhost:4005/api/health | jq .buildId`+A public showcase must be a separate checkout/service built with:++```bash+NEXT_PUBLIC_OS_DEMO=1 bun run build+```-If the build itself broke (TypeScript or compile error), leave the running-service alone, fix the checkout, and rebuild before restarting. If chunks are-404ing after restart (build/run version mismatch): stop the service, remove-`.next`, rebuild, then start it again.+Demo mode is mock-only: no normal owner auth, no live host API, no real PTY/exec, no MCP and+no API-key storage. Do not toggle demo mode in the production owner checkout.-## 9c. Healthcheck+## 11. Updating-`GET /api/health` returns `{status, buildId, uptime, version}` with-`Cache-Control: no-store`. Wire it into:+### Operator update-**systemd watchdog** (implemented + live): the production unit keeps-`Type=simple` (no readiness handshake → no startup race) plus:+Use Settings → About or:-```ini-[Service]-WatchdogSec=30-NotifyAccess=all+```bash+mso update status+mso update run+mso update log```-`instrumentation.ts` `register()` pings `WATCHDOG=1` every ~10 s via the-`systemd-notify` binary — Node has no native AF_UNIX SOCK_DGRAM, and-`NotifyAccess=all` is required because the ping comes from a child PID, not-`main`. A wedged event loop that misses the 30 s deadline → systemd-auto-restarts (catches hangs that `Restart=always`, crash-only, can't). All a-no-op when `NOTIFY_SOCKET` is unset (dev / demo / CI).+The updater verifies the incoming checkout/build before replacing the service. A successful+finalizer log ends with `UPDATE OK`.++If the installed source is correct but the production build tree is inconsistent, use:-After editing the unit: `sudo systemctl daemon-reload && sudo systemctl restart mso.service`-Verify: `systemctl show mso -p WatchdogUSec,NRestarts,ActiveState`+```bash+mso update run --rebuild+```-**External monitor** (Uptime Kuma / Healthchecks.io / etc):+### Developer release-- URL: `https://mso.rahmanef.com/api/health`-- Expected: HTTP 200 + JSON body-- Interval: 60s-- Timeout: 5s-- Alert when: `status!="ok"` OR 2 consecutive failures+After code/docs changes and verification:-**Dokploy**: configure the application healthcheck endpoint at `/api/health`.+```bash+bun run ship "feat(scope): describe the verified change"+```-## 9e. Backup & retention+The command updates the generated changelog, runs pre-push gates (including an out-of-tree+production build), pushes the exact commit, then performs the in-place build/replacement and+post-deploy chunk verification. When started through MCP, finalization is handed to the+owner user manager so replacing MSO cannot kill its own deploy controller.-`~/.mso/` is the persistence root:+A Git push by itself is **not** a production deployment.-- `auth-devices.json` — approved-device allowlist (losing it = re-approve every device)-- `config.json` — BYOK key + AI model preferences-- `audit.log` — append-only JSONL forensic trail-- `chrome-profile/` — Playwright user data (browser app, optional)+## 12. Rollback-**Backup recommendation**: nightly `restic` (or `rsync` to off-host) of `~/.mso/`. ≤10MB typical.+Prefer an explicit known-good Git commit and the same verified rebuild/update machinery,+not ad-hoc partial `.next` changes. Keep the old running process alive if the candidate+build itself fails.-```bash-# example: restic to S3-compatible / Backblaze B2 / local NAS-restic -r b2:my-bucket backup ~/.mso --tag mso --exclude chrome-profile-```+For a live chunk mismatch after the source ref is already correct, `mso update run --rebuild`+is the supported recovery path. Verify `/api/health` and `scripts/post-deploy-smoke.sh`+afterward.-**Audit log rotation** (avoid unbounded growth):+## 13. Backups and persistence-```-# /etc/logrotate.d/mso-/home/rahman/.mso/audit.log {- su rahman rahman- size 1M- rotate 4- copytruncate- compress- delaycompress- missingok- notifempty-}-```+MSO owner-local state under `~/.mso/` includes:-The `su` directive tells logrotate which user owns the rotated files-(required when the path lives under a non-root home). `copytruncate` is-the right choice here: the audit writer in `lib/host/audit.ts` opens the-log with each `appendFile` call, so no HUP/USR1 signal is needed to make-it reopen the fd — truncate-in-place is safe.+- approved devices;+- AI/provider configuration;+- MCP OAuth client/token hashes;+- audit/activity/workflow memory;+- managed-app snapshots under `~/.mso/backups/`.-## 9d. Zero-downtime restart (advanced)+Back up `~/.mso` with the same care as credentials. Managed-app snapshots can contain the+managed application's secrets and are not encrypted by MSO.-`systemctl restart` kills the running process then starts the new one — brief-200-500 ms gap during which `/_next/static` chunks 404 mid-flight. For higher-availability:+Camoufox login state is **not** under `~/.mso`; it lives in the local-share/local-state+paths documented above and is even more sensitive because it can contain reusable session+cookies.-1. Run two instances on adjacent ports (4005 + 4006) behind a reverse proxy- (Caddy/nginx).-2. Update systemd to a socket-activated `[email protected]` template.-3. Rolling restart: `systemctl restart [email protected]` first; verify- `/api/health`; then 4005.+Rotate/retain `~/.mso/audit.log` with normal host log management. Inspect logs before+sharing them because command/path context may be private.-For a single-owner personal tool, this is overkill — the 200-500 ms gap is fine.+## 14. Uninstall-## 10. Uninstall+The supported installer uninstall removes the MSO systemd unit but deliberately keeps the+checkout and `~/.mso` data:```bash-sudo systemctl disable --now mso.service os-browser.service 2>/dev/null-sudo rm /etc/systemd/system/mso.service /etc/systemd/system/os-browser.service-rm -rf ~/mso ~/.mso # ~/.mso holds devices/config/audit log+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --uninstall```++Delete code/private state only as a separate deliberate owner action after deciding what to+retain. Camoufox is a separate user service/profile and is not silently deleted by the MSO+installer.++## 15. Verification checklist++After install/update:++1. service is active;+2. local and public `/api/health` report the expected build id;+3. login works on an approved browser over HTTPS/localhost;+4. `scripts/post-deploy-smoke.sh` passes;+5. if UI changed, test desktop + phone portrait + phone landscape;+6. if MCP changed, compare Settings → MCP signature and refresh the external app/tool+ snapshot;+7. if managed-app origins changed, sign in again and test each explicit app hostname.diff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.mdindex 7b7eb3b1..bfed1542 100644--- a/docs/MANAGED-APPS.md+++ b/docs/MANAGED-APPS.md@@ -1,573 +1,234 @@-# Managed applications — Hermes and OpenClaw--> **Mostly current, with one reversal.** Workspace modes and the upstream-> feature-discovery pipeline were REMOVED in `a2c3882` — Hermes and OpenClaw are-> ordinary app windows now. Sections describing per-feature windows, the SPA-bundle-> parsers or `workspace-mode.ts` are history. Everything about the origin split, the-> proxy, the update centre and the approval model is still accurate.->-> Originally shipped `c411187` (registry) → `52cfff5` (workspace modes) → `0feaab4` (discovery) →-> `5b4b5c9` (routes/icons) → `c597d08` (proxy hardening) → `d880f68` (origin split). Re-checked-> against the code and the live host 2026-07-25; where those disagree the code is what is-> documented, and the divergence is called out. Writing this pass surfaced two defects — systemd-> detection and backup — both repaired in the same phase; §3 and §6 describe the repaired behaviour.-> **Update centre added 2026-07-25** (jobs, update/channel/rollback/uninstall, restore): §6a is the-> new section, §1, §3 and §8 were corrected against it — restore is now the one writer into an app's-> own state dir, so the old absolute "nothing is ever written" invariant no longer held as stated.--Per-app specifics (units, ports, install layouts, upstream quirks) live in-[HERMES-INTEGRATION.md](./HERMES-INTEGRATION.md) and-[OPENCLAW-INTEGRATION.md](./OPENCLAW-INTEGRATION.md); this doc is the subsystem — contract,-lifecycle, discovery, proxy, gaps.--## 1. What it is, and the boundary it keeps--MSO is the **shell**. Hermes and OpenClaw are **separate applications** that happen to run on the-same VPS: their own runtime, config, data, versions, health, logs and backups. MSO gives them a-window, a status card, a dock, and a switch — nothing else.--Three channels, nothing else: their **own CLI** for the version probe (`runner.ts:12` — the CLI-feature view types the same verbs into an ordinary PTY instead); **systemd/docker** for detect,-start/stop/restart, logs (`manager.ts:29`, `:121`, `:196`); their **own loopback HTTP surface** for-health, discovery and the proxied dashboard (`manager.ts:65`, `features.ts`, `…/proxy/…/route.ts`).--Non-goals, stated so nobody re-litigates them:--- **No source copying, forking or vendoring** — no upstream file is in this repo. **No DOM- scraping** — discovery parses an upstream's *own* route/nav table out of its built bundle,- never a rendered page.-- **Nothing under `~/.hermes/` or `~/.openclaw/` is written except by a restore the operator asked- for.** Those trees are the upstream's source of truth and its own upgrader owns them. A casual- cockpit write would fork the config away from what the installer expects, make upgrades- unpredictable, and make MSO the owner of a data model it does not define — so detection, health,- discovery, version and backup are all read-only, and an update mutates that tree only by running- the app's **own** updater. `restore.ts` is the single exception and the only writer in the- subsystem: it puts back bytes MSO itself copied out, behind the five gates in §6a. That is why- MSO refuses to persist a channel by editing `~/.openclaw` and runs an update instead.-- **No shared identity** — MSO's session never reaches an upstream, the proxy strips it- (`proxy-headers.ts:56`); you still log into Hermes as Hermes. **No plugin management** —- MSO neither installs nor enables plugins in either app.--### The one thing not to misunderstand--The origin split in §5 is a **browser-realm boundary**: it stops upstream *page JS* from reaching-the cockpit's API. It does nothing about the daemon. A plugin installed into Hermes runs inside the-Hermes process with Hermes' privileges, and Hermes executes shell commands on this VPS — so-installing an untrusted plugin into either app hands that daemon arbitrary code execution on the-host, the same blast radius as `curl … | sh`. No iframe, sandbox attribute or CSP here changes that.--## 2. The contract--`ManagedAppId = "hermes" | "openclaw"` — a closed union (`lib/managed-apps/types.ts:1`) narrowed by-`isManagedAppId()` (`catalog.ts:43`) at the top of every route. There is no "add an app at runtime"-path: a new app is a catalog entry plus a doc. One definition per app (`types.ts:15`, values at-`catalog.ts:13`):--| Field | What it is for |-|---|---|-| `id` / `name` / `description` / `gradient` | the union member, display strings, tile brand |-| `command` | the CLI on `PATH`. Version probe, `package` detection, CLI feature view |-| `serviceNames` | systemd unit candidates, tried in order. Plural because installers name the unit differently; each candidate's existence is checked, so order is a preference, not the answer |-| `containerNames` | ordered docker container candidates, for a containerised install of the same app |-| `dashboardUrl` | the **loopback** HTTP surface: health, discovery, proxy upstream |-| `stateDirName` | the app's state dir under `$HOME` (`.hermes`, `.openclaw`) — read for discovery, copied for backup, never written; the fallback when `homeDir` is unset |-| `assetDir?` / `homeDir?` | overrides for the built-SPA dir and the install home; **when set**, `homeDir` is what discovery reads (`features.ts:23`) **and** what backup copies (`manager.ts:142`) — same precedence in both |--**Why both service names and container names.** Detection has to answer "how is this installed *here*" —-a user unit on one host, a system unit on the next, a container on a third — and the install type then-decides which actions exist at all (`manager.ts:80`): systemd and docker get the full set, a bare CLI on-`PATH` gets `backup` only, because there is no supervisor to start or stop.--**Why the dashboard URL must be loopback.** The proxy re-validates its target on every request and-502s unless the scheme is `http:` and the host is `127.0.0.1`, `localhost` or `::1`-(`proxy/[[...path]]/route.ts:114`). That route carries the owner's session and is the one route-untrusted upstream JS can drive, so its target must be a service on this machine — without the check,-`HERMES_DASHBOARD_URL=http://169.254.169.254/…` makes the cockpit an authenticated SSRF gateway.--**Env overrides** (`.env.example`, all optional; `expandHome()` at `catalog.ts:7` expands a leading-`~` because these are hand-written):--| Var | Default | Read by |-|---|---|---|-| `HERMES_DASHBOARD_URL` | `http://127.0.0.1:9119` | health, discovery, proxy |-| `OPENCLAW_DASHBOARD_URL` | `http://127.0.0.1:18789` | health, discovery, proxy |-| `HERMES_HOME` | `~/.hermes` | discovery **and** the backup source |-| `HERMES_WEB_DIST` | `<home>/hermes-agent/hermes_cli/web_dist` | discovery only |-| `OPENCLAW_CONTROL_UI_DIST` | `~/.local/lib/node_modules/openclaw/dist/control-ui` | discovery only |--`homeDir` is the only field that moves the backup source (`manager.ts:142`), and only Hermes has one in-the catalog — there is no `OPENCLAW_HOME`, so OpenClaw's source is always `~/.openclaw`. One wart left:-`ManagedAppView.dashboardAvailable` (`types.ts:41`) is computed and never read.--## 3. Lifecycle--**Detection** (`manager.ts:42`), first match wins: each `serviceNames` entry probed with `systemctl---user show -p LoadState -p ActiveState <unit>` then the same in the system scope → `docker ps -a---format {{.Names}}` against `containerNames` → `which <command>` → `not-installed`.--`show`, not `is-active`, and this is the systemd trap worth remembering: **`is-active` cannot say-"no such unit"** — on systemd 255 an unknown unit prints `inactive` with rc 4 and an empty stderr,-byte-identical to a stopped one, so reading that as "exists but stopped" pins detection to the-first configured name forever. `LoadState=not-found` is unambiguous and one call returns-`ActiveState` with it (`manager.ts:29`); a non-zero exit is *no answer* — no `systemctl`, no user-bus — so the next scope is tried and nothing is concluded. Both apps through the real-`listManagedApps()` right now (real `systemctl`, real CLIs, no mocks):-`hermes | systemd | running | healthy=true | dash=true | Hermes Agent v0.19.0 (2026.7.20) ·-upstream a61183b5` and `openclaw | systemd | running | healthy=true | dash=true | OpenClaw-2026.7.1-2 (0790d9f)`.--`systemctl --user show -p LoadState -p ActiveState openclaw.service openclaw-gateway.service`-shows what that rests on: the first `not-found`, the second `loaded` + `active`. OpenClaw matches-`openclaw-gateway.service` — card "running", logs from that unit's journal, lifecycle actions on-the unit that exists; Hermes matches `hermes-dashboard.service`. The docker and `package` branches-are reachable now that a phantom unit cannot win the loop, but nothing here exercises them (§8.6).--**State** (`types.ts:7`), derived at `manager.ts:92` — the union's sixth member, `error`, is never-produced:--| State | Means |-|---|---|-| `not-installed` | no unit, no container, no binary — no actions offered |-| `stopped` | installed (`LoadState=loaded`, or the container exists), `ActiveState` not `active`. Lifecycle actions are still offered |-| `starting` | a `start` is in flight in this process (the lock below) |-| `running` | active, and health did not answer "no" |-| `unhealthy` | active, but the health probe answered non-2xx |--**Health** (`manager.ts:65`): `GET <dashboardUrl>/health`, 4 s timeout, redirects followed-(default `fetch`), `response.ok` → boolean; throw → `null`; never probed while stopped → `null`.-Weaker than it looks for an app with no `/health`: Hermes' `302 → /login` chain ends `200`, so it-reports `healthy: true` (HERMES-INTEGRATION.md §2). The probe proves the dashboard answers HTTP.--**Version** (`manager.ts:74`): `<command> --version`, first line, capped at 160 chars.--**Actions**: `start | stop | restart | backup` (`types.ts:4`) — systemd via `systemctl --user <action>`-then the system scope (`manager.ts:121`), docker via `docker <action>`. Everything runs through-`execFile` with `shell: false` (`runner.ts:12`) — no argument reaches a shell — 30 s, 128 KB cap.--**Operation lock** (`manager.ts:15`, taken at `:186`, released in `finally`): one action per app,-in-memory, process-local; a second throws → `409`. Not a file lock and it does not survive a restart —-it stops double-clicks and makes `starting` observable, nothing more. On top of it,-`rateLimited("managed-app:<id>", 12, 60_000)` (`[id]/route.ts:23`) — fixed-window, **per app**.--**Audit**: each action appends `managed-app.action` with `target=<id>`, `detail=<action>`, `ok` and-`actor` (the approved device id from the session, via `getSessionActor()`) to `~/.mso/audit.log`.-Long operations are logged **twice**: the route writes the launch (`detail=update.<action>` +-`meta.jobId` + `meta.argv`), and `job-audit.ts` writes the outcome (`detail=job.<kind>.<status>` +-`meta.jobId/exitCode/error`) — matched on `jobId`, and the actor is carried across by-`rememberJobActor()` because the job outlives the request. Without the second line the trail said an-uninstall had been *launched* and nothing said whether it worked: job records prune at 20/app or 30-days, so that was the only durable trace. It is written once per job id, from `job-runner.ts`'s-`finish()` — the one place that sees every ending, including a job nobody polls — and from the poll-route as a backstop for a record this process did not run (a deploy reconciles those to-`interrupted`). Log output is redacted first-(`manager.ts:18`): `Bearer …` and `key|token|secret|password|authorization` assignments become-`[redacted]`, 8 KB per line.--**Demo mode**: `verifyAuth()` returns `false` whenever `IS_DEMO` (`lib/agent/server.ts:12`), so the whole-subsystem 401s in a demo build; the action route also answers `403` (`[id]/route.ts:20`) as a backstop.--### Endpoints--| Endpoint | Method | Auth + gates |-|---|---|---|-| `/api/v1/managed-apps` | GET | `verifyAuth`; 503 on failure |-| `/api/v1/managed-apps/[id]` | GET | `verifyAuth`, id validated |-| `/api/v1/managed-apps/[id]` | POST `{action}` | `verifyAuth` → demo 403 → rate limit 429 → action allowlist 400 → lock/unsupported 409, audited |-| `/api/v1/managed-apps/[id]/logs` | GET | `verifyAuth`; last 100 journald/docker lines, redacted |-| `/api/v1/managed-apps/[id]/features` | GET | `verifyAuth`; 60 s cache; 503 if discovery throws |-| `/api/v1/managed-apps/[id]/update` | GET | `verifyAuth`, id validated; **cache read only, never probes** — `cachedUpdateStatus()`, `checkedAt: null` until something has probed (§6a) |-| `/api/v1/managed-apps/[id]/update` | POST `{action}` | same gates as the action route; `check` spends `managed-app-check:<id>` (10/60 s) and the four destructive actions the `managed-app:<id>` bucket (12/60 s); `check` answers inline, the rest answer `202 {job}` |-| `/api/v1/managed-apps/[id]/jobs` | GET | `verifyAuth`; history without transcripts |-| `/api/v1/managed-apps/[id]/jobs/[jobId]` | GET | `verifyAuth`; `?since=` poll; 404 for another app's job |-| `/api/v1/managed-apps/[id]/backups` | GET | `verifyAuth`; snapshots a rollback can choose from |-| `/api/v1/managed-apps/[id]/proxy/[[...path]]` | GET/HEAD/POST/PUT/PATCH/DELETE | `verifyAuth`; in split mode also requires the middleware host stamp, else 404 (§5) |--**Detection is not on the dashboard's path.** Neither the proxy nor discovery consults it (both go-straight at `dashboardUrl`), so a detection miss never takes a dashboard down — which is exactly how-a wrong card survives unnoticed: the card is the only place it shows.--## 4. Feature discovery--Each app's **own navigation** becomes MSO app tiles. Nothing is hardcoded as a feature-list: if discovery finds nothing, the OS shows nothing.--**Hermes** (`features.ts:49`) — its built SPA off disk, then its plugin API: `<dist>/index.html` →-the `assets/index-*.js` it names (`:42`) → the `{ path, labelKey, label }` nav table-(`feature-parser.ts:64`), falling back to the route→component record in the same bundle (`:75`) and-then to `<home>/hermes-agent/web/src/App.tsx`, because a git install keeps the nav SSOT in-TypeScript. Plugin tabs from `GET <dashboardUrl>/api/dashboard/plugins` (public, unauthenticated, no-credential involved) are spliced in the way upstream's own `buildNavItems()` does (`:94`), honouring-`position: before:/after:`, `override` and `hidden`. A stopped dashboard costs the plugin tabs only.--**OpenClaw** (`features.ts:75`) — its route table, live then on disk: `./assets/app-route-paths-*.js`-named by `GET <dashboardUrl>/`, parsed for the `key: { path, aliases }` map (`feature-parser.ts:126`);-else the `index-*.js` chunk's page + settings route factories (`:133`); else the same chunk inside-the installed package, which is what keeps the launchpad populated while the gateway is down.--**Tripwires.** A route must match `^/(?!/)[A-Za-z0-9/_-]*$` (`feature-parser.ts:19`), and a run is-accepted only with ≥ 5 entries including `/sessions` (Hermes) or ≥ 12 including `/chat` (OpenClaw)-— otherwise `checked()` discards **the whole run** (`:58`). So an upstream bundle reshuffle that breaks a-regex yields an empty list, never a plausible-looking partial one: the workspace keeps the shared apps-(Terminal, Files, Assistant, Monitor, Settings) and loses the upstream tiles until the parser is updated,-while the proxy, the management card and the CLI view carry on. Discovery failure is **silent by design**-— `/features` answers `503` only if discovery throws, not when it finds nothing.--Routable-but-dead keys are marked `available: false` (`feature-parser.ts:12`: `workboard` behind a-feature flag, `plugin` a plugin host) and the dock filters them out (`dynamic-features.tsx:49`). Results-are cached 60 s per app, in-process (`features.ts:15`); nothing invalidates on upstream upgrade, so a new-nav entry appears within a minute. Live counts move with every release and live in the per-app docs.--Each key gets its own lucide icon from a per-key map, with a hashed palette fallback so a wall of-new upstream tiles still reads as distinct (`feature-icons.ts:73`), and may map to a **read-only**-CLI subcommand (`feature-cli.ts:21`) — no verified subcommand means no CLI toggle, and the three commands-that start a wizard when bare (`openclaw config`, `openclaw doctor`, `hermes model`) are mapped to-documented read-only forms so opening a tab never writes. `feature-cli.test.ts` pins those maps against-the verbatim `--help` verb lists.--## 5. The proxy and its containment--The dashboards render in an OS window as an iframe over a reverse proxy. The iframe keeps-`allow-same-origin` (`feature-app.tsx:107`) because these SPAs need their own cookies and storage or-they do not boot at all. That is the whole security problem:--- **On the cockpit origin** that also made upstream JS same-origin with the cockpit, so it could- take `window.top.fetch` and POST `/api/v1/exec/run` with the owner's session. Proven in real- Chromium. **No CSP can stop it** — a policy binds a realm, not a reference across realms.-- **Cross-origin**, `window.top` is opaque. Verified in Chromium 148: `top.location`, `top.origin`,- `top.fetch` and `document.domain = "rahmanef.com"` all throw `SecurityError`, with a same-origin- control in the same run that *does* break through.--Hence the **origin split**: each dashboard is served from its own host-(`hermes.mso.rahmanef.com`, `openclaw.mso.rahmanef.com`) pointed at this same process. One host-*per app*, never one shared host — a shared one would put Hermes and OpenClaw back in a single-origin where they can script each other (`origin.ts:12`).--`proxy.ts` (Next 16's middleware) enforces the other half. The **`Host` header** decides which-app a request belongs to and `X-Forwarded-Host` is deliberately ignored, because a request able-to claim the cockpit host while on an app host would escape the rewrite (`proxy.ts:112`). On an-app host **every path** is rewritten into that app's proxy (`:146`), so `/api/v1/exec/run` does-not exist there, and `/_next/*` 404s (`:129`). A host **inside the namespace that is not an app**-also 404s (`:121`, `origin.ts:71`): the session cookie is widened to `mso.rahmanef.com`, so a new-`X.mso.rahmanef.com` record must not be able to serve an authenticated cockpit — the parent name-is never matched, so this cannot lock the operator out. The rewrite stamps-`x-os-managed-app-host` and **deletes any inbound copy** on every request (`:132`, `:182`,-`:196`); the route trusts it only in split mode (`route.ts:92`), since forged it would buy-root-mounted mode on the cockpit origin. CSRF depth-2 runs **before** the rewrite (`:128`) —-afterwards the path already looks like `/api/…`.--### Containment, item by item--| Control | Where | Why |-|---|---|---|-| loopback-only upstream + path segment validation | `route.ts:114`, `:104` | the proxy carries the owner's authority, so an arbitrary target is authenticated SSRF; empty, `.`, `..`, `\` and NUL segments are rejected before the upstream URL is built |-| request header allowlist | `proxy-headers.ts:14` | `authorization` is never forwarded; with `www-authenticate` withheld too, the proxy cannot become a credential relay |-| response header allowlist | `proxy-headers.ts:30` | upstream `x-frame-options` / `content-security-policy` / `permissions-policy` are never echoed, so an upstream cannot un-frame itself or replace our policy |-| cookie namespacing + path pinning | `proxy-headers.ts:46`, `:56`, `:112`, `:121` | upstream cookies become `mapp_<id>_<name>` with `Domain` dropped, `SameSite=Lax`, `Secure` mirroring the browser's hop, and `Path` = the proxy prefix (single-origin) or `/` (the app owns its host root). An upstream can neither read nor overwrite the cockpit `session` cookie, nor a sibling app's |-| request body cap | `route.ts:33`, `:63` | 1 MB, counted **as it streams**, because a chunked request has no `content-length` to test |-| service-worker refusal | `route.ts:109`, `proxy-headers.ts:182` | a SW registered from proxied bytes installs on this origin and keeps answering after the window closes; `worker-src blob:` is the real control, the 404 means the script never reaches the browser |-| redirect refusal | `route.ts:158`, `proxy-headers.ts:160` | a `Location` resolving off the upstream origin is refused, not relayed: it is an open redirect, and per CSP3 §6.6.2.6 one hop drops path matching for every source in the policy |-| upstream timeout + HTML/CSS buffering | `route.ts:129`, `proxy-html.ts:17` | 20 s then 502; a rewritable body is buffered to 2 MB and one that outgrows the cap is streamed unrewritten rather than truncated |--### The CSP is intersected, not replaced--Ours is the only policy the browser sees, but the upstream's is not discarded: it is-**intersected per directive** (`proxy-csp.ts:214`) — a source survives only if both policies allow-it, and the tighter side wins. Rules that matter:--- Every fetch directive is scoped to the app's absolute proxy URL. CSP matches such sources by **path- prefix**, which is what leaves `/api/v1/exec`, `/api/v1/fs` and `/api/v1/term` outside the policy in- single-origin mode; `'self'` is deliberately absent everywhere. No `'unsafe-eval'` (neither bundle- contains `eval(` or `new Function(`), `worker-src` is `blob:` only.-- `frame-ancestors` is always ours — being framed by the cockpit is the point, so an upstream- `frame-ancestors 'none'` can never win; `base-uri` is ours only in single-origin mode, where we- inject `<base href>`. Upstream **hashes** are copied in, upstream **nonces** never are: a nonce- matches a script element whatever its URL, re-opening the origin scoping (`proxy-csp.ts:134`).-- An external `https:` host the upstream **declares** is honoured (its own UI needs it), with no- wildcards and **never the cockpit origin** (`:174`) — `connect-src https://mso.rahmanef.com` out- of a compromised upstream is the thing scoping exists to stop. Hosts that *nothing* grants are- disclosed in the window rather than failing silently (`proxy-headers.ts:228`).--### Origin-split vs single-origin — RESOLVED, single-origin is gone--This section used to be a comparison table presenting single-origin as the "dev, demo,-rollback" path, including the row `window.top` reach → **open**. That was the reason it-had to go, not a caveat to live with.--`38d010d` ("serve dashboards from an app host or not at all") removed it. The route now-returns 404 when no app host is configured-(`app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts`), because a CSP binds a realm-and not a reference across realms: upstream JS in a same-origin frame reaches-`window.top.fetch('/api/v1/exec')`, and `window.open('/')` hands it a whole cockpit realm.-No header can intervene.--So there is exactly one supported mode:--| | origin-split (the only mode) |-|---|---|-| trigger | `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` contains `{id}` |-| iframe `src` | `https://<id>.mso.rahmanef.com/<route>` — the app owns its host root |-| document rewriting | none — the upstream's own URLs resolve as shipped |-| cookie `Path` | `/`, namespaced to the app host |-| `window.top` reach | opaque (cross-origin) |-| needs | DNS + TLS per host, a Traefik router, the widened session cookie |+# Managed applications++> **Current reference.** MSO currently manages exactly two independent applications:+> **Hermes** and **OpenClaw**. Older workspace-mode and dynamic upstream-feature-discovery+> designs are historical; there is no `/features` route in the current API.++Managed applications are separate daemons with their own install, config, data and+privileges. MSO does not turn them into MSO slices. It provides a management layer around+their existing CLI/systemd/dashboard interfaces.++```mermaid+flowchart LR+ U[MSO owner] --> M[Managed Apps UI]+ M --> API[/api/v1/managed-apps/*]+ API --> C[lib/managed-apps]+ C --> S[systemd / Docker / CLI probes]+ C --> J[long-running job runner]+ C --> B[backup + restore]+ C --> P[dashboard proxy]+ S --> H[Hermes]+ S --> O[OpenClaw]+ J --> H+ J --> O+ P --> H+ P --> O+```++## 1. Current application model++| App | Primary service(s) | Dashboard upstream | State directory |+|---|---|---|---|+| Hermes | `hermes-dashboard.service`, `hermes-gateway.service` | `127.0.0.1:9119` by default | `~/.hermes` or `HERMES_HOME` |+| OpenClaw | `openclaw-gateway.service` | `127.0.0.1:18789` by default | `~/.openclaw` |++Detection reads systemd first, then Docker/package evidence. If MSO cannot reach the user+systemd bus, it reports that uncertainty instead of silently treating a running app as+"not installed". Install and restore fail closed when the required state cannot be proven.++## 2. User experience++Opening Hermes/OpenClaw first detects the app:++- **not installed** → Install surface;+- **installed but stopped** → Start surface;+- **running/starting/unhealthy with a reachable dashboard** → vendor dashboard surface;+- **Details** → MSO-owned management surface regardless of vendor UI.++The Details surface exposes lifecycle state, version, health, logs, update centre and+backups. It does not scrape the vendor's internal navigation into MSO launcher items.++## 3. Lifecycle versus jobs++Short lifecycle actions are bounded synchronous operations:-Without a host template the dashboards are simply not proxied — the windows fall back to-the CLI view and to opening the app in the user's own browser. **Do not reintroduce a-cockpit-origin path proxy as a convenience.**+- `start`+- `stop`+- `restart`+- `backup`-### Turning it on is THREE steps, and the third one has no error message+Install, update, uninstall and restore can outlive one HTTP request. They run as persisted+managed-app jobs with states `queued`, `running`, `succeeded`, `failed` or `interrupted`,+a bounded transcript, heartbeat/liveness data and app ownership. Closing the MSO window+does not cancel a running job.-Reported by the same operator as §7's user-bus gap, and it cost an afternoon: the Hermes-window showed a terminal, so the dashboard looked broken. It was not — this deployment had-no app host, and nothing anywhere said so.+The public managed-app API is:-| Step | Skipping it looks like |+| Route | Purpose ||---|---|-| 1. Set **both** `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, add the DNS record + a reverse-proxy route per app host | The window opens a terminal, silently |-| 2. **Rebuild**, not just restart — `NEXT_PUBLIC_*` is baked into the client bundle | Same terminal: the server is in split mode and the browser is still running the old bundle |-| 3. **Sign out and back in** | The frame 401s while the cockpit keeps working |--Step 3 is the one with no signal, and it cannot be given one server-side. `Domain=` is-attached to the session cookie only when it is ISSUED (`login/route.ts`, via-`sessionCookieAttrs`) and there is no sliding refresh, so every pre-existing session stays-host-only and is never sent to `<id>.<parent>`. A Cookie header carries no Domain, so a-cookie that was never sent is indistinguishable from one that never existed — the server-cannot tell "stale session" from "not logged in".--So all three now say it where it will be read, none of them relying on this file:--- **Step 1** — the window itself. `feature-app.tsx` renders one line above the terminal- when `featureSource()` is null, naming the variable. Only in that case: with a dashboard- configured nothing renders, so it cannot become the always-on banner that was removed.-- **Steps 2 and 3** — the failure page. The proxy route's errors are what the frame- displays (that is what `failAncestors()` is for), and `proxy-error-page.ts` turns them- from `{"error":"unauthorized"}` into a page that names the re-login. Navigations only,- chosen by `Sec-Fetch-Dest`: an upstream SPA's own `fetch()` hits the same route and keeps- getting JSON.-- **Before any of it** — `mso doctor` prints the template when set, `off` when neither var- is set, and FAILS when exactly one is, which is the configuration §5 warns is unsafe.--Live verification (unauthenticated, so 401 is the expected success signal):+| `GET /api/v1/managed-apps` | detect/list Hermes and OpenClaw |+| `GET /api/v1/managed-apps/[id]` | detect/read one managed app |+| `POST /api/v1/managed-apps/[id]` | start/stop/restart/backup |+| `GET /api/v1/managed-apps/[id]/logs` | recent logs |+| `GET /api/v1/managed-apps/[id]/backups` | snapshot list |+| `POST /api/v1/managed-apps/[id]/install` | start install job |+| `GET/POST /api/v1/managed-apps/[id]/update` | update status and actions |+| `GET /api/v1/managed-apps/[id]/jobs` | job history/current work |+| `GET/DELETE /api/v1/managed-apps/[id]/jobs/[jobId]` | job status/cancel where supported |+| `/api/v1/managed-apps/[id]/proxy/*` | authenticated vendor-dashboard reverse proxy |+There is intentionally no `/features` endpoint.++## 4. Install++MSO can install both apps non-interactively through `scripts/managed-app-install` and the+same job layer used for updates. An optional model-provider API key can be supplied during+install. The key is accepted in the request body, passed to the child through its+environment and immediately dropped from React state; it is not put in argv, job records or+MSO's audit transcript.++The UI keeps a manual install command visible as a recovery path if automation cannot work+on another host.++## 5. Update centre++Every real update takes an MSO state snapshot first. If that snapshot fails, the update is+abandoned before invoking the upstream updater.++### Hermes++- supports check + apply;+- upstream has no true update dry-run; its read-only check is the preview;+- branch switching exists upstream but is not presented as an ordinary channel menu;+- MSO deliberately does **not** combine a restored state snapshot with an automatic Hermes+ branch/version pin, because Hermes' git/stash behaviour can overwrite the state just+ restored.++### OpenClaw++- supports check + apply + real `--dry-run`;+- supports channels/tags and exact-version pinning within MSO's allowlist;+- normal update restarts and verifies the app rather than leaving new bytes behind an old+ process.++Update commands use argv arrays, not shell interpolation. User-supplied branch/channel/tag+values pass explicit validation first.++## 6. Backups++Snapshots live under:++```text+~/.mso/backups/<app>/<timestamp>/```-H=hermes.mso.rahmanef.com # no trailing slash on the proxy URL: Next 308s it away first-curl -sI -H "Host: $H" 127.0.0.1:4005/ # 401 + frame-ancestors 'self' <cockpit>-curl -s -H "Host: $H" 127.0.0.1:4005/_next/static/x.js # 404 — /_next is cockpit-only-curl -s -X POST -H "Host: $H" 127.0.0.1:4005/api/v1/exec/run # 403 cross_origin_blocked-curl -s -H 'Host: staging.mso.rahmanef.com' 127.0.0.1:4005/ # 404 — unclaimed namespace host-curl -s -H 'Host: mso.rahmanef.com' 127.0.0.1:4005/api/v1/managed-apps/hermes/proxy # 401; 404 signed in-```-Residual, by design: the proxy is **HTTP only** — a route handler cannot service an `Upgrade` — so-OpenClaw's socket-driven panels load their chrome and stay empty, and those features open on the CLI-view instead (`feature-cli.ts:41`, `:60`). The `connect-src` residual is §8.8.--## 6. Backup--`backup` (`manager.ts:141`) copies the app's state dir recursively, timestamps preserved, to-`~/.mso/backups/<id>/<ISO-stamp>/` (parent `0700`), then writes `manifest.json` (`0600`)-containing `{applicationId, createdAt, source, skipped: {symlinks, dirs, dirNames}}`. The source is-`expandHome(homeDir)` when the catalog has one, else `homedir() + stateDirName` — so a Hermes-install relocated with `HERMES_HOME` is what actually gets copied.--Two things are left out, both matched by **basename** so they apply at any depth (`manager.ts:139`,-`:155`). First `node_modules`, `.venv`, `venv`, `__pycache__`, `.git`, `.cache`, `backups` —-re-installable bytes, not state, and `backups` is the app's **own** backup dir (1.1 GB under-`~/.hermes`, `du -sh ~/.hermes/backups`) which a backup has no business copying into a second one.-Second **symlinks, skipped rather than followed or recreated**: following one copies bytes from-outside the app, recreating an absolute one aims a future restore outside the tree. A skip and not a-refusal for a reason worth keeping — refusing the run on the first link is what the predecessor did,-and with `find ~/.hermes -type l | wc -l` → 58 and `~/.openclaw` → 2063 that meant the action failed-on every real install and never ran once. The skip is recorded, not silent: the counts go in the-manifest, because a restore is only safe if you know what the copy never had. Adding-`-not -path '*/node_modules/*'` and the other six names to that `find` leaves 1 and 9 — the rest sit-inside pruned trees and are never reached, so those are the order of `skipped.symlinks`.--`du -sh --exclude=node_modules --exclude=.venv --exclude=venv --exclude=__pycache__ --exclude=.git---exclude=.cache --exclude=backups ~/.hermes ~/.openclaw` gives the size: **366 MB** and **237 MB**,-against 2.7 GB and 1.7 GB unexcluded, with 227 GB free on `/home` (`df -h /home`). `~/.mso/backups/`-is created by the first run; this host has one snapshot per app, from the first real backup runs.-`manager.test.ts` covers the shape in a fixture home: state files copied, `node_modules/` and `backups/`-absent, an `/etc/passwd` symlink neither followed nor recreated, manifest counters as claimed.--## 6a. Update centre — update, rollback, uninstall--Everything destructive is a **job** (`jobs.ts` + `job-runner.ts` + `job-store.ts`): the POST starts-one and returns an id, the client polls `/jobs/<id>?since=`. A route handler cannot hold an-`openclaw update` open — upstream's own default step timeout is 1800 s and it restarts services on-the way out. The child is spawned by this process and **dies with it** (`mso.service` is-`KillMode=control-group`, `Delegate=no`, so `detached` buys a process group, never a cgroup); the-durable part is the record under `~/.mso/managed-app-jobs/` (0700 dir, 0600 files), and a job-whose owner pid is gone — or which stopped heart-beating for 45 s — reconciles to `interrupted`-rather than sitting at `running` and stranding the lock. **Do not deploy while an update runs.**--A job takes the **same** `lock.ts` lock as start/stop/restart/backup, so an update and a `restart`-can never interleave. Every argv is an array through `spawn(shell: false)`; a channel/tag/branch is-allowlisted (`update-cli.ts`) *before* it becomes an element, and the job layer refuses any argument-carrying a control character as a tripwire on that. Transcripts go through the same `redact()` as-the logs route, per **complete line** (a secret split across two stdout chunks would walk past a-per-chunk regex), tail-capped at 256 KB.--**A backup runs inside the operation, before anything spawns** (`prepare`), for update, uninstall-and rollback — a throw there ends the job `failed` with the CLI never invoked. Uninstall-additionally requires the caller to echo the app id in the body. `dryRun` skips the backup, because-a preview writes nothing — and because a preview is therefore the one unprotected path, MSO first-asks the installed CLI whether it still advertises `uninstall --dry-run` (`assertPreviewSupported`,-one `--help` spawn) and refuses the preview if it does not. `--yes` cannot simply be dropped from a-preview: `hermes uninstall` hits `_require_tty()` before it reads `--dry-run` unless `--yes` was-passed, and `openclaw uninstall --non-interactive` exits 1 without it. Jobs spawn with stdin closed,-so a preview without the confirmation flag is exit 1 and no output.--The argv, verified against each CLI's own `--help` on this host: `hermes update --yes [--branch N]`,-`hermes uninstall --yes [--dry-run]` (never `--full`), `openclaw update --yes [--dry-run --json]-[--channel C] [--tag T] [--no-restart]`, `openclaw uninstall --non-interactive --yes --service---state [--dry-run]` (never `--all`/`--workspace`). `--json` is a dry-run-only flag: in a real run it-silences the progress stream the UI exists to show. No interactive verb is ever invoked.--**Install is NOT automated** — both installers are interactive, so `capabilities.installCommand`-carries the exact command for the operator to run. **Channel switching is an update run** for-OpenClaw (upstream persists a channel only through one) and is *refused* for Hermes, whose-`--branch` rewrites a working tree and is exposed only as a per-update pin.--**A rollback pin is OpenClaw-only** (`--tag`). Hermes has none: its pin is `--branch`, i.e. a-checkout switch, and `hermes update` auto-stashes local changes first. A restore puts working-tree-files back while `.git` — which the backup prunes — is untouched, so the tree is dirty against an-unchanged HEAD and the pin would stash exactly what was just restored (with `--yes` that is a-*non-interactive* update: default re-applies the stash, `updates.non_interactive_local_changes:-discard` drops it, a conflicting apply ends in `git reset --hard`) while the job reports success. The-route refuses a pin for Hermes with a 400 and the panel does not render the field (`app-support.ts`-`rollbackPin`, mirrored against `UpdateAdapter.pin` by a test).--**Restore now exists** (`restore.ts`), and it **overwrites; it never deletes**. Five gates first: the-app must not be running (a live app would flush its WALs back over the restore), the backup id must-match the minted stamp, its manifest must name this app, the manifest's recorded source must still-be exactly this app's state dir, and that dir must be a real non-symlink directory that is not-`$HOME` or an ancestor of it. A destination symlink aborts the whole run — `fs.copyFile` opens with-`O_CREAT|O_TRUNC` and follows links, which is the exact escape. A `pre-restore` snapshot is taken as-the undo. Because a snapshot has no `node_modules`/`.venv`/`.git`, a rename-aside-and-replace would-leave a broken install; so files created since the snapshot stay, and the result says so-(`overwriteOnly: true`, `notRestored`). An MSO snapshot is a **state** backup, not an install image.--## 7. Operations--### The user bus, and why an installed app can read as "not installed"--Both apps run as systemd **USER** units, so everything in §3 goes through-`systemctl --user`. That command finds the user's systemd instance through-`XDG_RUNTIME_DIR` — and **a systemd SYSTEM unit with `User=` does not have one**, because-it inherits no login session. Inside such a cockpit every `systemctl --user` answers:+They may contain credentials and should be protected like the app's original state. The+snapshot directory is private and its manifest is `0600`.++Snapshots skip symlinks and recursively exclude reinstallable/cache trees:++- `node_modules`+- `.venv`+- `venv`+- `__pycache__`+- `.git`+- `.cache`+- `backups`++The manifest records the app, original source path, reason, file/byte counts and exclusions.++## 7. Restore++Restore is implemented and intentionally conservative.++1. MSO must prove the app is stopped; an uncertain systemd reading is a refusal.+2. Backup id and manifest must identify this app and its current state directory.+3. Target state directory must be a real safe directory, not a symlink or home ancestor.+4. MSO checks the snapshot/target trees for symlink collisions **before** writing.+5. MSO first creates a `pre-restore` safety snapshot of the current state.+6. Snapshot files overwrite matching files.+7. Files created after the snapshot are **not deleted**.+8. Excluded reinstallable/cache directories above were never in the snapshot and therefore+ are not restored.++That means restore is an overwrite restore, not a byte-for-byte directory replacement. The+result explicitly reports the safety-backup id and excluded content.++## 8. Uninstall++MSO only exposes conservative upstream uninstall scopes and takes a backup first.++- Hermes removal keeps its state/config by default; MSO does not expose the destructive+ full-state removal flag.+- OpenClaw removal targets its gateway service + local state; MSO does not add the workspace+ removal scope.+- The UI can preview the upstream removal when the installed CLI proves it supports the+ dry-run flag, and server-side confirmation is still required for a real removal.++A later reinstall is a fresh installation; use the MSO snapshot if you need the previous+credentials/pairings/history back.+## 9. Dashboard origin boundary++The safe default is **no embedded vendor dashboard**. To embed them, configure both halves+of one split-origin decision:++```dotenv+NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.example.com+OS_SESSION_COOKIE_DOMAIN=.mso.example.com+OS_PUBLIC_ORIGIN=https://mso.example.com```-Failed to connect to bus: No medium found++Then route only the known app hostnames to the same MSO process. Each managed-app hostname+is rewritten exclusively into that app's proxy; cockpit pages/API/static chunks are not+served there.++```mermaid+flowchart LR+ TOP[https://mso.example.com] -->|iframe| HH[https://hermes.mso.example.com]+ TOP -->|iframe| OH[https://openclaw.mso.example.com]+ HH -->|MSO proxy| H[Hermes loopback]+ OH -->|MSO proxy| O[OpenClaw loopback]+ HH -. cross-origin realm .-> TOP+ OH -. cross-origin realm .-> TOP```-Two failures fall out of that single gap, and neither one names it:+Why this exists: vendor SPAs need `allow-same-origin` to work. If the vendor JavaScript+shared the cockpit origin, it would have the owner's browser realm and session. A separate+hostname makes `window.top` cross-origin. This is a browser-realm boundary only; a plugin+installed **inside Hermes/OpenClaw** still runs with that daemon's host privileges.-| Symptom | Actually happening |-|---|---|-| One-click install always fails, `exited with code 1` | `scripts/managed-app-install` reached `systemctl --user daemon-reload` and died under `set -e` — *after* the upstream installer had finished. The unit file is written but never enabled |-| An installed, running app shows as **not installed**, with an Install button that fails the same way forever | `detect()` discarded the `--user` answer, found nothing system-scope, then fell through to `which <cmd>` — which also missed, because a unit's PATH has no `~/.local/bin`, where both CLIs install their launcher |--Handled in three places, deliberately overlapping so that no single one has to be right:--- `lib/managed-apps/user-bus.ts` re-derives `XDG_RUNTIME_DIR=/run/user/<uid>` **at call- time**, whenever the current value has no bus socket behind it. This is what repairs a- cockpit that was installed before the fix, without re-running the installer, and it also- covers the boot race where mso.service starts before logind creates the directory.-- `lib/managed-apps/runner.ts` → `resolveCommand()` falls back to `~/.local/bin` and- `~/.bun/bin` when PATH misses — the same lesson `hermes_cmd()` in- `scripts/managed-app-install` had already learned the hard way.-- `scripts/install.sh` writes `Environment=XDG_RUNTIME_DIR=/run/user/<uid>` (the uid written out —- the `%U` specifier expands to 0 for a `User=<name>` system unit) plus a PATH that- includes those directories, and runs `loginctl enable-linger`. **Linger is not optional**:- without it `/run/user/<uid>` is destroyed at logout and the variable points at nothing.--`scripts/managed-app-install` preflights the bus *before* doing ~20 minutes of work, and-when it cannot reach one it prints the exact host commands to fix it rather than failing at-the last step. When detection is only *guessing* that an app is absent, `ManagedAppView.diagnostic`-says so and the install screen shows it — the mistake `lib/camoufox/service.ts` already refuses-to make, and which its test *"does not disguise an unreachable user bus as 'not installed'"* pins.--| Var | Read at | Notes |-|---|---|---|-| `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` | **build** (client) + runtime (server, middleware) | e.g. `{id}.mso.rahmanef.com`. Presence of `{id}` is what turns split mode on |-| `OS_SESSION_COOKIE_DOMAIN` | runtime | adds `Domain=` so the session reaches the app hosts (`lib/auth/session-cookie.ts:68`) |-| `OS_PUBLIC_ORIGIN` | runtime | the origin named in `frame-ancestors` and used to scope the policy; unset falls back to the template's parent, and a value that resolves to nothing fails closed to `frame-ancestors 'none'`. The `HERMES_*` / `OPENCLAW_*` vars (§2) are runtime too |--The two split-origin vars are **one decision with two switches: set both, or neither.**-`OS_SESSION_COOKIE_DOMAIN` without the template hands the session to every host under the domain-while each of them still serves the whole cockpit; the template without the cookie domain gives-app hosts that 401 on every request.--**Deploy order** — forced by the build-time/runtime split:--1. DNS for `hermes.os.…` and `openclaw.os.…`, then the Traefik router- (`/etc/dokploy/traefik/dynamic/mso-managed-apps.yml`: one `web` + one `websecure` router per host,- `service: mso-service`, `certResolver: letsencrypt`; that shared service forwards to- `http://172.17.0.1:4005` with `passHostHeader: true`, which is why middleware can trust `Host`).-2. Set both env vars in `.env.local`.-3. `pnpm build` — `NEXT_PUBLIC_*` is baked into the client bundle here. Built without it, the- browser still points at the old same-origin URL the server has stopped answering, and the- window comes up blank.-4. `sudo systemctl restart mso.service` — never restart before building (`CLAUDE.md`).--**Verify** with the curls in §5, plus `https://hermes.mso.rahmanef.com/` → `401` unauthenticated and the-dashboard rendering in an app window when signed in. Both app hosts resolve to the cockpit's own A/AAAA.--**Turning the feature OFF** (there is no "roll back to single-origin" any more — that mode was-removed for security, see §7): remove the two Traefik routers (or the DNS records) **FIRST**. With the-template unset an app host no longer matches an app and no longer 404s, so a still-resolving host would-serve the full cockpit. Then unset both env vars, `pnpm build`, restart; the dashboards stop being-proxied and the windows fall back to the CLI view. Domain cookies already in a jar survive, and logout-can only clear cookies it knows about (`lib/auth/session-cookie.ts:108`), so revoke the devices-(Settings → Devices) or wait out `SESSION_EXPIRY_HOURS`.--**Workspace modes are GONE** (`a2c3882`). Hermes and OpenClaw are ordinary app windows now — each-upstream already ships its own sidebar, so re-hosting its navigation in the MSO shell bought nothing and-rested on six regexes against minified third-party bundles. `os-shell/workspace-mode.ts` and the whole-upstream feature-discovery pipeline (`lib/managed-apps/features.ts`, `feature-parser.ts`,-`dynamic-features.tsx`, `feature-icons.ts`, the `/features` route) were deleted with it.-Switching writes the key and fires an event — nothing restarts, no server call. The mode decides which-apps the dock/launchpad show (`:85`, applied in `app/os-root.tsx:39`) and which discovered features-mount (`dynamic-features.tsx:25`). Right-click → **Workspace** works in every shell-(`integrations.ts:87`); a visible switcher exists only in the Dashboard sidebar.--## 8. Gaps--1. **No install flow, and no cancel verb.** Install stays a copyable command (both installers are- interactive) — MSO does not fake one. A hung job is bounded only by its timeout (SIGTERM to the- process group, SIGKILL 10 s later); there is no Cancel button, and adding one means exporting- `signalTree` from `job-runner.ts`. Hermes has no channel and no dry-run verb, so those controls- are absent for it by design, not by omission.-2. **OpenClaw panels stay empty** — its control UI is WebSocket-driven, the proxy is fetch-based.- Takes a Node-runtime WS proxy outside the App Router (or an upstream HTTP fallback) with the- same origin/cookie containment re-derived for sockets. Until then those open on the CLI view.-3. **The backup a restore rests on is still thin**: no size cap, and a manifest that records counts- and what was skipped but carries no per-file inventory or checksum, so nothing can *prove* a- snapshot is complete — restore verifies provenance (§6a), never integrity. Takes an inventory +- checksum and a size guard. Restore also refuses rather than stopping the app; that is deliberate- (§6a), but it means a rollback is two clicks, not one.-4. **No notifications** — a crash or unhealthy flip shows only while the card is open, polling- every 10 s. Takes a server-side watcher plus the toast/activity bus.-5. **No resource-aware behaviour, no start-on-boot** — actions are never declined under memory- pressure, and `systemctl enable/disable` is not exposed.-6. **No integration or journey tests**, and the **docker and `package` detection branches have no test- and no install here to exercise them** — everything verified about detection is systemd. Unit- coverage is solid on the parsers, header plumbing, systemd/backup behaviour, CSP intersection and- split-origin behaviour (`lib/managed-apps/*.test.ts`, `app/api/v1/managed-apps/proxy*.test.ts`);- nothing drives a browser login → dashboard → action.-7. **Workspace switcher parity** — visible control only in the Dashboard shell; macOS, Windows,- iOS and Android have the right-click submenu only.-8. **An upstream can widen its own `connect-src`** to a third-party `https` host it declares- (never to the cockpit). Tightening means dropping `HONOUR_EXTERNAL` (`proxy-csp.ts:125`) and- accepting the breakage it was added to avoid.-9. **Dead edges**: `state: "error"` never produced, `dashboardAvailable` unread, `filterAppsForWorkspace`- still filtering a legacy `managed-applications` id no descriptor uses.-10. **The completion audit is per process**: `job-audit.ts` remembers what it has written in memory,- so a job that ends, is never polled, and outlives a restart can be logged a second time when its- record is finally read. Duplicate append-only lines carrying the same `jobId` are the deliberate- trade against a durable "already audited" store.--All of it lives in `lib/managed-apps/` (contract, catalog, manager, runner, discovery, origin math,-proxy), `app/api/v1/managed-apps/` (routes), `proxy.ts` (host gating), and-`frontend/slices/managed-apps/` (UI).+There is no supported same-origin dashboard fallback. If the two split-origin environment+variables are unset, MSO leaves vendor dashboards unembedded and the management UI remains+usable.++## 10. Proxy properties++The dashboard proxy is not a generic forward proxy. It resolves only the catalogued+loopback upstream for the selected managed app. It rewrites response headers and cookies+for the app host, strips/adjusts headers that would block the intended frame, and applies a+CSP that keeps the upstream app within its own realm while allowing the cockpit to frame+it.++Never map an arbitrary wildcard hostname to MSO under the cookie domain. Provision only+hostnames you explicitly intend to serve.++## 11. Project ingress is a separate feature++`OS_PROJECT_INGRESS_ROUTES` is not part of Hermes/OpenClaw dashboard management. It is a+generic opt-in seam for exact project-owned POST callbacks. It defaults empty, is capped at+eight exact routes, targets loopback services only, and applies an HMAC-V2-shaped request+prefilter. The target project still owns the real secret verification.++## 12. Troubleshooting quick map++- state says "not installed" but you know it is running → check whether MSO can reach the+ user's systemd bus; do not rerun an installer until detection is trustworthy;+- dashboard frame missing but service is healthy → split-origin config/DNS/proxying may be+ intentionally absent; the Details surface still works;+- update refused → inspect the pre-update backup error first;+- restore refused → stop the app and resolve any state-path/symlink diagnostic rather than+ bypassing the gate;+- long update appears to vanish → reopen Details; job state/transcript is server-side.++See the per-app references for upstream-specific behaviour.diff --git a/docs/MCP.md b/docs/MCP.mdindex 6ae1298d..050a2efa 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -1,5 +1,10 @@# MCP — drive this VPS from ChatGPT, Claude.ai or Cursor+> **Current deep reference.** For ChatGPT specifically, use+> [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) for current custom-MCP-app terminology,+> setup values and diagrams. This file owns protocol, tool, discovery, workflow and+> security internals.+mso ships an MCP server so an AI client can call the same host operations the webUI does: list and read files, write them, check CPU/memory/disk, list processes andmanaged apps, and — if you grant it — run shell commands.@@ -13,45 +18,45 @@ unauthenticated one.```bash# .env.localOS_MCP_ENABLED=1-OS_MCP_MAX_SCOPE=exec # optional: exec is the default; use read/write to opt down+OS_MCP_MAX_SCOPE=read # read | write | exec; default ceiling is exec```-Then `bun run build && sudo systemctl restart mso.service` (build THEN restart —-see CLAUDE.md's deploy hazard).+After changing deployment environment, use the normal MSO update/rebuild path (Settings →+About or `mso update run --rebuild`). A Git push or editing `.env.local` does not change the+running service by itself.-## Connect ChatGPT+## Connect an MCP client-Settings → Connectors → New App. Every field is copy-pasteable from-**mso → Settings → MCP**.+The stable server contract is the remote HTTPS endpoint plus OAuth discovery:-| Field | Value |+| Purpose | Path ||---|---|-| MCP Server URL | `https://mso.rahmanef.com/mcp` |-| Authentication | `OAuth` |-| Registration method | `User-Defined OAuth Client` |-| Client ID | `chatgpt-mso` (any string) |-| Client Secret | *empty* |-| Token endpoint auth method | `none` |-| Auth URL | `https://mso.rahmanef.com/oauth/authorize` |-| Token URL | `https://mso.rahmanef.com/oauth/token` |-| Resource | `https://mso.rahmanef.com/mcp` |--Clicking Create sends you to mso's consent screen. **You must already be signed in-to mso on that device** — the consent page cannot authorize anything on its own;-it converts an existing approved session into a bearer.--Claude.ai, Cursor and `mcp-remote` register themselves through RFC 7591 DCR — give-them the MCP Server URL and nothing else.--Verify discovery before you click Create:--```bash-curl -s https://mso.rahmanef.com/.well-known/oauth-protected-resource | jq-curl -s https://mso.rahmanef.com/.well-known/oauth-authorization-server | jq-```--A 404 there is the cause of ChatGPT's unhelpful "MCP server does not implement-OAuth" — it means `OS_MCP_ENABLED` is not set on the running process.+| MCP | `/mcp` |+| authorize | `/oauth/authorize` |+| token | `/oauth/token` |+| dynamic registration | `/oauth/register` |+| authorization metadata | `/.well-known/oauth-authorization-server` |+| protected-resource metadata | `/.well-known/oauth-protected-resource` |++MSO supports OAuth 2.1-style authorization-code flow with PKCE S256 and public clients+(token endpoint auth `none`). The current authorization metadata advertises only+`authorization_code`; there is no refresh-token grant. The authorization page is a normal+signed-in MSO page: an approved human browser session converts into a scoped MCP bearer; the+consent page is not a second login mechanism. Expired/revoked bearers therefore require a+new authorization flow.++For ChatGPT, the current product surface is a **custom MCP app/connector in Developer+Mode**. Its UI and plan availability are owned by OpenAI and can change during the beta, so+this deep reference does not freeze ChatGPT menu labels. Use+[`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) for the current field mapping, OAuth sequence,+tool-snapshot refresh and troubleshooting.++Clients that support RFC 7591 Dynamic Client Registration can register through+`/oauth/register`. ChatGPT can also use the predefined public `chatgpt-mso` client without a+secret.++A 404 from either well-known discovery document normally means `OS_MCP_ENABLED=1` is not+active in the **running** process (demo mode also forces MCP off).## The three scopes@@ -104,6 +109,8 @@ 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.21.1 tools=28 read=15 write=10 exec=3 -->+Current catalog: **28 tools** (15 read, 10 write, 3 exec), server `1.6.0` / toolset`2026.08.21.1`. `project_capabilities` and `project_function_call` add one stableproject-automation seam without creating a dynamic MCP tool catalog; existing tool names@@ -402,10 +409,14 @@ between them — usually wrong, and the MSO one billed a separate API key. Nothireplaces it: ask the client to generate the image with its own capability.Importing the result is unchanged and deliberately preserved: **`fs_upload_file`** takes-one ChatGPT conversation/generated file through `openai/fileParams`, downloads the-temporary OpenAI URL immediately (HTTPS only, `*.oaiusercontent.com` or an OpenAI-regional `oaisdmnt*.blob.core.windows.net` storage account, redirects re-validated),-checks type and size, writes inside `OS_FS_WRITE_ROOTS`, and returns bytes plus SHA-256.+one ChatGPT conversation/generated file through `openai/fileParams`, downloads its+temporary OpenAI HTTPS URL immediately, re-validates up to three redirects, caps the file+at **20 MiB**, accepts PNG/WebP/JPEG or generic octet-stream, and writes inside+`OS_FS_WRITE_ROOTS`. Allowed download hosts are OpenAI `*.oaiusercontent.com` content hosts+or the explicitly matched `oaisdmntpr<region>.blob.core.windows.net` storage-account+family—not arbitrary Azure Blob hosts. The result returns path, bytes and SHA-256. An+existing same-name file may be replaced, so the tool is classified as a write/destructive+action. See `CHATGPT-PLUGIN.md` for the end-to-end diagram.`OS_CODEX_BUILTIN_TOOLS` still exists and still takes an allowlisted list, but itsdefault is now EMPTY and `image_generation` is no longer an accepted value — naming itdiff --git a/docs/MODELS-INTEGRATION.md b/docs/MODELS-INTEGRATION.mdindex 9eb77656..9537b2ce 100644--- a/docs/MODELS-INTEGRATION.md+++ b/docs/MODELS-INTEGRATION.md@@ -1,64 +1,87 @@-# @rahmanef/models → mso AI integration--**Status: first slice SHIPPED + verified (2026-07-15).** Designed by a 3-agent workflow-(`models-integration-design`) that mapped both codebases; grounded against live code.--## What it does-mso's AI (the **Alfa** assistant) now resolves its model + BYOK key + host-gated-endpoint through the vendored **`@rahmanef/models`** registry (`resolveModel()`),-instead of a single hardcoded Anthropic key. Multi-provider, single-owner, self-contained.--## Key decisions-- **Vendored the lib** (`lib/models/*.js`, 7 files) rather than an npm/file/github dep —- the src is **zero-dep ESM** (`node:` builtins + relative imports only), so it drops in with- **0 new npm deps** and no install-graph/deploy risk. Server-only (reads `node:fs`/env — never- import from a client component). *Sync from `models-rahmanef-com/src/*.js` when it updates.*-- **`resolveModel()` only, not `chat()`** — the lib's `chat()` returns buffered JSON; mso- streams SSE. So we use the lib for key + **host-gate** (a provider's key is pinned to its own- `baseUrl`, can't be redirected) + model + protocol, and **keep the Anthropic SDK** for the stream.-- **`hostCredentialStore()`** (`lib/config/store.ts`) implements the lib's `CredentialStore` over the- existing **0600 `~/.mso/config.json`**, per-provider, with the env chain (`ANTHROPIC_API_KEY`…)- as fallback. Single-owner → `tenantId` ignored. Legacy `anthropicApiKey` stays a read alias →- **existing installs migrate for free**.-- **No new cloud/Convex** — reuses the host config file. Essence intact.--## The seam (`app/api/assistant/route.ts`)-`resolveModel(await resolveModelRef(), { store: hostCredentialStore() })` → `{apiKey, baseUrl,-model, protocol}`; `new Anthropic({ apiKey, baseURL })`; `model: resolved.model`. Throws on no key →-`501 no_api_key` (unchanged UX). Non-anthropic protocol → `501 provider_not_wired` (fenced until the-streaming adapter lands). SSE writer, abort→billing-cutoff, rate-limit, auth, approve-per-call gate-all **untouched**; every client speaks the neutral `delta|tool_use|done|error` vocab → zero client changes.--## Verified-`GET /api/config` → `{provider, model, hasApiKey, apiKeyMasked}`; Settings → AI shows a **model-`<Select>`** (claude-opus-4-8/sonnet-5/haiku-4-5/fable-5); Alfa with no key → graceful "No Anthropic-API key set…" (the resolveModel path ran + threw → 501). With a key (config file or `ANTHROPIC_API_KEY`-in `.env.local`) Alfa streams via the resolved provider/model. Build bundles the vendored ESM cleanly.--## Slices 2 + 3 — SHIPPED (2026-07-15)-- **Slice 2 — openai-protocol streaming adapter** (`lib/ai/openai-stream.ts`): native `fetch`- `POST {baseUrl}/chat/completions {stream:true}`, parses `choices[].delta` → `delta`, accumulates- `tool_calls[]` by index → `tool_use`+`done`; `toOpenAITools`/`toOpenAIMessages` translate tools +- `tool_use`/`tool_result` both ways. The `route.ts` 501 fence is **gone** — it now branches on- `resolved.protocol` (anthropic = SDK, else = adapter), sharing the SSE writer / abort / rate-limit;- the client's `delta|tool_use|done|error` vocab is unchanged (zero client changes). Unit-tested- (`openai-stream.test.ts`: cross-read SSE buffering + split tool_call reassembly). **Unlocks OpenAI- + ~34 compatible providers** (`registry.js`).-- **Slice 3 — provider picker**: `GET /api/models[?provider=]` (`app/api/models/route.ts`,- session-gated, `listModels()` from the offline-tolerant models.dev cache) + a provider `<Select>`- in `ai-section.tsx` (8 curated providers) with catalog-backed free-text model suggestions- (`<datalist>`, so an id absent from the catalog still works offline). `config/route.ts` +- `store.ts` already persisted keys per-provider → unchanged. (Optional: `MODELS_CACHE_DIR=~/.mso/models-cache`.)-- **Verified live:** `/api/models?provider=openai` → 56 models; picker lists Anthropic / OpenAI /- OpenRouter / Google / Groq / xAI / DeepSeek / Mistral; Alfa streams via the resolved provider once- a key is set (Settings → AI or the provider env var).--## Out of scope-Usage/spend stats, simultaneous multi-model, and **OAuth sign-in**: the OpenAI *platform* API-(`/v1`) is **BYOK-key-only** — there is no OAuth flow that mints `/v1` credentials. The only "OpenAI-OAuth" that exists is the ChatGPT-*consumer* device-auth (Codex backend, unofficial / ToS-gray, NOT-`/v1`) — a separate, large, fragile effort against an unofficial API, deliberately not bundled here.--## Files-`lib/models/` (vendored), `lib/config/store.ts`, `app/api/assistant/route.ts`,-`app/api/config/route.ts`, `frontend/slices/os-settings/components/ai-section.tsx`.+# Alfa model and credential integration++> **Current reference.** Alfa supports BYOK API providers, custom OpenAI/Anthropic-compatible+> endpoints, and a separate OpenAI Codex/ChatGPT-subscription OAuth path. Do not confuse+> that provider login with the ChatGPT MCP connector OAuth described in+> `docs/CHATGPT-PLUGIN.md`.++## 1. Credential store++Alfa's server-side selection and credentials live in private host state (normally+`~/.mso/config.json`, mode `0600`). Built-in environment variables remain fallback inputs.+Credentials are not compiled into the client bundle.++The current provider picker covers the common built-ins (Anthropic, OpenAI, OpenRouter,+Google, Groq, xAI, DeepSeek and Mistral) and can use the vendored model registry for a+broader catalog. Custom providers can define a base URL and OpenAI- or+Anthropic-compatible protocol; custom URLs are SSRF-checked before use.++## 2. Streaming architecture++```mermaid+flowchart LR+ UI[Alfa UI] --> R[/api/assistant]+ R --> RES[resolve provider + model + credential]+ RES -->|Anthropic protocol| AN[Anthropic streaming adapter]+ RES -->|OpenAI-compatible| OA[OpenAI streaming adapter]+ RES -->|openai-codex| CX[ChatGPT Codex Responses adapter]+ AN --> S[neutral delta / tool_use / done / error stream]+ OA --> S+ CX --> S+ S --> UI+```++The client consumes one neutral stream vocabulary. Provider-specific wire formats are+translated server-side, so changing model provider does not fork the shell UI.++## 3. BYOK API-key providers++For normal OpenAI Platform usage, Alfa uses a user-supplied API key. The OpenAI Platform+API does not mint ordinary `/v1` credentials through the ChatGPT MCP connector flow.+Likewise, an Anthropic/OpenRouter/etc API key is unrelated to MSO's own OAuth server.++A custom endpoint stores its provider metadata in the host config and routes through the+same streaming abstraction after URL/protocol validation.++## 4. OpenAI Codex / ChatGPT subscription provider++`openai-codex` is a distinct optional Alfa provider. It uses the ChatGPT consumer+OAuth/device flow and the ChatGPT Codex backend rather than the OpenAI Platform+`/v1/chat/completions` API. Its implementation lives in `lib/ai/oauth/codex.ts` and+`lib/ai/codex-stream.ts`.++This path exists so the owner can choose to run Alfa against an eligible ChatGPT+subscription. It is a consumer-backend integration and can be more fragile than the public+Platform API. Tokens are host-side private state.++Current Alfa requests through this adapter can carry Alfa's tool definitions; the older+"chat-only/no tools" limitation from the original July plan no longer describes `main`.++## 5. ChatGPT MCP OAuth is different++There are two completely independent OAuth stories:++| Flow | Who is the OAuth server/provider? | Credential grants access to | Stored by |+|---|---|---|---|+| ChatGPT ↔ MSO MCP | **MSO** is the OAuth server | MSO MCP tools (`read/write/exec`) | ChatGPT holds bearer; MSO stores only its hash |+| Alfa `openai-codex` | OpenAI/ChatGPT consumer flow | ChatGPT Codex backend for Alfa model inference | MSO host config |++Authorizing ChatGPT as an MCP client does **not** give Alfa a model credential. Connecting+Alfa to `openai-codex` does **not** grant ChatGPT permission to operate the VPS.++## 6. Data boundary++BYOK means the owner controls the credential; it does not mean prompt/tool data stays on+the VPS. Messages and any tool context included in a model request go to the selected model+provider. Host mutation approval and filesystem boundaries remain separate MSO controls.++## 7. Source map++- `lib/config/store.ts` — credential/provider persistence+- `app/api/config/route.ts` — Settings configuration API+- `app/api/models/route.ts`, `app/api/models/test/route.ts` — catalog/test surfaces+- `app/api/assistant/route.ts` — common assistant gateway+- `lib/ai/openai-stream.ts` — OpenAI-compatible streaming+- `lib/ai/codex-stream.ts` — ChatGPT Codex Responses streaming+- `lib/ai/oauth/codex.ts` — Codex OAuth/device flow+- `frontend/slices/os-settings/components/` — provider Settings UIdiff --git a/docs/OPENCLAW-INTEGRATION.md b/docs/OPENCLAW-INTEGRATION.mdindex 18c815ad..da39c064 100644--- a/docs/OPENCLAW-INTEGRATION.md+++ b/docs/OPENCLAW-INTEGRATION.md@@ -1,408 +1,91 @@-# OpenClaw — integration notes+# OpenClaw integration-> **⚠ SUPERSEDED IN PART (`a2c3882`, 2026-07-28).** Every passage about *feature-> discovery* — parsing OpenClaw's built SPA bundle to spawn one MSO window per-> upstream nav route — describes DELETED code (`lib/managed-apps/features.ts`,-> `feature-parser.ts`, `dynamic-features.tsx`, `feature-icons.ts`, the `/features`-> route, `os-shell/workspace-mode.ts`). OpenClaw is an ordinary app window now,-> opening on its own dashboard, because it already ships its own sidebar. Passages about-> the origin split, the proxy, the CLI fallback and the update centre are still accurate.-> Any mention of managed-app "single-origin mode" is also dead — see MANAGED-APPS.md §7.+> **Current reference.** OpenClaw is one of MSO's two managed applications. MSO presents+> the vendor dashboard as one surface and no longer turns OpenClaw's internal routes into+> MSO launcher features.-> Originally re-checked against the installed source under `~/.openclaw` and-> `~/.local/lib/node_modules/openclaw` (read-only) and the live gateway on 2026-07-25.-> Shipped `c411187` → `d880f68`. Where this file and the code disagree, the code is what is-> documented and the divergence is called out. §2's detection defect — the card reading "stopped"-> while the gateway served — was found by writing this file and fixed in the same phase.+## Runtime identity-The subsystem itself — contract, lifecycle, proxy internals, CSP intersection, backup, deploy-order, gaps — is [MANAGED-APPS.md](./MANAGED-APPS.md). This file is only what is true of-**OpenClaw**. Its sibling [HERMES-INTEGRATION.md](./HERMES-INTEGRATION.md) has the same seven-sections in the same order, so the two read side by side.--**OpenClaw is a separate application.** MSO gives it a window, a status card, a dock and a-switch. Nothing in this repo copies, forks or vendors its source, scrapes its DOM, or writes a-byte under `~/.openclaw/`. Read-only inspection of that tree is how discovery works.-------## 1. What it is and where it lives--OpenClaw — a multi-channel agent gateway: one WebSocket gateway process serving a "Control UI"-SPA, plus a CLI, chat-channel bridges, sandboxes, node hosts and plugins. MSO uses it for-exactly three things: one status card, its Control UI routes as MSO app tiles, a read-only CLI-view.--| | Value | Verified by |-|---|---|---|-| Version | `OpenClaw 2026.7.1-2 (0790d9f)` | `openclaw --version` |-| Install method | global npm under `~/.local` | path below |-| CLI | `/home/rahman/.local/bin/openclaw` | `which openclaw` |-| Install dir | `~/.local/lib/node_modules/openclaw` (370 MB) | unit `ExecStart`, `du -sh` |-| State dir | `~/.openclaw` (1.7 GB — **separate from the install**, unlike Hermes) | `catalog.ts:37`, `du -sh` |-| Gateway port | `18789`, bound `0.0.0.0` (because `gateway.bind: "lan"`) | `ss -tlnp`, `~/.openclaw/openclaw.json` |-| Public today | **yes** — `oc.rahmanef.com` (`200`) | `/etc/dokploy/traefik/dynamic/oc-openclaw.yml` → `http://172.17.0.1:18789`, `passHostHeader: true` |-| MSO app host | `openclaw.mso.rahmanef.com` → mso `:4005` → proxy → `127.0.0.1:18789` | `mso-managed-apps.yml`, `curl` in §5 |--One **user** systemd unit, `~/.config/systemd/user/openclaw-gateway.service`. There is no-system-scope unit, and no `openclaw.service` — that name does not exist on this host, which is why-§2 starts with which unit MSO actually drives.--```-ExecStart=/usr/bin/node /home/rahman/.local/lib/node_modules/openclaw/dist/index.js gateway --port 18789-Restart=always RestartPreventExitStatus=78 SuccessExitStatus=0 143 KillMode=control-group-Environment=OPENCLAW_GATEWAY_PORT=18789 OPENCLAW_SYSTEMD_UNIT=openclaw-gateway.service-Environment=OPENCLAW_SERVICE_KIND=gateway OPENCLAW_SERVICE_VERSION=2026.6.10-```--`OPENCLAW_SERVICE_VERSION=2026.6.10` and `Description=OpenClaw Gateway (v2026.6.10)` are **stale** —-the installed CLI is `2026.7.1-2`. The unit is generated by `openclaw daemon install` and stamps the-version that wrote it, so it drifts on any upgrade that does not re-install the service. Cosmetic, but-it is the signal that the *unit is written by the app*, not by hand — see §7.--State-dir contents worth knowing (all read-only to MSO): `openclaw.json` plus the updater's-own `.pre-update` / `.last-good` / `.bak*` snapshots, `credentials/`, `identity/`, `devices/`,-`logs/`, `plugin-skills/`, `skill-workshop/`, `exec-approvals.json`, and `workspace/` — agent-workspaces, each with its own `node_modules`.--**`gateway.bind: "lan"` is why the port is on `0.0.0.0`,** which lets Traefik reach it across-the docker bridge for `oc.rahmanef.com`. MSO does not depend on it: the proxy targets-`127.0.0.1:18789` and would keep working if the bind were narrowed to loopback.-------## 2. How MSO detects and controls it--Catalog entry at `lib/managed-apps/catalog.ts:27`.--| Field | Value |-|---|---|-| `command` | `openclaw` |-| `serviceNames` | `["openclaw-gateway.service", "openclaw.service"]` — live unit first |-| `containerNames` | `["openclaw", "openclaw-gateway"]` |-| `dashboardUrl` | `http://127.0.0.1:18789` (`OPENCLAW_DASHBOARD_URL`) |-| `stateDirName` | `.openclaw` |-| overrides | `OPENCLAW_CONTROL_UI_DIST` (discovery only) |--### Which unit MSO actually drives--**`openclaw.service` does not exist on this host.** The running unit is-`openclaw-gateway.service`, and detection checks each candidate's `LoadState` before accepting it-(`manager.ts:29`), so that is the one it lands on:-`systemctl --user show -p LoadState -p ActiveState openclaw.service openclaw-gateway.service` →-`not-found`, then `loaded` + `active`. `listManagedApps()` returns `installationType: "systemd"`,-**`state: "running"`**, `healthy: true`, `dashboardAvailable: true`, version-`OpenClaw 2026.7.1-2 (0790d9f)`, `supportedActions: ["start","stop","restart","backup"]`.--The trap worth carrying forward: `systemctl is-active <unknown-unit>` prints `inactive` with rc 4 and-an empty stderr on systemd 255, byte-identical to a stopped unit. Read that as "the unit exists" — as-the first version of this code did — and the phantom `openclaw.service` wins detection: the card read-"stopped" while the gateway served, `journalctl -u openclaw.service` returned the one line-`-- No entries --`, and every lifecycle action `409`d on a unit that was not there. The catalog now-lists the live unit first (`catalog.ts:34`), but that ordering is a preference; `LoadState` decides-([MANAGED-APPS.md §3](./MANAGED-APPS.md)).--- **Logs** are that unit's journal: `available: true`, 100 lines, redacted (`manager.ts:18`).-- **`start`/`stop`/`restart`** run `systemctl --user <action> openclaw-gateway.service`- (`manager.ts:121`), system scope only if that fails. They restart the **gateway**, dropping- connected channel bridges and Control-UI sockets — the same blast radius as OpenClaw's own- `openclaw daemon start | stop | restart | status`.-- **The dashboard never depended on detection.** The proxy and discovery go straight at- `dashboardUrl`, which is why a wrong card was the *only* symptom, and why it went unnoticed.--### The rest of the lifecycle--**Health** is genuinely meaningful here — unlike Hermes:-`curl -s http://127.0.0.1:18789/health` → `200`, `application/json`, **unauthenticated**, no-redirect, body `{"ok":true,"status":"live"}`. `response.ok` is a real liveness answer.--**Version** is `openclaw --version`, a single line, so nothing is truncated.--**`backup` copies `~/.openclaw`** (no `OPENCLAW_HOME` exists, so that path is always the source).-With the exclusions in [MANAGED-APPS.md §6](./MANAGED-APPS.md) it is **237 MB** instead of 1.7 GB —-`~/.openclaw/workspace` alone drops 1.2 GB → 83 MB once one agent workspace's `node_modules` and-`.venv` are pruned (`du -sh --exclude=node_modules --exclude=.venv ~/.openclaw/workspace`). Symlinks-are skipped, not refused: `find ~/.openclaw -type l | wc -l` → **2063**, all but 9 inside those-pruned trees, and those 9 are `plugin-skills/{browser-automation,canvas}`, the Chromium-`browser/openclaw/user-data/Singleton{Socket,Cookie,Lock}` links and four-`agents/main/agent/codex-home/tmp/arg0/*` wrappers — none of which a restore should recreate; the-first of them is what used to abort the run. OpenClaw's own `openclaw backup` ("Create and verify-local backup archives for OpenClaw state") is still the only path that *verifies* an archive, and-the updater snapshots `openclaw.json` itself.-------## 3. Auth model, and how the proxy lives with it--**OpenClaw sets no cookies at all.** Verified two ways: the live gateway returns no-`Set-Cookie` on `/`, `/health`, `/config`, `/status`, `/rpc` or `/v1/status`, and the Control-UI bundle reads none — the only `cookie` matches in `dist/control-ui/assets/*.js` are two in-`tool-display-*.js`, inside an `authorization|cookie|x-api-key|…` **redaction** pattern for-displaying tool output. That is the fact `proxy-headers.ts:41-45` records, and it is why the-`mapp_openclaw_` namespace carries nothing today — it exists so a future upstream cookie-cannot collide with the cockpit's `session`, or with Hermes' five.--Its auth is a **gateway token presented over the WebSocket**. From `openclaw.json`:-`gateway.auth.mode = "token"` (the token itself is in that file; MSO never reads it),-`gateway.bind = "lan"`, `gateway.controlUi.allowInsecureAuth = true`,-`gateway.controlUi.allowedOrigins = ["https://oc.rahmanef.com"]`.--**The handshake, captured live.** The gateway accepts an `Upgrade` on `/` — the same path that-serves the SPA — and immediately pushes a challenge before any credential is sent:--```-$ curl -i --http1.1 --max-time 2 -H 'Connection: Upgrade' -H 'Upgrade: websocket' \- -H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: <16 random bytes, base64>' \- http://127.0.0.1:18789/-HTTP/1.1 101 Switching Protocols-{"type":"event","event":"connect.challenge","payload":{"nonce":"…","ts":…}}-```--(`--max-time` is not optional — after `101` curl holds the socket open and never exits.)--The upgrade is **not** origin-gated: it returns the same `101` and challenge with `Origin:-https://evil.example`, and gates at the protocol layer instead. `allowedOrigins` and-`allowInsecureAuth` govern the Control UI's own checks — and that allowlist names-`oc.rahmanef.com` only, **not** `openclaw.mso.rahmanef.com`. Costs nothing today (no socket-crosses the proxy); first thing to add if a socket proxy lands.--**Where the token lives client-side.** The SPA reads it from the URL **fragment**-`#token=<…>`, strips it, and persists it in `localStorage` under-`openclaw.control.token.v1` (plus a per-gateway `openclaw.control.token.v1:<gateway>`-variant, alongside `openclaw.control.currentGateway.v1:`, `openclaw.control.settings.v1`,-`openclaw.control.user.v1`). A `?token=` query still parses but logs *"Auth token passed as-query parameter (?token=). Use URL fragment instead: #token=<token>. Query parameters may-appear in server logs."* The supported way to get a URL is `openclaw dashboard --no-open`.--**MSO never mints, reads or injects that token.** `featureSource()` (`feature-cli.ts:102`)-builds the iframe `src` as `https://openclaw.mso.rahmanef.com/<route>` — origin plus path, no-fragment — and nothing in `lib/managed-apps/` reads `openclaw.json` (grep: the only upstream-reads are the control-UI assets and the gateway's HTTP surface). So the framed SPA starts with-**no gateway token** — the second independent reason its panels are empty (§4 is the first).-Injecting one would mean lifting a credential out of another application's config and putting-it in a URL, which is the boundary this subsystem exists to keep.--**So there is no login flow inside the frame at all**: no `302`, no form, no `Set-Cookie`,-nothing for `rewriteSetCookie()` to namespace, nothing for the re-entry guard to rescue.-------## 4. The dashboard's shape, and what works through the proxy--A Vite/rolldown-built SPA at `~/.local/lib/node_modules/openclaw/dist/control-ui`, served by-the gateway itself. Three properties matter to the proxy:--- **`./`-relative asset URLs and no `<base>`** — `index.html` points at `./assets/…`,- `./favicon.svg`, `./manifest.webmanifest`. Hermes is the opposite (§4 there).-- **The gateway is an SPA-fallback server**: every path returns the same 14 406-byte- `index.html` (verified on `/config`, `/status`, `/rpc`, `/v1/status`) and serves `/assets` at- any depth. That is why root-mounting works for nested routes like `/settings/appearance` even- with relative URLs, and why origin-split mode needs **no** document rewriting — no- `<base href>`, no rebasing, no fetch shim, nothing to hash-pin.-- **Two inline `<script>` blocks** (a theme bootstrap), matching exactly the two `sha256-`- sources in its own `script-src` (§5).--It also ships `sw.js` + `manifest.webmanifest` and calls `navigator.serviceWorker.register(…,-{updateViaCache:'none'})`. OpenClaw is the reason the proxy refuses service-worker paths-outright (`route.ts:109`, `proxy-headers.ts:182`): a worker registered from proxied bytes-installs on *this* origin and keeps answering after the window closes. The emitted `worker-src`-is `'none'` too (§5), so it is closed twice.--### Why the panels are empty--**Every panel in the Control UI is driven by the gateway WebSocket.** The client builds its URL-from `location` — `${https ? 'wss' : 'ws'}://${location.host}<basePath>` — so on-`openclaw.mso.rahmanef.com` it targets that host, which is mso. **A Next route handler cannot-service an `Upgrade`**: it is handed a `Request` and returns a `Response`, and the proxy's-transport is `fetch()`. So the frame loads its chrome, HTML, CSS and JS — and sits with no data.--That is recorded as `SOCKET_FEATURES.openclaw = "all"` (`feature-cli.ts:42`), and it changes-the default view: `defaultView()` (`:60`) opens **on the CLI** for every OpenClaw feature that-has a command, because opening on the UI would be opening on a surface that cannot populate.-The UI toggle is still there, and the window states the reason rather than letting the-emptiness look like a bug. The one exception is **Appearance** (`/settings/appearance`), which-has no CLI equivalent, so it falls back to `"ui"` and opens on the empty panel with the notice.--Also inert in the frame: new-window links. `allow-popups` is deliberately absent from the-sandbox (`feature-app.tsx:107`); the four `window.open(` call sites across the control-UI-bundle are external links, ctrl-click terminal links and an open-in-editor deep link —-destinations for the user's own browser, not this frame.--### The CLI equivalents--Feature keys map to **verified read-only** `openclaw` subcommands (`feature-cli.ts:27`), each-checked against `openclaw --help` and its own `<command> --help` on this host. Several UI keys-share one command, so the map is many-to-one:--| Command | Keys |-|---|---|-| `chat` · `sessions` · `mcp` · `logs` · `worktrees` | the same-named key |-| `agents` | `agents`, `ai-agents` |-| `cron` | `cron`, `automation` |-| `tasks` | `tasks`, `dreams`, `workboard` (gated) |-| `skills` | `skills`, `skill-workshop` |-| `nodes` | `nodes`, `infrastructure`, `instances` |-| `channels` | `channels`, `communications` |-| `plugins` | `plugin` (gated) |-| `status` / `status --usage` / `audit` | `overview` / `usage` / `activity` |-| `config validate` / `doctor --lint` | `config` / `debug` |-| *none* | `appearance` — opens on the UI |--A bare group command is safe because the CLI view types into a live PTY and a group prints its-action list. Two commands are **not** safe bare and are deliberately mapped to their documented-read-only forms: `openclaw config` is *"Run without subcommand for guided setup"*, and-`openclaw doctor` prompts and applies repairs unless `--lint` / `--non-interactive`.-`feature-cli.test.ts` pins the map against the verbatim `--help` verb lists, so an upstream-rename fails a test rather than shelling something that writes.-------## 5. Its own CSP and framing headers, and what the intersection does--OpenClaw ships a real policy and real framing refusal. Live, on every HTML response — read it-with a GET, because the two `sha256-` sources are derived from the body it is about to send-and a `curl -sI` (HEAD) returns the same policy with `script-src 'self'` and no hashes:--```-X-Frame-Options: DENY-Referrer-Policy: no-referrer-X-Content-Type-Options: nosniff-Permissions-Policy: camera=(), microphone=(self), geolocation=()-Content-Security-Policy: default-src 'self'; base-uri 'none'; object-src 'none';- frame-ancestors 'none'; script-src 'self' 'sha256-xlWU9W5DLkdwhgKfV5ywIgqPfePNDkqtaKOBVD1gkB4='- 'sha256-YE++OxiPw+vXrIb7PDq83l6z34Hi3wFFCJVdIBVD5zU='; style-src 'self' 'unsafe-inline'- https://fonts.googleapis.com; img-src 'self' data: blob:; media-src 'self' data: blob:;- font-src 'self' https://fonts.gstatic.com; worker-src 'self';- connect-src 'self' ws: wss: https://api.openai.com https://tweakcn.com-```--The response allowlist (`proxy-headers.ts:30`) copies **none** of those to the browser — an-upstream `X-Frame-Options: DENY` plus `frame-ancestors 'none'` would un-frame the dashboard,-the one thing the proxy exists to prevent. The policy is not discarded either: it is fed into-`contentSecurityPolicy()` and **intersected per directive** (`proxy-csp.ts:214`). Computed-from the live header, root-mounted:--```-default-src O; script-src O 'sha256-xlWU9W5…' 'sha256-YE++OxiP…';-style-src O 'unsafe-inline' https://fonts.googleapis.com; img-src O data: blob:;-font-src O https://fonts.gstatic.com; media-src O data: blob:; worker-src 'none';-connect-src O https://api.openai.com https://tweakcn.com; frame-src O; form-action O;-base-uri 'none'; frame-ancestors 'self' https://mso.rahmanef.com; object-src 'none'- …where O = https://openclaw.mso.rahmanef.com/-```--Six things the intersection did, and why each is the right answer:--| Directive | Outcome | Why |-|---|---|---|-| `script-src` | lost `'unsafe-inline'`, gained OpenClaw's two `sha256-` | upstream grants no `'unsafe-inline'`, so the tighter side wins and its own inline scripts survive on the hashes it authored. Hashes copy, **nonces never** (`proxy-csp.ts:134`) — a nonce matches an element whatever its URL, re-opening origin scoping. Root-mounted MSO injects and pins nothing (`:233`); single-origin adds a third hash for its shim |-| `worker-src` | `'none'` | ours `blob:`-only ∩ theirs `'self'` = ∅ — this is what stops §4's service worker outliving the window |-| `connect-src` | kept `api.openai.com`, `tweakcn.com`; dropped bare `ws:`/`wss:` | a host the upstream *declares* is honoured, but only `https://`, no wildcards, and **never the cockpit** (`:174`) — `connect-src https://mso.rahmanef.com` from a compromised upstream is the reach scoping removes. This is not what kills its own socket — §4's missing `Upgrade` is: nothing on the app host answers one, so no `wss://` request is ever made for a policy to judge. What is gone is a socket to any *other* host |-| `style-src`, `font-src` | kept `fonts.googleapis.com`, `fonts.gstatic.com` | declared upstream, so honoured — OpenClaw keeps its webfonts where Hermes, declaring nothing, does not |-| `base-uri` | `'none'` honoured | root-mounted nothing injects `<base href>`, so upstream's stricter value can win (`:104`); single-origin ours must win or relative URLs escape the prefix |-| `frame-ancestors` | overridden to `'self' <cockpit>` | always ours — being framed by the cockpit is the point. The origin is deployment env only (`origin.ts:101`); resolving to nothing emits `'none'`, so a misconfiguration refuses visibly instead of naming a guessed framer |--One upstream host is refused by **both** policies: `generativelanguage.googleapis.com`,-referenced in `chat-page-DrPkxqJK.js` but absent from OpenClaw's own `connect-src` — so it is-blocked in OpenClaw's own deployment too. It is the one OpenClaw entry in-`PROXY_BLOCKED_EXTERNALS` (`proxy-headers.ts:228`) and the window says *"The Gemini live-audio-socket in chat cannot connect."*--Live, unauthenticated, `curl -sI https://openclaw.mso.rahmanef.com/` returns `401` with-`content-security-policy: default-src 'none'; frame-ancestors 'self' https://mso.rahmanef.com`-and `x-middleware-rewrite: /api/v1/managed-apps/openclaw/proxy` — the host gating and the-framing grant both working, before auth. Full verification set:-[MANAGED-APPS.md §5](./MANAGED-APPS.md).-------## 6. Feature discovery for OpenClaw--`discoverOpenClaw()` (`features.ts:75`) reads OpenClaw's **own route table**. Nothing is-hardcoded; there is no plugin-manifest step (Hermes has one, OpenClaw exposes no equivalent).--1. `GET http://127.0.0.1:18789/`, find `./assets/app-route-paths-*.js` in the HTML, fetch it,- parse the `key: { path, aliases }` map (`parseOpenClawRoutePaths`, `feature-parser.ts:126`).- Today that chunk is `app-route-paths-Ckh-KQjG.js`.-2. Empty? Parse the `index-*.js` chunk's page and settings route factories (`:133`).-3. Still empty (gateway down)? Read the same `app-route-paths-*.js` from disk under- `OPENCLAW_CONTROL_UI_DIST` or `~/.local/lib/node_modules/openclaw/dist/control-ui`. That- lookup is a glob, so it is version-independent — this is what keeps the launchpad populated- while the gateway is stopped.--The parser keys on **property names** (`path`, and the map key), which survive minification;-the wrapping variable does not, so the regex is deliberately anchor-free-(`feature-parser.ts:23`). **Titles come from the map KEY, not the path**-(`feature-parser.ts:8`, `:120`) — which is why `/settings/general` is titled "Settings" (key-`config`) and `/dreaming` is "Dreaming" (key `dreams`); an unknown key is title-cased.--Live result, reproduced end to end: **26 routes, 24 offered.**--- `/chat` `/overview` `/activity` `/agents` `/instances` `/sessions` `/usage` `/debug` `/logs`- `/skills` `/skills/workshop` `/cron` `/tasks` `/nodes` `/dreaming`-- `/settings/{channels,general,communications,appearance,automation,mcp,infrastructure,ai-agents,worktrees}`-- **Not offered**: `/workboard` (feature flag) and `/plugin` (a plugin host panel) are marked- `available: false` (`feature-parser.ts:12`) and filtered out of the dock- (`dynamic-features.tsx:49`) rather than shipped as dead tiles.--**The tripwire.** `checked()` (`feature-parser.ts:58`) accepts a run only if it has **≥ 12-entries and includes `/chat`**; otherwise the *whole* run is discarded, so a route-map-reshuffle that breaks the regex yields **zero** tiles, never a plausible partial list.--**Exact symptom when an upgrade breaks it:** the OpenClaw workspace keeps only the shared apps-(Terminal, Files, Assistant, Monitor, Settings) and every OpenClaw tile disappears from dock and-Launchpad. `/api/v1/managed-apps/openclaw/features` still answers `200 {"features":[]}` — a-`503` only happens if discovery *throws*. The status card, the proxy and the CLI view are-unaffected, so the dashboard stays reachable. Results cache 60 s (`features.ts:15`) and nothing-invalidates on upgrade, so a fix or a new upstream route appears within a minute. Unlike Hermes-the primary source is **the live gateway**, so if it ever serves a different bundle than the one-on disk, step 1 wins and the tile list changes when the gateway stops.-------## 7. Upgrade and operational notes--OpenClaw updates itself, and it already has everything an update centre would drive:-`openclaw update` (`--channel stable|extended-stable|beta|dev`, `--dry-run`, `--no-restart`,-plus `update status | repair | wizard`), `openclaw doctor --post-upgrade` for plugin-compat-findings, `openclaw uninstall`. MSO has **no update centre** — no check-update, channels,-update, rollback or install wizard (see [MANAGED-APPS.md §8](./MANAGED-APPS.md)). Nothing in-MSO's action set writes upstream state, which is why the current surface is safe. OpenClaw also-snapshots its own config across an upgrade (`openclaw.json.pre-update`, `.last-good`), so a-config regression is recoverable with its own tooling and needs nothing from MSO.--Re-check after any OpenClaw upgrade:--| Check | Why |+| Property | Current MSO value ||---|---|-| `systemctl --user list-units '*openclaw*'` | `openclaw daemon install` **writes the unit**, and MSO's catalog hard-codes candidate names. A rename means a catalog edit: detection would report `not-installed` rather than guess (§2) |-| tile count (open the OpenClaw workspace) | a route-map reshape trips the tripwire → 0 tiles |-| `curl -s 127.0.0.1:18789/ \| grep app-route-paths` | the asset hash changes every release; live discovery follows the HTML so it self-heals, and the on-disk fallback globs |-| `curl -s 127.0.0.1:18789/health` and `openclaw --version` | the only health signal MSO uses, and the string shown verbatim on the card |-| the CLI toggles | `feature-cli.test.ts` pins the verb map; a renamed subcommand should fail that test, not surprise a user |-| its `Content-Security-Policy` | the intersection is only as good as the source; see below |--**What an upgrade can break in the frame.** OpenClaw already pins its inline scripts by hash,-so a policy *tightening* is mostly absorbed — ours only gets tighter and its own hashes travel.-Three concrete edges:--- **A new inline script without a new hash** breaks in the frame *and* in OpenClaw's own- deployment (root-mounted MSO adds no `'unsafe-inline'` back and pins nothing,- `proxy-csp.ts:233`), so upstream sees it first.-- **A new external `connect-src`/`style-src` host** is honoured automatically if declared- (https, non-wildcard, not the cockpit). One it *calls without declaring* stays blocked, and- only reaches the window's notice if added to `PROXY_BLOCKED_EXTERNALS` by hand.-- **Switching from hashes to a nonce** makes `script-src` unintersectable: nonces are never- copied and dropping one would leave `'none'`, so `intersect()` hands the directive back to- ours (`proxy-csp.ts:188`) — root-mounted that means `'unsafe-inline'` returns and script- containment loosens to the origin scope alone.--**Known divergences from this integration:**--- **No restore path** ([MANAGED-APPS.md §8](./MANAGED-APPS.md)): `backup` (§2) copies the state dir,- nothing reads a snapshot back — a rollback is `openclaw backup`'s archive or a manual `cp -a`.-- **The panels stay empty** (§4) and will until a Node-runtime WebSocket proxy exists outside- the App Router, with the origin and token containment re-derived for sockets — and- `controlUi.allowedOrigins` extended to the app host.-- No MSO surface covers `openclaw daemon`, sandboxes, node hosts, channels or exec approvals;- those stay with the CLI and the Control UI. `dashboardAvailable` is computed, never consumed.+| Managed id | `openclaw` |+| Preferred service | `openclaw-gateway.service` |+| Other recognized service | `openclaw.service` |+| Dashboard upstream | `http://127.0.0.1:18789` by default |+| State | `~/.openclaw` |++## What MSO can do++- detect install/runtime/version/health;+- install OpenClaw non-interactively;+- start, stop and restart the gateway;+- read logs;+- snapshot state;+- check, dry-run and apply updates;+- switch supported update channels/tags;+- restore a snapshot and optionally use a validated package-version pin;+- conservatively uninstall service + local state;+- optionally proxy the Control UI from its own managed-app hostname.++## Install++The one-click flow runs `scripts/managed-app-install openclaw` as a managed-app job and uses+OpenClaw's non-interactive onboarding with its required risk acknowledgement. MSO defaults+the gateway bind to loopback unless the deployment explicitly needs another supported bind.++A model-provider key is optional. When supplied it travels in the request body and child+environment, never the persisted argv or job log.++## Update semantics++OpenClaw supports a real dry run, so the UI exposes it. MSO validates channel/tag/version+inputs before they become separate argv values. Package specs or arbitrary git sources are+not accepted as rollback pins; the permitted shape is a known dist-tag or an exact version.++Every real update starts with an MSO snapshot of `~/.openclaw`. A failed backup aborts the+update. Normal updates allow the upstream restart/verification path to run; leaving new+package bytes on disk behind an old process is deliberately not the default.++## Backup and restore++Snapshots are stored under `~/.mso/backups/openclaw/<timestamp>/`. Symlinks are skipped and+reinstallable/cache trees such as `node_modules`, `.cache`, `.git`, virtualenv directories+and nested backups are excluded.++Restore requires OpenClaw to be stopped (and that state to be provable). MSO validates the+snapshot manifest and target, checks symlink collisions, takes a `pre-restore` safety+snapshot, then overwrites snapshot files. Files created since the snapshot remain in place;+excluded directories are not reconstructed.++If the desired rollback also requires a previous OpenClaw package release, the update+adapter can apply a validated exact version/tag separately from the restored state.++## Uninstall++MSO uses the upstream non-interactive uninstall scoped to the gateway service and local+state. It does not add OpenClaw's workspace-removal scope. A preview is available when the+installed CLI still advertises its dry-run contract. A real uninstall requires explicit+confirmation and an MSO backup first.++## Dashboard and origin++When split-origin embedding is enabled, a hostname such as+`openclaw.mso.example.com` is rewritten only into OpenClaw's authenticated dashboard proxy+and forwarded to loopback `:18789`. Without the two split-origin environment settings, the+Control UI is not embedded and MSO's Details surface remains usable.++The origin boundary protects the cockpit browser realm, not the host from OpenClaw itself.+An OpenClaw plugin has the privileges of the OpenClaw daemon and can run host code according+to OpenClaw's own trust model.++## Troubleshooting++- **Gateway installed but stopped:** use Start from the MSO surface; the vendor iframe is+ intentionally not mounted while nothing is serving it.+- **Dry run works but update fails:** inspect the mandatory snapshot and then the job+ transcript; the real run also restarts/verifies the service.+- **Control UI cannot connect after a new install:** check the app-origin allowlist/bind+ values created by the installer and the split-origin hostname.+- **Restore refused:** stop OpenClaw first and fix the reported state-path/symlink problem.+- **Need to remove the workspace too:** MSO intentionally does not expose that destructive+ uninstall scope; review and run the upstream operation yourself if you truly need it.diff --git a/docs/PRODUCT_HUNT.md b/docs/PRODUCT_HUNT.mdindex 8ed0630b..93dde7bf 100644--- a/docs/PRODUCT_HUNT.md+++ b/docs/PRODUCT_HUNT.md@@ -1,4 +1,7 @@-# Product Hunt+# Product Hunt copy draft++> **Marketing collateral, not technical authority.** Keep claims aligned with+> `README.md`, `SECURITY.md` and current reference docs before publishing.## Product name@@ -10,42 +13,38 @@ Manage your Linux server from any browser.## Description-MSO is an open-source, mobile-friendly visual shell for a Linux server you own.-It combines a real terminal, file manager, live system metrics, media tools,-and an optional BYOK AI assistant in one private browser workspace.+MSO is an open-source, mobile-friendly visual shell for a Linux server you own. It combines+Files, real PTY Terminal, Code with an integrated terminal, live system metrics, a remote+Camoufox browser, media tools, optional BYOK Alfa AI, and managed Hermes/OpenClaw controls+inside one private browser workspace.## First comment draft-I built MSO because managing a personal Linux server from a phone is still more-awkward than it should be. SSH is powerful, but it is not always comfortable on-mobile, and most admin workflows make you jump between terminal tabs, file-transfer tools, metrics dashboards, docs, and AI chat.+I built MSO because managing a personal Linux server from a phone is still more awkward than+it should be. SSH is powerful, but on mobile I kept jumping between terminal tabs, file+transfer tools, metrics dashboards, docs and AI chat.-MSO is a visual shell for a server you already own. It is not a real operating-system, Linux distribution, desktop environment, or VPS provider. The "OS" name-is the desktop metaphor: one browser workspace for terminal, files, metrics,-media tools, and optional BYOK AI.+MSO is not a Linux distribution, desktop environment or VPS provider. "OS" is the interface+metaphor: a responsive workspace over a server you already own.-It is single-owner on purpose. An authenticated session can access files and run-commands as the Linux user that owns the process, so the recommended deployment-is behind Tailscale or another VPN. The public demo uses mock data only.+It is deliberately single-owner. An authenticated session can access files and run commands+as the Linux user that owns the process, so the recommended deployment is behind Tailscale+or another tightly controlled HTTPS path. The public demo uses mock data only.-This is Public Alpha / Developer Preview software and has not had a third-party-security audit. I am looking for feedback on the core workflow before widening-the scope.+The project is Public Alpha / Developer Preview and has not had a third-party security+audit. I am looking for feedback on the core workflow before widening scope.## Feedback questions-1. Which server task would you most want to perform from your phone?-2. Is the visual shell useful, or would you prefer a simpler dashboard?-3. Which security or deployment concern would stop you from trying it?+1. Which server task would you most want to do comfortably from your phone?+2. Is the OS-style workspace useful, or would you prefer a simpler admin dashboard?+3. Which security/deployment concern would stop you from trying it?4. Which Linux distributions should be tested next?-## Known limitations+## Known limitations to disclose-- Public alpha-- Single-owner+- Public Alpha / Developer Preview+- Single-owner, no multi-user RBAC- No third-party security audit-- No multi-user RBAC-- Recommended for private network access-- Some apps are optional or experimental+- Private-network/TLS deployment strongly recommended+- Some integrations (Camoufox, Hermes/OpenClaw, MCP, model providers) are optionaldiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 996292ba..20f251da 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,11 +2,51 @@Running log of what shipped each phase. Newest at top.-> **Architecture note:** Phases 0–14 below were built on **Convex self-hosted +-> a Control-Room host-agent bridge**. That stack was **removed** in Phase 15 —-> mso is now a self-contained Next.js app (`lib/host` + signed-cookie auth).-> Read those phases as history. **This file is the source of truth for what exists** —-> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.+> **How to read this log:** it is the source of truth for **why/when work shipped**, not+> today's API/runbook. Phases 0–14 were built on **Convex self-hosted + a Control-Room+> host-agent bridge**; that stack was removed in Phase 15 and later entries describe the+> self-contained Next.js/`lib/host` architecture. For the current implementation start at+> [`docs/README.md`](./README.md) and [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md); keep old+> entries intact as historical evidence even when their commands/counts have been superseded.++## 2026-08-24 — documentation authority + ChatGPT MCP guide (DONE)++The documentation set was audited against current source and the deployed/public MCP+contract instead of patching isolated stale paragraphs. `docs/README.md` now classifies the+repository into current reference, generated/current records, historical point-in-time+plans/audits, and marketing collateral; `docs/ARCHITECTURE.md` is current again, while the+June audit and old shell/BYOK plans keep their original evidence behind explicit historical+banners. The long-standing `PROGRESS.md` header that incorrectly said Architecture was no+longer maintained was corrected without rewriting old entries.++MCP/ChatGPT documentation is now split by responsibility. `docs/MCP.md` remains the deep+protocol/security/discovery/workflow reference, and new `docs/CHATGPT-PLUGIN.md` is the+operator-facing custom MCP app guide with architecture, OAuth sequence, scope/tool,+tool-snapshot refresh, workflow-id, ChatGPT-file-upload and credential-boundary Mermaid+diagrams. It pins the live MSO MCP contract at server `1.6.0`, toolset `2026.08.21.1`, 28+tools (15 read / 10 write / 3 exec), documents the authorization-code-only PKCE flow and+90-day bearer reauthorization boundary, and clearly separates MSO MCP OAuth from Alfa's+OpenAI Codex/ChatGPT-subscription OAuth. Current OpenAI Developer Mode availability and+frozen-action behaviour are labeled as an external dated dependency rather than an MSO+promise.++Managed-app, Hermes, OpenClaw, install, security, troubleshooting, FAQ, model-provider and+slice references were brought to current behaviour: no runtime `/features` scraping or+workspace modes, no supported same-origin vendor dashboard, restore/update/install jobs are+documented, Camoufox replaces the retired Playwright daemon, current persistent profile+paths are explicit, and deploy/recovery uses `bun run ship` / `mso update run --rebuild`+instead of stale manual production build instructions. Official operational skills were+updated where their managed-app/deploy capability maps had drifted.++A new committed `scripts/check-docs.mjs` now makes common drift a quality-gate failure. It+checks relative Markdown links and generated CLI freshness, requires every `docs/*.md` to+be classified, validates current MCP version/scope/tool **names** in the three contract+docs, and validates actual slice/AppShell feature names/counts. `package.json` and+`scripts/gates.sh` both run it. Verification: full `bun run verify` exit 0; 181 test files+passed (1 skipped), 1573 tests passed (1 expected fail, 4 skipped); 0 value cycles; docs+checker reports 38 Markdown files / 28 MCP tools / 21 slices / 10 AppShell feature dirs;+9 official skills valid; WCAG palette audit 0 AA failures; dependency audit clean at+high/critical. One pre-existing max-lines lint warning remains in `lib/mcp/dispatch.test.ts`.## 2026-08-21 — opt-in project MCP/function capabilities; stock MSO unchanged (DONE)diff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 00000000..d0c4ceab--- /dev/null+++ b/docs/README.md@@ -0,0 +1,68 @@+# MSO documentation map++This index separates **current reference** from **historical evidence** so a dated plan+cannot quietly become today's architecture documentation.++## Authority order++1. Current code and live descriptors (`/api/health`, `GET /mcp`).+2. Generated contracts (`CLI.md`, `CHANGELOG.md`).+3. Current reference docs below.+4. `PROGRESS.md` for why/when a change shipped.+5. Historical plans/audits for their dated context only.++Run `node scripts/check-docs.mjs` to validate relative links plus selected+machine-verifiable facts. The repository quality gate runs it automatically.++## Current reference++| Document | Contract |+|---|---|+| [`../README.md`](../README.md) | Product overview and quickstart |+| [`ARCHITECTURE.md`](./ARCHITECTURE.md) | Current runtime, shell, host, MCP and deployment architecture |+| [`INSTALL.md`](./INSTALL.md) | Owner installation, TLS, updates, backup and uninstall |+| [`DEVELOPMENT.md`](./DEVELOPMENT.md) | Development and release workflow |+| [`CLI.md`](./CLI.md) | Generated `mso` CLI contract |+| [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |+| [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup, diagrams, scopes and file bridge |+| [`CONNECTORS-GATEWAY-INTEGRATION.md`](./CONNECTORS-GATEWAY-INTEGRATION.md) | MSO ↔ connectors-gateway action-name contract |+| [`MANAGED-APPS.md`](./MANAGED-APPS.md) | Hermes/OpenClaw lifecycle, jobs, update, backup/restore, dashboard boundary |+| [`HERMES-INTEGRATION.md`](./HERMES-INTEGRATION.md) | Hermes-specific integration behaviour |+| [`OPENCLAW-INTEGRATION.md`](./OPENCLAW-INTEGRATION.md) | OpenClaw-specific integration behaviour |+| [`MODELS-INTEGRATION.md`](./MODELS-INTEGRATION.md) | Alfa BYOK/custom/Codex provider model |+| [`SLICE-CATALOG.md`](./SLICE-CATALOG.md) | Current slice/AppShell feature inventory |+| [`TROUBLESHOOTING.md`](./TROUBLESHOOTING.md) | Symptom → cause → supported recovery |+| [`FAQ.md`](./FAQ.md) | Product/security/operator boundaries |+| [`../SECURITY.md`](../SECURITY.md) | Security posture and vulnerability reporting |+| [`../CONTRIBUTING.md`](../CONTRIBUTING.md) | Contributor setup and gates |+| [`../CLAUDE.md`](../CLAUDE.md) | Repository/operator implementation rules |+| [`../skills/README.md`](../skills/README.md) | Skill catalog, trust and discovery semantics |++## Generated/current records++| Document | Source |+|---|---|+| [`CLI.md`](./CLI.md) | `node scripts/gen-cli-docs.mjs` / `bin/mso --help` |+| [`CHANGELOG.md`](./CHANGELOG.md) | Git subjects via `scripts/gen-changelog.mjs`; never hand-edit |+| [`PROGRESS.md`](./PROGRESS.md) | Hand-written shipping rationale; newest first; canonical historical WHY |++## Historical point-in-time documents++These are retained because they contain design reasoning or finding numbers referenced by+source comments. They are **not current implementation contracts**.++| Document | Status |+|---|---|+| [`AUDIT-2026-06-11.md`](./AUDIT-2026-06-11.md) | Archived audit at its named date; later fixes changed many findings |+| [`SHELL-FIDELITY-PLAN.md`](./SHELL-FIDELITY-PLAN.md) | Historical design backlog/baseline; current shell design lives in code + architecture |+| [`DRAWER-MENU-BYOK-PLAN.md`](./DRAWER-MENU-BYOK-PLAN.md) | Historical implementation plan; phases A–C and OpenAI Codex D1 shipped; remaining ideas are not promises |++## Marketing/demo collateral++These files are copy/script drafts, not technical authority:++- [`PRODUCT_HUNT.md`](./PRODUCT_HUNT.md)+- [`DEMO-SCRIPT.md`](./DEMO-SCRIPT.md)++When a current-reference doc and one of these drafts disagree, update the draft or follow+the current-reference doc.diff --git a/docs/SHELL-FIDELITY-PLAN.md b/docs/SHELL-FIDELITY-PLAN.mdindex 7792dc67..ba3212d2 100644--- a/docs/SHELL-FIDELITY-PLAN.md+++ b/docs/SHELL-FIDELITY-PLAN.md@@ -1,5 +1,12 @@# Shell Fidelity Plan — five lightweight, convincing OS clones+> **Historical design plan / backlog baseline.** The inventory below was written from the+> 2026-06-11 shell state and intentionally preserves its original gaps/budgets. Several+> phases subsequently shipped and the AppShell structure changed. Current shell contracts+> live in [`ARCHITECTURE.md`](./ARCHITECTURE.md), the per-shell design files under+> `frontend/slices/appshell/design/`, and current E2E tests. Treat unchecked items here as+> ideas to re-validate, not current bugs or promises.+> Goal: each shell (macOS · Windows 11 · iOS · Android · Dashboard) should feel> *native to its OS* — visually and behaviourally — while the whole thing stays> a lightweight web app. Builds on the multishell port (done; its plan doc wasdiff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.mdindex d63082f5..93859123 100644--- a/docs/SLICE-CATALOG.md+++ b/docs/SLICE-CATALOG.md@@ -1,59 +1,56 @@-# mso — Slice Catalog+# MSO slice catalog-> **Generated from `frontend/slices/` on 2026-07-28.** The previous version listed six-> slices that no longer existed (`browser` and five `shell-*` slices that converged into-> `appshell/features/*`) and omitted five that do. If this table and the directory ever-> disagree again, the directory is right.+> **Current reference.** Counts are checked against the directory tree by+> `scripts/check-docs.mjs`; the directory remains the final authority.-Every OS app is a vertical slice. Slices are authored lift-ready (props-driven, no-hardcoded consumer URLs/env/roles). Slices read the host through the `lib/os-api`-contract, served by `lib/host` (fs/exec/sys) or `MockAdapter`.+<!-- slice-catalog: slices=21 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)-| Slug | Kind | Category | Purpose |-|---|---|---|---|-| `app-store` | full | ui | App Store — discover & install apps |-| `appshell` | full | ui | AppShell — manifest-driven desktop + mobile shell |-| `assistant` | full | ai | Alfa — AI assistant chat |-| `auth` | full | auth | Auth — HMAC signed-cookie gate |-| `camoufox-browser` | full | ui | Browser — real Firefox over VNC |-| `code-editor` | full | ui | Code — overlay syntax editor |-| `create-app` | frontend | ui | Create App — author an os-rr app from a manifest |-| `docs` | frontend | ui | Docs — in-app documentation browser |-| `files-manager` | full | infra | Files — VPS file manager |-| `image-editor` | frontend | ui | Image Editor — layered raster editor |-| `image-picker` | ui | ui | Image Picker — one-button image/wallpaper chooser (gallery · upload · link · Unsplash · reposition) |-| `managed-apps` | — | — | Managed applications — Hermes + OpenClaw lifecycle, update centre, dashboard proxy. |-| `media-studio` | full | ui | Media Studio — photo / image editor |-| `media-viewer` | full | ui | Preview — media quick-look |-| `os-settings` | full | ui | Settings — appearance + VPS server |-| `os-shell` | full | ui | os-shell — Manef Shell OS consumer of the AppShell framework |-| `os-terminal` | full | infra | Terminal — xterm.js pty app |-| `quicklinks` | full | ui | Quicklinks — website shortcuts with favicons |-| `reel-editor` | frontend | ui | Reel — video timeline editor |-| `shell-settings` | full | ui | Shell feature — Settings (appearance panels) |-| `system-monitor` | full | infra | System Monitor — CPU / RAM / disk |--## Shell features (12) — `appshell/features/*`--Each mounts into a named `<Slot>` via `defineFeature`. `appshell/defaults.ts` bundles-them as `DEFAULT_FEATURES`. `desktop-icons` and `force-quit` live here but are imported-directly by `appshell/components/desktop.tsx` rather than being slot features.--| Feature |-|---|-| `clipboard` |-| `control-center` |-| `desktop-icons` |-| `force-quit` |-| `inspector` |-| `lock-screen` |-| `notifications` |-| `quick-look` |-| `search` |-| `share` |-| `shortcut-help` |-| `widgets` |--`shell-settings` is a flat UI-primitives slice, not a feature unit.+| Slug | Purpose |+|---|---|+| `app-store` | App Store / app discovery surface |+| `appshell` | Generic desktop/mobile shell framework |+| `assistant` | Alfa assistant, agents/playbooks and tool activity |+| `auth` | Authentication UI/helpers |+| `camoufox-browser` | Remote Camoufox/noVNC Browser app |+| `code-editor` | Code/text editor with integrated terminal |+| `create-app` | Create App manifest authoring surface |+| `docs` | In-app documentation browser |+| `files-manager` | VPS Files manager |+| `image-editor` | Layered raster image editor |+| `image-picker` | Reusable image/wallpaper picker |+| `managed-apps` | Hermes/OpenClaw install/lifecycle/update/backup/proxy |+| `media-studio` | Image/media studio surface |+| `media-viewer` | Preview/Quick Look-style media viewer |+| `os-settings` | MSO Settings |+| `os-shell` | MSO consumer manifest/capabilities for AppShell |+| `os-terminal` | Interactive PTY Terminal / Claude Code surface |+| `quicklinks` | Website shortcuts/favicons |+| `reel-editor` | Video/reel timeline editor |+| `shell-settings` | Shared shell settings UI primitives |+| `system-monitor` | CPU/memory/disk/process monitoring |++## AppShell feature directories (10)++`frontend/slices/appshell/features/` currently contains:++- `clipboard`+- `control-center`+- `desktop-icons`+- `force-quit`+- `inspector`+- `lock-screen`+- `notifications`+- `search`+- `shortcut-help`+- `widgets`++Not every directory is a user-visible slot contribution: `desktop-icons` and `force-quit`+are shell infrastructure used directly by the desktop runtime. `shell-settings` is a normal+top-level slice, not an AppShell feature directory.++See `docs/ARCHITECTURE.md` for the shell/manifest relationship.diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 5c9a3706..baa2b98c 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -1,171 +1,241 @@# Troubleshooting-Symptoms → causes → fixes. Errors are quoted as the UI/logs print them.+> **Current reference.** Symptoms → likely cause → supported recovery. Historical browser+> sidecar and manual deploy instructions are intentionally not used here.## Login & sessions### Login returns `not_configured` (HTTP 500)-`OS_SESSION_SECRET` is missing/shorter than 32 bytes, or `OS_LOGIN_PASSWORD`-is shorter than 6 chars. The app **fails closed** on weak config. Fix-`.env.local` (`openssl rand -hex 32` for the secret) and restart.+`OS_SESSION_SECRET` is missing/too short or `OS_LOGIN_PASSWORD` is invalid. MSO fails+closed. Fix `.env.local`, then restart through your normal service/update path.### "Too many attempts, try again later" (HTTP 429)-Per-IP login rate limit tripped. Wait for the window to pass (minutes, not-hours) and try again. Behind a reverse proxy, make sure it forwards-`X-Forwarded-For` — otherwise every user shares the proxy's IP and one-person's typos rate-limit everyone.+The per-IP login limiter tripped. Wait for the window to pass. Behind a reverse proxy,+forward the real client IP consistently so every user does not share the proxy address.-### Logged in but stuck "pending approval"+### Correct password but "pending approval"-Working as designed: a correct password only creates a *pending* device.-Approve it from an already-approved device (Settings → Devices) or from the-server: `node scripts/approve-device.js <deviceId> "label"` — the id is shown-on that browser's login screen.+Expected for a new browser. Approve the shown device id from an already-approved browser+(Settings → Devices) or from the server using the approval script.-### Login succeeds but I'm immediately logged out (no session)+### Login returns success but the browser is logged out immediately-The session cookie is `Secure` — over plain HTTP the browser **silently drops-it**. Serve the app over HTTPS (reverse proxy with TLS, or Tailscale HTTPS).-TLS is mandatory even inside a VPN.+The session cookie is `Secure`. Plain HTTP on a normal IP/hostname causes browsers to drop+it. Use HTTPS/Tailscale Serve or access through a localhost SSH tunnel.-### Session drops sooner than expected+### Existing sessions suddenly died-Default lifetime is 24h (`SESSION_EXPIRY_HOURS`). Changing-`OS_SESSION_SECRET` (or restarting with a different one) invalidates ALL-sessions immediately — check you're not regenerating it on every deploy.+A changed `OS_SESSION_SECRET` invalidates all signed sessions. Confirm deployment automation+is not regenerating it.## Deploy & build-### UI is unstyled/broken after a deploy+### UI is unstyled or JS/CSS chunks 404 after deploy-Chunk mismatch: `next start` loaded one build's manifest but `.next/static`-on disk is from another. Browser console shows CSS/JS 404s or a wrong-MIME-refusal (`X-Content-Type-Options: nosniff` makes that fatal on purpose).--**Rule: build, THEN restart — never restart then rebuild.** If already-mismatched:+The running `next start` process and on-disk `.next` tree do not match. Do **not** keep+mutating the live `.next` tree manually. After any active updater/finalizer has finished,+run the supported recovery rebuild:```bash-rm -rf .next && bun run build && sudo systemctl restart mso.service+mso update run --rebuild```-### Build runs out of memory ("Ineffective mark-compacts near heap limit")+Then verify `/api/health` and run the post-deploy smoke check. Developer changes should be+released with `bun run ship "<conventional commit>"`, which performs the verified+build/restart sequence.-The Next build wants ~2 GB+. Give Node more heap and/or add swap:+### Build runs out of memory-```bash-NODE_OPTIONS=--max-old-space-size=4096 bun run build-```+A Next production build can need multiple GiB. Add swap or raise the Node heap for the+build process, then run the supported build/release path again. Do not restart a healthy+old service after a failed build.### "Another next build process is already running"-Usually a stale lock from a killed build: `rm -f .next/lock` and rebuild.-First confirm nothing is actually building: `ps -eo pid,args | grep "[.]bin/next build"`.+First confirm a release/self-update is not actually active. Multiple simultaneous builds+against the production checkout are unsafe. If no process owns the build and only a stale+lock remains, remove the stale lock, then use the normal update/release command.++### A new route still 404s after deployment++Confirm Git `HEAD`, `origin/main`, `/api/health` build id and the deployment log all refer to+the expected release. If the deployment is correct but the build tree is inconsistent, use+`mso update run --rebuild` rather than hand-restarting around a partial build.++### Update button says a newer version exists forever++Check Settings → About and `~/.mso/self-update.log`. A successful self-update ends with+`UPDATE OK`. Also verify only one production process is serving the public origin. If the+browser cached an old service worker, unregister it once and hard reload after the server is+confirmed healthy.++## Files++### "Folder is outside the writable area"++The target is outside `OS_FS_WRITE_ROOTS`. Widen the write jail deliberately in+`.env.local` if needed; do not use the sensitive-path escape hatch as a convenience.++### Folder tree cannot see an expected path++Reads are bounded by `OS_FS_READ_ROOTS` plus the process user's Unix permissions. Credential+paths remain hidden even when they are physically beneath an allowed root.++### "Access to credential files is blocked"++Expected. MSO blocks its own private state, `.env*` and sensitive-home paths through the+normal file API. Edit such material through a trusted host-admin channel rather than+teaching the web file manager to read it.++## Terminal / Code integrated terminal++### Terminal says too many sessions++MSO caps concurrent live PTYs. Close unused tabs. Normal page/tab navigation sends a close,+and stale detached shells can be reclaimed after a grace period when capacity is exhausted;+attached active terminals are not reclaimed to make room.++### Terminal disappears after server restart++PTYs are processes, not persisted sessions. A server restart terminates them. The client+can open a fresh shell; command history/persistent work should live in the shell/tool itself+(e.g. files, tmux when intentionally used), not PTY memory.++### Code editor Terminal button works but starts in the wrong directory++Integrated Code Terminal uses the editor/project working directory passed as `cwd`. Confirm+the opened file/project path is inside an allowed writable root; otherwise host cwd+resolution falls back/refuses according to the host policy.++## Camoufox Browser++### Browser says Camoufox is not installed++The current Browser app uses the `camoufox-vnc.service` **user unit** plus+`scripts/camoufox-vnc-service`. The retired Playwright browser daemon and+`OS_BROWSER_URL`/`OS_BROWSER_SECRET` are not part of current MSO.++Check the prerequisites documented in `docs/INSTALL.md`: Camoufox, a headless X server,+x11vnc, noVNC/websockify, the VNC password file and the user systemd runtime/linger setup.++### Browser is installed but Off++That is the expected idle state. The user unit is intentionally not enabled at boot and has+a finite lease. Start it from Browser/Settings; stop it again when done.++### noVNC loads but the viewer reports missing metadata/assets++MSO's launcher builds a private runtime noVNC webroot that symlinks the distribution assets+and provides the package metadata Debian omits. Restart the Camoufox session so the runtime+webroot is rebuilt from the installed noVNC package.-### A brand-new route/page 404s after deploy+### Camoufox starts with no saved logins-Incremental builds occasionally miss a new `app/**/route.ts`/page folder.-Clean rebuild: `rm -rf .next && bun run build`, restart.+Verify `CAMOUFOX_PROFILE` points at the persistent profile under the user's local share tree,+not a cache directory. Stop the session before restoring the profile/session backup. Treat+the profile as account credentials: it can contain live cookies.-### "Versi baru" (new version) toast loops or update never arrives+### Browser is slow on mobile-The service worker bakes the BUILD_ID into its cache name; a loop means the-served build keeps flip-flopping (two processes serving different builds?).-One-off fix in the browser: DevTools → Application → Service Workers →-Unregister, then hard-reload.+The app is a real remote Firefox canvas, not a responsive website renderer. MSO's container+is responsive, but the remote browser itself still has a desktop viewport. Use landscape or+zoom/pan as appropriate; do not "fix" it by exposing VNC credentials to the client model.-## Files app+## Managed applications-### "Folder is outside the writable area (OS_FS_WRITE_ROOTS)"+### Hermes/OpenClaw is reported "not installed" but you know it exists-You tried to create/rename/delete outside the write jail. Widen it in-`.env.local` (`OS_FS_WRITE_ROOTS=~:~/projects:/srv/data`) and restart.-Top-level system dirs are refused even if listed — keep writes narrow.+Look for the diagnostic that says MSO cannot reach the owner systemd user bus. Detection+fails closed for install/restore because rerunning an installer or restoring over a live+unknown service is unsafe. Fix the user bus/linger/service environment first.-### Folder tree is empty / can't browse where I expect+### Installed app is stopped and shows no dashboard-Reads are bounded by `OS_FS_READ_ROOTS` (default home + `~/projects`). Set-`OS_FS_READ_ROOTS=/` for read-only browsing of the whole box. Also remember-the process user's own permissions still apply — mso can't read what-`youruser` can't.+Expected. MSO mounts the vendor dashboard only when there is a live upstream. Start the app;+management/log/update actions remain under Details.-### "Access to mso credential files is blocked"+### App is healthy but dashboard is not embedded-By design: the FS API refuses the app's own `.env*` files and everything-under `~/.mso/` (device allowlist, BYOK key, audit log, browser profile),-even inside a legal read/write root — otherwise one stolen session could read-`OS_SESSION_SECRET` and forge cookies forever. Edit those files over SSH.+Embedded dashboards are opt-in. Confirm both+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, DNS/TLS for the+explicit app hosts, and sign in again after changing the cookie domain. With both variables+unset, no vendor dashboard is served by design.-### Mutating API call returns `cross_origin_blocked` (HTTP 403)+### Update fails before invoking the upstream updater-`proxy.ts` rejects mutating `/api` requests whose `Sec-Fetch-Site`/`Origin`-isn't same-origin (CSRF depth-2). Hitting the API from another web page won't-work by design; scripts/curl without browser headers pass normally.+The mandatory MSO pre-update state snapshot failed. Fix that first; the update is designed+to abort before changing the app if it cannot create its recovery point.-### Upload fails on big files+### Restore is refused-Request body is capped at 500 MB. Move bigger files with `scp`/`rsync`.+The app must be stopped and MSO must be able to prove that. The backup manifest/source and+current state directory must match, and symlink collisions are rejected before writes.+Follow the specific refusal instead of bypassing the guard.-## Terminal / exec+## Alfa / model providers-### Command refused by the destructive-command guard+### Alfa says no API key/provider configured-`rm -rf /`, `mkfs`, `dd` to a block device, fork bombs, recursive-`chmod/chown` on `/` etc. are refused. Do real disk surgery over SSH, or (not-recommended) set `OS_EXEC_ALLOW_DESTRUCTIVE=1`.+Configure a BYOK provider in Settings → AI, set the corresponding server environment key,+or intentionally connect the optional `openai-codex` provider. These are model credentials,+not MCP credentials.-### Command output cut off / command killed after a while+### Custom provider URL is rejected-One-shot exec has a 30 s timeout and a 1 MiB output cap. Long jobs: run them-detached (`nohup … &`, `tmux`) and tail the log file instead.+MSO SSRF-checks custom base URLs and refuses private/link-local/unsafe destinations according+to its custom-provider policy. Use a legitimate endpoint reachable under that policy.-## Browser app+### OpenAI Codex sign-in and ChatGPT MCP are being confused-### Browser app shows as disabled / errors immediately+They are different flows. `openai-codex` under Settings → AI is an Alfa inference provider.+The ChatGPT custom MCP app authorizes ChatGPT to call MSO tools through MSO's `/oauth/*`.+See `docs/MODELS-INTEGRATION.md` and `docs/CHATGPT-PLUGIN.md`.-`OS_BROWSER_URL`/`OS_BROWSER_SECRET` unset in `.env.local`, or the-`os-browser` service isn't running. Check `journalctl -u os-browser -f`.+## MCP / ChatGPT custom app-### os-browser refuses to start: "OS_BROWSER_SECRET missing/short (>=16)"+### `/mcp` or OAuth discovery returns 404-Exactly that — give it a real secret (`openssl rand -hex 16`) and use the-same value in the main app's `.env.local`.+`OS_MCP_ENABLED=1` is not active in the running service (or demo mode forced MCP off).+After changing config, use the supported rebuild/update path and recheck `GET /mcp`.-### Chromium fails to launch on a fresh box+### ChatGPT says the MCP server does not support OAuth-Missing system deps: `npx playwright install chromium --with-deps` (needs-sudo once for the deps).+Check both well-known endpoints from the same public origin ChatGPT reaches. A 404 normally+means MCP is disabled in the running MSO process.-## Assistant (AI)+### OAuth opens but cannot complete-### Assistant returns 501+The consent page is a normal MSO browser page. Use an already-approved device and active+MSO session, review the requested `read/write/exec` tier, then Allow.-No API key. Set `ANTHROPIC_API_KEY` in `.env.local` or paste a key under-Settings → AI (stored in `~/.mso/config.json`). It's BYOK — without a key-the endpoint stays off and everything else works.+### ChatGPT still shows old tools after MSO changed-## Service & networking+Compare Settings → MCP toolset version/hash/count, refresh/recreate the ChatGPT custom MCP+app, and run Scan Tools. "Mark ChatGPT refreshed" in MSO is only an acknowledgement; it+does not refresh ChatGPT remotely.-### Port already in use+### Tool exists but returns scope denied-Another process owns :4005 (or :3000 locally). `ss -ltnp | grep 4005`, stop-the squatter or change `Environment=PORT=` in the unit.+The OAuth bearer was granted below that tool's tier. Reauthorize intentionally at the needed+scope rather than raising `OS_MCP_MAX_SCOPE` blindly.-### Works on the VPS, unreachable from outside+### `fs_upload_file` fails-By design you should firewall :4005/:4002 and reach it via Tailscale or the-reverse proxy. Check the proxy is pointing at `127.0.0.1:4005` and the-firewall allows the proxy, not the app port.+The bridge accepts a current ChatGPT-provided file reference, up to 20 MiB, and writes only+inside `OS_FS_WRITE_ROOTS`. Temporary OpenAI download URLs expire and are host/type/redirect+validated. Reattach/regenerate the file instead of supplying an arbitrary public URL.-### Service restarts in a loop+### Project/skill seems missing-`journalctl -u mso -n 50` — most common: missing `.env.local`-(`EnvironmentFile=` path wrong), Node not at `/usr/bin` (adjust `ExecStart`),-or the build is absent (`bun run build` never ran in that WorkingDirectory).+Check the scan report. Project and skill enumeration are bounded; if `truncated:true`,+continue with the returned cursor instead of concluding absence.-## Still stuck?+## Where to look next-Check the audit log (`~/.mso/audit.log`) for what the server actually did,-and `journalctl -u mso` for stack traces. Issues/PRs welcome.+- release/update: `docs/DEVELOPMENT.md`, `docs/INSTALL.md`+- ChatGPT connector: `docs/CHATGPT-PLUGIN.md`, `docs/MCP.md`+- managed apps: `docs/MANAGED-APPS.md`+- Camoufox: `claude-skills/mso-camoufox/SKILL.md`+- security: `SECURITY.md`diff --git a/lib/managed-apps/origin.ts b/lib/managed-apps/origin.tsindex 45f2dc6f..54f46aeb 100644--- a/lib/managed-apps/origin.ts+++ b/lib/managed-apps/origin.ts@@ -5,7 +5,7 @@// made them same-origin with the cockpit: upstream JS could reach `window.top` and// call /api/v1/exec with the user's session, and no CSP can stop it (CSP binds a// realm, not a reference across realms). So each app gets its OWN host, pointed at-// this same process: `hermes.mso.rahmanef.com`, `openclaw.mso.rahmanef.com`.+// this same process: `hermes.mso.example.com`, `openclaw.mso.example.com`.// `window.top` is then cross-origin and opaque.//// One host PER APP, not one shared host: a shared one would put Hermes and@@ -13,27 +13,27 @@//// Middleware (`proxy.ts`) enforces the other half: on an app host, every path is// rewritten into that app's proxy and everything else 404s, so /api/v1/exec does-// not exist on those origins at all. Unset template = single-origin mode (dev,-// demo, any deployment without the DNS records), where the path-scoped CSP in-// proxy-csp.ts is the only containment and the window.top reach stays open.+// not exist on those origins at all. An unset/invalid template disables vendor+// dashboard embedding entirely; MSO's own Details management surface remains usable.+// There is deliberately no same-origin iframe fallback.//// Edge-safe and client-safe: no node builtins, no catalog import (that one reads// node:os). NEXT_PUBLIC_ because the iframe `src` is built in the browser.import { MANAGED_APP_IDS, type ManagedAppId } from "./types";-/** e.g. `{id}.mso.rahmanef.com`. Empty/unset = single-origin mode. */+/** e.g. `{id}.mso.example.com`. Empty/unset = vendor dashboard embedding disabled. */const TEMPLATE = process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE?.trim() ?? "";const TOKEN = "{id}";export const splitOriginEnabled = (): boolean => TEMPLATE.includes(TOKEN);-/** The host this app's dashboard is served from, or null in single-origin mode. */+/** The host this app's dashboard is served from, or null when dashboard embedding is disabled. */export function managedAppHost(id: ManagedAppId): string | null {return splitOriginEnabled() ? TEMPLATE.replace(TOKEN, id).toLowerCase() : null;}-/** `https://<host>` — the iframe origin. null in single-origin mode. */+/** `https://<host>` — the iframe origin. null when dashboard embedding is disabled. */export function managedAppOrigin(id: ManagedAppId): string | null {const host = managedAppHost(id);return host ? `https://${host}` : null;@@ -47,8 +47,8 @@ export function managedAppIdForHost(host: string | null | undefined): ManagedAppreturn MANAGED_APP_IDS.find((id) => managedAppHost(id) === bare) ?? null;}-/** The name the app hosts live under (`{id}.mso.rahmanef.com` → `mso.rahmanef.com`).- * Deployment-owned; null in single-origin mode or when the leftover is a single+/** The name the app hosts live under (`{id}.mso.example.com` → `mso.example.com`).+ * Deployment-owned; null when embedding is disabled or when the leftover is a single* label ("com", ""), which is nobody's deployment. */function templateParent(): string | null {if (!splitOriginEnabled()) return null;@@ -59,10 +59,10 @@ function templateParent(): string | null {}/** A host INSIDE the app namespace that is not one of the apps — e.g. someone adds- * `staging.mso.rahmanef.com` pointing at this port, or a `*.os` wildcard appears.+ * `staging.mso.example.com` pointing at this port, or a wildcard appears.** Such a host must 404, not serve the cockpit: the session cookie is widened to- * `Domain=mso.rahmanef.com` so it is sent there, and a page on it would be+ * `Domain=mso.example.com` so it is sent there, and a page on it would be* same-origin with a full cockpit — the exact reach the split removes, handed back* by a DNS edit nobody connected to this file. Only the namespace is refused, never* the parent itself, so this cannot lock the operator out of the cockpit.@@ -93,8 +93,8 @@ export const MANAGED_APP_HOST_HEADER = "x-os-managed-app-host";* OS_PUBLIC_ORIGIN is not NEXT_PUBLIC — in the browser only the fallback* resolves, and every caller is server-side.*- * Fallback is the template's parent name (`{id}.mso.rahmanef.com` →- * `https://mso.rahmanef.com`), which is deployment-owned too. A wrong value fails+ * Fallback is the template's parent name (`{id}.mso.example.com` →+ * `https://mso.example.com`), which is deployment-owned too. A wrong value fails* CLOSED — naming the wrong origin means the frame is refused, which is visible.* null when nothing resolves, and the caller must then refuse framing outright* rather than guess. */diff --git a/package.json b/package.jsonindex 16fef173..39b9a635 100644--- a/package.json+++ b/package.json@@ -13,7 +13,7 @@"typecheck": "tsc --noEmit","test": "vitest run","coverage": "vitest run --coverage",- "check": "node scripts/check-cycles.mjs && node scripts/check-contrast.mjs && node scripts/check-skill-flows.mjs",+ "check": "node scripts/check-cycles.mjs && node scripts/check-docs.mjs && node scripts/check-contrast.mjs && node scripts/check-skill-flows.mjs","audit": "node scripts/audit.mjs","verify": "bun run typecheck && bun run lint && bun run coverage && bun run check && bun run audit","e2e": "node scripts/e2e/shell.mjs",diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjsnew file mode 100755index 00000000..144144d1--- /dev/null+++ b/scripts/check-docs.mjs@@ -0,0 +1,112 @@+#!/usr/bin/env node+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { spawnSync } from "node:child_process";++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const fail = [];+const read = (p) => readFileSync(join(ROOT, p), "utf8");++// --- MCP toolset: source is authoritative; docs carry a machine-readable marker.+const toolset = read("lib/mcp/toolset.ts");+const server = /MCP_SERVER_VERSION\s*=\s*"([^"]+)"/.exec(toolset)?.[1];+const version = /MCP_TOOLSET_VERSION\s*=\s*"([^"]+)"/.exec(toolset)?.[1];+if (!server || !version) fail.push("could not parse MCP version constants");++const toolFiles = [+ "lib/mcp/tools.ts",+ "lib/mcp/tools-read.ts",+ "lib/mcp/tools-discovery.ts",+ "lib/mcp/tools-learning.ts",+ "lib/mcp/tools-power.ts",+];+const tools = new Map();+for (const file of toolFiles) {+ const text = read(file);+ const matches = text.matchAll(/name:\s*"([^"]+)"[\s\S]*?scope:\s*"(read|write|exec)"/g);+ for (const [, name, scope] of matches) tools.set(name, scope);+}+const counts = { read: 0, write: 0, exec: 0 };+for (const scope of tools.values()) counts[scope] += 1;+const marker = `server=${server} version=${version} tools=${tools.size} read=${counts.read} write=${counts.write} exec=${counts.exec}`;+for (const file of ["docs/MCP.md", "docs/CHATGPT-PLUGIN.md", "docs/CONNECTORS-GATEWAY-INTEGRATION.md"]) {+ const text = read(file);+ if (!text.includes(`<!-- mcp-toolset: ${marker} -->`)) {+ fail.push(`${file}: MCP marker stale; expected ${marker}`);+ }+ for (const name of tools.keys()) {+ if (!text.includes(`\`${name}\``)) fail.push(`${file}: MCP tool ${name} is not documented`);+ }+}++// --- Slice catalog counts.+const dirs = (p) => readdirSync(join(ROOT, p), { withFileTypes: true }).filter((x) => x.isDirectory()).map((x) => x.name);+const sliceCount = dirs("frontend/slices").length;+const featureCount = dirs("frontend/slices/appshell/features").length;+const sliceMarker = `<!-- slice-catalog: slices=${sliceCount} appshell-features=${featureCount} -->`;+const sliceDoc = read("docs/SLICE-CATALOG.md");+if (!sliceDoc.includes(sliceMarker)) {+ fail.push(`docs/SLICE-CATALOG.md: count marker stale; expected ${sliceMarker}`);+}+for (const name of dirs("frontend/slices")) {+ if (!sliceDoc.includes(`\`${name}\``)) fail.push(`docs/SLICE-CATALOG.md: slice ${name} is not documented`);+}+for (const name of dirs("frontend/slices/appshell/features")) {+ if (!sliceDoc.includes(`\`${name}\``)) fail.push(`docs/SLICE-CATALOG.md: AppShell feature ${name} is not documented`);+}++// --- Every top-level docs/*.md must be classified in docs/README.md.+const map = read("docs/README.md");+for (const name of readdirSync(join(ROOT, "docs")).filter((x) => x.endsWith(".md"))) {+ if (name === "README.md") continue;+ if (!map.includes(`(${name.startsWith(".") ? name : `./${name}`})`)) {+ fail.push(`docs/README.md: ${name} is not classified`);+ }+}++// --- Relative Markdown links across project-authored docs/skills must resolve.+const markdownRoots = ["README.md", "SECURITY.md", "CONTRIBUTING.md", "CLAUDE.md", "docs", "skills", "claude-skills"];+const markdown = [];+function walk(path) {+ const full = join(ROOT, path);+ if (!existsSync(full)) return;+ const stat = readdirSafe(full);+ if (stat === null) { if (path.endsWith(".md")) markdown.push(path); return; }+ for (const entry of stat) {+ if (["node_modules", ".git", ".next", "coverage"].includes(entry.name)) continue;+ const child = join(path, entry.name);+ if (entry.isDirectory()) walk(child);+ else if (entry.isFile() && entry.name.endsWith(".md")) markdown.push(child);+ }+}+function readdirSafe(path) {+ try { return readdirSync(path, { withFileTypes: true }); } catch { return null; }+}+for (const root of markdownRoots) {+ const full = join(ROOT, root);+ if (existsSync(full) && !readdirSafe(full) && root.endsWith(".md")) markdown.push(root);+ else walk(root);+}+const linkRe = /\[[^\]]+\]\(([^)]+)\)/g;+for (const file of [...new Set(markdown)]) {+ const text = read(file);+ for (const m of text.matchAll(linkRe)) {+ const raw = m[1].trim();+ if (!raw || raw.startsWith("#") || /^[a-z][a-z0-9+.-]*:/i.test(raw)) continue;+ const target = raw.split("#", 1)[0].split("?", 1)[0];+ if (!target) continue;+ if (!existsSync(resolve(ROOT, dirname(file), target))) fail.push(`${file}: broken link ${raw}`);+ }+}++// --- Generated CLI docs must track bin/mso --help.+const cli = spawnSync(process.execPath, [join(ROOT, "scripts/gen-cli-docs.mjs"), "--check"], { cwd: ROOT, encoding: "utf8" });+if (cli.status !== 0) fail.push((cli.stderr || cli.stdout || "docs/CLI.md is stale").trim());++if (fail.length) {+ console.error("documentation check failed:");+ for (const item of fail) console.error(`- ${item}`);+ process.exit(1);+}+console.log(`docs: current — ${markdown.length} markdown files, ${tools.size} MCP tools, ${sliceCount} slices, ${featureCount} AppShell feature dirs`);diff --git a/scripts/gates.sh b/scripts/gates.shindex 3f1e9727..b741577f 100755--- a/scripts/gates.sh+++ b/scripts/gates.sh@@ -59,6 +59,7 @@ fi# NOTE: check-slices.mjs used to run here. It and all 20 slice.json were deleted on# 2026-08-03 (commit 844eef3) — do NOT let a hook reinstall re-add that line.node scripts/check-cycles.mjs || fail "check-cycles: new import cycle introduced."+node scripts/check-docs.mjs || fail "documentation drift detected." "fix current docs or their machine-readable markers before pushing."# docs/CHANGELOG.md is derived from git, so it can only be stale, never wrong —# and a stale one is what Settings → About would show. `bun run ship` regenerates# it before committing; this catches a plain `git push`.