Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(cli): close the opencode parity gap on run/session/stats/pair/doctor --json/completion (#165)

Abdurrahman Fakhrul526f0ad5a8c6
diff --git a/bin/mso b/bin/mso
index 4c8e1774..7311fd53 100755
--- a/bin/mso
+++ b/bin/mso
@@ -43,7 +43,7 @@
# memory-backup * Local memory snapshot: preview | history | create | verify (memory-backup --help)
# status Public service status (no session needed)
# health Is this CLI's session valid?
-# doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
+# doctor [--fix|--json] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues, --json is read-only
# agent [--continue|--resume <query>|--yolo|-yolo] Interactive MSO Agent; --oneshot <prompt> for autonomous non-TTY runs
# chat Alias for agent
# model [ref] Select active model from a connected provider
@@ -103,6 +103,11 @@
# login Force a fresh login
# logout Drop the session (server-side + local jar)
#
+# Agent run (scriptable, non-interactive)
+# run <prompt…> One autonomous turn, same loop as `agent`; --json, --file, --thinking
+# session * list | show | export | import session records without a TUI
+# stats --usage Token + compaction ledger for agent sessions (no cost: not recorded)
+#
# Service (local systemd)
# service * status | start | stop | restart | logs
# build Compile HEAD out-of-tree (safe against the live checkout)
@@ -120,7 +125,8 @@
# Escape hatches
# crud * Generic resource CRUD, incl. editor documents
# api * Call ANY endpoint directly
-# completion [shell] Print a shell completion script (bash|zsh)
+# completion [shell] Completion script for bash/zsh/fish (verbs + subcommands); sh gets the bare verb list
+# pair [--json] Loopback/public origin, this CLI's device, pending approvals, next command
# version Show version
#
# Examples:
diff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.ts
index f4ea3426..9f0c0b61 100644
--- a/bin/mso-update-offline.test.ts
+++ b/bin/mso-update-offline.test.ts
@@ -39,6 +39,10 @@ function fixture() {
"scripts/cli/onboarding.sh", "scripts/cli/onboarding-ai.sh",
"scripts/cli/local-maintenance.sh",
"scripts/cli/commands.sh",
+ "scripts/cli/agent-run.sh",
+ "scripts/cli/completion.sh",
+ "scripts/cli/pair.sh",
+ "scripts/cli/doctor-json.sh",
"scripts/cli/help.sh",
"scripts/cli/commands-host.sh",
"scripts/cli/commands-runtime.sh",
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index df0d264a..11b8e184 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,12 +6,27 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
## 2026-10-28
+**Added**
+
+- `cli` close the opencode parity gap on run/session/stats/pair/doctor --json/completion
+
+**Changed**
+
+- `agent` drop the inert thinking option from the one-shot turn
+
+**Tests**
+
+- `cli` keep offline-update and private-state fixtures in sync with the new CLI slices
+
**Docs**
-- `agents` use a placeholder host in the knowledge refresh
-- `agents` refresh AGENTS.md and add .mso/KNOWLEDGE.md for #154-#162
+- `agents` refresh AGENTS.md and add .mso/KNOWLEDGE.md for #154-#162 (#164)
- `antislop` design direction, agent pointer, and the R-10 glass audit (#163)
+**Other**
+
+- `cli` drop em dashes from the new copy (antislop R-02)
+
## 2026-10-27
**Added**
diff --git a/docs/CLI.md b/docs/CLI.md
index 29953890..afe2f06c 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -83,7 +83,7 @@ Commands:
memory-backup * Local memory snapshot: preview | history | create | verify (memory-backup --help)
status Public service status (no session needed)
health Is this CLI's session valid?
- doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues
+ doctor [--fix|--json] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issues, --json is read-only
agent [--continue|--resume <query>|--yolo|-yolo] Interactive MSO Agent; --oneshot <prompt> for autonomous non-TTY runs
chat Alias for agent
model [ref] Select active model from a connected provider
@@ -143,6 +143,11 @@ Commands:
login Force a fresh login
logout Drop the session (server-side + local jar)
+ Agent run (scriptable, non-interactive)
+ run <prompt…> One autonomous turn, same loop as `agent`; --json, --file, --thinking
+ session * list | show | export | import session records without a TUI
+ stats --usage Token + compaction ledger for agent sessions (no cost: not recorded)
+
Service (local systemd)
service * status | start | stop | restart | logs
build Compile HEAD out-of-tree (safe against the live checkout)
@@ -160,7 +165,8 @@ Commands:
Escape hatches
crud * Generic resource CRUD, incl. editor documents
api * Call ANY endpoint directly
- completion [shell] Print a shell completion script (bash|zsh)
+ completion [shell] Completion script for bash/zsh/fish (verbs + subcommands); sh gets the bare verb list
+ pair [--json] Loopback/public origin, this CLI's device, pending approvals, next command
version Show version
Examples:
diff --git a/lib/security/private-shell-state.test.ts b/lib/security/private-shell-state.test.ts
index 6794e332..122b26e1 100644
--- a/lib/security/private-shell-state.test.ts
+++ b/lib/security/private-shell-state.test.ts
@@ -11,6 +11,7 @@ const CLI_MODULES = [
"scripts/cli/runtime.sh", "scripts/cli/service.sh", "scripts/cli/transport.sh", "scripts/cli/onboarding.sh", "scripts/cli/onboarding-ai.sh",
"scripts/cli/commands.sh", "scripts/cli/commands-host.sh", "scripts/cli/commands-runtime.sh",
"scripts/cli/commands-state.sh", "scripts/cli/config-command.sh", "scripts/cli/commands-admin.sh",
+ "scripts/cli/agent-run.sh", "scripts/cli/completion.sh", "scripts/cli/pair.sh", "scripts/cli/doctor-json.sh",
].map((rel) => path.join(ROOT, rel));
const EDITOR = path.join(ROOT, "claude-skills/mso-image-editor/image-editor.sh");
const ULTIMATE = path.join(ROOT, "scripts/security-ultimate.sh");
diff --git a/scripts/cli/agent-run-session.test.ts b/scripts/cli/agent-run-session.test.ts
new file mode 100644
index 00000000..f2655272
--- /dev/null
+++ b/scripts/cli/agent-run-session.test.ts
@@ -0,0 +1,166 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { describe, expect, it } from "vitest";
+
+const fixture = `
+set -euo pipefail
+die(){ echo "$*" >&2; exit 1; }
+enc(){ printf '%s' "$1"; }
+U_run="run <prompt>"
+U_session="session"
+U_stats="stats"
+source scripts/cli/agent-run.sh
+`;
+
+describe("scripts/cli/agent-run.sh", () => {
+ it("run_agent_session list renders one TAB-separated row per session from a stubbed jget payload", () => {
+ const script = `
+${fixture}
+jget(){
+ printf '%s' '{"sessions":[{"id":"ses-1","source":"cli","updatedAt":"2026-10-28T12:00:00Z","historyTurns":3,"estimatedTokens":450,"title":"Test Session"}]}'
+}
+run_agent_session list
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(out.trim()).toBe(
+ "ses-1\tcli\t2026-10-28T12:00:00Z\t3t\t450tk\tTest Session",
+ );
+ });
+
+ it("run_agent_session show latest resolves the newest session id first and returns the record", () => {
+ const script = `
+${fixture}
+jget(){
+ echo "call:$1" >&2
+ if [ "$1" = "/api/v1/agent-sessions?limit=1" ]; then
+ printf '%s' '{"sessions":[{"id":"ses-newest-99"}]}'
+ elif [ "$1" = "/api/v1/agent-sessions?ref=ses-newest-99" ]; then
+ printf '%s' '{"session":{"id":"ses-newest-99","title":"Latest Work"}}'
+ else
+ die "unexpected endpoint: $1"
+ fi
+}
+run_agent_session show latest
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).toBe(0);
+ expect(res.stderr).toContain("call:/api/v1/agent-sessions?limit=1");
+ expect(res.stderr).toContain("call:/api/v1/agent-sessions?ref=ses-newest-99");
+ expect(JSON.parse(res.stdout)).toEqual({
+ session: { id: "ses-newest-99", title: "Latest Work" },
+ });
+ });
+
+ it("run_agent_session import creates a NEW session then POSTs history to that new id", () => {
+ const script = `
+${fixture}
+jpost(){
+ action=$(jq -r .action <<<"$2")
+ echo "jpost action=$action body=$2" >&2
+ if [ "$action" = "create" ]; then
+ printf '%s' '{"session":{"id":"new-id-999"}}'
+ elif [ "$action" = "update" ]; then
+ printf '%s' '{"ok":true}'
+ else
+ die "unexpected action: $action"
+ fi
+}
+printf '%s' '{"session":{"id":"foreign-id-111","title":"Imported","history":[{"role":"user","content":"hello"}]}}' | run_agent_session import -
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).toBe(0);
+ const calls = res.stderr
+ .trim()
+ .split("\n")
+ .filter((l) => l.startsWith("jpost action="));
+ expect(calls).toHaveLength(2);
+ expect(calls[0]).toContain("action=create");
+ expect(calls[1]).toContain("action=update");
+ expect(calls[1]).toContain('"id":"new-id-999"');
+ expect(calls[1]).not.toContain("foreign-id-111");
+ });
+
+ it("run_agent_session import rejects a file whose JSON has no history array", () => {
+ const script = `
+${fixture}
+f=$(mktemp)
+trap 'rm -f "$f"' EXIT
+printf '%s' '{"session":{"id":"s1","title":"No history"}}' > "$f"
+run_agent_session import "$f"
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("is not a session export (no history array)");
+ });
+
+ it("run_agent_session rm exits nonzero with a message that says the store is append-only", () => {
+ const script = `
+${fixture}
+jget(){
+ printf '%s' '{"sessions":[{"id":"ses-1"}]}'
+}
+run_agent_session rm
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("the agent-session store is append-only");
+ });
+
+ it("run_agent_stats --json sums estimatedTokens/historyTurns from a stubbed 2-session payload", () => {
+ const script = `
+${fixture}
+jget(){
+ printf '%s' '{"sessions":[{"id":"s1","estimatedTokens":150,"historyTurns":3,"lifetimeEstimatedTokens":200,"compactionCount":1,"archiveCount":0,"source":"cli"},{"id":"s2","estimatedTokens":250,"historyTurns":7,"lifetimeEstimatedTokens":300,"compactionCount":0,"archiveCount":0,"source":"web"}]}'
+}
+run_agent_stats --json
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ const data = JSON.parse(out);
+ expect(data.sessions).toBe(2);
+ expect(data.tokens).toBe(400);
+ expect(data.turns).toBe(10);
+ });
+
+ it("run_agent_stats --days abc exits nonzero", () => {
+ const script = `
+${fixture}
+jget(){ printf '%s' '{"sessions":[]}'; }
+run_agent_stats --days abc
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("--days needs a whole number");
+ });
+
+ it("run_agent_stats --usage prints the human ledger with summed tokens", () => {
+ const script = `
+${fixture}
+jget(){
+ printf '%s' '{"sessions":[{"id":"s1","estimatedTokens":150,"historyTurns":3,"lifetimeEstimatedTokens":200,"compactionCount":1,"archiveCount":0,"source":"cli"},{"id":"s2","estimatedTokens":250,"historyTurns":7,"lifetimeEstimatedTokens":300,"compactionCount":0,"archiveCount":0,"source":"web"}]}'
+}
+run_agent_stats --usage
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(out).toContain("tokens now 400");
+ expect(out).toContain("tokens total 500");
+ });
+
+ // Regression: `--out` must not be parsed as the session reference.
+ it("run_agent_session export --out with no ref exports the newest session to that file", () => {
+ const script = `
+${fixture}
+jget(){
+ case "$1" in
+ *"limit=1"*) printf '{"sessions":[{"id":"newest-id"}]}' ;;
+ *"ref=newest-id"*) printf '{"session":{"id":"newest-id"}}' ;;
+ *) printf '{"error":"unexpected %s"}' "$1" >&2; exit 9 ;;
+ esac
+}
+run_agent_session export --out "$OUT"
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8", env: { ...process.env, OUT: "/tmp/mso-export-test.json" } });
+ expect(res.status).toBe(0);
+ // The confirmation goes to stderr so `mso session export` stays pipeable.
+ expect(res.stderr).toContain("wrote /tmp/mso-export-test.json");
+ expect(JSON.parse(require("node:fs").readFileSync("/tmp/mso-export-test.json", "utf8")).session.id).toBe("newest-id");
+ });
+});
diff --git a/scripts/cli/agent-run.sh b/scripts/cli/agent-run.sh
new file mode 100644
index 00000000..72115af8
--- /dev/null
+++ b/scripts/cli/agent-run.sh
@@ -0,0 +1,147 @@
+#!/usr/bin/env bash
+# Scriptable agent verbs: `run` (one autonomous turn), `session` (session records
+# without a TUI) and `stats --usage` (the session token/compaction ledger).
+# Sourced by scripts/cli/runtime.sh, which sources mso-cli-agent.sh first.
+#
+# All three are thin adapters over the SAME agent loop and stores the interactive
+# `mso agent` uses, so a scripted run cannot drift from what a human gets.
+# shellcheck disable=SC2154
+
+# `mso run "…"`: non-interactive twin of `mso agent`. Each flag is validated here
+# because a mistyped scope must fail before any provider call is paid for; the
+# attached-file limits themselves stay in the agent's one-shot parser.
+run_agent_run() {
+ local prompt="" args=()
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --json) args+=(--json); shift ;;
+ --approve-scope)
+ case "${2-}" in
+ read|write|exec) args+=(--approve-scope "$2"); shift 2 ;;
+ *) die "--approve-scope must be read, write, or exec" ;;
+ esac ;;
+ --continue|-c)
+ # No value follows: the prompt is a positional arg. Shifting once here used
+ # to swallow it as a resume ref.
+ args+=(--continue); shift ;;
+ --resume|-r)
+ [ -n "${2-}" ] || die "--resume needs a session reference (latest|id|title)"
+ args+=(--resume "$2"); shift 2 ;;
+ --file|-f)
+ # Attached-file semantics live in the agent's one-shot parser (size caps,
+ # stdin-once rules); this adapter only forwards.
+ [ -n "${2-}" ] || die "usage: mso $U_run"
+ args+=(--file "$2"); shift 2 ;;
+ --thinking) args+=(--thinking); shift ;;
+ -*) die "unexpected flag for 'mso run': $1 (usage: mso $U_run)" ;;
+ *)
+ [ -z "$prompt" ] || die "mso run takes ONE prompt; quote it: mso run \"…\""
+ prompt="$1"; shift ;;
+ esac
+ done
+ [ -n "$prompt" ] || die "usage: mso $U_run"
+ # run_agent() is the same entry point `mso agent` uses; it validates the prompt,
+ # ensures provider/model readiness, then execs the shared agent runtime.
+ run_agent --oneshot "$prompt" "${args[@]}"
+}
+
+# Resolve a session reference without duplicating the server's id/name/latest logic.
+__mso_session_ref() {
+ local ref="${1:-latest}" id
+ if [ "$ref" = latest ]; then
+ id=$(jget "/api/v1/agent-sessions?limit=1" | jq -r '.sessions[0].id // empty')
+ [ -n "$id" ] || die "no agent sessions yet"
+ printf '%s' "$id"
+ else printf '%s' "$ref"; fi
+}
+
+run_agent_session() {
+ case "${1:-list}" in
+ list)
+ jget "/api/v1/agent-sessions?limit=$(enc "${2:-30}")" |
+ jq -r '(.sessions // [])[] | "\(.id)\t\(.source)\t\(.updatedAt)\t\(.historyTurns)t\t\(.estimatedTokens)tk\t\(.title)"' ;;
+ show)
+ ref=$(__mso_session_ref "${2-latest}")
+ jget "/api/v1/agent-sessions?ref=$(enc "$ref")" ;;
+ export)
+ # Flags can come before or without a ref: `export --out f` means "latest".
+ ref="latest"; out=""
+ local a="${2-}"
+ while [ -n "$a" ]; do
+ case "$a" in
+ --out) out="${3:?--out needs a file}"; shift 2; a="${2-}" ;;
+ *) ref="$a"; shift; a="${2-}" ;;
+ esac
+ done
+ ref=$(__mso_session_ref "$ref")
+ if [ -n "$out" ]; then
+ jget "/api/v1/agent-sessions?ref=$(enc "$ref")" > "$out"
+ echo "wrote $out" >&2
+ else jget "/api/v1/agent-sessions?ref=$(enc "$ref")"; fi ;;
+ import)
+ src=""; title=""
+ local a="${2-}"
+ while [ -n "$a" ]; do
+ case "$a" in
+ --title) title="${3:?--title needs a value}"; shift 2; a="${2-}" ;;
+ *) [ -z "$src" ] || die "import takes ONE file; quote it"; src="$a"; shift; a="${2-}" ;;
+ esac
+ done
+ [ -n "$src" ] || die "usage: mso $U_session"
+ if [ "$src" = - ]; then body=$(cat); else [ -f "$src" ] || die "no such file: $src"; body=$(cat -- "$src"); fi
+ printf '%s' "$body" | jq -e '(.session.history // .history) | type == "array"' >/dev/null 2>&1 \
+ || die "$src is not a session export (no history array)"
+ # Import replays the recorded history into a NEW session. Reusing the source
+ # id would let a foreign export overwrite a live conversation.
+ history=$(printf '%s' "$body" | jq -c '.session.history // .history')
+ fallback_title=$(printf '%s' "$body" | jq -r '.session.title // "Imported session"' | cut -c1-120)
+ created=$(jpost "/api/v1/agent-sessions" "$(jq -nc --arg t "${title:-$fallback_title}" '{action:"create",title:$t}')")
+ new_id=$(printf '%s' "$created" | jq -r '.session.id // empty')
+ [ -n "$new_id" ] || die "server did not return a session id"
+ jpost "/api/v1/agent-sessions" "$(jq -nc --arg id "$new_id" --argjson h "$history" '{action:"update",id:$id,history:$h}')" >/dev/null
+ printf '%s\n' "$created" ;;
+ rm|delete)
+ # The session API has no delete action; say so instead of pretending.
+ die "mso session rm: the agent-session store is append-only over the API. Archive instead: mso agent-sessions show $(__mso_session_ref "${2-latest}")" ;;
+ *) die "usage: mso $U_session" ;;
+ esac
+}
+
+# `mso stats --usage`: what opencode's `stats --cost/--models` gives, from the
+# records MSO already stores: per-session estimated tokens, compaction, archives.
+run_agent_stats() {
+ json=0; days=0; models=0
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --json) json=1; shift ;;
+ --models) models=1; shift ;;
+ --usage) shift ;;
+ --days) [ -n "${2-}" ] && [[ "$2" =~ ^[0-9]+$ ]] || die "--days needs a whole number"; days="$2"; shift 2 ;;
+ *) die "usage: mso $U_stats" ;;
+ esac
+ done
+ data=$(jget "/api/v1/agent-sessions?limit=200")
+ if [ "$days" -gt 0 ]; then
+ cutoff=$(date -u -d "-$days days" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-"${days}"d +%Y-%m-%dT%H:%M:%SZ)
+ data=$(printf '%s' "$data" | jq --arg c "$cutoff" '.sessions |= [.[] | select(.updatedAt >= $c)]')
+ fi
+ if [ "$json" = 1 ]; then
+ printf '%s' "$data" | jq '{sessions: (.sessions|length), tokens: ([.sessions[].estimatedTokens]|add // 0), lifetimeTokens: ([.sessions[].lifetimeEstimatedTokens]|add // 0), turns: ([.sessions[].historyTurns]|add // 0), compactions: ([.sessions[].compactionCount]|add // 0), archives: ([.sessions[].archiveCount]|add // 0), bySource: ([.sessions[].source]|group_by(.)|map({source:.[0],count:length}))}'
+ return 0
+ fi
+ printf '%s' "$data" | jq -r '
+ "sessions \(.sessions|length)",
+ "tokens now \(([.sessions[].estimatedTokens]|add // 0))",
+ "tokens total \(([.sessions[].lifetimeEstimatedTokens]|add // 0))",
+ "turns \(([.sessions[].historyTurns]|add // 0))",
+ "compactions \(([.sessions[].compactionCount]|add // 0))",
+ "archives \(([.sessions[].archiveCount]|add // 0))",
+ "",
+ "by source",
+ (([.sessions[].source] // []) | group_by(.) | map(" \(.[0])\t\(length)") | .[])'
+ if [ "$models" = 1 ]; then
+ # Per-model cost is not recorded per session yet; name the gap, do not invent it.
+ echo
+ echo "per-model cost: not recorded. Sessions store estimated tokens, not provider/model attribution."
+ fi
+}
diff --git a/scripts/cli/agent-run.test.ts b/scripts/cli/agent-run.test.ts
new file mode 100644
index 00000000..1d7e1dbf
--- /dev/null
+++ b/scripts/cli/agent-run.test.ts
@@ -0,0 +1,127 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { describe, expect, it } from "vitest";
+
+const fixture = `
+set -euo pipefail
+die(){ echo "$*" >&2; exit 1; }
+enc(){ printf '%s' "$1"; }
+U_run="run <prompt>"
+U_session="session"
+U_stats="stats"
+source scripts/cli/agent-run.sh
+`;
+
+describe("scripts/cli/agent-run.sh", () => {
+ it("run_agent_run forwards prompt + --json + --approve-scope to run_agent in the right argv order", () => {
+ const script = `
+${fixture}
+run_agent(){
+ jq -nc --args '$ARGS.positional' -- "$@"
+}
+run_agent_run "build feature" --json --approve-scope write
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(JSON.parse(out)).toEqual([
+ "--oneshot",
+ "build feature",
+ "--json",
+ "--approve-scope",
+ "write",
+ ]);
+ });
+
+ it("run_agent_run forwards prompt + --file to run_agent in argv order", () => {
+ const script = `
+${fixture}
+run_agent(){
+ jq -nc --args '$ARGS.positional' -- "$@"
+}
+run_agent_run "prompt" --file /tmp/x
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(JSON.parse(out)).toEqual([
+ "--oneshot",
+ "prompt",
+ "--file",
+ "/tmp/x",
+ ]);
+ });
+
+ it("run_agent_run --file with no value exits nonzero with the usage message", () => {
+ const script = `
+${fixture}
+run_agent(){ :; }
+run_agent_run --file
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("usage: mso");
+ });
+
+ it("run_agent_run forwards --thinking to run_agent", () => {
+ const script = `
+${fixture}
+run_agent(){
+ jq -nc --args '$ARGS.positional' -- "$@"
+}
+run_agent_run "prompt" --thinking
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(JSON.parse(out)).toEqual([
+ "--oneshot",
+ "prompt",
+ "--thinking",
+ ]);
+ });
+
+ it("run_agent_run rejects --approve-scope bogus and exits nonzero", () => {
+ const script = `
+${fixture}
+run_agent(){ :; }
+run_agent_run --approve-scope bogus "hello"
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("--approve-scope must be read, write, or exec");
+ });
+
+ it("run_agent_run rejects a SECOND positional prompt and exits nonzero", () => {
+ const script = `
+${fixture}
+run_agent(){ :; }
+run_agent_run "a" "b"
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("mso run takes ONE prompt; quote it");
+ });
+
+ it("run_agent_run with no prompt exits nonzero", () => {
+ const script = `
+${fixture}
+run_agent(){ :; }
+run_agent_run
+`;
+ const res = spawnSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("usage: mso");
+ });
+
+ // Regression: `--continue` takes no value. The first version shifted before
+ // inspecting, so it swallowed the prompt as a resume reference and died.
+ it("run_agent_run keeps the prompt when --continue is present", () => {
+ const script = `
+${fixture}
+run_agent(){ jq -nc --args '$ARGS.positional' -- "$@"; }
+run_agent_run --continue "carry on"
+`;
+ const out = execFileSync("bash", ["-c", script], { encoding: "utf8" });
+ expect(JSON.parse(out)).toEqual(["--oneshot", "carry on", "--continue"]);
+ });
+
+ it("run_agent_run requires a reference after --resume", () => {
+ const res = spawnSync("bash", ["-c", `${fixture}\nrun_agent(){ :; }\nrun_agent_run "p" --resume`], { encoding: "utf8" });
+ expect(res.status).not.toBe(0);
+ expect(res.stderr).toContain("--resume needs a session reference");
+ });
+});
diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.sh
index 9d4e4426..f71eb688 100755
--- a/scripts/cli/commands-admin.sh
+++ b/scripts/cli/commands-admin.sh
@@ -67,6 +67,7 @@ case "$cmd" in
logout) if [ -s "$JAR" ]; then jpost "/api/auth/logout" >/dev/null 2>&1 || true; fi
mso_private_state_remove_file "$JAR" || die "refusing unsafe cookie jar: $JAR"
echo "signed out (jar cleared)" ;;
+ pair) source "$ROOT/scripts/cli/pair.sh"; mso_pair "$@" ;;
# ── service (local systemd) ──────────────────────────────────────────────
service)
@@ -135,14 +136,8 @@ case "$cmd" in
if [ -n "$body" ]; then req -X "$m" -H 'content-type: application/json' -d "$body" "$B$p"
else req -X "$m" "$B$p"; fi ;;
- # Verb list comes from verbs(), so completion cannot go stale.
- completion)
- case "${1:-bash}" in
- bash) printf 'complete -W "%s" mso\n' "$(verbs | grep -v '^-' | sort -u | tr '\n' ' ')" ;;
- zsh) printf 'compdef _gnu_generic mso\ncompctl -k "(%s)" mso\n' "$(verbs | grep -v '^-' | sort -u | tr '\n' ' ')" ;;
- *) die "completion: bash|zsh (eval \"\$(mso completion bash)\")" ;;
- esac
- exit 0 ;;
+ # Verb list comes from verbs(), subcommands from U_<verb> usage strings.
+ completion) source "$ROOT/scripts/cli/completion.sh"; mso_completion "$@"; exit 0 ;;
*) die "internal CLI routing error: $cmd reached the wrong command family" ;;
esac
}
diff --git a/scripts/cli/commands-host.sh b/scripts/cli/commands-host.sh
index 8d52ed7d..bc638790 100755
--- a/scripts/cli/commands-host.sh
+++ b/scripts/cli/commands-host.sh
@@ -42,7 +42,15 @@ case "$cmd" in
# ── host ─────────────────────────────────────────────────────────────────
exec) jpost "/api/v1/exec/run" "$(jq -n --arg c "$*" '{cmd:$c}')" ;;
- stats) jget "/api/v1/sys/stats" ;;
+ stats)
+ # `stats` alone is live host truth (CPU/mem/disk). The agent ledger lives behind
+ # --usage/--days/--models, matching what opencode calls `stats --cost/--models`.
+ case "${1-}" in
+ --usage|--days|--models) run_agent_stats "$@" ;;
+ --json) jget "/api/v1/sys/stats" | jq . ;;
+ "") jget "/api/v1/sys/stats" ;;
+ *) die "usage: mso $U_stats" ;;
+ esac ;;
ps) jget "/api/v1/sys/processes" ;;
units)
data=$(jget "/api/v1/sys/services")
@@ -68,12 +76,25 @@ case "$cmd" in
# Layer-by-layer, cheapest first, so the FIRST failure names the real cause
# instead of the symptom three layers up ("login failed" when node is missing).
doctor)
+ format="prose"
fix=0
- case "${1-}" in
- "") ;;
- --fix) fix=1 ;;
- *) die "usage: mso $U_doctor" ;;
- esac
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --json) format="json" ;;
+ --fix) fix=1 ;;
+ *) die "usage: mso $U_doctor" ;;
+ esac
+ shift
+ done
+ if [ "$format" = "json" ] && [ "$fix" = 1 ]; then
+ echo "doctor --json is read-only; run \`mso doctor --fix\` for repairs" >&2
+ exit 2
+ fi
+ if [ "$format" = "json" ]; then
+ # shellcheck source=doctor-json.sh
+ source "${ROOT:-.}/scripts/cli/doctor-json.sh"
+ mso_doctor_json
+ fi
fails=0
chk() { if eval "$2" >/dev/null 2>&1; then printf ' ok %s\n' "$1"; else printf ' FAIL %s — %s\n' "$1" "$3"; fails=$((fails+1)); fi; }
fixed() { printf ' FIXED %s\n' "$1"; }
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index 387d6fe8..aef63982 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -6,6 +6,8 @@ mso_cmd_runtime() {
local cmd="$1"; shift || true
case "$cmd" in
agent|chat) run_agent "$@" ;;
+ run) run_agent_run "$@" ;;
+ session) run_agent_session "$@" ;;
model) run_model_setup "$@" ;;
setup) run_onboard "${1-}" ;;
onboard) run_onboard "${1-}" ;;
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 881b2274..2453acb1 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -23,7 +23,8 @@ verbs() {
U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
U_domain="domain status|setup --user <user> --connection <cloudflare-connection> [--origin <https://host>] [--template <{id}.host>] [--zone <name|id>] [--tunnel <UUID>] [--local <http://loopback:port>] [--manual] [--apply]|ensure <id> [--apply]|doctor <id>|repair-env [--apply]|restore [--apply]"
-U_doctor="doctor [--fix]"
+U_doctor="doctor [--fix] [--json]"
+U_pair="pair [--json]"
U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|save|delete <id> --revision <revision> [--input <JSON|@file>]"
U_workflow="workflow list|embeds|embed-save --input <JSON|@file>|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"
U_integrations="integrations [interactive]|transfer|status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute <JSON>"
@@ -36,6 +37,9 @@ U_mapp="mapp enable <id> [install-key=value...]|start|stop|restart <id>|catalog|
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
U_service="service status|start|stop|restart|logs [n]"
+U_stats="stats [--json] | stats --usage [--days N] [--json] [--models]"
+U_run="run <prompt…> [--json] [--file <path>] [--thinking] [--approve-scope read|write|exec] [--continue|-c|--resume <ref>]"
+U_session="session list [limit]|show [id|name|latest]|export [id|name|latest] [--out <file>]|import <file|-> [--title <title>]"
U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"
U_reset="reset [--scope config|all] [--json] [--apply --confirm <preview-token>]"
U_uninstall="uninstall [--purge] [--remove-code] [--service name.service] [--json] [--apply --confirm <preview-token>]"
@@ -58,7 +62,10 @@ U_jev="jev status|decide <model.route|failure.triage|recipe.promote> [JSON|@file
U_skills="skills list|read <id>|search <query…>|available|info <id>|install <id…> [-y] [--force]|remove <id…> [-y]|store list|store install|remove <id> <revision>"
U_mcp="mcp project <JSON>|list|pat <label> [read|write|exec] [ttlDays]|activity [n]|service-token --label <label> --client-id <id> --scope <read|write|exec> --tools <name,name> [--constraints-json <json>]|revoke <id>|revoke all"
U_oauth="oauth <provider> start|poll OAuth currently: openai (ChatGPT Codex)"
+U_completion="completion [bash|zsh|fish|sh]"
# Command families are sourced here so bin/mso remains only bootstrap + entrypoint.
+# shellcheck source=agent-run.sh
+source "$ROOT/scripts/cli/agent-run.sh"
# shellcheck source=commands-host.sh
source "$ROOT/scripts/cli/commands-host.sh"
# shellcheck source=commands-runtime.sh
@@ -104,11 +111,11 @@ mso_cli_main() {
case "$cmd" in
version|--version|-V|-v|ls|cat|raw|share|usage|search|project-candidates|write|mkdir|rm|mv|cp|zip|upload|exec|stats|ps|units|unit|packages|cleanup|status|health|doctor)
mso_cmd_host "$cmd" "$@" ;;
- agent|chat|model|setup|onboard|provider|providers|integrations|channels|agent-groups|flow|workflow|gateway|domain|heartbeat|web|camoufox|apps|mapp|term)
+ agent|chat|model|setup|onboard|provider|providers|integrations|channels|agent-groups|flow|workflow|gateway|domain|heartbeat|web|camoufox|apps|mapp|term|run|session)
mso_cmd_runtime "$cmd" "$@" ;;
ai|cockpit|threads|agent-sessions|agent-profiles|agents|org|a2a|memory|memory-graph|agent-vault|config|prefs|federation|models|jev|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;
- devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|passwd|service|build|deploy|update|reset|uninstall|crud|api|completion)
+ devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|passwd|service|build|deploy|update|reset|uninstall|crud|api|completion|pair)
mso_cmd_admin "$cmd" "$@" ;;
help|-h|--help) usage; exit 0 ;;
*) mso_cli_unknown "$cmd" ;;
diff --git a/scripts/cli/completion.sh b/scripts/cli/completion.sh
new file mode 100644
index 00000000..56000bb3
--- /dev/null
+++ b/scripts/cli/completion.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env bash
+# Shell completion: verbs from the dispatch table, subcommands from U_<verb> usage
+# strings, so neither can go stale when a new arm is added.
+# Sourced by scripts/cli/commands-admin.sh. Uses `verbs` and the U_ vars from
+# scripts/cli/commands.sh, plus `die` from bin/mso.
+# shellcheck disable=SC2154
+
+# Segments of a usage string look like `threads list|show <id>|rm <id>`; the first
+# token of each segment is the subcommand. Pipes inside <...> and [...] are part of
+# an argument's own alternation, not subcommand separators, so they are masked first.
+__mso_completion_subcommands() {
+ local cv="$1" key u masked="" db=0 da=0 i len c parts part wlist w tok seen=" "
+ key="${cv//-/_}"
+ eval "u=\${U_${key}-}"
+ [ -n "$u" ] || return 0
+ u="${u#"${cv}"}"
+ u="${u#" "}"
+ if [[ "$u" =~ ^\[([a-zA-Z].*\|.*)\]$ ]]; then
+ u="${BASH_REMATCH[1]}"
+ fi
+ len=${#u}
+ for (( i=0; i<len; i++ )); do
+ c="${u:i:1}"
+ case "$c" in
+ "[") ((db++)) ;;
+ "]") ((db > 0)) && ((db--)) ;;
+ "<") ((da++)) ;;
+ ">") ((da > 0)) && ((da--)) ;;
+ "|") ((db > 0 || da > 0)) && c=" " ;;
+ esac
+ masked+="$c"
+ done
+ # `--flag value|next` is a flag alternation, not two subcommands.
+ while [[ "$masked" =~ (--[a-zA-Z0-9_-]+[[:space:]]+[a-zA-Z0-9_-]+)\|([a-zA-Z0-9_-]+) ]]; do
+ masked="${masked//${BASH_REMATCH[0]}/${BASH_REMATCH[1]} ${BASH_REMATCH[2]}}"
+ done
+ IFS="|" read -ra parts <<< "$masked"
+ subs=()
+ for part in "${parts[@]}"; do
+ part="${part#"${part%%[![:space:]]*}"}"
+ if [[ "$part" =~ ^${cv}[[:space:]]+(.*)$ ]]; then
+ part="${BASH_REMATCH[1]}"
+ part="${part#"${part%%[![:space:]]*}"}"
+ fi
+ read -ra wlist <<< "$part"
+ tok=""
+ for w in "${wlist[@]}"; do
+ w="${w//[\[\]()]/}"
+ case "$w" in
+ "") continue ;;
+ -*|"$cv") break ;;
+ \<*) continue ;;
+ *) tok="$w"; break ;;
+ esac
+ done
+ case "$tok" in
+ "") continue ;;
+ *)
+ if [[ "$tok" =~ ^[a-zA-Z0-9_-]+$ ]] && [[ "$seen" != *" $tok "* ]]; then
+ subs+=("$tok")
+ seen="$seen$tok "
+ fi ;;
+ esac
+ done
+ echo "${subs[*]}"
+}
+
+mso_completion() {
+ local vlist v subs
+ vlist="$(verbs | grep -v '^-' | sort -u | tr '\n' ' ')"
+ vlist="${vlist% }"
+
+ case "${1:-bash}" in
+ bash)
+ printf '# bash completion for mso\n'
+ printf '_mso() {\n'
+ printf ' local cur="${COMP_WORDS[COMP_CWORD]}"\n'
+ printf ' if [ "$COMP_CWORD" -eq 1 ]; then\n'
+ printf ' COMPREPLY=( $(compgen -W "%s" -- "$cur") )\n' "$vlist"
+ printf ' return 0\n'
+ printf ' fi\n'
+ printf ' if [ "$COMP_CWORD" -eq 2 ]; then\n'
+ printf ' case "${COMP_WORDS[1]}" in\n'
+ for v in $vlist; do
+ subs=$(__mso_completion_subcommands "$v")
+ if [ -n "$subs" ]; then
+ printf ' %s) COMPREPLY=( $(compgen -W "%s" -- "$cur") ) ;;\n' "$v" "$subs"
+ fi
+ done
+ printf ' esac\n'
+ printf ' return 0\n'
+ printf ' fi\n'
+ printf '}\n'
+ printf 'complete -F _mso mso\n' ;;
+ zsh)
+ printf '#compdef mso\n'
+ printf '_mso() {\n'
+ printf ' local -a verbs\n'
+ printf ' verbs=(%s)\n\n' "$vlist"
+ printf ' if (( CURRENT == 2 )); then\n'
+ printf ' compadd -a verbs\n'
+ printf ' return\n'
+ printf ' fi\n\n'
+ printf ' if (( CURRENT == 3 )); then\n'
+ printf ' case "$words[2]" in\n'
+ for v in $vlist; do
+ subs=$(__mso_completion_subcommands "$v")
+ if [ -n "$subs" ]; then
+ printf ' %s) compadd %s ;;\n' "$v" "$subs"
+ fi
+ done
+ printf ' esac\n'
+ printf ' return\n'
+ printf ' fi\n'
+ printf '}\n'
+ printf 'compdef _mso mso 2>/dev/null || true\n' ;;
+ fish)
+ printf 'complete -c mso -n '\''__fish_use_subcommand'\'' -a '\''%s'\''\n' "$vlist"
+ for v in $vlist; do
+ subs=$(__mso_completion_subcommands "$v")
+ if [ -n "$subs" ]; then
+ printf 'complete -c mso -n '\''__fish_seen_subcommand_from %s'\'' -a '\''%s'\''\n' "$v" "$subs"
+ fi
+ done ;;
+ sh)
+ printf '# Bare list of mso verbs for shells without native completion hooks\n'
+ for v in $vlist; do
+ printf '%s\n' "$v"
+ done ;;
+ *) die "completion: bash|zsh|fish|sh (eval \"\$(mso completion bash)\")" ;;
+ esac
+}
diff --git a/scripts/cli/doctor-json.sh b/scripts/cli/doctor-json.sh
new file mode 100644
index 00000000..a97b5985
--- /dev/null
+++ b/scripts/cli/doctor-json.sh
@@ -0,0 +1,167 @@
+#!/usr/bin/env bash
+# Shared health checks implementation for machine-readable `mso doctor --json`.
+# Bash + jq only; no credentials or secrets leaked into stdout.
+
+doctor_browser_origin_ok() {
+ case "$1" in
+ https://*) return 0 ;;
+ http://127.*:*|http://localhost:*|http://\[::1\]:*) return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+# Emits checks in TSV format: name <tab> status <tab> detail <tab> fix
+doctor_checks() {
+ local local_runtime=0
+ case "$B" in
+ 'http://127.'*:*|'http://localhost:'*|'http://[::1]:'*) local_runtime=1 ;;
+ esac
+
+ # 1. curl
+ if command -v curl >/dev/null 2>&1; then
+ printf '%s\t%s\t%s\t%s\n' "curl" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "curl" "fail" "" "install curl"
+ fi
+
+ # 2. jq
+ if command -v jq >/dev/null 2>&1; then
+ printf '%s\t%s\t%s\t%s\n' "jq" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "jq" "fail" "" "install jq"
+ fi
+
+ # 3. node
+ if node "${ROOT:-.}/scripts/check-node-runtime.mjs" >/dev/null 2>&1; then
+ printf '%s\t%s\t%s\t%s\n' "node" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "node" "fail" "" "install Node 22.12+, 24.x or 26+"
+ fi
+
+ # 4. env file
+ if [ -f "$ENVF" ]; then
+ printf '%s\t%s\t%s\t%s\n' "env file" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "env file" "fail" "no $ENVF" "copy .env.example and fill it"
+ fi
+
+ # 5. login password
+ if [ -n "${PASS-}" ]; then
+ printf '%s\t%s\t%s\t%s\n' "login password" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "login password" "fail" "OS_LOGIN_PASSWORD unset in $ENVF" "OS_LOGIN_PASSWORD unset in $ENVF"
+ fi
+
+ # 6. session secret
+ if [ -n "${OS_SESSION_SECRET-}" ]; then
+ printf '%s\t%s\t%s\t%s\n' "session secret" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "session secret" "fail" "OS_SESSION_SECRET unset in $ENVF" "OS_SESSION_SECRET unset in $ENVF"
+ fi
+
+ # 7. login transport
+ if doctor_browser_origin_ok "$B"; then
+ printf '%s\t%s\t%s\t%s\n' "login transport" "ok" "browser must use HTTPS or http://localhost (never plain http://server-ip)" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "login transport" "fail" "browser login requires HTTPS or a loopback URL" "use a TLS proxy/gateway, or SSH -L and open http://localhost"
+ fi
+
+ # 8. public origin (only when set)
+ if [ -n "${OS_PUBLIC_ORIGIN-}" ]; then
+ if doctor_browser_origin_ok "$OS_PUBLIC_ORIGIN"; then
+ printf '%s\t%s\t%s\t%s\n' "public origin" "ok" "$OS_PUBLIC_ORIGIN" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "public origin" "fail" "OS_PUBLIC_ORIGIN=$OS_PUBLIC_ORIGIN is not a valid browser login origin" "use https://..."
+ fi
+ fi
+
+ # 9. app dashboards
+ local tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"
+ if [ -n "$tpl" ]; then
+ printf '%s\t%s\t%s\t%s\n' "app dashboards" "ok" "$tpl — host-only app sessions; REBUILD after changing the template" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "app dashboards" "skip" "off: no app host — managed-app windows open on the CLI view" ""
+ fi
+
+ # 10. service unit
+ if [ "$local_runtime" = 0 ]; then
+ printf '%s\t%s\t%s\t%s\n' "service unit" "skip" "skipped: --base is remote" ""
+ elif ! service_manager_read show --property=Version --value >/dev/null 2>&1; then
+ printf '%s\t%s\t%s\t%s\n' "service unit" "skip" "systemd manager unavailable; runtime health checked below" ""
+ elif ! service_manager_read is-active --quiet mso.service 2>/dev/null; then
+ printf '%s\t%s\t%s\t%s\n' "service unit" "fail" "mso.service not active" "run: mso doctor --fix or mso service start"
+ else
+ printf '%s\t%s\t%s\t%s\n' "service unit" "ok" "" ""
+ fi
+
+ # 11. reachable
+ doctor_health_ok() {
+ local direct=()
+ [ "$local_runtime" = 0 ] || direct=(--noproxy '*')
+ curl "${direct[@]}" -fsS --max-time 5 "$B/api/health" 2>/dev/null \
+ | jq -e 'type == "object" and .status == "ok" and .service == "mso"' >/dev/null 2>&1
+ }
+ if doctor_health_ok; then
+ printf '%s\t%s\t%s\t%s\n' "reachable" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "reachable" "fail" "no healthy MSO at $B" "for local recovery run: mso web --local --print"
+ fi
+
+ # 12. device known
+ local d=""
+ if command -v cli_device >/dev/null 2>&1 || type cli_device >/dev/null 2>&1; then
+ d=$(cli_device 2>/dev/null || true)
+ fi
+ local device_ready=0
+ if [ "$local_runtime" = 0 ]; then
+ printf '%s\t%s\t%s\t%s\n' "device known" "skip" "skipped: --base is remote; check it on that host" ""
+ device_ready=1
+ elif dev_script --is-approved "$d" >/dev/null 2>&1; then
+ printf '%s\t%s\t%s\t%s\n' "device known" "ok" "" ""
+ device_ready=1
+ else
+ printf '%s\t%s\t%s\t%s\n' "device known" "fail" "this CLI device is not approved" "run: mso doctor --fix (or mso device approve $d \"mso cli\")"
+ fi
+
+ # 13. session
+ fresh_session_check() {
+ mso_private_state_remove_file "$JAR" || return 1
+ JAR=$(mso_private_state_ensure_file "$JAR") || return 1
+ [ "$(jget /api/auth/me 2>/dev/null | jq -r .authenticated 2>/dev/null)" = true ]
+ }
+ if [ "$device_ready" = 1 ]; then
+ if ( fresh_session_check >/dev/null 2>&1 ); then
+ printf '%s\t%s\t%s\t%s\n' "session" "ok" "" ""
+ else
+ printf '%s\t%s\t%s\t%s\n' "session" "fail" "cannot sign in" "verify password, approved device, and browser/CLI origin above"
+ fi
+ else
+ printf '%s\t%s\t%s\t%s\n' "session" "fail" "skipped until the local CLI device is approved" ""
+ fi
+}
+
+mso_doctor_json() {
+ local json
+ json=$(doctor_checks | jq -R -s -c --arg base "$B" '
+ split("\n") | map(select(length > 0) | split("\t")) |
+ map({
+ name: .[0],
+ status: .[1],
+ detail: (if .[2] == "" then null else .[2] end),
+ fix: (if .[3] == "" then null else .[3] end)
+ }) as $checks |
+ ($checks | map(select(.status == "fail")) | length) as $failed |
+ {
+ ok: ($failed == 0),
+ base: $base,
+ checks: $checks,
+ failed: $failed
+ }
+ ')
+ printf '%s\n' "$json"
+ if [ "$(jq -r .ok <<<"$json")" = "true" ]; then
+ exit 0
+ else
+ exit 1
+ fi
+}
diff --git a/scripts/cli/pair.sh b/scripts/cli/pair.sh
new file mode 100644
index 00000000..36cce8be
--- /dev/null
+++ b/scripts/cli/pair.sh
@@ -0,0 +1,95 @@
+#!/usr/bin/env bash
+# Ready-to-use origins and pending-device approval paths without mutations or tunnels.
+
+mso_pair() {
+ local json_mode=0
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --json)
+ json_mode=1
+ shift ;;
+ -h|--help|help)
+ echo "usage: mso pair [--json]"
+ return 0 ;;
+ *)
+ echo "usage: mso pair [--json]" >&2
+ exit 1 ;;
+ esac
+ done
+
+ # Loopback upstream is authoritative for local login
+ local loopback_url
+ loopback_url="$(gateway_local_url)"
+
+ # Check configured public origin first, then cheap cached gateway state
+ local public_origin=""
+ if [ -n "${OS_PUBLIC_ORIGIN:-}" ]; then
+ public_origin="$OS_PUBLIC_ORIGIN"
+ else
+ local can_root scope_id state_file
+ can_root="$(realpath -e -- "$ROOT" 2>/dev/null || true)"
+ if [ -n "$can_root" ]; then
+ scope_id="$(printf '%s\n%s' "$can_root" "$loopback_url" | sha256sum | awk '{print $1}')"
+ state_file="$HOME/.mso/private/gateway/$scope_id/state.json"
+ if [ -f "$state_file" ]; then
+ public_origin="$(jq -r '.url // empty' "$state_file" 2>/dev/null || true)"
+ fi
+ fi
+ fi
+
+ # Stable CLI device identity
+ local dev_id
+ dev_id="$(cli_device)"
+
+ # Cheap read-only session probe matching mso health without triggering lazy login
+ local signed_in="false"
+ if [ -s "${JAR:-}" ]; then
+ local health_body
+ health_body="$(curl -sS --max-time 2 -b "$JAR" "${ORIGIN[@]}" "$B/api/auth/me" 2>/dev/null || true)"
+ if [ "$(jq -r '.authenticated // false' <<<"$health_body" 2>/dev/null)" = "true" ]; then
+ signed_in="true"
+ fi
+ fi
+
+ # Query local allowlist directly without network roundtrips
+ local pending_out pending_lines pending_count=0 next_cmd=""
+ pending_out="$(dev_script --pending 2>/dev/null || true)"
+ pending_lines="$(sed -n 's/^[[:space:]]*\(mso device approve .*\)$/\1/p' <<<"$pending_out")"
+ if [ -n "$pending_lines" ]; then
+ pending_count="$(grep -c . <<<"$pending_lines")"
+ next_cmd="$(head -n 1 <<<"$pending_lines")"
+ fi
+
+ if [ "$json_mode" -eq 1 ]; then
+ jq -n \
+ --arg loopback "$loopback_url" \
+ --arg public "$public_origin" \
+ --arg device "$dev_id" \
+ --argjson signedIn "$signed_in" \
+ --argjson pending "$pending_count" \
+ --arg next "$next_cmd" \
+ '{
+ loopback: $loopback,
+ public: (if $public == "" then null else $public end),
+ device: $device,
+ signedIn: $signedIn,
+ pending: $pending,
+ next: (if $next == "" then null else $next end)
+ }'
+ return 0
+ fi
+
+ local public_display="${public_origin:-not configured}"
+ local signed_status="not signed in"
+ [ "$signed_in" = "true" ] && signed_status="signed in"
+
+ echo "Loopback: $loopback_url (browser login requires HTTPS or localhost, never plain http://<server-ip>)"
+ echo "Public origin: $public_display"
+ echo "CLI device: $dev_id ($signed_status)"
+ echo "Pending: $pending_count"
+ if [ -n "$next_cmd" ]; then
+ echo "Next: $next_cmd"
+ else
+ echo "Next: none"
+ fi
+}
diff --git a/scripts/mso-agent-oneshot.mjs b/scripts/mso-agent-oneshot.mjs
index 718056d8..dbe81f9e 100644
--- a/scripts/mso-agent-oneshot.mjs
+++ b/scripts/mso-agent-oneshot.mjs
@@ -1,17 +1,65 @@
+import fs from "node:fs";
+
const SCOPE_RANK = { read: 0, write: 1, exec: 2 };
+const MAX_FILES = 20;
+const MAX_FILE_BYTES = 200_000;
-export function parseOneShot(argv = []) {
+export function parseOneShot(argv = [], io = {}) {
let index = argv.indexOf("--oneshot"); if (index < 0) index = argv.indexOf("-z");
if (index < 0) return null;
- const prompt = argv[index + 1];
- if (!prompt || prompt.startsWith("-")) throw new Error("--oneshot requires a prompt argument");
+ const promptArg = argv[index + 1];
+ if (!promptArg || promptArg.startsWith("-")) throw new Error("--oneshot requires a prompt argument");
let approvalScope = "read";
const scopeIndex = argv.indexOf("--approve-scope");
if (scopeIndex >= 0) {
approvalScope = argv[scopeIndex + 1];
if (!["read", "write", "exec"].includes(approvalScope)) throw new Error("--approve-scope must be read, write, or exec");
}
- return { prompt, json: argv.includes("--json"), approvalScope };
+
+ const files = [];
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === "--file") {
+ const val = argv[i + 1];
+ if (!val || (val.startsWith("-") && val !== "-")) throw new Error("--file requires a path argument");
+ files.push(val);
+ i++;
+ }
+ }
+ if (files.length > MAX_FILES) throw new Error(`maximum of ${MAX_FILES} files can be attached`);
+
+ let seenStdin = false;
+ const fileBlocks = [];
+ const readFn = io.readFileSync || fs.readFileSync;
+ for (const filePath of files) {
+ let content;
+ if (filePath === "-") {
+ if (seenStdin) throw new Error("stdin (-) can only be read once");
+ seenStdin = true;
+ content = io.stdin !== undefined ? io.stdin : readFn(0, "utf8");
+ } else {
+ try {
+ content = readFn(filePath, "utf8");
+ } catch (err) {
+ if (err && (err.code === "ENOENT" || err.message?.includes("ENOENT"))) {
+ throw new Error(`${filePath}: no such file`);
+ }
+ throw err;
+ }
+ }
+ content = typeof content === "string" ? content : String(content);
+ const bytes = Buffer.byteLength(content, "utf8");
+ if (bytes > MAX_FILE_BYTES) throw new Error(`${filePath}: file exceeds ${MAX_FILE_BYTES} byte limit (${bytes} bytes)`);
+ fileBlocks.push(`<file path="${filePath}">\n${content}\n</file>`);
+ }
+
+ const prompt = fileBlocks.length ? `${fileBlocks.join("\n\n")}\n\n${promptArg}` : promptArg;
+ return {
+ prompt,
+ json: argv.includes("--json"),
+ approvalScope,
+ files,
+ thinking: argv.includes("--thinking"),
+ };
}
export function oneShotApproves(approvalScope, toolScope) {
@@ -21,9 +69,12 @@ export function oneShotApproves(approvalScope, toolScope) {
export function oneShotHelp() {
return [
"Usage: mso agent [--continue|--resume <query>]",
- " mso agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]",
+ " mso agent --oneshot <prompt> [--json] [--approve-scope read|write|exec] [--file <path>] [--thinking]",
"",
"One-shot runs the same autonomous MSO Agent tool loop without a TTY.",
"Default approval scope is read; write/exec require an explicit --approve-scope.",
+ "Attach files to prompt: --file <path> (repeatable, up to 20 files; '-' reads stdin).",
+ "Reasoning metrics: --thinking reports the reasoning TOKENS the provider returned;",
+ " reasoning text is not captured by the stream, so no reasoning block is invented.",
].join("\n");
}
diff --git a/scripts/mso-agent-oneshot.test.ts b/scripts/mso-agent-oneshot.test.ts
index 208f756b..7f66b559 100644
--- a/scripts/mso-agent-oneshot.test.ts
+++ b/scripts/mso-agent-oneshot.test.ts
@@ -1,13 +1,35 @@
-import { describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
import { oneShotApproves, oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";
describe("MSO Agent one-shot CLI contract", () => {
+ let tmpDir: string;
+
+ beforeAll(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-oneshot-test-"));
+ });
+
+ afterAll(() => {
+ if (tmpDir && fs.existsSync(tmpDir)) {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ });
+
it("defaults autonomous runs to read-only approvals", () => {
- expect(parseOneShot(["--oneshot", "inspect health", "--json"])).toEqual({ prompt: "inspect health", json: true, approvalScope: "read" });
+ expect(parseOneShot(["--oneshot", "inspect health", "--json"])).toEqual({
+ prompt: "inspect health",
+ json: true,
+ approvalScope: "read",
+ files: [],
+ thinking: false,
+ });
expect(oneShotApproves("read", "read")).toBe(true);
expect(oneShotApproves("read", "write")).toBe(false);
expect(oneShotApproves("read", "exec")).toBe(false);
});
+
it("requires an explicit scope before autonomous write/exec calls", () => {
expect(parseOneShot(["-z", "run fixture", "--approve-scope", "write"])?.approvalScope).toBe("write");
expect(oneShotApproves("write", "write")).toBe(true);
@@ -15,8 +37,96 @@ describe("MSO Agent one-shot CLI contract", () => {
expect(oneShotApproves("exec", "exec")).toBe(true);
expect(() => parseOneShot(["-z", "x", "--approve-scope", "root"])).toThrow(/read, write, or exec/);
});
- it("documents that one-shot uses the autonomous agent loop", () => {
- expect(oneShotHelp()).toContain("same autonomous MSO Agent tool loop");
- expect(oneShotHelp()).toContain("Default approval scope is read");
+
+ it("--file attaches contents with the delimiter and preserves the literal path", () => {
+ const filePath = path.join(tmpDir, "sample.txt");
+ fs.writeFileSync(filePath, "sample file content");
+ const result = parseOneShot(["--oneshot", "do task", "--file", filePath]);
+ expect(result).not.toBeNull();
+ expect(result!.files).toEqual([filePath]);
+ expect(result!.prompt).toBe(`<file path="${filePath}">\nsample file content\n</file>\n\ndo task`);
+ });
+
+ it("preserves relative paths literally in the delimiter", () => {
+ const result = parseOneShot(["--oneshot", "do task", "--file", "rel/path/to/file.js"], {
+ readFileSync: () => "console.log('hi')",
+ });
+ expect(result!.files).toEqual(["rel/path/to/file.js"]);
+ expect(result!.prompt).toBe(`<file path="rel/path/to/file.js">\nconsole.log('hi')\n</file>\n\ndo task`);
+ });
+
+ it("two --file flags attach in order", () => {
+ const f1 = path.join(tmpDir, "first.txt");
+ const f2 = path.join(tmpDir, "second.txt");
+ fs.writeFileSync(f1, "first file body");
+ fs.writeFileSync(f2, "second file body");
+ const result = parseOneShot(["--oneshot", "compare", "--file", f1, "--file", f2]);
+ expect(result!.files).toEqual([f1, f2]);
+ expect(result!.prompt).toBe(
+ `<file path="${f1}">\nfirst file body\n</file>\n\n<file path="${f2}">\nsecond file body\n</file>\n\ncompare`
+ );
+ });
+
+ it("--file - reads stdin once; a second - throws", () => {
+ const result = parseOneShot(["--oneshot", "summarize", "--file", "-"], { stdin: "stdin stream content" });
+ expect(result!.files).toEqual(["-"]);
+ expect(result!.prompt).toBe(`<file path="-">\nstdin stream content\n</file>\n\nsummarize`);
+
+ expect(() =>
+ parseOneShot(["--oneshot", "summarize", "--file", "-", "--file", "-"], { stdin: "stdin stream content" })
+ ).toThrow(/stdin/i);
+ });
+
+ it("oversized file throws with the file path and the limit in the message", () => {
+ const bigFile = path.join(tmpDir, "oversized.txt");
+ fs.writeFileSync(bigFile, Buffer.alloc(200_001, "a").toString());
+ expect(() => parseOneShot(["--oneshot", "check", "--file", bigFile])).toThrow(
+ new RegExp(`${bigFile.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}.*200000`)
+ );
+
+ const okFile = path.join(tmpDir, "max-size.txt");
+ fs.writeFileSync(okFile, Buffer.alloc(200_000, "b").toString());
+ expect(() => parseOneShot(["--oneshot", "check", "--file", okFile])).not.toThrow();
+ });
+
+ it("missing file throws", () => {
+ const missing = path.join(tmpDir, "nonexistent.txt");
+ expect(() => parseOneShot(["--oneshot", "check", "--file", missing])).toThrow(`${missing}: no such file`);
+ });
+
+ it("--thinking sets thinking=true and leaves prompt untouched", () => {
+ const withThinking = parseOneShot(["--oneshot", "plan architecture", "--thinking"]);
+ expect(withThinking).not.toBeNull();
+ expect(withThinking!.thinking).toBe(true);
+ expect(withThinking!.prompt).toBe("plan architecture");
+
+ const withoutThinking = parseOneShot(["--oneshot", "plan architecture"]);
+ expect(withoutThinking).not.toBeNull();
+ expect(withoutThinking!.thinking).toBe(false);
+ expect(withoutThinking!.prompt).toBe("plan architecture");
+ });
+
+ it("--file without a value throws", () => {
+ expect(() => parseOneShot(["--oneshot", "task", "--file"])).toThrow(/--file requires a path/);
+ expect(() => parseOneShot(["--oneshot", "task", "--file", "--thinking"])).toThrow(/--file requires a path/);
+ expect(() => parseOneShot(["--oneshot", "task", "--file", "--json"])).toThrow(/--file requires a path/);
+ });
+
+ it("enforces maximum cap of 20 files", () => {
+ const argv = ["--oneshot", "task"];
+ for (let i = 0; i < 21; i++) argv.push("--file", `file${i}.txt`);
+ expect(() => parseOneShot(argv, { readFileSync: () => "content" })).toThrow(/maximum of 20 files/);
+ });
+
+ it("documents that one-shot uses the autonomous agent loop and documents new flags", () => {
+ const help = oneShotHelp();
+ expect(help).toContain("same autonomous MSO Agent tool loop");
+ expect(help).toContain("Default approval scope is read");
+ expect(help).toContain("--file <path>");
+ expect(help).toContain("--thinking");
+ // Reworded deliberately: the stream reports reasoning TOKENS, not reasoning text,
+ // so the help must not promise a reasoning block it cannot produce.
+ expect(help).toContain("reports the reasoning TOKENS the provider returned");
+ expect(help).not.toContain("include reasoning blocks in the payload/output");
});
-});
+});
\ No newline at end of file
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index e62ee249..e486f8e7 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -27,6 +27,9 @@ async function runOneShot(opts) {
permission: "ask", pendingApproval: null,
};
session.history.push({ role: "user", text: opts.prompt });
+ // `--thinking` is a REPORTING flag only: the stream exposes reasoning token counts,
+ // not reasoning text, so nothing here changes the turn. Passing `thinking` into
+ // agentRound would be dead config, so the flag is consumed in the payload below.
const result = await agentRound(null, session, null, undefined, null, { quiet: true, approvalScope: opts.approvalScope });
await persistSession(session);
const payload = {
@@ -34,6 +37,12 @@ async function runOneShot(opts) {
model: `${s.config?.provider || ""}/${s.config?.model || ""}`.replace(/^\//, ""),
approvalScope: opts.approvalScope, text: result?.text || "", rounds: result?.rounds || 0,
toolCalls: result?.calls || [], usage: result?.usage || session.usage, routing: session.lastRouting, elapsedMs: result?.elapsedMs || session.lastElapsedMs,
+ // Prove what was actually attached instead of leaving --file unverifiable.
+ ...(opts.files?.length ? { files: opts.files } : {}),
+ // `--thinking` surfaces the reasoning ACCOUNTING the provider really reported.
+ // Streams capture reasoning tokens, not reasoning text, so claiming a reasoning
+ // block here would be invented output.
+ ...(opts.thinking ? { thinking: true, reasoningTokens: (result?.usage ?? session.usage)?.reasoningTokens ?? null } : {}),
...(result?.turnLimitReached ? { turnLimitReached: true } : {}),
};
if (opts.json) process.stdout.write(`${JSON.stringify(payload)}\n`);