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
feat(host): begin native platform runtime adapters
Rahman83d9aeec736f
diff --git a/docs/NATIVE-HOST-RELAY.md b/docs/NATIVE-HOST-RELAY.mdnew file mode 100644index 00000000..5f8022fd--- /dev/null+++ b/docs/NATIVE-HOST-RELAY.md@@ -0,0 +1,65 @@+# Native MSO hosts and shared remote MCP++> Implementation contract. This describes the requested target, not a shipped capability. Current release uses native Linux, Lima on macOS, WSL2 on Windows, and per-installation HTTPS for remote MCP.++## Product target++MSO installs and hosts directly under the user's ordinary account in macOS Terminal, a Linux shell, or Windows PowerShell. No Lima, WSL, Docker, VM, mandatory VPS, personal domain, or public inbound port. The same bounded host capability kernel serves local UI, CLI, and MCP. OS-specific operations expose honest availability instead of pretending that systemd or Linux /proc exists.++The public, shared control plane uses **mso.manef.dev**: `/dashboard` is the user and device console, `/mcp` is one HTTPS Streamable HTTP endpoint with OAuth. The local MSO agent makes an outbound TLS connection to that relay. Each user signs into the shared service and pairs only their own devices. MSO installations stay loopback-bound; the relay cannot read a local file or issue a host command by itself.++The current personal MSO installation at mso.rahmanef.com must remain independent. Do not redirect mso.manef.dev or expose `/mcp` as a relay until the shared service is deployed and ownership isolation is verified. A missing DNS record is not a functioning gateway.++## Native host boundaries++| Platform | Direct install | Terminal | Service | Host differences |+|---|---|---|---|---|+| Linux | Verified POSIX installer | Bash / installed shell | systemd if available, foreground otherwise | Existing Linux capability set |+| macOS | Native Node/Bun/Git and native build dependencies | zsh / Bash / selected shell | launchd or foreground | macOS metrics, process inventory, filesystem and service adapters |+| Windows | Native Node/Bun/Git and node-pty Windows binding | PowerShell | Windows Service or foreground | Win32 paths, process inventory, shell, permissions and service adapters |++Installer acceptance: fresh install and in-place update without a guest; no hidden second checkout; preserve authentication, config and local state; build and start on each architecture; `mso doctor`, PTY, file allowlist, execution, login, MCP, shutdown and restart succeed. Native macOS/Windows remain unverified until real-machine smoke runs pass.++## Shared relay++```mermaid+flowchart LR+ C["ChatGPT / MCP client"] -->|OAuth| R["mso.manef.dev/mcp"]+ U["User browser"] -->|sign in, pair, revoke| D["mso.manef.dev/dashboard"]+ D --> R+ R -->|matched call, bounded lifetime| A["Outbound device connection"]+ A --> K["Local MSO capability kernel"]+```++- The shared service is a separate trust domain from the user's host. Accounts, clients, grants and devices are keyed by the authenticated account, and every lookup repeats that check.+- Pair with a short-lived one-time code confirmed in the browser and on the device. Store only token hashes; rotate device credentials and support immediate device/client revocation.+- Remote MCP uses existing `read < write < exec` semantics. Start at read. A user's explicit grant and the device's local ceiling must both allow a call; tool discovery and dispatch enforce the same effective scope.+- Calls and results are transient, bounded in bytes and time, correlated by an unguessable request ID, and dropped when the device disconnects. Never log payloads, shell input, file bodies, OAuth codes or raw tokens.+- Device selection is explicit with stable user-visible names; multiple devices cannot silently substitute for one another. Offline devices fail clearly, and no relay job silently wakes a host.+- Bind OAuth grants to the shared MCP resource and the authenticated account. Separate relay OAuth identities from each machine's owner login and preserve per-device local authorization.+- HTTPS, rate limits, origin checks, CSRF protection on the dashboard, secure cookies, audit metadata, and cross-account denial are release gates. Transport security alone is not an authorization boundary.+- Keep an optional private direct-host MCP route for an owner who already has a domain. The shared route is the no-domain default.++## Action mapping from the supplied Remote Desktop Commander list++Reuse existing MSO tools and contracts; do not copy that product's instruction text or invent overlapping globals.++| Supplied actions | MSO route / work |+|---|---|+| create_directory, move_file, read_file, read_multiple_files, write_file, get_file_info, list_directory | `fs_mkdir`, `fs_move`, `fs_read`, `read_pipeline`, `fs_write`, `fs_list`; preserve root/credential guards |+| edit_block | Add a revision-checked text patch to the guarded file layer; document formats need reviewed format-specific adapters |+| start_process, interact_with_process, read_process_output, list_processes, list_sessions, kill_process, force_terminate | Existing `exec_run`, `exec_job_start/status/cancel`, `sys_processes`, terminal sessions; add explicit session ownership, input and graceful/force semantics only where missing |+| start_search, get_more_search_results, list_searches, stop_search | Existing `fs_search` and `project_candidate_search`; add paginated content-search jobs with cancellation rather than unbounded grep |+| list_devices, ping, shutdown, who_am_i | Shared paired-device inventory/health/revocation and local agent lifecycle; distinguish shared account identity from MSO host identity |+| get_config, set_config_value | Owner-only reviewed configuration with revision and least privilege; never accept empty allowed-roots as an implicit unrestricted host |+| get_prompts, get_recent_tool_calls, get_usage_stats | Trusted skills/flow catalog, existing scoped activity, and private relay usage counters; no content logging |+| write_pdf | Reviewed document adapter only; existing file write must not treat binary/PDF as text |+| give_feedback_to_desktop_commander | No equivalent; vendor feedback action is irrelevant to MSO |++## Release gates++1. Real Mac and Windows installations on clean devices, both architecture families where supported; an automated Linux VM cannot substitute for these proofs.+2. Runtime parity tests for path containment, credential denylist, shell/PTY, metrics, filesystem, session restart, updater and service fallback.+3. Two-account, two-device relay tests: pairing code reuse, stolen credential, crossed device IDs, crossed OAuth resources, wrong scope, offline timeout, replay, revoke during a call and payload/response size limits.+4. Browser login and dashboard pairing/revocation plus ChatGPT connector OAuth and actual read/write/exec flows after explicit grants.+5. Deploy the shared service, verify mso.manef.dev DNS/TLS/`/dashboard`/`/mcp` and public OAuth discovery, then release the native installers. Record exact commits/build IDs; keep the existing personal host reachable throughout.diff --git a/docs/README.md b/docs/README.mdindex 91f2a273..f841c925 100644--- a/docs/README.md+++ b/docs/README.md@@ -81,6 +81,7 @@ evidence and review freshness. The repository quality gate runs both automatical| Document | Status ||---|---|| [`EXTERNAL-FEATURE-CONTRACT.md`](./EXTERNAL-FEATURE-CONTRACT.md) | v1 target contract for modular shell/external features; implementation status is explicit |+| [`NATIVE-HOST-RELAY.md`](./NATIVE-HOST-RELAY.md) | Requested native macOS/Windows hosts and shared no-domain MCP relay; implementation and verification gates remain explicit |## Generated/current recordsdiff --git a/lib/host/path-roots.test.ts b/lib/host/path-roots.test.tsnew file mode 100644index 00000000..46a8d617--- /dev/null+++ b/lib/host/path-roots.test.ts@@ -0,0 +1,15 @@+import path from "node:path";+import { describe, expect, it } from "vitest";+import { parseRootEnv } from "./path-roots";++describe("native filesystem root configuration", () => {+ it("does not split Windows drive letters when parsing semicolon-separated roots", () => {+ expect(parseRootEnv(String.raw`C:\Users\Alice;D:\Work`, path.win32.delimiter)).toEqual([+ String.raw`C:\Users\Alice`, String.raw`D:\Work`,+ ]);+ });++ it("keeps the Linux/macOS colon-separated contract", () => {+ expect(parseRootEnv("/home/a:/srv/project", path.posix.delimiter)).toEqual(["/home/a", "/srv/project"]);+ });+});diff --git a/lib/host/path-roots.ts b/lib/host/path-roots.tsindex d8a064d6..468f66b1 100644--- a/lib/host/path-roots.ts+++ b/lib/host/path-roots.ts@@ -7,15 +7,17 @@ export function homeDir(): string {function expandHome(p: string): string {if (p === "~") return homeDir();- if (p.startsWith("~/")) return path.join(homeDir(), p.slice(2));+ if (p.startsWith("~/") || p.startsWith("~\\")) return path.join(homeDir(), p.slice(2));return p;}+export function parseRootEnv(raw: string, delimiter = path.delimiter): string[] {+ return raw.split(delimiter).map((entry) => entry.trim()).filter(Boolean).map(expandHome);+}+function rootsFromEnv(name: string, fallback: string[]): string[] {const env = process.env[name];- if (env && env.trim())- return env.split(":").map((s) => s.trim()).filter(Boolean).map(expandHome);- return fallback;+ return env && env.trim() ? parseRootEnv(env) : fallback;}export function readRootList(): string[] {diff --git a/lib/host/pty.ts b/lib/host/pty.tsindex d5b0c6e5..c1154ab6 100644--- a/lib/host/pty.ts+++ b/lib/host/pty.ts@@ -116,12 +116,15 @@ export async function openPty(opts: {throw new HostError(`Too many terminal sessions (max ${MAX_SESSIONS}) — close one first`);const cwd = await resolveCwd(opts.cwd); // write-root bounded; explicit invalid paths fail- const shell = process.env.SHELL || "/bin/bash";+ const isWindows = process.platform === "win32";+ const shell = isWindows+ ? process.env.POWERSHELL_EXE || "powershell.exe"+ : process.env.SHELL || "/bin/bash";const env = childEnv(); // process.env minus the app's own secretsenv.TERM = "xterm-256color";env.COLORTERM = "truecolor";- const pty = spawn(shell, ["-l"], {+ const pty = spawn(shell, isWindows ? ["-NoLogo"] : ["-l"], {name: "xterm-256color",cols: clampDim(opts.cols),rows: clampDim(opts.rows),diff --git a/lib/host/sys.test.ts b/lib/host/sys.test.tsindex ea901865..f4e665d0 100644--- a/lib/host/sys.test.ts+++ b/lib/host/sys.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { stats } from "./sys";+import { parsePosixProcesses, parseWindowsProcesses, stats } from "./sys";// The System Monitor polls /api/v1/sys/stats every 1500ms. Taking both /proc/stat// samples inside one call made every one of those requests sleep 120ms; reusing@@ -33,3 +33,24 @@ async function timed() {const value = await stats();return { ms: Date.now() - t0, value };}+++describe("native process inventory", () => {+ it("parses macOS ps columns and ranks recent CPU", () => {+ const rows = parsePosixProcesses(" 42 /usr/bin/zsh 12.5 2048 S\n 7 WindowServer 45.1 102400 R\n");+ expect(rows).toEqual([+ { pid: 7, name: "WindowServer", cpu: 45.1, mem: 100, status: "R" },+ { pid: 42, name: "/usr/bin/zsh", cpu: 12.5, mem: 2, status: "S" },+ ]);+ });++ it("parses Windows CIM sample, excludes idle, and normalizes cores", () => {+ const output = JSON.stringify([+ { IDProcess: 0, Name: "Idle", PercentProcessorTime: 400, WorkingSet: 0 },+ { IDProcess: 12, Name: "powershell", PercentProcessorTime: 200, WorkingSet: 104857600 },+ ]);+ expect(parseWindowsProcesses(output, 8)).toEqual([+ { pid: 12, name: "powershell", cpu: 25, mem: 100, status: "running" },+ ]);+ });+});diff --git a/lib/host/sys.ts b/lib/host/sys.tsindex 88801571..7634d746 100644--- a/lib/host/sys.ts+++ b/lib/host/sys.ts@@ -1,16 +1,26 @@// SERVER-ONLY. Host telemetry behind /api/v1/sys/*. CPU% is a short two-sample-// delta of /proc/stat; mem/disk/uptime from os + statfs; processes parsed from-// `ps`. Linux-oriented (the deploy target); degrades to zeros if /proc absent.+// delta of /proc/stat on Linux or os.cpus() elsewhere. Memory/disk/uptime come+// from Node; process inventory uses fixed platform commands without shell input.import os from "os";import { promises as fs } from "fs";import type { Process, SysStats } from "@/lib/os-api/types";-import { runCommand } from "./exec";+import { execFile } from "node:child_process";+import { promisify } from "node:util";++const execFileAsync = promisify(execFile);async function cpuSample(): Promise<{ idle: number; total: number }> {+ if (process.platform !== "linux") {+ const times = os.cpus().map((core) => core.times);+ return {+ idle: times.reduce((sum, core) => sum + core.idle, 0),+ total: times.reduce((sum, core) => sum + Object.values(core).reduce((a, b) => a + b, 0), 0),+ };+ }try {const line = (await fs.readFile("/proc/stat", "utf8")).split("\n")[0];const n = line.trim().split(/\s+/).slice(1).map(Number);- const idle = (n[3] || 0) + (n[4] || 0); // idle + iowait+ const idle = (n[3] || 0) + (n[4] || 0);const total = n.reduce((a, b) => a + (b || 0), 0);return { idle, total };} catch {@@ -54,7 +64,7 @@ export async function stats(): Promise<SysStats> {let disk = { used: 0, total: 0 };try {- const s = await fs.statfs("/");+ const s = await fs.statfs(process.platform === "win32" ? os.homedir() : "/");const total = s.blocks * s.bsize;disk = { used: total - s.bfree * s.bsize, total };} catch {@@ -70,26 +80,45 @@ export async function stats(): Promise<SysStats> {};}+export function parsePosixProcesses(output: string): Process[] {+ return output.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {+ const fields = line.split(/\s+/);+ if (fields.length < 5) return null;+ const pid = Number(fields[0]);+ const cpu = Number(fields[fields.length - 3]);+ const rss = Number(fields[fields.length - 2]);+ if (!Number.isInteger(pid) || pid <= 0) return null;+ return {+ pid,+ name: fields.slice(1, -3).join(" "),+ cpu: Number.isFinite(cpu) ? cpu : 0,+ mem: Math.round((Number.isFinite(rss) ? rss : 0) / 1024),+ status: fields[fields.length - 1] || "",+ };+ }).filter((p): p is Process => p !== null).sort((a, b) => b.cpu - a.cpu).slice(0, 40);+}++export function parseWindowsProcesses(output: string, cores: number): Process[] {+ const parsed: unknown = JSON.parse(output);+ const rows = Array.isArray(parsed) ? parsed : [parsed];+ return rows.filter((row): row is Record<string, unknown> => !!row && typeof row === "object").map((row) => ({+ pid: Number(row.IDProcess) || 0,+ name: String(row.Name || "?"),+ cpu: Math.min(100, (Number(row.PercentProcessorTime) || 0) / Math.max(1, cores)),+ mem: Math.round((Number(row.WorkingSet) || 0) / (1024 * 1024)),+ status: "running",+ })).filter((row) => row.pid > 0).sort((a, b) => b.cpu - a.cpu).slice(0, 40);+}+export async function processes(): Promise<Process[]> {- const r = await runCommand(- "ps -eo pid,comm,pcpu,rss,stat --sort=-pcpu --no-headers | head -40",- );- return r.stdout- .split("\n")- .map((l) => l.trim())- .filter(Boolean)- .map((l) => {- // comm may contain spaces ("npm exec eslint"): pid is the first token,- // pcpu/rss/stat are the space-free last three — name is what's between.- const m = l.split(/\s+/);- if (m.length < 5) return { pid: 0, name: "?", status: "", cpu: 0, mem: 0 };- return {- pid: Number(m[0]) || 0,- name: m.slice(1, -3).join(" "),- status: m[m.length - 1] ?? "",- cpu: Number(m[m.length - 3]) || 0,- mem: Math.round((Number(m[m.length - 2]) || 0) / 1024), // RSS KB → MB- };- })- .filter((p) => p.pid > 0);+ if (process.platform === "win32") {+ const command = "Get-CimInstance Win32_PerfFormattedData_PerfProc_Process | Select-Object IDProcess,Name,PercentProcessorTime,WorkingSet | ConvertTo-Json -Compress";+ const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { timeout: 15_000, maxBuffer: 1_000_000 });+ return parseWindowsProcesses(stdout, os.cpus().length);+ }+ const args = process.platform === "darwin"+ ? ["-axo", "pid=,comm=,%cpu=,rss=,stat="]+ : ["-eo", "pid,comm,pcpu,rss,stat", "--sort=-pcpu", "--no-headers"];+ const { stdout } = await execFileAsync("ps", args, { timeout: 15_000, maxBuffer: 1_000_000 });+ return parsePosixProcesses(stdout);}