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.

refactor: split CLI into bounded command modules

Rahmanc5464a618beb
diff --git a/bin/mso b/bin/mso
index 25d8f1b1..a5f13725 100755
--- a/bin/mso
+++ b/bin/mso
@@ -161,1125 +161,16 @@ need curl; need jq; need realpath; need stat; need mktemp; need sha256sum
# PORT → MSO_PORT → 4005. This keeps non-default installer ports working on Linux
# while WSL/no-systemd users still have an explicit override for manually-started
# runtimes.
-gateway_local_url() {
- local port=""
- if [ -n "${MSO_GATEWAY_LOCAL_URL:-}" ]; then
- printf '%s' "$MSO_GATEWAY_LOCAL_URL"
- return
- fi
- case "$B" in
- http://127.*:*|http://localhost:*|http://\[::1\]:*) printf '%s' "$B"; return ;;
- esac
- if command -v systemctl >/dev/null 2>&1; then
- port=$(systemctl show -p Environment --value mso.service 2>/dev/null \
- | tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)
- fi
- port="${port:-${MSO_PORT:-4005}}"
- [[ "$port" =~ ^[0-9]{1,5}$ ]] || die "invalid MSO gateway port: $port"
- printf 'http://127.0.0.1:%s' "$port"
-}
-
-maybe_update_notice() {
- local verb="$1"
- [ -t 2 ] || return 0
- case "$verb" in update|version|--version|-V|-v|help|-h|--help|completion) return 0 ;; esac
- [ -x "$ROOT/scripts/mso-update" ] || return 0
- MSO_UPDATE_ROOT="$ROOT" "$ROOT/scripts/mso-update" notice || true
-}
-# shellcheck source=scripts/lib/private-state.sh
-. "$ROOT/scripts/lib/private-state.sh"
-# shellcheck source=scripts/lib/runtime-exclusion.sh
-. "$ROOT/scripts/lib/runtime-exclusion.sh"
-
-service_manager_read() {
- local manager="${MSO_SYSTEMCTL_BIN:-systemctl}"
- "$manager" "$@"
-}
-
-service_manager_write() {
- if [ -n "${MSO_SYSTEMCTL_BIN:-}" ]; then "$MSO_SYSTEMCTL_BIN" "$@";
- else sudo systemctl "$@"; fi
-}
-
-require_service_checkout_cli() {
- local configured canonical_root canonical_service
- configured="$(service_manager_read show -p WorkingDirectory --value mso.service 2>/dev/null || true)"
- [ -n "$configured" ] || die "mso.service has no readable WorkingDirectory; refusing lifecycle action"
- canonical_root="$(realpath -e -- "$ROOT" 2>/dev/null || true)"
- canonical_service="$(realpath -e -- "$configured" 2>/dev/null || true)"
- [ -n "$canonical_root" ] && [ -n "$canonical_service" ] \
- || die "cannot canonicalize mso.service WorkingDirectory"
- [ "$canonical_service" = "$canonical_root" ] \
- || die "mso.service belongs to $canonical_service, not this checkout $canonical_root"
-}
-
-service_unit_local_url() {
- local raw port
- raw="$(service_manager_read show -p Environment --value mso.service 2>/dev/null || true)"
- port="$(printf '%s\n' "$raw" | tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)"
- if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then port=4005; fi
- printf 'http://127.0.0.1:%s' "$port"
-}
-
-service_wait_ready() {
- local local_url="$1" attempts="${MSO_SERVICE_READY_ATTEMPTS:-40}" expected_version body i curl_bin="${MSO_CURL_BIN:-curl}"
- [[ "$attempts" =~ ^[0-9]+$ ]] && [ "$attempts" -ge 1 ] && [ "$attempts" -le 120 ] || attempts=40
- expected_version="$(jq -r '.version // empty' "$ROOT/package.json" 2>/dev/null || true)"
- [ -n "$expected_version" ] || return 1
- for ((i = 1; i <= attempts; i++)); do
- body="$("$curl_bin" --noproxy '*' -fsS --connect-timeout 1 --max-time 2 "$local_url/api/health" 2>/dev/null || true)"
- if jq -e --arg version "$expected_version" '
- type == "object" and .status == "ok" and .service == "mso" and
- (.buildId | type == "string" and length > 0) and
- (.buildSha | type == "string" and test("^[0-9a-f]{7,40}$")) and
- .version == $version and has("runtimeInstanceId")
- ' <<<"$body" >/dev/null 2>&1; then
- return 0
- fi
- [ "$i" -ge "$attempts" ] || sleep 0.25
- done
- return 1
-}
-
-service_handoff_marker() {
- local canonical base key dir
- canonical="$(realpath -e -- "$ROOT" 2>/dev/null || true)"
- [ -n "$canonical" ] || die "cannot canonicalize checkout for service handoff"
- base="$(mso_private_state_dir "${MSO_SERVICE_HANDOFF_DIR:-$HOME/.mso/private/service-handoff}")" \
- || die "unsafe service handoff state directory"
- key="$(printf '%s' "$canonical" | sha256sum | awk '{print $1}')"
- [[ "$key" =~ ^[0-9a-f]{64}$ ]] || die "cannot derive service handoff scope"
- dir="$(mso_private_state_dir "$base/$key")" || die "unsafe scoped service handoff directory"
- printf '%s/runtime' "$dir"
-}
-
-service_handoff_fallback_locked() {
- local gateway local_url marker probe out
- SERVICE_FALLBACK_QUIESCED=0
- gateway="${MSO_GATEWAY_BIN:-$ROOT/scripts/mso-gateway}"
- [ -x "$gateway" ] || die "missing gateway lifecycle helper: $gateway"
- local_url="$(service_unit_local_url)"; marker="$(service_handoff_marker)"
- probe="$(MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" \
- "$gateway" runtime-assert-update-safe 2>&1)" || die "cannot hand off service port $local_url: $probe"
- case "$probe" in
- *'runtime: update-owned'*)
- out="$(MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" \
- MSO_GATEWAY_RECOVERY_MARKER="$marker" "$gateway" runtime-stop 2>&1)" \
- || die "could not quiesce gateway-owned fallback at $local_url: $out"
- case "$out" in
- *'runtime: stopped-owned'*|*'runtime: recovered-stale-owned'*|*'runtime: already-down'*) SERVICE_FALLBACK_QUIESCED=1 ;;
- *) die "unexpected fallback handoff result at $local_url: $out" ;;
- esac ;;
- *'runtime: update-safe'*) ;;
- *) die "unexpected service handoff probe at $local_url: $probe" ;;
- esac
- SERVICE_HANDOFF_URL="$local_url"; SERVICE_HANDOFF_MARKER="$marker"
-}
-
-service_restore_fallback_after_failure() {
- local gateway="${MSO_GATEWAY_BIN:-$ROOT/scripts/mso-gateway}"
- [ "${SERVICE_FALLBACK_QUIESCED:-0}" = 1 ] || return 0
- if ! MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$SERVICE_HANDOFF_URL" \
- "$gateway" local-start >/dev/null 2>&1; then
- printf 'mso: service action failed and fallback restore also failed at %s; recovery marker preserved\n' "$SERVICE_HANDOFF_URL" >&2
- return 1
- fi
- mso_private_state_remove_file "$SERVICE_HANDOFF_MARKER" >/dev/null 2>&1 \
- || { printf 'mso: fallback restored but recovery marker could not be cleared\n' >&2; return 1; }
-}
-
-service_lifecycle_safe() {
- local verb="$1" rc=0 active=0
- require_service_checkout_cli
- runtime_exclusion_acquire_shared \
- || die "offline update/deploy is mutating this checkout or another service handoff is active; retry after it finishes"
- service_manager_read is-active --quiet mso.service && active=1 || true
- SERVICE_FALLBACK_QUIESCED=0; SERVICE_HANDOFF_URL=''; SERVICE_HANDOFF_MARKER=''
- [ "$active" = 1 ] || service_handoff_fallback_locked
- service_manager_write "$verb" mso.service || rc=$?
- if [ "$rc" -eq 0 ] && ! service_wait_ready "$(service_unit_local_url)"; then
- printf 'mso: service %s returned success but /api/health did not become ready; restoring fallback if available\n' "$verb" >&2
- rc=24
- # A Type=simple unit can report a successful start before Next later fails.
- # Stop any unhealthy survivor so the quiesced fallback can reclaim its port.
- service_manager_write stop mso.service >/dev/null 2>&1 || true
- fi
- runtime_exclusion_release
- if [ "$rc" -ne 0 ]; then
- service_restore_fallback_after_failure || return 1
- return "$rc"
- fi
- [ -z "${SERVICE_HANDOFF_MARKER:-}" ] || mso_private_state_remove_file "$SERVICE_HANDOFF_MARKER" >/dev/null 2>&1 || true
-}
-
-service_start_safe() { service_lifecycle_safe start; }
-service_restart_safe() { service_lifecycle_safe restart; }
-
-deploy_safe() {
- local local_url helper
- require_service_checkout_cli
- service_manager_read is-active --quiet mso.service \
- || die "mso.service is not active; start the intended service first, then run mso deploy"
- local_url="$(gateway_local_url)"
- # The outer helper owns checkout-wide runtime inventory/quiesce/restore around
- # the in-place build, so deploy never mutates `.next` under a fallback runtime.
- helper="${MSO_SERVICE_UPDATE_BIN:-$ROOT/scripts/mso-service-update}"
- [ -x "$helper" ] || [ -f "$helper" ] || die "missing service deployment helper: $helper"
- MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" /bin/bash "$helper" --rebuild-only
- echo "deployed → $B"
-}
-
-# ── local ops (no HTTP, no login) ───────────────────────────────────────────
-# These edit ~/.mso/auth-devices.json on THIS machine. They are deliberately local
-# (they must keep working while the service is down) — but that makes them the one
-# family of verbs `--base` does not follow. Pointing at a remote host and running
-# `device approve` used to silently edit the LOCAL allowlist and report success,
-# so the operator believed they had approved a device that was still pending.
-dev_script() {
- case "$B" in
- http://127.0.0.1:*|http://localhost:*|http://[::1]:*) ;;
- *) die "device commands edit the LOCAL allowlist (~/.mso/auth-devices.json) and cannot reach $B.
- Run them ON that host, or over ssh: ssh <host> mso device $*" ;;
- esac
- node "$ROOT/scripts/approve-device.js" "$@"
-}
-
-# ── auth ────────────────────────────────────────────────────────────────────
-PASS="${MSO_PASSWORD:-${OS_PASSWORD:-${OS_LOGIN_PASSWORD:-}}}"
-DEV="${MSO_DEVICE:-${OS_DEVICE:-}}"
-# A stable per-host CLI device id, so `mso approve` only ever has to run once.
-DEVF="${MSO_DEVICE_FILE:-$HOME/.mso/cli.device.id}"
-cli_device() {
- [ -n "$DEV" ] && { printf '%s' "$DEV"; return; }
- [ -s "$DEVF" ] || { mkdir -p "$(dirname "$DEVF")"; head -c16 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$DEVF"; chmod 600 "$DEVF"; }
- cat "$DEVF"
-}
-
-# Jar is per-base as well as per-user: switching --base must not reuse a cookie
-# minted for a different origin. Live bearer material belongs only in an owner-only
-# directory, never a predictable shared /tmp name.
-PRIVATE_STATE_ROOT="${MSO_PRIVATE_STATE_DIR:-$HOME/.mso/private}"
-BASE_KEY=$(printf '%s' "$B" | sha256sum | cut -c1-32)
-JAR_REQUESTED="${MSO_JAR:-$PRIVATE_STATE_ROOT/cli/cookies/$BASE_KEY.jar}"
-JAR=$(mso_private_state_ensure_file "$JAR_REQUESTED") || die "refusing unsafe cookie jar: $JAR_REQUESTED"
-
-# proxy.ts blocks mutating /api requests that can't prove same-origin. A browser
-# proves it with Sec-Fetch-Site; the documented fallback for non-browser clients
-# is an Origin whose host matches the Host header — which is exactly what $B is.
-# Sent on every call so `login` works before any session cookie exists.
-ORIGIN=(-H "origin: $B")
-
-login() {
- local d out code body; d=$(cli_device)
- [ -n "$PASS" ] || die "no OS_LOGIN_PASSWORD in $ENVF (or export MSO_PASSWORD)"
- JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- out=$(jq -n --arg p "$PASS" --arg d "$d" '{password:$p,deviceId:$d,deviceLabel:"mso cli"}' \
- | curl -sS -w $'\n%{http_code}' -c "$JAR" -X POST "$B/api/auth/login" \
- "${ORIGIN[@]}" -H 'content-type: application/json' -d @- 2>/dev/null || true)
- code="${out##*$'\n'}"; body="${out%$'\n'*}"
- [ "$code" = "200" ] && return 0
- case "$code" in
- 000|"") die "MSO runtime is not reachable at $B. Run: mso web (local UI) or mso gateway start (temporary public HTTPS)" ;;
- 403) die "device is not approved by the running MSO instance. Check: mso device pending ; then approve the exact id with: mso device approve $d \"mso cli\"" ;;
- 401) die "login password was rejected by the running MSO instance" ;;
- 429) die "login is rate-limited; retry after the server window resets" ;;
- 500) die "running MSO auth is not configured correctly; run: mso doctor" ;;
- *) die "login failed ($code): ${body:-no response body}; run: mso doctor" ;;
- esac
-}
-
-# Request with the cached cookie; on 401/403 (expired) log in once and retry.
-# Login is lazy on purpose: `mso -h`, `mso device …` and `mso service …` are
-# local-only and must keep working while the service is down or unapproved.
-req() {
- local out code body
- JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- [ -s "$JAR" ] || login
- JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
- code="${out##*$'\n'}"; body="${out%$'\n'*}"
- if [ "$code" = "401" ] || [ "$code" = "403" ]; then
- login
- JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
- code="${out##*$'\n'}"; body="${out%$'\n'*}"
- fi
- case "$code" in 2*) printf '%s' "$body" ;; *) die "request failed ($code): $body" ;; esac
-}
-# Binary-safe variant: streams straight to stdout, no capture, no code check.
-reqraw() {
- JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- [ -s "$JAR" ] || login
- JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- curl -fsS -b "$JAR" "${ORIGIN[@]}" "$@"
-}
-
-enc() { jq -rn --arg v "$1" '$v|@uri'; }
-jget() { req "$B$1"; }
-jpost() { req -H 'content-type: application/json' -d "${2:-{\}}" "$B$1"; }
-jdel() { req -X DELETE -H 'content-type: application/json' -d "${2:-{\}}" "$B$1"; }
-# Build a JSON object from k=v pairs (numbers + booleans coerced).
-kv_args() { local j='{}' kv k v; for kv in "$@"; do k="${kv%%=*}"; v="${kv#*=}"
- if [[ "$v" =~ ^-?[0-9]+([.][0-9]+)?$ || "$v" == "true" || "$v" == "false" ]]; then
- j=$(jq -c --arg k "$k" --argjson v "$v" '.+{($k):$v}' <<<"$j")
- else j=$(jq -c --arg k "$k" --arg v "$v" '.+{($k):$v}' <<<"$j"); fi; done; printf '%s' "$j"; }
-json_arg() { jq -e . >/dev/null 2>&1 <<<"${1-}" || die "not valid JSON: ${1-}"; printf '%s' "$1"; }
-
-# POST a JSON value that may contain a credential without putting the JSON in
-# curl's argv. We force a fresh login first so there is no retry that would need to
-# replay consumed stdin. The body exists only in this shell process and the pipe.
-secret_post() {
- local route="$1" body="$2" out code payload
- login
- JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- out=$(printf '%s' "$body" | curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' \
- -H 'content-type: application/json' -d @- "$B$route" || true)
- code="${out##*$'\n'}"; payload="${out%$'\n'*}"
- case "$code" in 2*) printf '%s' "$payload" ;; *) die "request failed ($code): $payload" ;; esac
-}
-
-# Build an outbound A2A credential JSON body while keeping the secret off process argv.
-# Non-secret metadata travels in env vars; the secret is read only from stdin.
-a2a_credential_body() {
- local agent_id="$1" label="$2" kind="$3" header_name="${4-}" scheme_name="${5-}"
- A2A_AGENT_ID="$agent_id" A2A_LABEL="$label" A2A_KIND="$kind" A2A_HEADER_NAME="$header_name" A2A_SCHEME_NAME="$scheme_name" node -e '
- let secret=""; process.stdin.setEncoding("utf8"); process.stdin.on("data",d=>secret+=d); process.stdin.on("end",()=>{
- const body={action:"credential-create",agentId:process.env.A2A_AGENT_ID,label:process.env.A2A_LABEL,kind:process.env.A2A_KIND,secret,activate:true};
- if(process.env.A2A_HEADER_NAME) body.headerName=process.env.A2A_HEADER_NAME;
- if(process.env.A2A_SCHEME_NAME) body.schemeName=process.env.A2A_SCHEME_NAME;
- process.stdout.write(JSON.stringify(body));
- });'
-}
-
-a2a_agent_id() {
- local ref="$1" found
- found="$(jget "/api/v1/a2a" | jq -r --arg q "${ref,,}" '[.agents[] | select((.id|ascii_downcase)==$q or (.alias|ascii_downcase)==$q or (.card.name|ascii_downcase)==$q)] | if length==1 then .[0].id else empty end')"
- [ -n "$found" ] || die "A2A peer not found or ambiguous: $ref"
- printf '%s' "$found"
-}
-
-a2a_agent_schemes() {
- local agent_id="$1"
- jget "/api/v1/a2a" | jq -r --arg id "$agent_id" '.agents[] | select(.id==$id) | .card.securitySchemeNames[]?'
-}
-
-a2a_agent_scheme_json() {
- local agent_id="$1" scheme_name="$2"
- jget "/api/v1/a2a" | jq -c --arg id "$agent_id" --arg scheme "$scheme_name" '.agents[] | select(.id==$id) | (.card.securitySchemes[$scheme] // {})'
-}
-
-tty_ok() { [ -r /dev/tty ] && [ -w /dev/tty ]; }
-tty_print() { if tty_ok; then printf '%s' "$*" > /dev/tty; else printf '%s' "$*"; fi; }
-tty_line() {
- local prompt="$1" default="${2-}" value=""
- if ! tty_ok; then REPLY="$default"; return; fi
- tty_print "$prompt"
- IFS= read -r value < /dev/tty || true
- REPLY="${value:-$default}"
-}
-tty_secret() {
- local prompt="$1" value=""
- tty_ok || die "a terminal is required to enter a secret; run this command interactively"
- tty_print "$prompt"
- stty -echo < /dev/tty
- IFS= read -r value < /dev/tty || true
- stty echo < /dev/tty
- tty_print $'\n'
- REPLY="$value"
-}
-
-ensure_local_cli_device() {
- local d; d=$(cli_device)
- case "$B" in
- http://127.0.0.1:*|http://localhost:*|http://[::1]:*) ;;
- *) return 0 ;;
- esac
- if ! dev_script --is-approved "$d" >/dev/null 2>&1; then
- dev_script "$d" "mso cli" >/dev/null
- [ "${MSO_CLI_QUIET:-0}" = "1" ] || echo " ✓ approved this local CLI device"
- fi
-}
-
-ensure_onboard_runtime() {
- case "$B" in
- http://127.*:*|http://localhost:*|http://\[::1\]:*)
- MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$B" \
- "$ROOT/scripts/mso-gateway" local-start >/dev/null \
- || die "local MSO runtime is not ready. Run: mso update ; then: mso web"
- [ "${MSO_CLI_QUIET:-0}" = "1" ] || echo " ✓ verified local MSO runtime at $B" ;;
- *) return 0 ;;
- esac
-}
-
-onboard_ai() {
- local yes="$1" choice provider key body response interval code url poll
- if [ "$yes" = 1 ]; then
- echo " -- AI provider skipped (-y keeps external accounts unconfigured)"
- return
- fi
- echo
- echo "AI for Alfa"
- echo " 0) Skip for now"
- echo " 1) OpenAI ChatGPT OAuth (Codex consumer backend; no API key)"
- echo " 2) Anthropic API key"
- echo " 3) OpenAI Platform API key"
- echo " 4) OpenRouter API key"
- echo " 5) Google Gemini API key"
- echo " 6) Groq API key"
- echo " 7) xAI API key"
- echo " 8) DeepSeek API key"
- echo " 9) Mistral API key"
- tty_line "Choose [0]: " 0; choice="$REPLY"
- case "$choice" in
- 0|'') echo " -- skipped"; return ;;
- 1)
- response=$(jpost "/api/oauth/openai" '{"action":"start"}')
- code=$(jq -r '.userCode // empty' <<<"$response")
- url=$(jq -r '.verificationUrl // empty' <<<"$response")
- interval=$(jq -r '.intervalMs // 5000' <<<"$response")
- [ -n "$code" ] && [ -n "$url" ] || die "OpenAI OAuth did not return a device code"
- echo
- echo "Open this URL in any browser: $url"
- echo "Enter code: $code"
- echo "Waiting for authorization (Ctrl-C cancels this local wait; it does not expose the code)..."
- while true; do
- sleep "$(( interval / 1000 > 2 ? interval / 1000 : 3 ))"
- poll=$(jpost "/api/oauth/openai" '{"action":"poll"}')
- if [ "$(jq -r '.ok // false' <<<"$poll")" = true ]; then
- echo " ✓ OpenAI connected as $(jq -r '.slug' <<<"$poll")"
- return
- fi
- [ "$(jq -r '.pending // false' <<<"$poll")" = true ] || die "OpenAI OAuth failed: $poll"
- tty_print "."
- done ;;
- 2) provider=anthropic ;;
- 3) provider=openai ;;
- 4) provider=openrouter ;;
- 5) provider=google ;;
- 6) provider=groq ;;
- 7) provider=xai ;;
- 8) provider=deepseek ;;
- 9) provider=mistral ;;
- *) echo " ! unknown choice; skipped"; return ;;
- esac
- echo " $provider uses an API key here (not OAuth). The key is never placed in argv."
- tty_secret "Paste $provider API key: "; key="$REPLY"
- [ -n "$key" ] || { echo " -- empty key; skipped"; return; }
- body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
- secret_post "/api/config" "$body" >/dev/null
- unset key body REPLY
- echo " ✓ $provider configured for Alfa"
-}
-
-onboard_style() {
- local yes="$1" choice style
- if [ "$yes" = 1 ]; then
- echo " -- response preset left unchanged (-y keeps existing/default settings)"
- return
- else
- echo
- echo "Alfa response preset (this is a response style, not a SKILL.md install)"
- echo " 0) Normal / off"
- echo " 1) Caveman — terse fragments, preserve technical substance"
- echo " 2) Ponytail — minimal senior-dev solution, avoid unnecessary code"
- tty_line "Choose [0]: " 0; choice="$REPLY"
- case "$choice" in 1) style=caveman ;; 2) style=ponytail ;; *) style=off ;; esac
- fi
- jpost "/api/config" "$(jq -nc --arg v "$style" '{tokenSaver:$v}')" >/dev/null
- echo " ✓ Alfa response preset: $style"
-}
-
-wait_managed_job() {
- local app="$1" id="$2" since=0 data chunk status next
- echo " installing $app (job $id)..."
- while true; do
- data=$(jget "/api/v1/managed-apps/$(enc "$app")/jobs/$(enc "$id")?since=$since")
- chunk=$(jq -r '.job.log // empty' <<<"$data")
- [ -z "$chunk" ] || printf '%s' "$chunk"
- next=$(jq -r '.job.logOffset // 0' <<<"$data"); since="$next"
- status=$(jq -r '.job.status // "unknown"' <<<"$data")
- case "$status" in
- succeeded) echo " ✓ $app installed"; return ;;
- failed|interrupted) die "$app install ended: $status — $(jq -r '.job.error // "see job log"' <<<"$data")" ;;
- esac
- sleep 2
- done
-}
-
-onboard_apps() {
- local yes="$1" choice apps app response id
- if [ "$yes" = 1 ]; then
- echo " -- optional managed apps skipped (-y uses minimal defaults)"
- return
- fi
- echo
- echo "Optional managed applications"
- echo " These have their own runtime/provider settings; Alfa credentials above do not configure them."
- echo " 0) None"
- echo " 1) Hermes"
- echo " 2) OpenClaw"
- echo " 3) Both"
- tty_line "Choose [0]: " 0; choice="$REPLY"
- case "$choice" in 1) apps="hermes" ;; 2) apps="openclaw" ;; 3) apps="hermes openclaw" ;; *) return ;; esac
- for app in $apps; do
- if jget "/api/v1/managed-apps" | jq -e --arg id "$app" '.apps[] | select(.id==$id and .installed==true)' >/dev/null; then
- echo " ✓ $app already installed"
- continue
- fi
- response=$(jpost "/api/v1/managed-apps/$(enc "$app")/install" '{}')
- id=$(jq -r '.job.id // empty' <<<"$response")
- [ -n "$id" ] || die "could not start $app install: $response"
- wait_managed_job "$app" "$id"
- done
-}
-
-onboard_skills() {
- local yes="$1" choice ids
- echo
- echo "Curated installable skills"
- node "$ROOT/scripts/skill-market.mjs" available
- if [ "$yes" = 1 ]; then
- echo " -- none installed automatically; run: mso skills install ponytail caveman rtk -y"
- return
- fi
- echo "Enter skill ids separated by spaces/commas, 'all', or blank to skip."
- tty_line "Skills: " ""; choice="$REPLY"
- [ -n "$choice" ] || return
- if [ "$choice" = all ]; then ids=$(node "$ROOT/scripts/skill-market.mjs" available --json | jq -r '.skills[].id' | tr '\n' ' ')
- else ids=$(printf '%s' "$choice" | tr ',' ' '); fi
- # The user's selection is the confirmation; suppress per-skill install prompts.
- # shellcheck disable=SC2086
- node "$ROOT/scripts/skill-market.mjs" install $ids -y
-}
-
-run_onboard() {
- local yes=0
- case "${1-}" in -y|--yes) yes=1 ;; "") ;; *) die "usage: mso onboard [-y|--yes]" ;; esac
- echo "MSO onboarding"
- echo "=============="
- ensure_local_cli_device
- ensure_onboard_runtime
- if [ "$yes" = 0 ] && ! tty_ok; then
- die "interactive onboarding needs a terminal; use 'mso onboard -y' for safe minimal defaults"
- fi
- # Runtime liveness was verified without auth above; now prove the approved-device session.
- jget "/api/auth/me" >/dev/null
- onboard_ai "$yes"
- onboard_style "$yes"
- onboard_apps "$yes"
- onboard_infra "$yes"
- onboard_skills "$yes"
- echo
- echo "Onboarding complete."
- echo " mso -h command reference"
- echo " mso doctor verify this install"
- echo " mso skills available installable skills"
- echo " mso config show Alfa provider/style"
- echo " mso provider list Dokploy/Cloudflare/Hostinger state"
- echo " mso launch the interactive MSO Agent"
- echo " mso mapp list Hermes/OpenClaw state"
-}
+# Runtime helpers are split by responsibility; bin/mso remains the entrypoint/dispatcher.
+# shellcheck source=../scripts/cli/runtime.sh
+source "$ROOT/scripts/cli/runtime.sh"
# Terminal agent + infrastructure-provider CLI slice. Sourced only after the
# generic HTTP/auth/onboarding helpers above exist, so it reuses those SSOT seams.
# shellcheck source=../scripts/mso-cli-agent.sh
source "$ROOT/scripts/mso-cli-agent.sh"
-# Print the header block verbatim — stops at the first non-comment line, so the
-# help can never drift out of sync with the comment above.
-usage() { awk 'NR>1 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "$0"; }
-
-# Every verb the dispatch table implements, one per line, aliases split out. Read
-# from the table itself so a new arm can never be missing from did-you-mean.
-verbs() {
- awk '/^cmd="/ { on = 1 }
- on && match($0, /^ [a-zA-Z|-]+\)/) {
- s = substr($0, 3, RLENGTH - 3); gsub(/\|/, "\n", s); print s
- }' "$0"
-}
-
-# One usage string per command group, used by BOTH `--help` and the error path —
-# so the help you get when you ask cannot disagree with the help you get when
-# you're wrong.
-U_camoufox="camoufox status|start|stop|session"
-U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
-U_doctor="doctor [--fix]"
-U_provider="provider list|show <id>|set <dokploy|cloudflare|hostinger>|rm <id>|doctor [id]|projects|zones"
-U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
-U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
-U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
-U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
-U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
-U_service="service status|start|stop|restart|logs [n]"
-U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"
-U_update="update [--rebuild] | status | log"
-U_threads="threads list|show <id>|save <json>|rm <id>"
-U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"
-U_agents="agents list [current-session-id]|send <source-session-id> <target> <message> [message|task]|inbox <session-id> [--all]"
-U_a2a="a2a list|state|sessions|spawn <source-session> <objective> [title]|inbox <session>|discover <url>|add <url> [alias]|rm <target>|send <target> <message> [--wait]|stream <target> <message>|task <target> <taskId> [history]|cancel <target> <taskId>|handoff <target> <objective> [context] [--wait]|local sessions|local handoff <session> <objective>|local spawn <sourceSession> <objective> [title]|local inbox <session>|auth list [target]|auth add <target> [label] [bearer|api-key|oauth2]|auth use <target> <credentialId|none>|auth rm <credentialId>|inbound list|inbound create [label] [read|write|exec]|inbound rm <tokenId>"
-U_memory="memory list|add <text>|rm <id>"
-U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"
-U_prefs="prefs show|set <json>"
-U_models="models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]"
-U_skills="skills list|read <id>|search <query…>|available|info <id>|install <id…> [-y] [--force]|remove <id…> [-y]"
-U_mcp="mcp list|activity [n]|revoke <id>|revoke all"
-U_oauth="oauth <provider> start|poll OAuth currently: openai (ChatGPT Codex)"
-U_audit="audit [n] [prefix] e.g. mso audit 20 exec."
-U_crud="crud list <dir> | get <path> | set <path> <cmd k=v…|text> | del <path> | cmds"
-U_api="api <METHOD> <path> [json] e.g. mso api GET /api/v1/sys/stats"
-
-# `mso <command> --help` — per-command help, resolved before dispatch so no group
-# has to handle the flag itself.
-if [ $# -ge 2 ]; then
- case "$2" in
- -h|--help|help)
- eval "u=\${U_$1-}"
- [ -n "${u-}" ] && { echo "usage: mso $u"; exit 0; }
- # No group usage means a flat verb: show the header line documenting it.
- usage | grep -E "^ +$1( |$)" || usage
- exit 0 ;;
- esac
-fi
-
-cmd="${1:-agent}"; maybe_update_notice "$cmd"; shift || true
-if [ "$cmd" = agent ] || [ "$cmd" = chat ]; then set -- "${AGENT_START_ARGS[@]}" "$@"; fi
-case "$cmd" in
- version|--version|-V|-v)
- app_version="$(jq -r '.version // "unknown"' "$ROOT/package.json" 2>/dev/null || printf unknown)"
- build_sha="$(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || printf unknown)"
- echo "mso CLI $VERSION · app $app_version · build $build_sha (base $B, root $ROOT)"
- exit 0 ;;
-
- # ── files ────────────────────────────────────────────────────────────────
- ls) jget "/api/v1/fs/list?path=$(enc "${1:-~}")" ;;
- cat) jget "/api/v1/fs/read?path=$(enc "${1:?path}")" | jq -r . ;;
- raw) reqraw "$B/api/v1/fs/raw?path=$(enc "${1:?path}")"; exit 0 ;;
- share) reqraw "$B/api/v1/temp-share/$(enc "${1:?temporary link id}")?download=1"; exit 0 ;;
- usage) jget "/api/v1/fs/usage?path=$(enc "${1:-~}")" ;;
- search) jget "/api/v1/fs/search?q=$(enc "${1:?query}")${2:+&root=$(enc "$2")}" ;;
- write) jpost "/api/v1/fs/write" "$(jq -n --arg p "${1:?path}" --arg c "${2-}" '{path:$p,content:$c}')" ;;
- mkdir) jpost "/api/v1/fs/mkdir" "$(jq -n --arg p "${1:?path}" '{path:$p}')" ;;
- rm) jdel "/api/v1/fs/delete" "$(jq -n --arg p "${1:?path}" '{path:$p}')" ;;
- mv) jpost "/api/v1/fs/move" "$(jq -n --arg f "${1:?from}" --arg t "${2:?to}" '{from:$f,to:$t}')" ;;
- cp) jpost "/api/v1/fs/copy" "$(jq -n --arg f "${1:?from}" --arg t "${2:?to}" '{from:$f,to:$t}')" ;;
- zip)
- base="${1:?base dir}"; shift
- [ $# -gt 0 ] || die "usage: mso zip <baseDir> <name…> > out.zip"
- q="base=$(enc "$base")"; for n in "$@"; do q="$q&n=$(enc "$n")"; done
- reqraw "$B/api/v1/fs/zip?$q"; exit 0 ;;
- upload)
- src="${1:?local file}"; dst="${2:?destination dir on the host}"
- [ -f "$src" ] || die "no such local file: $src"
- req -F "dest=$dst" -F "file=@$src" "$B/api/v1/fs/upload" ;;
-
- # ── host ─────────────────────────────────────────────────────────────────
- exec) jpost "/api/v1/exec/run" "$(jq -n --arg c "$*" '{cmd:$c}')" ;;
- stats) jget "/api/v1/sys/stats" ;;
- ps) jget "/api/v1/sys/processes" ;;
- units)
- data=$(jget "/api/v1/sys/services")
- if [ -n "${1-}" ]; then
- jq -r --arg q "${1,,}" '.services[] | select(((.unit+" "+.description+" "+.scope+" "+.active+" "+.sub)|ascii_downcase|contains($q))) | "\(.scope):\(.unit)\t\(.active)/\(.sub)\t\(.description)\(if .controllable then " [allowlisted]" else "" end)"' <<<"$data"
- else
- jq -r '.services[] | "\(.scope):\(.unit)\t\(.active)/\(.sub)\t\(.description)\(if .controllable then " [allowlisted]" else "" end)"' <<<"$data"
- fi ;;
- unit)
- sub="${1:-}"; scope="${2:-}"; unit="${3:-}"
- case "$sub" in
- logs) [ -n "$scope" ] && [ -n "$unit" ] || die "usage: mso $U_unit"
- jget "/api/v1/sys/services/logs?scope=$(enc "$scope")&unit=$(enc "$unit")&limit=$(enc "${4:-120}")" | jq -r '.entries[]?' ;;
- start|stop|restart) [ -n "$scope" ] && [ -n "$unit" ] || die "usage: mso $U_unit"
- jpost "/api/v1/sys/services" "$(jq -n --arg s "$scope" --arg u "$unit" --arg a "$sub" '{scope:$s,unit:$u,action:$a}')" ;;
- *) die "usage: mso $U_unit" ;;
- esac ;;
- packages) jget "/api/v1/sys/packages" ;;
- cleanup) if [ "${1-}" = "--run" ]; then jpost "/api/v1/sys/cleanup"; else jget "/api/v1/sys/cleanup"; fi ;;
- status) jget "/api/status" ;;
- health) jget "/api/auth/me" ;;
-
- # 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)
- fix=0
- case "${1-}" in
- "") ;;
- --fix) fix=1 ;;
- *) die "usage: mso $U_doctor" ;;
- esac
- 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"; }
- browser_origin_ok() {
- case "$1" in
- https://*) return 0 ;;
- http://127.*:*|http://localhost:*|http://\[::1\]:*) return 0 ;;
- *) return 1 ;;
- esac
- }
- doctor_label="mso doctor"; [ "$fix" = 1 ] && doctor_label="$doctor_label --fix"
- echo "$doctor_label (base $B)"
- chk "curl" "command -v curl" "install curl"
- chk "jq" "command -v jq" "install jq"
- chk "node" "command -v node" "install Node >=20.9"
- chk "env file" "[ -f '$ENVF' ]" "no $ENVF — copy .env.example and fill it"
- chk "login password" "[ -n '$PASS' ]" "OS_LOGIN_PASSWORD unset in $ENVF"
- chk "session secret" "[ -n \"\${OS_SESSION_SECRET-}\" ]" "OS_SESSION_SECRET unset in $ENVF"
-
- # Browser login is stricter than CLI reachability: the session cookie is
- # always Secure. Plain HTTP on a server/LAN IP can answer /api/health and even
- # accept the password, but the browser cannot retain the session. Loopback is
- # the development exception. Never auto-create a public tunnel in --fix.
- if browser_origin_ok "$B"; then
- echo " ok login transport — browser must use HTTPS or http://localhost (never plain http://server-ip)"
- else
- printf ' FAIL login transport — browser login requires HTTPS or a loopback URL; use a TLS proxy/gateway, or SSH -L and open http://localhost\n'
- fails=$((fails+1))
- fi
- if [ -n "${OS_PUBLIC_ORIGIN-}" ] && ! browser_origin_ok "$OS_PUBLIC_ORIGIN"; then
- printf ' FAIL public origin — OS_PUBLIC_ORIGIN=%s is not a valid browser login origin; use https://...\n' "$OS_PUBLIC_ORIGIN"
- fails=$((fails+1))
- elif [ -n "${OS_PUBLIC_ORIGIN-}" ]; then
- printf ' ok public origin (%s)\n' "$OS_PUBLIC_ORIGIN"
- fi
-
- # Not a chk with a pass/fail: serving NO managed-app dashboards is supported.
- tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"; dom="${OS_SESSION_COOKIE_DOMAIN-}"
- if [ -n "$tpl" ] && [ -n "$dom" ]; then
- echo " ok app dashboards ($tpl) — after changing this, REBUILD and sign in again"
- elif [ -z "$tpl$dom" ]; then
- echo " -- app dashboards (off: no app host — managed-app windows open on the CLI view)"
- else
- printf ' FAIL app dashboards — set BOTH NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE and OS_SESSION_COOKIE_DOMAIN, or neither\n'
- fails=$((fails+1))
- fi
-
- if ! service_manager_read is-active --quiet mso.service 2>/dev/null; then
- if [ "$fix" = 1 ] && service_manager_read show -p WorkingDirectory --value mso.service 2>/dev/null | grep -q .; then
- if ( service_start_safe >/dev/null 2>&1 ); then fixed "service unit started"; else printf ' FAIL service unit — automatic start failed; run: mso service logs\n'; fails=$((fails+1)); fi
- else
- printf ' FAIL service unit — mso.service not active%s\n' "$([ "$fix" = 1 ] && printf '; no existing unit could be safely started' || printf ' — run: mso doctor --fix or mso service start')"
- fails=$((fails+1))
- fi
- else
- echo " ok service unit"
- fi
- chk "reachable" "curl -fsS --max-time 5 '$B/api/health'" "nothing answering at $B"
-
- d=$(cli_device); device_ready=0
- case "$B" in
- http://127.0.0.1:*|http://localhost:*|http://[::1]:*)
- if dev_script --is-approved "$d" >/dev/null 2>&1; then
- echo " ok device known"; device_ready=1
- elif [ "$fix" = 1 ]; then
- if dev_script "$d" "mso cli" >/dev/null 2>&1; then fixed "local CLI device approved"; device_ready=1
- else printf ' FAIL device known — could not approve the local CLI device; inspect: mso device list\n'; fails=$((fails+1)); fi
- else
- printf ' FAIL device known — this CLI device is not approved; run: mso doctor --fix (or mso device approve %s "mso cli")\n' "$d"
- fails=$((fails+1))
- fi ;;
- *) echo " -- device known (skipped: --base is remote; check it on that host)"; device_ready=1 ;;
- esac
-
- fresh_session_check() {
- mso_private_state_remove_file "$JAR" || return 1
- JAR=$(mso_private_state_ensure_file "$JAR") || return 1
- [ "$(jget /api/auth/me | jq -r .authenticated)" = true ]
- }
- if [ "$device_ready" = 1 ]; then
- if ( fresh_session_check >/dev/null 2>&1 ); then
- [ "$fix" = 1 ] && fixed "session refreshed" || echo " ok session"
- else
- printf ' FAIL session — cannot sign in; verify password, approved device, and browser/CLI origin above\n'
- fails=$((fails+1))
- fi
- else
- printf ' FAIL session — skipped until the local CLI device is approved\n'
- fails=$((fails+1))
- fi
- echo
- if [ "$fix" = 1 ]; then
- echo "--fix only changes safe local state: existing service start, this host's CLI approval, and its cookie jar."
- echo "It never changes DNS, TLS certificates, firewall rules, public exposure, or credentials."
- fi
- [ "$fails" -eq 0 ] && echo "all good." || echo "$fails check(s) failed."
- exit $(( fails > 0 ? 1 : 0 )) ;;
-
- agent|chat) run_agent "$@" ;;
- model) run_model_setup "$@" ;;
- setup) run_onboard "${1-}" ;;
- onboard) run_onboard "${1-}" ;;
- provider|providers) run_provider "$@" ;;
-
- # ── local/public gateway + browser launcher ───────────────────────────────
- gateway) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" "$@" ;;
- web) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" web "$@" ;;
-
- # ── camoufox (the real browser the Browser app drives) ────────────────────
- camoufox)
- case "${1:-status}" in
- status) jget "/api/v1/camoufox/service" ;;
- start) jpost "/api/v1/camoufox/service" '{"action":"start"}' ;;
- stop) jpost "/api/v1/camoufox/service" '{"action":"stop"}' ;;
- session) jget "/api/v1/camoufox/session" ;;
- *) die "usage: mso $U_camoufox" ;;
- esac ;;
-
- # ── managed apps (hermes, openclaw…) ─────────────────────────────────────
- apps) jget "/api/v1/apps" ;;
- mapp)
- sub="${1:-list}"; shift || true
- case "$sub" in
- list) jget "/api/v1/managed-apps" ;;
- show) jget "/api/v1/managed-apps/$(enc "${1:?id}")" ;;
- logs) jget "/api/v1/managed-apps/$(enc "${1:?id}")/logs" ;;
- backups) jget "/api/v1/managed-apps/$(enc "${1:?id}")/backups" ;;
- jobs) jget "/api/v1/managed-apps/$(enc "${1:?id}")/jobs" ;;
- job) jget "/api/v1/managed-apps/$(enc "${1:?id}")/jobs/$(enc "${2:?jobId}")" ;;
- # Cached result only. The live probe is `update <id> check` (POST), gated.
- pending) jget "/api/v1/managed-apps/$(enc "${1:?id}")/update" ;;
- install) jpost "/api/v1/managed-apps/$(enc "${1:?id}")/install" "$(kv_args "${@:2}")" ;;
- update) jpost "/api/v1/managed-apps/$(enc "${1:?id}")/update" "$(kv_args "${@:2}")" ;;
- # start|stop|restart|backup — MANAGED_APP_ACTIONS in lib/managed-apps/types.ts.
- power) [ -n "${2-}" ] || die "usage: mso mapp power <id> <start|stop|restart|backup>"
- jpost "/api/v1/managed-apps/$(enc "${1:?id}")" "$(jq -n --arg a "$2" '{action:$a}')" ;;
- cancel) [ -n "${2-}" ] || die "usage: mso mapp cancel <id> <jobId>"
- jdel "/api/v1/managed-apps/$(enc "${1:?id}")/jobs/$(enc "$2")" ;;
- *) die "usage: mso $U_mapp" ;;
- esac ;;
-
- # ── terminal ─────────────────────────────────────────────────────────────
- term)
- sub="${1:-open}"; shift || true
- case "$sub" in
- # cols/rows are required by the route; a CLI has no viewport, so default to
- # the real terminal's size when there is one and 120x30 when piped.
- open) jpost "/api/v1/term/open" "$(jq -n --arg c "${1-}" \
- --argjson x "${2:-$(tput cols 2>/dev/null || echo 120)}" \
- --argjson y "${3:-$(tput lines 2>/dev/null || echo 30)}" \
- '{cwd:$c,cols:$x,rows:$y}')" ;;
- input) jpost "/api/v1/term/input" "$(jq -n --arg i "${1:?id}" --arg d "${2:?text}" '{id:$i,data:$d}')" ;;
- resize) jpost "/api/v1/term/resize" "$(jq -n --arg i "${1:?id}" --argjson c "${2:?cols}" --argjson r "${3:?rows}" '{id:$i,cols:$c,rows:$r}')" ;;
- stream) reqraw -N "$B/api/v1/term/stream?id=$(enc "${1:?id}")"; exit 0 ;;
- close) jpost "/api/v1/term/close" "$(jq -n --arg i "${1:?id}" '{id:$i}')" ;;
- *) die "usage: mso $U_term" ;;
- esac ;;
-
- # ── assistant / state ────────────────────────────────────────────────────
- ai) jpost "/api/assistant" "$(jq -n --arg m "$*" '{messages:[{role:"user",content:$m}]}')" ;;
- threads)
- case "${1:-list}" in
- list) jget "/api/threads" ;;
- show) jget "/api/threads?id=$(enc "${2:?id}")" ;;
- save) jpost "/api/threads" "${2:?json — {id,messages:[…]}}" ;;
- rm) jdel "/api/threads?id=$(enc "${2:?id}")" ;;
- *) die "usage: mso $U_threads" ;;
- esac ;;
- agent-sessions)
- case "${1:-list}" in
- list) jget "/api/v1/agent-sessions${2:+?limit=$(enc "$2")}" ;;
- show) jget "/api/v1/agent-sessions?id=$(enc "${2:?id}")" ;;
- create) jpost "/api/v1/agent-sessions" "$(jq -n --arg title "${2:-MSO Agent session}" '{action:"create",title:$title}')" ;;
- *) die "usage: mso $U_agent_sessions" ;;
- esac ;;
- agents)
- sub="${1:-list}"; shift || true
- case "$sub" in
- list)
- current="${1:-}"
- if [ -n "$current" ]; then jget "/api/v1/local-agents?session=$(enc "$current")";
- else jget "/api/v1/local-agents"; fi ;;
- send)
- source_id="${1:?source-session-id}"; target="${2:?target}"; message="${3:?message}"; kind="${4:-message}"
- [ "$kind" = "message" ] || [ "$kind" = "task" ] || die "kind must be message or task"
- jpost "/api/v1/local-agents" "$(jq -n --arg sid "$source_id" --arg target "$target" --arg message "$message" --arg kind "$kind" '{action:"send",sessionId:$sid,target:$target,message:$message,kind:$kind}')" ;;
- inbox)
- session_id="${1:?session-id}"; include="${2:-}"
- [ "$include" = "" ] || [ "$include" = "--all" ] || die "usage: mso $U_agents"
- jget "/api/v1/local-agents?inbox=1&session=$(enc "$session_id")$([ "$include" = "--all" ] && printf '&includeRead=1')" ;;
- *) die "usage: mso $U_agents" ;;
- esac ;;
- a2a)
- sub="${1:-list}"; shift || true
- case "$sub" in
- list) jget "/api/v1/a2a" ;;
- state) jget "/api/v1/a2a?action=state" ;;
- sessions) jget "/api/v1/a2a?action=local-sessions" ;;
- discover) jget "/api/v1/a2a?action=discover&url=$(enc "${1:?url}")" ;;
- add|register)
- url="${1:?url}"; alias="${2:-}"
- jpost "/api/v1/a2a" "$(jq -n --arg url "$url" --arg alias "$alias" '{action:"register",url:$url} + (if $alias == "" then {} else {alias:$alias} end)')" ;;
- rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg target "${1:?target}" '{action:"remove",target:$target}')" ;;
- send)
- target="${1:?target}"; message="${2:?message}"; wait="${3:-}"
- [ "$wait" = "" ] || [ "$wait" = "--wait" ] || die "usage: mso $U_a2a"
- jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg message "$message" --arg wait "$wait" '{action:"send",target:$target,message:$message,returnImmediately:($wait != "--wait")}')" ;;
- stream)
- target="${1:?target}"; message="${2:?message}"
- body="$(jq -n --arg target "$target" --arg message "$message" '{action:"stream",target:$target,message:$message}')"
- JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"; [ -s "$JAR" ] || login
- reqraw -N -H 'content-type: application/json' -d "$body" "$B/api/v1/a2a" ;;
- task|status)
- target="${1:?target}"; task_id="${2:?taskId}"; history="${3:-10}"
- [[ "$history" =~ ^[0-9]+$ ]] || die "history must be 0-100"; [ "$history" -le 100 ] || die "history must be 0-100"
- jget "/api/v1/a2a?action=task&target=$(enc "$target")&taskId=$(enc "$task_id")&historyLength=$history" ;;
- cancel) jpost "/api/v1/a2a" "$(jq -n --arg target "${1:?target}" --arg taskId "${2:?taskId}" '{action:"cancel",target:$target,taskId:$taskId}')" ;;
- handoff|delegate)
- target="${1:?target}"; objective="${2:?objective}"; context="${3:-}"; wait="${4:-}"
- if [ "$context" = "--wait" ]; then wait="--wait"; context=""; fi
- [ "$wait" = "" ] || [ "$wait" = "--wait" ] || die "usage: mso $U_a2a"
- jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg objective "$objective" --arg context "$context" --arg wait "$wait" '{action:"handoff",target:$target,objective:$objective,returnImmediately:($wait != "--wait")} + (if $context == "" then {} else {context:$context} end)')" ;;
- spawn)
- source_ref="${1:?sourceSession}"; objective="${2:?objective}"; title="${3:-}"
- jpost "/api/v1/a2a" "$(jq -n --arg sourceSessionRef "$source_ref" --arg objective "$objective" --arg title "$title" '{action:"local-spawn",sourceSessionRef:$sourceSessionRef,objective:$objective} + (if $title == "" then {} else {title:$title} end)')" ;;
- inbox)
- session_ref="${1:?session}"
- jget "/api/v1/a2a?action=local-inbox&session=$(enc "$session_ref")" ;;
- local)
- local_sub="${1:-sessions}"; shift || true
- case "$local_sub" in
- sessions|list) jget "/api/v1/a2a?action=local-sessions" ;;
- handoff|delegate)
- session_ref="${1:?session}"; objective="${2:?objective}"
- jpost "/api/v1/a2a" "$(jq -n --arg sessionRef "$session_ref" --arg objective "$objective" '{action:"local-handoff",sessionRef:$sessionRef,objective:$objective}')" ;;
- spawn)
- source_ref="${1:?sourceSession}"; objective="${2:?objective}"; title="${3:-}"
- jpost "/api/v1/a2a" "$(jq -n --arg sourceSessionRef "$source_ref" --arg objective "$objective" --arg title "$title" '{action:"local-spawn",sourceSessionRef:$sourceSessionRef,objective:$objective} + (if $title == "" then {} else {title:$title} end)')" ;;
- inbox)
- session_ref="${1:?session}"
- jget "/api/v1/a2a?action=local-inbox&session=$(enc "$session_ref")" ;;
- *) die "usage: mso $U_a2a" ;;
- esac ;;
- auth)
- auth_sub="${1:-list}"; shift || true
- case "$auth_sub" in
- list)
- if [ -n "${1-}" ]; then agent_id="$(a2a_agent_id "$1")"; jget "/api/v1/a2a?action=credentials&agentId=$(enc "$agent_id")";
- else jget "/api/v1/a2a?action=credentials"; fi ;;
- add)
- target="${1:?target}"; label="${2:-default}"; kind="${3:-bearer}"
- case "$kind" in bearer|api-key|oauth2) ;; *) die "credential kind must be bearer, api-key, or oauth2" ;; esac
- agent_id="$(a2a_agent_id "$target")"; header_name=""; scheme_name=""
- schemes="$(a2a_agent_schemes "$agent_id")"; scheme_count="$(printf '%s\n' "$schemes" | sed '/^$/d' | wc -l | tr -d ' ')"
- if [ "$scheme_count" -eq 1 ]; then scheme_name="$(printf '%s\n' "$schemes" | sed '/^$/d' | head -1)";
- elif [ "$scheme_count" -gt 1 ]; then
- default_scheme="$(printf '%s\n' "$schemes" | sed '/^$/d' | head -1)"
- tty_line "Agent Card scheme [$default_scheme]: " "$default_scheme"; scheme_name="$REPLY"
- printf '%s\n' "$schemes" | grep -Fxq -- "$scheme_name" || die "unknown Agent Card security scheme: $scheme_name"
- fi
- scheme_json="{}"; [ -z "$scheme_name" ] || scheme_json="$(a2a_agent_scheme_json "$agent_id" "$scheme_name")"
- scheme_kind="$(printf '%s' "$scheme_json" | jq -r '.kind // empty')"
- case "$scheme_kind" in
- api-key)
- [ "$kind" = "api-key" ] || die "Agent Card scheme $scheme_name requires credential kind api-key"
- scheme_location="$(printf '%s' "$scheme_json" | jq -r '.location // empty')"
- [ "$scheme_location" = "header" ] || die "MSO 1.8 supports header API keys only; scheme $scheme_name uses ${scheme_location:-unknown}"
- default_header="$(printf '%s' "$scheme_json" | jq -r '.name // "X-API-Key"')"
- tty_line "API-key header [$default_header]: " "$default_header"; header_name="$REPLY"
- [ "${header_name,,}" = "${default_header,,}" ] || die "API-key header must match Agent Card header: $default_header" ;;
- http)
- http_scheme="$(printf '%s' "$scheme_json" | jq -r '.scheme // empty')"
- [ "${http_scheme,,}" = "bearer" ] || die "unsupported A2A HTTP auth scheme: ${http_scheme:-unknown}"
- [ "$kind" = "bearer" ] || die "Agent Card scheme $scheme_name requires credential kind bearer" ;;
- oauth2|openid)
- [ "$kind" = "oauth2" ] || die "Agent Card scheme $scheme_name requires credential kind oauth2" ;;
- mtls) die "A2A mTLS credential profiles are not supported in MSO 1.8" ;;
- unknown) die "unsupported or invalid A2A security scheme: $scheme_name" ;;
- '')
- if [ "$kind" = "api-key" ]; then tty_line "API-key header [X-API-Key]: " "X-API-Key"; header_name="$REPLY"; fi ;;
- *) die "unsupported A2A security scheme kind: $scheme_kind" ;;
- esac
- tty_secret "Credential secret: "; secret="$REPLY"; [ -n "$secret" ] || die "credential secret is required"
- body="$(printf '%s' "$secret" | a2a_credential_body "$agent_id" "$label" "$kind" "$header_name" "$scheme_name")"; unset secret REPLY
- secret_post "/api/v1/a2a" "$body"; unset body ;;
- use)
- target="${1:?target}"; credential_id="${2:?credentialId or none}"; [ "$credential_id" = "none" ] && credential_id=""
- jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg credentialId "$credential_id" '{action:"credential-use",target:$target,credentialId:$credentialId}')" ;;
- rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg credentialId "${1:?credentialId}" '{action:"credential-remove",credentialId:$credentialId}')" ;;
- *) die "usage: mso $U_a2a" ;;
- esac ;;
- inbound)
- in_sub="${1:-list}"; shift || true
- case "$in_sub" in
- list) jget "/api/v1/a2a?action=credentials" ;;
- create|add)
- label="${1:-peer}"; scope="${2:-read}"; case "$scope" in read|write|exec) ;; *) die "scope must be read, write, or exec" ;; esac
- jpost "/api/v1/a2a" "$(jq -n --arg label "$label" --arg scope "$scope" '{action:"inbound-token-create",label:$label,scope:$scope}')" ;;
- rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg tokenId "${1:?tokenId}" '{action:"inbound-token-remove",tokenId:$tokenId}')" ;;
- *) die "usage: mso $U_a2a" ;;
- esac ;;
- *) die "usage: mso $U_a2a" ;;
- esac ;;
- memory)
- case "${1:-list}" in
- list) jget "/api/memory" ;;
- add) jpost "/api/memory" "$(jq -n --arg t "${2:?text}" '{text:$t}')" ;;
- rm) jdel "/api/memory?id=$(enc "${2:?id}")" ;;
- *) die "usage: mso $U_memory" ;;
- esac ;;
- config)
- case "${1:-show}" in
- show) jget "/api/config" ;;
- set) jpost "/api/config" "$(json_arg "${2:?json, e.g. '{\"model\":\"gpt-5.6\"}'}")" ;;
- key) provider="${2:?provider}"
- case "$provider" in anthropic|openai|openrouter|google|groq|xai|deepseek|mistral) ;;
- *) die "API-key provider must be one of: anthropic openai openrouter google groq xai deepseek mistral" ;; esac
- tty_secret "Paste $provider API key: "; key="$REPLY"
- [ -n "$key" ] || die "empty API key"
- body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
- secret_post "/api/config" "$body"; unset key body REPLY ;;
- style) style="${2:?off|caveman|ponytail}"
- case "$style" in off|caveman|ponytail) ;; *) die "style must be off, caveman or ponytail" ;; esac
- jpost "/api/config" "$(jq -nc --arg v "$style" '{tokenSaver:$v}')" ;;
- rm) jdel "/api/config?provider=$(enc "${2:?provider}")" ;;
- *) die "usage: mso $U_config" ;;
- esac ;;
- prefs)
- case "${1:-show}" in
- show) jget "/api/prefs" ;;
- set) jpost "/api/prefs" "$(json_arg "${2:?json, e.g. '{\"tweaks\":{\"theme\":\"dark\"}}'}")" ;;
- *) die "usage: mso $U_prefs" ;;
- esac ;;
- models) run_models "$@" ;;
- skills)
- case "${1:-list}" in
- list) jget "/api/skills" ;;
- read) [ -n "${2-}" ] || die "usage: mso $U_skills"
- jget "/api/skills?name=$(enc "$2")" ;;
- search) shift; [ $# -gt 0 ] || die "usage: mso $U_skills"
- jget "/api/skills?q=$(enc "$*")" ;;
- available) shift; node "$ROOT/scripts/skill-market.mjs" available "$@" ;;
- info) shift; node "$ROOT/scripts/skill-market.mjs" info "$@" ;;
- install) shift; node "$ROOT/scripts/skill-market.mjs" install "$@" ;;
- remove|rm) shift; node "$ROOT/scripts/skill-market.mjs" remove "$@" ;;
- *) jget "/api/skills?name=$(enc "$1")" ;;
- esac ;;
- # Generated from git subjects by scripts/gen-changelog.mjs; `jq -r` because the
- # value is a markdown document, not a data structure to pretty-print.
- changelog) jget "/api/changelog" | jq -r .markdown ;;
- stock) jget "/api/v1/stock/search?q=$(enc "${1:?query}")&page=${2:-1}" ;;
-
- # ── devices (local file, works even when the service is down) ────────────
- # Both shapes work: `mso devices` reads as a noun, `mso device list` matches the
- # subcommand-group habit every other area here uses (mapp/term/camoufox/service).
- devices|device)
- case "${1:-list}" in
- list) dev_script --list ;;
- pending) dev_script --pending ;;
- approve) [ -n "${2-}" ] || die "usage: mso device approve <deviceId> [label] [--role viewer|operator|owner]"
- dev_script "$2" "${@:3}" ;;
- role) [ -n "${2-}" ] && [ -n "${3-}" ] || die "usage: mso device role <deviceId> <viewer|operator|owner>"
- dev_script --set-role "$2" "$3" ;;
- revoke) [ -n "${2-}" ] || die "usage: mso device revoke <deviceId> | all --yes"
- if [ "$2" = "all" ]; then dev_script --revoke-all "${3-}"
- else dev_script --revoke "$2"; fi ;;
- *) die "usage: mso $U_device" ;;
- esac ;;
- approve) [ -n "${1-}" ] || die "usage: mso approve <deviceId> [label] [--role viewer|operator|owner] (ids: mso device list)"
- dev_script "$1" "${@:2}" ;;
- revoke) [ -n "${1-}" ] || die "usage: mso revoke <deviceId> (ids: mso device list)"
- dev_script --revoke "$1" ;;
- # ── provider OAuth (device-code, NOT a browser redirect) ─────────────────
- oauth)
- p="${1:?provider (e.g. openai)}"; sub="${2:-start}"
- case "$sub" in
- start|poll) jpost "/api/oauth/$(enc "$p")" "$(jq -n --arg a "$sub" '{action:$a}')" ;;
- *) die "usage: mso $U_oauth" ;;
- esac ;;
-
- # ── MCP tokens (the bearers that let ChatGPT et al. drive this host) ─────
- mcp)
- case "${1:-list}" in
- list) jget "/api/mcp/tokens" ;;
- activity) jget "/api/mcp/activity?limit=${2:-80}" ;;
- revoke) [ -n "${2-}" ] || die "usage: mso mcp revoke <id|all> (ids: mso mcp list)"
- jdel "/api/mcp/tokens?id=$(enc "$2")" ;;
- *) die "usage: mso $U_mcp" ;;
- esac ;;
-
- # ── audit trail (the forensic record; MCP writes land here too) ──────────
- audit)
- q="limit=${1:-50}"; [ -n "${2-}" ] && q="$q&prefix=$(enc "$2")"
- jget "/api/v1/sys/audit?$q" ;;
-
- whoami) echo "cli device: $(cli_device)"; jget "/api/auth/me" ;;
- login) mso_private_state_remove_file "$JAR" || die "refusing unsafe cookie jar: $JAR"
- JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
- login; echo "logged in as device $(cli_device)" ;;
- 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)" ;;
-
- # ── service (local systemd) ──────────────────────────────────────────────
- service)
- case "${1:-status}" in
- status) systemctl status --no-pager mso.service ;;
- start) service_start_safe ;;
- stop) sudo systemctl stop mso.service ;;
- restart) service_restart_safe ;;
- logs) journalctl -u mso.service -n "${2:-50}" --no-pager ;;
- *) die "usage: mso $U_service" ;;
- esac ;;
- # NOT `next build` — this is mso.service's WorkingDirectory, and a build here
- # deletes .next under the running process, 404ing every chunk until a restart.
- # verify-build.sh compiles HEAD in a temp dir instead. `deploy` uses the same
- # checkout-wide quiesce/build/restart/restore lifecycle as service self-update.
- build) (cd "$ROOT" && bash scripts/verify-build.sh) ;;
- deploy) deploy_safe ;;
- # The same self-update Settings → About drives, so both surfaces get the same
- # preflight and the same transient-unit handoff (a build spawned from the service
- # would be killed by the restart it performs).
- update) local_url="$(gateway_local_url)"; MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" "$ROOT/scripts/mso-update" "$@" ;;
-
- # ── editor-document CRUD (one pattern, all editor features) ──────────────
- crud)
- sub="${1:-help}"; shift || true
- case "$sub" in
- list) jget "/api/v1/fs/list?path=$(enc "${1:?path}")" ;;
- get) jget "/api/v1/fs/read?path=$(enc "${1:?path}")" | jq -r . ;;
- del) jdel "/api/v1/fs/delete" "$(jq -n --arg p "${1:?path}" '{path:$p}')" ;;
- cmds) jget "/api/v1/editor/exec" | jq -r '.tools[] | " \(.name)\t\(.description)"' ;;
- set)
- path="${1:?path}"; shift; op="${1:?command-or-content}"; shift || true
- if [[ "$op" =~ ^[a-z]+\.[a-zA-Z]+$ ]]; then
- # Editor-doc command → ONE atomic server op: the route reads the doc
- # (or seeds it), applies the command, and writes it back in place.
- a=$(kv_args "$@")
- resp=$(jpost "/api/v1/editor/exec" "$(jq -n --arg p "$path" --arg n "$op" --argjson a "$a" '{path:$p,commands:[{name:$n,args:$a}]}')")
- jq -e '.dimsFallback' >/dev/null 2>&1 <<<"$resp" && echo " ! image dims unknown → defaulted (AVIF/HEIC/TIFF not probed)" >&2
- jq -r '.results[]? | " \(.name) \(if .ok then "ok" else "ERR" end) — \(.result)"' <<<"$resp"
- else
- jpost "/api/v1/fs/write" "$(jq -n --arg p "$path" --arg c "$op${*:+ $*}" '{path:$p,content:$c}')"
- fi ;;
- *) die "usage: mso $U_crud" ;;
- esac ;;
-
- # ── escape hatch: any endpoint at all ────────────────────────────────────
- api)
- m="${1:?METHOD}"; p="${2:?/api/...}"; body="${3-}"
- 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 ;;
- help|-h|--help) usage; exit 0 ;;
- *)
- # Dumping the help with no error line reads like the command worked and just
- # printed something — say what was rejected, and guess before showing the wall.
- echo "mso: unknown command '$cmd'" >&2
- # Match on a 3-char prefix as well as containment, so a transposition or a
- # dropped letter ("servce", "camofox") still finds its verb.
- head3="${cmd:0:3}"
- near=$(verbs | while read -r v; do
- case "$v" in "$cmd"*|*"$cmd"*|"$head3"*) echo " $v" ;; esac
- done)
- [ -n "$near" ] && { echo "did you mean:" >&2; echo "$near" >&2; }
- echo >&2; usage >&2; exit 1 ;;
-esac
-echo
+# shellcheck source=../scripts/cli/commands.sh
+source "$ROOT/scripts/cli/commands.sh"
+mso_cli_main "$@"
diff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.ts
index 2cf6278c..96d54bcb 100644
--- a/bin/mso-update-offline.test.ts
+++ b/bin/mso-update-offline.test.ts
@@ -31,6 +31,15 @@ function fixture() {
"bin/mso",
"scripts/mso-update",
"scripts/mso-cli-agent.sh",
+ "scripts/cli/runtime.sh",
+ "scripts/cli/service.sh",
+ "scripts/cli/transport.sh",
+ "scripts/cli/onboarding.sh",
+ "scripts/cli/commands.sh",
+ "scripts/cli/commands-host.sh",
+ "scripts/cli/commands-runtime.sh",
+ "scripts/cli/commands-state.sh",
+ "scripts/cli/commands-admin.sh",
"scripts/lib/private-state.sh",
"scripts/lib/update-state.sh",
"scripts/lib/runtime-exclusion.sh",
@@ -86,7 +95,7 @@ describe("mso offline update dispatch", () => {
});
it("keeps `mso update run` as a local compatibility alias", () => {
- const cli = fs.readFileSync(path.join(ROOT, "bin/mso"), "utf8");
+ const cli = fs.readFileSync(path.join(ROOT, "scripts/cli/commands-admin.sh"), "utf8");
const updater = fs.readFileSync(path.join(ROOT, "scripts/mso-update"), "utf8");
expect(cli).toMatch(/update\).*scripts\/mso-update/);
expect(updater).toMatch(/case "\$\{1:-run\}" in/);
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index 9a61f747..ad0308fe 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -9,6 +9,17 @@ import { describe, expect, it } from "vitest";
const CLI = path.join(__dirname, "mso");
const run = (...args: string[]) =>
execFileSync(CLI, args, { encoding: "utf8", env: { ...process.env, MSO_ENV: "/dev/null" } });
+const commandOwnerFiles = [
+ "scripts/cli/commands-host.sh",
+ "scripts/cli/commands-runtime.sh",
+ "scripts/cli/commands-state.sh",
+ "scripts/cli/commands-admin.sh",
+];
+const commandOwners = () => {
+ const fs = require("node:fs") as typeof import("node:fs");
+ const repo = path.join(__dirname, "..");
+ return commandOwnerFiles.map((rel) => fs.readFileSync(path.join(repo, rel), "utf8")).join("\n");
+};
describe("bin/mso", () => {
it("labels CLI, app, and build versions instead of presenting one ambiguous number", () => {
@@ -26,8 +37,7 @@ describe("bin/mso", () => {
});
it("documents every verb the dispatch table implements", () => {
- const src = require("node:fs").readFileSync(CLI, "utf8") as string;
- const body = src.slice(src.indexOf('cmd="${1:-agent}"'));
+ const body = commandOwners();
// Case arms look like ` ls)` / ` camoufox)` / ` devices|device)`. Aliases
// are split out too — an alias absent from the help is just as unfindable.
const verbs = [...body.matchAll(/^ {2}([a-z][a-z|-]*)\)/gm)].flatMap((m) => m[1].split("|"));
@@ -81,6 +91,9 @@ describe("bin/mso", () => {
});
const cli = [
fs.readFileSync(CLI, "utf8"),
+ fs.readFileSync(path.join(repo, "scripts/cli/transport.sh"), "utf8"),
+ fs.readFileSync(path.join(repo, "scripts/cli/commands.sh"), "utf8"),
+ ...commandOwnerFiles.map((rel) => fs.readFileSync(path.join(repo, rel), "utf8")),
fs.readFileSync(path.join(repo, "scripts/mso-cli-agent.sh"), "utf8"),
].join("\n");
diff --git a/lib/security/private-shell-state.test.ts b/lib/security/private-shell-state.test.ts
index 70112b3d..8dbfbf97 100644
--- a/lib/security/private-shell-state.test.ts
+++ b/lib/security/private-shell-state.test.ts
@@ -7,6 +7,11 @@ import { afterEach, describe, expect, it } from "vitest";
const ROOT = path.join(__dirname, "../..");
const HELPER = path.join(ROOT, "scripts/lib/private-state.sh");
const CLI = path.join(ROOT, "bin/mso");
+const CLI_MODULES = [
+ "scripts/cli/runtime.sh", "scripts/cli/service.sh", "scripts/cli/transport.sh", "scripts/cli/onboarding.sh",
+ "scripts/cli/commands.sh", "scripts/cli/commands-host.sh", "scripts/cli/commands-runtime.sh",
+ "scripts/cli/commands-state.sh", "scripts/cli/commands-admin.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");
const roots: string[] = [];
@@ -97,7 +102,10 @@ describe("private shell state", () => {
});
it("wires both clients away from shared /tmp defaults and validates every bearer file", () => {
- const cli = fs.readFileSync(CLI, "utf8");
+ const cli = [
+ fs.readFileSync(CLI, "utf8"),
+ fs.readFileSync(path.join(ROOT, "scripts/cli/transport.sh"), "utf8"),
+ ].join("\n");
const editor = fs.readFileSync(EDITOR, "utf8");
expect(cli).toContain("$HOME/.mso/private");
expect(cli).not.toContain('${TMPDIR:-/tmp}/mso-$(id -u)');
@@ -109,7 +117,7 @@ describe("private shell state", () => {
});
it("keeps shell scripts syntactically valid and the ultimate runner self-sufficient", () => {
- for (const script of [HELPER, CLI, EDITOR, ULTIMATE]) {
+ for (const script of [HELPER, CLI, ...CLI_MODULES, EDITOR, ULTIMATE]) {
expect(() => execFileSync("bash", ["-n", script])).not.toThrow();
}
const ultimate = fs.readFileSync(ULTIMATE, "utf8");
diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.sh
new file mode 100755
index 00000000..0753e49d
--- /dev/null
+++ b/scripts/cli/commands-admin.sh
@@ -0,0 +1,117 @@
+#!/usr/bin/env bash
+# Devices, OAuth/MCP/audit, service/update, CRUD and escape-hatch commands.
+mso_cmd_admin() {
+ local cmd="$1"; shift || true
+case "$cmd" in
+ # ── devices (local file, works even when the service is down) ────────────
+ # Both shapes work: `mso devices` reads as a noun, `mso device list` matches the
+ # subcommand-group habit every other area here uses (mapp/term/camoufox/service).
+ devices|device)
+ case "${1:-list}" in
+ list) dev_script --list ;;
+ pending) dev_script --pending ;;
+ approve) [ -n "${2-}" ] || die "usage: mso device approve <deviceId> [label] [--role viewer|operator|owner]"
+ dev_script "$2" "${@:3}" ;;
+ role) [ -n "${2-}" ] && [ -n "${3-}" ] || die "usage: mso device role <deviceId> <viewer|operator|owner>"
+ dev_script --set-role "$2" "$3" ;;
+ revoke) [ -n "${2-}" ] || die "usage: mso device revoke <deviceId> | all --yes"
+ if [ "$2" = "all" ]; then dev_script --revoke-all "${3-}"
+ else dev_script --revoke "$2"; fi ;;
+ *) die "usage: mso $U_device" ;;
+ esac ;;
+ approve) [ -n "${1-}" ] || die "usage: mso approve <deviceId> [label] [--role viewer|operator|owner] (ids: mso device list)"
+ dev_script "$1" "${@:2}" ;;
+ revoke) [ -n "${1-}" ] || die "usage: mso revoke <deviceId> (ids: mso device list)"
+ dev_script --revoke "$1" ;;
+ # ── provider OAuth (device-code, NOT a browser redirect) ─────────────────
+ oauth)
+ p="${1:?provider (e.g. openai)}"; sub="${2:-start}"
+ case "$sub" in
+ start|poll) jpost "/api/oauth/$(enc "$p")" "$(jq -n --arg a "$sub" '{action:$a}')" ;;
+ *) die "usage: mso $U_oauth" ;;
+ esac ;;
+
+ # ── MCP tokens (the bearers that let ChatGPT et al. drive this host) ─────
+ mcp)
+ case "${1:-list}" in
+ list) jget "/api/mcp/tokens" ;;
+ activity) jget "/api/mcp/activity?limit=${2:-80}" ;;
+ revoke) [ -n "${2-}" ] || die "usage: mso mcp revoke <id|all> (ids: mso mcp list)"
+ jdel "/api/mcp/tokens?id=$(enc "$2")" ;;
+ *) die "usage: mso $U_mcp" ;;
+ esac ;;
+
+ # ── audit trail (the forensic record; MCP writes land here too) ──────────
+ audit)
+ q="limit=${1:-50}"; [ -n "${2-}" ] && q="$q&prefix=$(enc "$2")"
+ jget "/api/v1/sys/audit?$q" ;;
+
+ whoami) echo "cli device: $(cli_device)"; jget "/api/auth/me" ;;
+ login) mso_private_state_remove_file "$JAR" || die "refusing unsafe cookie jar: $JAR"
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ login; echo "logged in as device $(cli_device)" ;;
+ 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)" ;;
+
+ # ── service (local systemd) ──────────────────────────────────────────────
+ service)
+ case "${1:-status}" in
+ status) systemctl status --no-pager mso.service ;;
+ start) service_start_safe ;;
+ stop) sudo systemctl stop mso.service ;;
+ restart) service_restart_safe ;;
+ logs) journalctl -u mso.service -n "${2:-50}" --no-pager ;;
+ *) die "usage: mso $U_service" ;;
+ esac ;;
+ # NOT `next build` — this is mso.service's WorkingDirectory, and a build here
+ # deletes .next under the running process, 404ing every chunk until a restart.
+ # verify-build.sh compiles HEAD in a temp dir instead. `deploy` uses the same
+ # checkout-wide quiesce/build/restart/restore lifecycle as service self-update.
+ build) (cd "$ROOT" && bash scripts/verify-build.sh) ;;
+ deploy) deploy_safe ;;
+ # The same self-update Settings → About drives, so both surfaces get the same
+ # preflight and the same transient-unit handoff (a build spawned from the service
+ # would be killed by the restart it performs).
+ update) local_url="$(gateway_local_url)"; MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" "$ROOT/scripts/mso-update" "$@" ;;
+
+ # ── editor-document CRUD (one pattern, all editor features) ──────────────
+ crud)
+ sub="${1:-help}"; shift || true
+ case "$sub" in
+ list) jget "/api/v1/fs/list?path=$(enc "${1:?path}")" ;;
+ get) jget "/api/v1/fs/read?path=$(enc "${1:?path}")" | jq -r . ;;
+ del) jdel "/api/v1/fs/delete" "$(jq -n --arg p "${1:?path}" '{path:$p}')" ;;
+ cmds) jget "/api/v1/editor/exec" | jq -r '.tools[] | " \(.name)\t\(.description)"' ;;
+ set)
+ path="${1:?path}"; shift; op="${1:?command-or-content}"; shift || true
+ if [[ "$op" =~ ^[a-z]+\.[a-zA-Z]+$ ]]; then
+ # Editor-doc command → ONE atomic server op: the route reads the doc
+ # (or seeds it), applies the command, and writes it back in place.
+ a=$(kv_args "$@")
+ resp=$(jpost "/api/v1/editor/exec" "$(jq -n --arg p "$path" --arg n "$op" --argjson a "$a" '{path:$p,commands:[{name:$n,args:$a}]}')")
+ jq -e '.dimsFallback' >/dev/null 2>&1 <<<"$resp" && echo " ! image dims unknown → defaulted (AVIF/HEIC/TIFF not probed)" >&2
+ jq -r '.results[]? | " \(.name) \(if .ok then "ok" else "ERR" end) — \(.result)"' <<<"$resp"
+ else
+ jpost "/api/v1/fs/write" "$(jq -n --arg p "$path" --arg c "$op${*:+ $*}" '{path:$p,content:$c}')"
+ fi ;;
+ *) die "usage: mso $U_crud" ;;
+ esac ;;
+
+ # ── escape hatch: any endpoint at all ────────────────────────────────────
+ api)
+ m="${1:?METHOD}"; p="${2:?/api/...}"; body="${3-}"
+ 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 ;;
+ *) 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
new file mode 100755
index 00000000..27c4c7aa
--- /dev/null
+++ b/scripts/cli/commands-host.sh
@@ -0,0 +1,167 @@
+#!/usr/bin/env bash
+# Files, host inspection, health and doctor commands.
+mso_cmd_host() {
+ local cmd="$1"; shift || true
+case "$cmd" in
+ version|--version|-V|-v)
+ app_version="$(jq -r '.version // "unknown"' "$ROOT/package.json" 2>/dev/null || printf unknown)"
+ build_sha="$(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || printf unknown)"
+ echo "mso CLI $VERSION · app $app_version · build $build_sha (base $B, root $ROOT)"
+ exit 0 ;;
+
+ # ── files ────────────────────────────────────────────────────────────────
+ ls) jget "/api/v1/fs/list?path=$(enc "${1:-~}")" ;;
+ cat) jget "/api/v1/fs/read?path=$(enc "${1:?path}")" | jq -r . ;;
+ raw) reqraw "$B/api/v1/fs/raw?path=$(enc "${1:?path}")"; exit 0 ;;
+ share) reqraw "$B/api/v1/temp-share/$(enc "${1:?temporary link id}")?download=1"; exit 0 ;;
+ usage) jget "/api/v1/fs/usage?path=$(enc "${1:-~}")" ;;
+ search) jget "/api/v1/fs/search?q=$(enc "${1:?query}")${2:+&root=$(enc "$2")}" ;;
+ write) jpost "/api/v1/fs/write" "$(jq -n --arg p "${1:?path}" --arg c "${2-}" '{path:$p,content:$c}')" ;;
+ mkdir) jpost "/api/v1/fs/mkdir" "$(jq -n --arg p "${1:?path}" '{path:$p}')" ;;
+ rm) jdel "/api/v1/fs/delete" "$(jq -n --arg p "${1:?path}" '{path:$p}')" ;;
+ mv) jpost "/api/v1/fs/move" "$(jq -n --arg f "${1:?from}" --arg t "${2:?to}" '{from:$f,to:$t}')" ;;
+ cp) jpost "/api/v1/fs/copy" "$(jq -n --arg f "${1:?from}" --arg t "${2:?to}" '{from:$f,to:$t}')" ;;
+ zip)
+ base="${1:?base dir}"; shift
+ [ $# -gt 0 ] || die "usage: mso zip <baseDir> <name…> > out.zip"
+ q="base=$(enc "$base")"; for n in "$@"; do q="$q&n=$(enc "$n")"; done
+ reqraw "$B/api/v1/fs/zip?$q"; exit 0 ;;
+ upload)
+ src="${1:?local file}"; dst="${2:?destination dir on the host}"
+ [ -f "$src" ] || die "no such local file: $src"
+ req -F "dest=$dst" -F "file=@$src" "$B/api/v1/fs/upload" ;;
+
+ # ── host ─────────────────────────────────────────────────────────────────
+ exec) jpost "/api/v1/exec/run" "$(jq -n --arg c "$*" '{cmd:$c}')" ;;
+ stats) jget "/api/v1/sys/stats" ;;
+ ps) jget "/api/v1/sys/processes" ;;
+ units)
+ data=$(jget "/api/v1/sys/services")
+ if [ -n "${1-}" ]; then
+ jq -r --arg q "${1,,}" '.services[] | select(((.unit+" "+.description+" "+.scope+" "+.active+" "+.sub)|ascii_downcase|contains($q))) | "\(.scope):\(.unit)\t\(.active)/\(.sub)\t\(.description)\(if .controllable then " [allowlisted]" else "" end)"' <<<"$data"
+ else
+ jq -r '.services[] | "\(.scope):\(.unit)\t\(.active)/\(.sub)\t\(.description)\(if .controllable then " [allowlisted]" else "" end)"' <<<"$data"
+ fi ;;
+ unit)
+ sub="${1:-}"; scope="${2:-}"; unit="${3:-}"
+ case "$sub" in
+ logs) [ -n "$scope" ] && [ -n "$unit" ] || die "usage: mso $U_unit"
+ jget "/api/v1/sys/services/logs?scope=$(enc "$scope")&unit=$(enc "$unit")&limit=$(enc "${4:-120}")" | jq -r '.entries[]?' ;;
+ start|stop|restart) [ -n "$scope" ] && [ -n "$unit" ] || die "usage: mso $U_unit"
+ jpost "/api/v1/sys/services" "$(jq -n --arg s "$scope" --arg u "$unit" --arg a "$sub" '{scope:$s,unit:$u,action:$a}')" ;;
+ *) die "usage: mso $U_unit" ;;
+ esac ;;
+ packages) jget "/api/v1/sys/packages" ;;
+ cleanup) if [ "${1-}" = "--run" ]; then jpost "/api/v1/sys/cleanup"; else jget "/api/v1/sys/cleanup"; fi ;;
+ status) jget "/api/status" ;;
+ health) jget "/api/auth/me" ;;
+
+ # 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)
+ fix=0
+ case "${1-}" in
+ "") ;;
+ --fix) fix=1 ;;
+ *) die "usage: mso $U_doctor" ;;
+ esac
+ 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"; }
+ browser_origin_ok() {
+ case "$1" in
+ https://*) return 0 ;;
+ http://127.*:*|http://localhost:*|http://\[::1\]:*) return 0 ;;
+ *) return 1 ;;
+ esac
+ }
+ doctor_label="mso doctor"; [ "$fix" = 1 ] && doctor_label="$doctor_label --fix"
+ echo "$doctor_label (base $B)"
+ chk "curl" "command -v curl" "install curl"
+ chk "jq" "command -v jq" "install jq"
+ chk "node" "command -v node" "install Node >=20.9"
+ chk "env file" "[ -f '$ENVF' ]" "no $ENVF — copy .env.example and fill it"
+ chk "login password" "[ -n '$PASS' ]" "OS_LOGIN_PASSWORD unset in $ENVF"
+ chk "session secret" "[ -n \"\${OS_SESSION_SECRET-}\" ]" "OS_SESSION_SECRET unset in $ENVF"
+
+ # Browser login is stricter than CLI reachability: the session cookie is
+ # always Secure. Plain HTTP on a server/LAN IP can answer /api/health and even
+ # accept the password, but the browser cannot retain the session. Loopback is
+ # the development exception. Never auto-create a public tunnel in --fix.
+ if browser_origin_ok "$B"; then
+ echo " ok login transport — browser must use HTTPS or http://localhost (never plain http://server-ip)"
+ else
+ printf ' FAIL login transport — browser login requires HTTPS or a loopback URL; use a TLS proxy/gateway, or SSH -L and open http://localhost\n'
+ fails=$((fails+1))
+ fi
+ if [ -n "${OS_PUBLIC_ORIGIN-}" ] && ! browser_origin_ok "$OS_PUBLIC_ORIGIN"; then
+ printf ' FAIL public origin — OS_PUBLIC_ORIGIN=%s is not a valid browser login origin; use https://...\n' "$OS_PUBLIC_ORIGIN"
+ fails=$((fails+1))
+ elif [ -n "${OS_PUBLIC_ORIGIN-}" ]; then
+ printf ' ok public origin (%s)\n' "$OS_PUBLIC_ORIGIN"
+ fi
+
+ # Not a chk with a pass/fail: serving NO managed-app dashboards is supported.
+ tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"; dom="${OS_SESSION_COOKIE_DOMAIN-}"
+ if [ -n "$tpl" ] && [ -n "$dom" ]; then
+ echo " ok app dashboards ($tpl) — after changing this, REBUILD and sign in again"
+ elif [ -z "$tpl$dom" ]; then
+ echo " -- app dashboards (off: no app host — managed-app windows open on the CLI view)"
+ else
+ printf ' FAIL app dashboards — set BOTH NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE and OS_SESSION_COOKIE_DOMAIN, or neither\n'
+ fails=$((fails+1))
+ fi
+
+ if ! service_manager_read is-active --quiet mso.service 2>/dev/null; then
+ if [ "$fix" = 1 ] && service_manager_read show -p WorkingDirectory --value mso.service 2>/dev/null | grep -q .; then
+ if ( service_start_safe >/dev/null 2>&1 ); then fixed "service unit started"; else printf ' FAIL service unit — automatic start failed; run: mso service logs\n'; fails=$((fails+1)); fi
+ else
+ printf ' FAIL service unit — mso.service not active%s\n' "$([ "$fix" = 1 ] && printf '; no existing unit could be safely started' || printf ' — run: mso doctor --fix or mso service start')"
+ fails=$((fails+1))
+ fi
+ else
+ echo " ok service unit"
+ fi
+ chk "reachable" "curl -fsS --max-time 5 '$B/api/health'" "nothing answering at $B"
+
+ d=$(cli_device); device_ready=0
+ case "$B" in
+ http://127.0.0.1:*|http://localhost:*|http://[::1]:*)
+ if dev_script --is-approved "$d" >/dev/null 2>&1; then
+ echo " ok device known"; device_ready=1
+ elif [ "$fix" = 1 ]; then
+ if dev_script "$d" "mso cli" >/dev/null 2>&1; then fixed "local CLI device approved"; device_ready=1
+ else printf ' FAIL device known — could not approve the local CLI device; inspect: mso device list\n'; fails=$((fails+1)); fi
+ else
+ printf ' FAIL device known — this CLI device is not approved; run: mso doctor --fix (or mso device approve %s "mso cli")\n' "$d"
+ fails=$((fails+1))
+ fi ;;
+ *) echo " -- device known (skipped: --base is remote; check it on that host)"; device_ready=1 ;;
+ esac
+
+ fresh_session_check() {
+ mso_private_state_remove_file "$JAR" || return 1
+ JAR=$(mso_private_state_ensure_file "$JAR") || return 1
+ [ "$(jget /api/auth/me | jq -r .authenticated)" = true ]
+ }
+ if [ "$device_ready" = 1 ]; then
+ if ( fresh_session_check >/dev/null 2>&1 ); then
+ [ "$fix" = 1 ] && fixed "session refreshed" || echo " ok session"
+ else
+ printf ' FAIL session — cannot sign in; verify password, approved device, and browser/CLI origin above\n'
+ fails=$((fails+1))
+ fi
+ else
+ printf ' FAIL session — skipped until the local CLI device is approved\n'
+ fails=$((fails+1))
+ fi
+ echo
+ if [ "$fix" = 1 ]; then
+ echo "--fix only changes safe local state: existing service start, this host's CLI approval, and its cookie jar."
+ echo "It never changes DNS, TLS certificates, firewall rules, public exposure, or credentials."
+ fi
+ [ "$fails" -eq 0 ] && echo "all good." || echo "$fails check(s) failed."
+ exit $(( fails > 0 ? 1 : 0 )) ;;
+ *) die "internal CLI routing error: $cmd reached the wrong command family" ;;
+esac
+}
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
new file mode 100755
index 00000000..71cdc19a
--- /dev/null
+++ b/scripts/cli/commands-runtime.sh
@@ -0,0 +1,67 @@
+#!/usr/bin/env bash
+# Agent/provider/gateway/browser/managed-app/terminal commands.
+mso_cmd_runtime() {
+ local cmd="$1"; shift || true
+case "$cmd" in
+ agent|chat) run_agent "$@" ;;
+ model) run_model_setup "$@" ;;
+ setup) run_onboard "${1-}" ;;
+ onboard) run_onboard "${1-}" ;;
+ provider|providers) run_provider "$@" ;;
+
+ # ── local/public gateway + browser launcher ───────────────────────────────
+ gateway) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" "$@" ;;
+ web) local_url="$(gateway_local_url)"; MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" "$ROOT/scripts/mso-gateway" web "$@" ;;
+
+ # ── camoufox (the real browser the Browser app drives) ────────────────────
+ camoufox)
+ case "${1:-status}" in
+ status) jget "/api/v1/camoufox/service" ;;
+ start) jpost "/api/v1/camoufox/service" '{"action":"start"}' ;;
+ stop) jpost "/api/v1/camoufox/service" '{"action":"stop"}' ;;
+ session) jget "/api/v1/camoufox/session" ;;
+ *) die "usage: mso $U_camoufox" ;;
+ esac ;;
+
+ # ── managed apps (hermes, openclaw…) ─────────────────────────────────────
+ apps) jget "/api/v1/apps" ;;
+ mapp)
+ sub="${1:-list}"; shift || true
+ case "$sub" in
+ list) jget "/api/v1/managed-apps" ;;
+ show) jget "/api/v1/managed-apps/$(enc "${1:?id}")" ;;
+ logs) jget "/api/v1/managed-apps/$(enc "${1:?id}")/logs" ;;
+ backups) jget "/api/v1/managed-apps/$(enc "${1:?id}")/backups" ;;
+ jobs) jget "/api/v1/managed-apps/$(enc "${1:?id}")/jobs" ;;
+ job) jget "/api/v1/managed-apps/$(enc "${1:?id}")/jobs/$(enc "${2:?jobId}")" ;;
+ # Cached result only. The live probe is `update <id> check` (POST), gated.
+ pending) jget "/api/v1/managed-apps/$(enc "${1:?id}")/update" ;;
+ install) jpost "/api/v1/managed-apps/$(enc "${1:?id}")/install" "$(kv_args "${@:2}")" ;;
+ update) jpost "/api/v1/managed-apps/$(enc "${1:?id}")/update" "$(kv_args "${@:2}")" ;;
+ # start|stop|restart|backup — MANAGED_APP_ACTIONS in lib/managed-apps/types.ts.
+ power) [ -n "${2-}" ] || die "usage: mso mapp power <id> <start|stop|restart|backup>"
+ jpost "/api/v1/managed-apps/$(enc "${1:?id}")" "$(jq -n --arg a "$2" '{action:$a}')" ;;
+ cancel) [ -n "${2-}" ] || die "usage: mso mapp cancel <id> <jobId>"
+ jdel "/api/v1/managed-apps/$(enc "${1:?id}")/jobs/$(enc "$2")" ;;
+ *) die "usage: mso $U_mapp" ;;
+ esac ;;
+
+ # ── terminal ─────────────────────────────────────────────────────────────
+ term)
+ sub="${1:-open}"; shift || true
+ case "$sub" in
+ # cols/rows are required by the route; a CLI has no viewport, so default to
+ # the real terminal's size when there is one and 120x30 when piped.
+ open) jpost "/api/v1/term/open" "$(jq -n --arg c "${1-}" \
+ --argjson x "${2:-$(tput cols 2>/dev/null || echo 120)}" \
+ --argjson y "${3:-$(tput lines 2>/dev/null || echo 30)}" \
+ '{cwd:$c,cols:$x,rows:$y}')" ;;
+ input) jpost "/api/v1/term/input" "$(jq -n --arg i "${1:?id}" --arg d "${2:?text}" '{id:$i,data:$d}')" ;;
+ resize) jpost "/api/v1/term/resize" "$(jq -n --arg i "${1:?id}" --argjson c "${2:?cols}" --argjson r "${3:?rows}" '{id:$i,cols:$c,rows:$r}')" ;;
+ stream) reqraw -N "$B/api/v1/term/stream?id=$(enc "${1:?id}")"; exit 0 ;;
+ close) jpost "/api/v1/term/close" "$(jq -n --arg i "${1:?id}" '{id:$i}')" ;;
+ *) die "usage: mso $U_term" ;;
+ esac ;;
+ *) die "internal CLI routing error: $cmd reached the wrong command family" ;;
+esac
+}
diff --git a/scripts/cli/commands-state.sh b/scripts/cli/commands-state.sh
new file mode 100755
index 00000000..001348e8
--- /dev/null
+++ b/scripts/cli/commands-state.sh
@@ -0,0 +1,201 @@
+#!/usr/bin/env bash
+# Assistant, sessions, A2A, memory/config/skills state commands.
+mso_cmd_state() {
+ local cmd="$1"; shift || true
+case "$cmd" in
+ # ── assistant / state ────────────────────────────────────────────────────
+ ai) jpost "/api/assistant" "$(jq -n --arg m "$*" '{messages:[{role:"user",content:$m}]}')" ;;
+ threads)
+ case "${1:-list}" in
+ list) jget "/api/threads" ;;
+ show) jget "/api/threads?id=$(enc "${2:?id}")" ;;
+ save) jpost "/api/threads" "${2:?json — {id,messages:[…]}}" ;;
+ rm) jdel "/api/threads?id=$(enc "${2:?id}")" ;;
+ *) die "usage: mso $U_threads" ;;
+ esac ;;
+ agent-sessions)
+ case "${1:-list}" in
+ list) jget "/api/v1/agent-sessions${2:+?limit=$(enc "$2")}" ;;
+ show) jget "/api/v1/agent-sessions?id=$(enc "${2:?id}")" ;;
+ create) jpost "/api/v1/agent-sessions" "$(jq -n --arg title "${2:-MSO Agent session}" '{action:"create",title:$title}')" ;;
+ *) die "usage: mso $U_agent_sessions" ;;
+ esac ;;
+ agents)
+ sub="${1:-list}"; shift || true
+ case "$sub" in
+ list)
+ current="${1:-}"
+ if [ -n "$current" ]; then jget "/api/v1/local-agents?session=$(enc "$current")";
+ else jget "/api/v1/local-agents"; fi ;;
+ send)
+ source_id="${1:?source-session-id}"; target="${2:?target}"; message="${3:?message}"; kind="${4:-message}"
+ [ "$kind" = "message" ] || [ "$kind" = "task" ] || die "kind must be message or task"
+ jpost "/api/v1/local-agents" "$(jq -n --arg sid "$source_id" --arg target "$target" --arg message "$message" --arg kind "$kind" '{action:"send",sessionId:$sid,target:$target,message:$message,kind:$kind}')" ;;
+ inbox)
+ session_id="${1:?session-id}"; include="${2:-}"
+ [ "$include" = "" ] || [ "$include" = "--all" ] || die "usage: mso $U_agents"
+ jget "/api/v1/local-agents?inbox=1&session=$(enc "$session_id")$([ "$include" = "--all" ] && printf '&includeRead=1')" ;;
+ *) die "usage: mso $U_agents" ;;
+ esac ;;
+ a2a)
+ sub="${1:-list}"; shift || true
+ case "$sub" in
+ list) jget "/api/v1/a2a" ;;
+ state) jget "/api/v1/a2a?action=state" ;;
+ sessions) jget "/api/v1/a2a?action=local-sessions" ;;
+ discover) jget "/api/v1/a2a?action=discover&url=$(enc "${1:?url}")" ;;
+ add|register)
+ url="${1:?url}"; alias="${2:-}"
+ jpost "/api/v1/a2a" "$(jq -n --arg url "$url" --arg alias "$alias" '{action:"register",url:$url} + (if $alias == "" then {} else {alias:$alias} end)')" ;;
+ rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg target "${1:?target}" '{action:"remove",target:$target}')" ;;
+ send)
+ target="${1:?target}"; message="${2:?message}"; wait="${3:-}"
+ [ "$wait" = "" ] || [ "$wait" = "--wait" ] || die "usage: mso $U_a2a"
+ jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg message "$message" --arg wait "$wait" '{action:"send",target:$target,message:$message,returnImmediately:($wait != "--wait")}')" ;;
+ stream)
+ target="${1:?target}"; message="${2:?message}"
+ body="$(jq -n --arg target "$target" --arg message "$message" '{action:"stream",target:$target,message:$message}')"
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"; [ -s "$JAR" ] || login
+ reqraw -N -H 'content-type: application/json' -d "$body" "$B/api/v1/a2a" ;;
+ task|status)
+ target="${1:?target}"; task_id="${2:?taskId}"; history="${3:-10}"
+ [[ "$history" =~ ^[0-9]+$ ]] || die "history must be 0-100"; [ "$history" -le 100 ] || die "history must be 0-100"
+ jget "/api/v1/a2a?action=task&target=$(enc "$target")&taskId=$(enc "$task_id")&historyLength=$history" ;;
+ cancel) jpost "/api/v1/a2a" "$(jq -n --arg target "${1:?target}" --arg taskId "${2:?taskId}" '{action:"cancel",target:$target,taskId:$taskId}')" ;;
+ handoff|delegate)
+ target="${1:?target}"; objective="${2:?objective}"; context="${3:-}"; wait="${4:-}"
+ if [ "$context" = "--wait" ]; then wait="--wait"; context=""; fi
+ [ "$wait" = "" ] || [ "$wait" = "--wait" ] || die "usage: mso $U_a2a"
+ jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg objective "$objective" --arg context "$context" --arg wait "$wait" '{action:"handoff",target:$target,objective:$objective,returnImmediately:($wait != "--wait")} + (if $context == "" then {} else {context:$context} end)')" ;;
+ spawn)
+ source_ref="${1:?sourceSession}"; objective="${2:?objective}"; title="${3:-}"
+ jpost "/api/v1/a2a" "$(jq -n --arg sourceSessionRef "$source_ref" --arg objective "$objective" --arg title "$title" '{action:"local-spawn",sourceSessionRef:$sourceSessionRef,objective:$objective} + (if $title == "" then {} else {title:$title} end)')" ;;
+ inbox)
+ session_ref="${1:?session}"
+ jget "/api/v1/a2a?action=local-inbox&session=$(enc "$session_ref")" ;;
+ local)
+ local_sub="${1:-sessions}"; shift || true
+ case "$local_sub" in
+ sessions|list) jget "/api/v1/a2a?action=local-sessions" ;;
+ handoff|delegate)
+ session_ref="${1:?session}"; objective="${2:?objective}"
+ jpost "/api/v1/a2a" "$(jq -n --arg sessionRef "$session_ref" --arg objective "$objective" '{action:"local-handoff",sessionRef:$sessionRef,objective:$objective}')" ;;
+ spawn)
+ source_ref="${1:?sourceSession}"; objective="${2:?objective}"; title="${3:-}"
+ jpost "/api/v1/a2a" "$(jq -n --arg sourceSessionRef "$source_ref" --arg objective "$objective" --arg title "$title" '{action:"local-spawn",sourceSessionRef:$sourceSessionRef,objective:$objective} + (if $title == "" then {} else {title:$title} end)')" ;;
+ inbox)
+ session_ref="${1:?session}"
+ jget "/api/v1/a2a?action=local-inbox&session=$(enc "$session_ref")" ;;
+ *) die "usage: mso $U_a2a" ;;
+ esac ;;
+ auth)
+ auth_sub="${1:-list}"; shift || true
+ case "$auth_sub" in
+ list)
+ if [ -n "${1-}" ]; then agent_id="$(a2a_agent_id "$1")"; jget "/api/v1/a2a?action=credentials&agentId=$(enc "$agent_id")";
+ else jget "/api/v1/a2a?action=credentials"; fi ;;
+ add)
+ target="${1:?target}"; label="${2:-default}"; kind="${3:-bearer}"
+ case "$kind" in bearer|api-key|oauth2) ;; *) die "credential kind must be bearer, api-key, or oauth2" ;; esac
+ agent_id="$(a2a_agent_id "$target")"; header_name=""; scheme_name=""
+ schemes="$(a2a_agent_schemes "$agent_id")"; scheme_count="$(printf '%s\n' "$schemes" | sed '/^$/d' | wc -l | tr -d ' ')"
+ if [ "$scheme_count" -eq 1 ]; then scheme_name="$(printf '%s\n' "$schemes" | sed '/^$/d' | head -1)";
+ elif [ "$scheme_count" -gt 1 ]; then
+ default_scheme="$(printf '%s\n' "$schemes" | sed '/^$/d' | head -1)"
+ tty_line "Agent Card scheme [$default_scheme]: " "$default_scheme"; scheme_name="$REPLY"
+ printf '%s\n' "$schemes" | grep -Fxq -- "$scheme_name" || die "unknown Agent Card security scheme: $scheme_name"
+ fi
+ scheme_json="{}"; [ -z "$scheme_name" ] || scheme_json="$(a2a_agent_scheme_json "$agent_id" "$scheme_name")"
+ scheme_kind="$(printf '%s' "$scheme_json" | jq -r '.kind // empty')"
+ case "$scheme_kind" in
+ api-key)
+ [ "$kind" = "api-key" ] || die "Agent Card scheme $scheme_name requires credential kind api-key"
+ scheme_location="$(printf '%s' "$scheme_json" | jq -r '.location // empty')"
+ [ "$scheme_location" = "header" ] || die "MSO 1.8 supports header API keys only; scheme $scheme_name uses ${scheme_location:-unknown}"
+ default_header="$(printf '%s' "$scheme_json" | jq -r '.name // "X-API-Key"')"
+ tty_line "API-key header [$default_header]: " "$default_header"; header_name="$REPLY"
+ [ "${header_name,,}" = "${default_header,,}" ] || die "API-key header must match Agent Card header: $default_header" ;;
+ http)
+ http_scheme="$(printf '%s' "$scheme_json" | jq -r '.scheme // empty')"
+ [ "${http_scheme,,}" = "bearer" ] || die "unsupported A2A HTTP auth scheme: ${http_scheme:-unknown}"
+ [ "$kind" = "bearer" ] || die "Agent Card scheme $scheme_name requires credential kind bearer" ;;
+ oauth2|openid)
+ [ "$kind" = "oauth2" ] || die "Agent Card scheme $scheme_name requires credential kind oauth2" ;;
+ mtls) die "A2A mTLS credential profiles are not supported in MSO 1.8" ;;
+ unknown) die "unsupported or invalid A2A security scheme: $scheme_name" ;;
+ '')
+ if [ "$kind" = "api-key" ]; then tty_line "API-key header [X-API-Key]: " "X-API-Key"; header_name="$REPLY"; fi ;;
+ *) die "unsupported A2A security scheme kind: $scheme_kind" ;;
+ esac
+ tty_secret "Credential secret: "; secret="$REPLY"; [ -n "$secret" ] || die "credential secret is required"
+ body="$(printf '%s' "$secret" | a2a_credential_body "$agent_id" "$label" "$kind" "$header_name" "$scheme_name")"; unset secret REPLY
+ secret_post "/api/v1/a2a" "$body"; unset body ;;
+ use)
+ target="${1:?target}"; credential_id="${2:?credentialId or none}"; [ "$credential_id" = "none" ] && credential_id=""
+ jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg credentialId "$credential_id" '{action:"credential-use",target:$target,credentialId:$credentialId}')" ;;
+ rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg credentialId "${1:?credentialId}" '{action:"credential-remove",credentialId:$credentialId}')" ;;
+ *) die "usage: mso $U_a2a" ;;
+ esac ;;
+ inbound)
+ in_sub="${1:-list}"; shift || true
+ case "$in_sub" in
+ list) jget "/api/v1/a2a?action=credentials" ;;
+ create|add)
+ label="${1:-peer}"; scope="${2:-read}"; case "$scope" in read|write|exec) ;; *) die "scope must be read, write, or exec" ;; esac
+ jpost "/api/v1/a2a" "$(jq -n --arg label "$label" --arg scope "$scope" '{action:"inbound-token-create",label:$label,scope:$scope}')" ;;
+ rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg tokenId "${1:?tokenId}" '{action:"inbound-token-remove",tokenId:$tokenId}')" ;;
+ *) die "usage: mso $U_a2a" ;;
+ esac ;;
+ *) die "usage: mso $U_a2a" ;;
+ esac ;;
+ memory)
+ case "${1:-list}" in
+ list) jget "/api/memory" ;;
+ add) jpost "/api/memory" "$(jq -n --arg t "${2:?text}" '{text:$t}')" ;;
+ rm) jdel "/api/memory?id=$(enc "${2:?id}")" ;;
+ *) die "usage: mso $U_memory" ;;
+ esac ;;
+ config)
+ case "${1:-show}" in
+ show) jget "/api/config" ;;
+ set) jpost "/api/config" "$(json_arg "${2:?json, e.g. '{\"model\":\"gpt-5.6\"}'}")" ;;
+ key) provider="${2:?provider}"
+ case "$provider" in anthropic|openai|openrouter|google|groq|xai|deepseek|mistral) ;;
+ *) die "API-key provider must be one of: anthropic openai openrouter google groq xai deepseek mistral" ;; esac
+ tty_secret "Paste $provider API key: "; key="$REPLY"
+ [ -n "$key" ] || die "empty API key"
+ body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
+ secret_post "/api/config" "$body"; unset key body REPLY ;;
+ style) style="${2:?off|caveman|ponytail}"
+ case "$style" in off|caveman|ponytail) ;; *) die "style must be off, caveman or ponytail" ;; esac
+ jpost "/api/config" "$(jq -nc --arg v "$style" '{tokenSaver:$v}')" ;;
+ rm) jdel "/api/config?provider=$(enc "${2:?provider}")" ;;
+ *) die "usage: mso $U_config" ;;
+ esac ;;
+ prefs)
+ case "${1:-show}" in
+ show) jget "/api/prefs" ;;
+ set) jpost "/api/prefs" "$(json_arg "${2:?json, e.g. '{\"tweaks\":{\"theme\":\"dark\"}}'}")" ;;
+ *) die "usage: mso $U_prefs" ;;
+ esac ;;
+ models) run_models "$@" ;;
+ skills)
+ case "${1:-list}" in
+ list) jget "/api/skills" ;;
+ read) [ -n "${2-}" ] || die "usage: mso $U_skills"
+ jget "/api/skills?name=$(enc "$2")" ;;
+ search) shift; [ $# -gt 0 ] || die "usage: mso $U_skills"
+ jget "/api/skills?q=$(enc "$*")" ;;
+ available) shift; node "$ROOT/scripts/skill-market.mjs" available "$@" ;;
+ info) shift; node "$ROOT/scripts/skill-market.mjs" info "$@" ;;
+ install) shift; node "$ROOT/scripts/skill-market.mjs" install "$@" ;;
+ remove|rm) shift; node "$ROOT/scripts/skill-market.mjs" remove "$@" ;;
+ *) jget "/api/skills?name=$(enc "$1")" ;;
+ esac ;;
+ # Generated from git subjects by scripts/gen-changelog.mjs; `jq -r` because the
+ # value is a markdown document, not a data structure to pretty-print.
+ changelog) jget "/api/changelog" | jq -r .markdown ;;
+ stock) jget "/api/v1/stock/search?q=$(enc "${1:?query}")&page=${2:-1}" ;;
+ *) die "internal CLI routing error: $cmd reached the wrong command family" ;;
+esac
+}
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
new file mode 100755
index 00000000..d12f7e19
--- /dev/null
+++ b/scripts/cli/commands.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# User-facing command usage + dispatch. Sourced by bin/mso.
+# Print the header block verbatim — stops at the first non-comment line, so the
+# help can never drift out of sync with the comment above.
+usage() { awk 'NR>1 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "$0"; }
+
+# Every verb the dispatch table implements, one per line, aliases split out. Read
+# from the table itself so a new arm can never be missing from did-you-mean.
+MSO_CLI_VERB_FILES=(
+ "$ROOT/scripts/cli/commands-host.sh"
+ "$ROOT/scripts/cli/commands-runtime.sh"
+ "$ROOT/scripts/cli/commands-state.sh"
+ "$ROOT/scripts/cli/commands-admin.sh"
+)
+verbs() {
+ awk 'match($0, /^ [a-zA-Z|-]+\)/) {
+ s = substr($0, 3, RLENGTH - 3); gsub(/\|/, "\n", s); print s
+ }' "${MSO_CLI_VERB_FILES[@]}"
+}
+
+# One usage string per command group, used by BOTH `--help` and the error path —
+# so the help you get when you ask cannot disagree with the help you get when
+# you're wrong.
+U_camoufox="camoufox status|start|stop|session"
+U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
+U_doctor="doctor [--fix]"
+U_provider="provider list|show <id>|set <dokploy|cloudflare|hostinger>|rm <id>|doctor [id]|projects|zones"
+U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
+U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
+U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
+U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
+U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
+U_service="service status|start|stop|restart|logs [n]"
+U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"
+U_update="update [--rebuild] | status | log"
+U_threads="threads list|show <id>|save <json>|rm <id>"
+U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"
+U_agents="agents list [current-session-id]|send <source-session-id> <target> <message> [message|task]|inbox <session-id> [--all]"
+U_a2a="a2a list|state|sessions|spawn <source-session> <objective> [title]|inbox <session>|discover <url>|add <url> [alias]|rm <target>|send <target> <message> [--wait]|stream <target> <message>|task <target> <taskId> [history]|cancel <target> <taskId>|handoff <target> <objective> [context] [--wait]|local sessions|local handoff <session> <objective>|local spawn <sourceSession> <objective> [title]|local inbox <session>|auth list [target]|auth add <target> [label] [bearer|api-key|oauth2]|auth use <target> <credentialId|none>|auth rm <credentialId>|inbound list|inbound create [label] [read|write|exec]|inbound rm <tokenId>"
+U_memory="memory list|add <text>|rm <id>"
+U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"
+U_prefs="prefs show|set <json>"
+U_models="models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]"
+U_skills="skills list|read <id>|search <query…>|available|info <id>|install <id…> [-y] [--force]|remove <id…> [-y]"
+U_mcp="mcp list|activity [n]|revoke <id>|revoke all"
+U_oauth="oauth <provider> start|poll OAuth currently: openai (ChatGPT Codex)"
+# Command families are sourced here so bin/mso remains only bootstrap + entrypoint.
+# shellcheck source=commands-host.sh
+source "$ROOT/scripts/cli/commands-host.sh"
+# shellcheck source=commands-runtime.sh
+source "$ROOT/scripts/cli/commands-runtime.sh"
+# shellcheck source=commands-state.sh
+source "$ROOT/scripts/cli/commands-state.sh"
+# shellcheck source=commands-admin.sh
+source "$ROOT/scripts/cli/commands-admin.sh"
+
+mso_cli_unknown() {
+ local cmd="$1" head3 near
+ echo "mso: unknown command '$cmd'" >&2
+ head3="${cmd:0:3}"
+ near=$(verbs | while read -r v; do
+ case "$v" in "$cmd"*|*"$cmd"*|"$head3"*) echo " $v" ;; esac
+ done)
+ [ -n "$near" ] && { echo "did you mean:" >&2; echo "$near" >&2; }
+ echo >&2; usage >&2; exit 1
+}
+
+mso_cli_main() {
+ if [ $# -ge 2 ]; then
+ case "$2" in
+ -h|--help|help)
+ eval "u=\${U_$1-}"
+ [ -n "${u-}" ] && { echo "usage: mso $u"; exit 0; }
+ usage | grep -E "^ +$1( |$)" || usage
+ exit 0 ;;
+ esac
+ fi
+
+ local cmd="${1:-agent}"
+ maybe_update_notice "$cmd"
+ shift || true
+ if [ "$cmd" = agent ] || [ "$cmd" = chat ]; then set -- "${AGENT_START_ARGS[@]}" "$@"; fi
+
+ case "$cmd" in
+ version|--version|-V|-v|ls|cat|raw|share|usage|search|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|gateway|web|camoufox|apps|mapp|term)
+ mso_cmd_runtime "$cmd" "$@" ;;
+ ai|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)
+ mso_cmd_state "$cmd" "$@" ;;
+ devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|service|build|deploy|update|crud|api|completion)
+ mso_cmd_admin "$cmd" "$@" ;;
+ help|-h|--help) usage; exit 0 ;;
+ *) mso_cli_unknown "$cmd" ;;
+ esac
+ echo
+}
diff --git a/scripts/cli/onboarding.sh b/scripts/cli/onboarding.sh
new file mode 100755
index 00000000..1dd6cbd6
--- /dev/null
+++ b/scripts/cli/onboarding.sh
@@ -0,0 +1,213 @@
+#!/usr/bin/env bash
+# TTY and guided onboarding helpers. Sourced by scripts/cli/runtime.sh.
+tty_ok() { [ -r /dev/tty ] && [ -w /dev/tty ]; }
+tty_print() { if tty_ok; then printf '%s' "$*" > /dev/tty; else printf '%s' "$*"; fi; }
+tty_line() {
+ local prompt="$1" default="${2-}" value=""
+ if ! tty_ok; then REPLY="$default"; return; fi
+ tty_print "$prompt"
+ IFS= read -r value < /dev/tty || true
+ REPLY="${value:-$default}"
+}
+tty_secret() {
+ local prompt="$1" value=""
+ tty_ok || die "a terminal is required to enter a secret; run this command interactively"
+ tty_print "$prompt"
+ stty -echo < /dev/tty
+ IFS= read -r value < /dev/tty || true
+ stty echo < /dev/tty
+ tty_print $'\n'
+ REPLY="$value"
+}
+
+ensure_local_cli_device() {
+ local d; d=$(cli_device)
+ case "$B" in
+ http://127.0.0.1:*|http://localhost:*|http://[::1]:*) ;;
+ *) return 0 ;;
+ esac
+ if ! dev_script --is-approved "$d" >/dev/null 2>&1; then
+ dev_script "$d" "mso cli" >/dev/null
+ [ "${MSO_CLI_QUIET:-0}" = "1" ] || echo " ✓ approved this local CLI device"
+ fi
+}
+
+ensure_onboard_runtime() {
+ case "$B" in
+ http://127.*:*|http://localhost:*|http://\[::1\]:*)
+ MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$B" \
+ "$ROOT/scripts/mso-gateway" local-start >/dev/null \
+ || die "local MSO runtime is not ready. Run: mso update ; then: mso web"
+ [ "${MSO_CLI_QUIET:-0}" = "1" ] || echo " ✓ verified local MSO runtime at $B" ;;
+ *) return 0 ;;
+ esac
+}
+
+onboard_ai() {
+ local yes="$1" choice provider key body response interval code url poll
+ if [ "$yes" = 1 ]; then
+ echo " -- AI provider skipped (-y keeps external accounts unconfigured)"
+ return
+ fi
+ echo
+ echo "AI for Alfa"
+ echo " 0) Skip for now"
+ echo " 1) OpenAI ChatGPT OAuth (Codex consumer backend; no API key)"
+ echo " 2) Anthropic API key"
+ echo " 3) OpenAI Platform API key"
+ echo " 4) OpenRouter API key"
+ echo " 5) Google Gemini API key"
+ echo " 6) Groq API key"
+ echo " 7) xAI API key"
+ echo " 8) DeepSeek API key"
+ echo " 9) Mistral API key"
+ tty_line "Choose [0]: " 0; choice="$REPLY"
+ case "$choice" in
+ 0|'') echo " -- skipped"; return ;;
+ 1)
+ response=$(jpost "/api/oauth/openai" '{"action":"start"}')
+ code=$(jq -r '.userCode // empty' <<<"$response")
+ url=$(jq -r '.verificationUrl // empty' <<<"$response")
+ interval=$(jq -r '.intervalMs // 5000' <<<"$response")
+ [ -n "$code" ] && [ -n "$url" ] || die "OpenAI OAuth did not return a device code"
+ echo
+ echo "Open this URL in any browser: $url"
+ echo "Enter code: $code"
+ echo "Waiting for authorization (Ctrl-C cancels this local wait; it does not expose the code)..."
+ while true; do
+ sleep "$(( interval / 1000 > 2 ? interval / 1000 : 3 ))"
+ poll=$(jpost "/api/oauth/openai" '{"action":"poll"}')
+ if [ "$(jq -r '.ok // false' <<<"$poll")" = true ]; then
+ echo " ✓ OpenAI connected as $(jq -r '.slug' <<<"$poll")"
+ return
+ fi
+ [ "$(jq -r '.pending // false' <<<"$poll")" = true ] || die "OpenAI OAuth failed: $poll"
+ tty_print "."
+ done ;;
+ 2) provider=anthropic ;;
+ 3) provider=openai ;;
+ 4) provider=openrouter ;;
+ 5) provider=google ;;
+ 6) provider=groq ;;
+ 7) provider=xai ;;
+ 8) provider=deepseek ;;
+ 9) provider=mistral ;;
+ *) echo " ! unknown choice; skipped"; return ;;
+ esac
+ echo " $provider uses an API key here (not OAuth). The key is never placed in argv."
+ tty_secret "Paste $provider API key: "; key="$REPLY"
+ [ -n "$key" ] || { echo " -- empty key; skipped"; return; }
+ body=$(printf '%s\0%s' "$provider" "$key" | provider_key_body)
+ secret_post "/api/config" "$body" >/dev/null
+ unset key body REPLY
+ echo " ✓ $provider configured for Alfa"
+}
+
+onboard_style() {
+ local yes="$1" choice style
+ if [ "$yes" = 1 ]; then
+ echo " -- response preset left unchanged (-y keeps existing/default settings)"
+ return
+ else
+ echo
+ echo "Alfa response preset (this is a response style, not a SKILL.md install)"
+ echo " 0) Normal / off"
+ echo " 1) Caveman — terse fragments, preserve technical substance"
+ echo " 2) Ponytail — minimal senior-dev solution, avoid unnecessary code"
+ tty_line "Choose [0]: " 0; choice="$REPLY"
+ case "$choice" in 1) style=caveman ;; 2) style=ponytail ;; *) style=off ;; esac
+ fi
+ jpost "/api/config" "$(jq -nc --arg v "$style" '{tokenSaver:$v}')" >/dev/null
+ echo " ✓ Alfa response preset: $style"
+}
+
+wait_managed_job() {
+ local app="$1" id="$2" since=0 data chunk status next
+ echo " installing $app (job $id)..."
+ while true; do
+ data=$(jget "/api/v1/managed-apps/$(enc "$app")/jobs/$(enc "$id")?since=$since")
+ chunk=$(jq -r '.job.log // empty' <<<"$data")
+ [ -z "$chunk" ] || printf '%s' "$chunk"
+ next=$(jq -r '.job.logOffset // 0' <<<"$data"); since="$next"
+ status=$(jq -r '.job.status // "unknown"' <<<"$data")
+ case "$status" in
+ succeeded) echo " ✓ $app installed"; return ;;
+ failed|interrupted) die "$app install ended: $status — $(jq -r '.job.error // "see job log"' <<<"$data")" ;;
+ esac
+ sleep 2
+ done
+}
+
+onboard_apps() {
+ local yes="$1" choice apps app response id
+ if [ "$yes" = 1 ]; then
+ echo " -- optional managed apps skipped (-y uses minimal defaults)"
+ return
+ fi
+ echo
+ echo "Optional managed applications"
+ echo " These have their own runtime/provider settings; Alfa credentials above do not configure them."
+ echo " 0) None"
+ echo " 1) Hermes"
+ echo " 2) OpenClaw"
+ echo " 3) Both"
+ tty_line "Choose [0]: " 0; choice="$REPLY"
+ case "$choice" in 1) apps="hermes" ;; 2) apps="openclaw" ;; 3) apps="hermes openclaw" ;; *) return ;; esac
+ for app in $apps; do
+ if jget "/api/v1/managed-apps" | jq -e --arg id "$app" '.apps[] | select(.id==$id and .installed==true)' >/dev/null; then
+ echo " ✓ $app already installed"
+ continue
+ fi
+ response=$(jpost "/api/v1/managed-apps/$(enc "$app")/install" '{}')
+ id=$(jq -r '.job.id // empty' <<<"$response")
+ [ -n "$id" ] || die "could not start $app install: $response"
+ wait_managed_job "$app" "$id"
+ done
+}
+
+onboard_skills() {
+ local yes="$1" choice ids
+ echo
+ echo "Curated installable skills"
+ node "$ROOT/scripts/skill-market.mjs" available
+ if [ "$yes" = 1 ]; then
+ echo " -- none installed automatically; run: mso skills install ponytail caveman rtk -y"
+ return
+ fi
+ echo "Enter skill ids separated by spaces/commas, 'all', or blank to skip."
+ tty_line "Skills: " ""; choice="$REPLY"
+ [ -n "$choice" ] || return
+ if [ "$choice" = all ]; then ids=$(node "$ROOT/scripts/skill-market.mjs" available --json | jq -r '.skills[].id' | tr '\n' ' ')
+ else ids=$(printf '%s' "$choice" | tr ',' ' '); fi
+ # The user's selection is the confirmation; suppress per-skill install prompts.
+ # shellcheck disable=SC2086
+ node "$ROOT/scripts/skill-market.mjs" install $ids -y
+}
+
+run_onboard() {
+ local yes=0
+ case "${1-}" in -y|--yes) yes=1 ;; "") ;; *) die "usage: mso onboard [-y|--yes]" ;; esac
+ echo "MSO onboarding"
+ echo "=============="
+ ensure_local_cli_device
+ ensure_onboard_runtime
+ if [ "$yes" = 0 ] && ! tty_ok; then
+ die "interactive onboarding needs a terminal; use 'mso onboard -y' for safe minimal defaults"
+ fi
+ # Runtime liveness was verified without auth above; now prove the approved-device session.
+ jget "/api/auth/me" >/dev/null
+ onboard_ai "$yes"
+ onboard_style "$yes"
+ onboard_apps "$yes"
+ onboard_infra "$yes"
+ onboard_skills "$yes"
+ echo
+ echo "Onboarding complete."
+ echo " mso -h command reference"
+ echo " mso doctor verify this install"
+ echo " mso skills available installable skills"
+ echo " mso config show Alfa provider/style"
+ echo " mso provider list Dokploy/Cloudflare/Hostinger state"
+ echo " mso launch the interactive MSO Agent"
+ echo " mso mapp list Hermes/OpenClaw state"
+}
diff --git a/scripts/cli/runtime.sh b/scripts/cli/runtime.sh
new file mode 100755
index 00000000..5257f0b5
--- /dev/null
+++ b/scripts/cli/runtime.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# Stable CLI runtime composition. Each module owns one responsibility.
+# shellcheck source=service.sh
+source "$ROOT/scripts/cli/service.sh"
+# shellcheck source=transport.sh
+source "$ROOT/scripts/cli/transport.sh"
+# shellcheck source=onboarding.sh
+source "$ROOT/scripts/cli/onboarding.sh"
diff --git a/scripts/cli/service.sh b/scripts/cli/service.sh
new file mode 100755
index 00000000..c8301a37
--- /dev/null
+++ b/scripts/cli/service.sh
@@ -0,0 +1,169 @@
+#!/usr/bin/env bash
+# Gateway/service/update lifecycle helpers. Sourced by scripts/cli/runtime.sh.
+gateway_local_url() {
+ local port=""
+ if [ -n "${MSO_GATEWAY_LOCAL_URL:-}" ]; then
+ printf '%s' "$MSO_GATEWAY_LOCAL_URL"
+ return
+ fi
+ case "$B" in
+ http://127.*:*|http://localhost:*|http://\[::1\]:*) printf '%s' "$B"; return ;;
+ esac
+ if command -v systemctl >/dev/null 2>&1; then
+ port=$(systemctl show -p Environment --value mso.service 2>/dev/null \
+ | tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)
+ fi
+ port="${port:-${MSO_PORT:-4005}}"
+ [[ "$port" =~ ^[0-9]{1,5}$ ]] || die "invalid MSO gateway port: $port"
+ printf 'http://127.0.0.1:%s' "$port"
+}
+
+maybe_update_notice() {
+ local verb="$1"
+ [ -t 2 ] || return 0
+ case "$verb" in update|version|--version|-V|-v|help|-h|--help|completion) return 0 ;; esac
+ [ -x "$ROOT/scripts/mso-update" ] || return 0
+ MSO_UPDATE_ROOT="$ROOT" "$ROOT/scripts/mso-update" notice || true
+}
+# shellcheck source=scripts/lib/private-state.sh
+. "$ROOT/scripts/lib/private-state.sh"
+# shellcheck source=scripts/lib/runtime-exclusion.sh
+. "$ROOT/scripts/lib/runtime-exclusion.sh"
+
+service_manager_read() {
+ local manager="${MSO_SYSTEMCTL_BIN:-systemctl}"
+ "$manager" "$@"
+}
+
+service_manager_write() {
+ if [ -n "${MSO_SYSTEMCTL_BIN:-}" ]; then "$MSO_SYSTEMCTL_BIN" "$@";
+ else sudo systemctl "$@"; fi
+}
+
+require_service_checkout_cli() {
+ local configured canonical_root canonical_service
+ configured="$(service_manager_read show -p WorkingDirectory --value mso.service 2>/dev/null || true)"
+ [ -n "$configured" ] || die "mso.service has no readable WorkingDirectory; refusing lifecycle action"
+ canonical_root="$(realpath -e -- "$ROOT" 2>/dev/null || true)"
+ canonical_service="$(realpath -e -- "$configured" 2>/dev/null || true)"
+ [ -n "$canonical_root" ] && [ -n "$canonical_service" ] \
+ || die "cannot canonicalize mso.service WorkingDirectory"
+ [ "$canonical_service" = "$canonical_root" ] \
+ || die "mso.service belongs to $canonical_service, not this checkout $canonical_root"
+}
+
+service_unit_local_url() {
+ local raw port
+ raw="$(service_manager_read show -p Environment --value mso.service 2>/dev/null || true)"
+ port="$(printf '%s\n' "$raw" | tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)"
+ if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then port=4005; fi
+ printf 'http://127.0.0.1:%s' "$port"
+}
+
+service_wait_ready() {
+ local local_url="$1" attempts="${MSO_SERVICE_READY_ATTEMPTS:-40}" expected_version body i curl_bin="${MSO_CURL_BIN:-curl}"
+ [[ "$attempts" =~ ^[0-9]+$ ]] && [ "$attempts" -ge 1 ] && [ "$attempts" -le 120 ] || attempts=40
+ expected_version="$(jq -r '.version // empty' "$ROOT/package.json" 2>/dev/null || true)"
+ [ -n "$expected_version" ] || return 1
+ for ((i = 1; i <= attempts; i++)); do
+ body="$("$curl_bin" --noproxy '*' -fsS --connect-timeout 1 --max-time 2 "$local_url/api/health" 2>/dev/null || true)"
+ if jq -e --arg version "$expected_version" '
+ type == "object" and .status == "ok" and .service == "mso" and
+ (.buildId | type == "string" and length > 0) and
+ (.buildSha | type == "string" and test("^[0-9a-f]{7,40}$")) and
+ .version == $version and has("runtimeInstanceId")
+ ' <<<"$body" >/dev/null 2>&1; then
+ return 0
+ fi
+ [ "$i" -ge "$attempts" ] || sleep 0.25
+ done
+ return 1
+}
+
+service_handoff_marker() {
+ local canonical base key dir
+ canonical="$(realpath -e -- "$ROOT" 2>/dev/null || true)"
+ [ -n "$canonical" ] || die "cannot canonicalize checkout for service handoff"
+ base="$(mso_private_state_dir "${MSO_SERVICE_HANDOFF_DIR:-$HOME/.mso/private/service-handoff}")" \
+ || die "unsafe service handoff state directory"
+ key="$(printf '%s' "$canonical" | sha256sum | awk '{print $1}')"
+ [[ "$key" =~ ^[0-9a-f]{64}$ ]] || die "cannot derive service handoff scope"
+ dir="$(mso_private_state_dir "$base/$key")" || die "unsafe scoped service handoff directory"
+ printf '%s/runtime' "$dir"
+}
+
+service_handoff_fallback_locked() {
+ local gateway local_url marker probe out
+ SERVICE_FALLBACK_QUIESCED=0
+ gateway="${MSO_GATEWAY_BIN:-$ROOT/scripts/mso-gateway}"
+ [ -x "$gateway" ] || die "missing gateway lifecycle helper: $gateway"
+ local_url="$(service_unit_local_url)"; marker="$(service_handoff_marker)"
+ probe="$(MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" \
+ "$gateway" runtime-assert-update-safe 2>&1)" || die "cannot hand off service port $local_url: $probe"
+ case "$probe" in
+ *'runtime: update-owned'*)
+ out="$(MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$local_url" \
+ MSO_GATEWAY_RECOVERY_MARKER="$marker" "$gateway" runtime-stop 2>&1)" \
+ || die "could not quiesce gateway-owned fallback at $local_url: $out"
+ case "$out" in
+ *'runtime: stopped-owned'*|*'runtime: recovered-stale-owned'*|*'runtime: already-down'*) SERVICE_FALLBACK_QUIESCED=1 ;;
+ *) die "unexpected fallback handoff result at $local_url: $out" ;;
+ esac ;;
+ *'runtime: update-safe'*) ;;
+ *) die "unexpected service handoff probe at $local_url: $probe" ;;
+ esac
+ SERVICE_HANDOFF_URL="$local_url"; SERVICE_HANDOFF_MARKER="$marker"
+}
+
+service_restore_fallback_after_failure() {
+ local gateway="${MSO_GATEWAY_BIN:-$ROOT/scripts/mso-gateway}"
+ [ "${SERVICE_FALLBACK_QUIESCED:-0}" = 1 ] || return 0
+ if ! MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ENVF" MSO_GATEWAY_LOCAL_URL="$SERVICE_HANDOFF_URL" \
+ "$gateway" local-start >/dev/null 2>&1; then
+ printf 'mso: service action failed and fallback restore also failed at %s; recovery marker preserved\n' "$SERVICE_HANDOFF_URL" >&2
+ return 1
+ fi
+ mso_private_state_remove_file "$SERVICE_HANDOFF_MARKER" >/dev/null 2>&1 \
+ || { printf 'mso: fallback restored but recovery marker could not be cleared\n' >&2; return 1; }
+}
+
+service_lifecycle_safe() {
+ local verb="$1" rc=0 active=0
+ require_service_checkout_cli
+ runtime_exclusion_acquire_shared \
+ || die "offline update/deploy is mutating this checkout or another service handoff is active; retry after it finishes"
+ service_manager_read is-active --quiet mso.service && active=1 || true
+ SERVICE_FALLBACK_QUIESCED=0; SERVICE_HANDOFF_URL=''; SERVICE_HANDOFF_MARKER=''
+ [ "$active" = 1 ] || service_handoff_fallback_locked
+ service_manager_write "$verb" mso.service || rc=$?
+ if [ "$rc" -eq 0 ] && ! service_wait_ready "$(service_unit_local_url)"; then
+ printf 'mso: service %s returned success but /api/health did not become ready; restoring fallback if available\n' "$verb" >&2
+ rc=24
+ # A Type=simple unit can report a successful start before Next later fails.
+ # Stop any unhealthy survivor so the quiesced fallback can reclaim its port.
+ service_manager_write stop mso.service >/dev/null 2>&1 || true
+ fi
+ runtime_exclusion_release
+ if [ "$rc" -ne 0 ]; then
+ service_restore_fallback_after_failure || return 1
+ return "$rc"
+ fi
+ [ -z "${SERVICE_HANDOFF_MARKER:-}" ] || mso_private_state_remove_file "$SERVICE_HANDOFF_MARKER" >/dev/null 2>&1 || true
+}
+
+service_start_safe() { service_lifecycle_safe start; }
+service_restart_safe() { service_lifecycle_safe restart; }
+
+deploy_safe() {
+ local local_url helper
+ require_service_checkout_cli
+ service_manager_read is-active --quiet mso.service \
+ || die "mso.service is not active; start the intended service first, then run mso deploy"
+ local_url="$(gateway_local_url)"
+ # The outer helper owns checkout-wide runtime inventory/quiesce/restore around
+ # the in-place build, so deploy never mutates `.next` under a fallback runtime.
+ helper="${MSO_SERVICE_UPDATE_BIN:-$ROOT/scripts/mso-service-update}"
+ [ -x "$helper" ] || [ -f "$helper" ] || die "missing service deployment helper: $helper"
+ MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" /bin/bash "$helper" --rebuild-only
+ echo "deployed → $B"
+}
diff --git a/scripts/cli/transport.sh b/scripts/cli/transport.sh
new file mode 100755
index 00000000..2860a6a0
--- /dev/null
+++ b/scripts/cli/transport.sh
@@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+# Local device, auth, HTTP and A2A transport helpers. Sourced by scripts/cli/runtime.sh.
+# ── local ops (no HTTP, no login) ───────────────────────────────────────────
+# These edit ~/.mso/auth-devices.json on THIS machine. They are deliberately local
+# (they must keep working while the service is down) — but that makes them the one
+# family of verbs `--base` does not follow. Pointing at a remote host and running
+# `device approve` used to silently edit the LOCAL allowlist and report success,
+# so the operator believed they had approved a device that was still pending.
+dev_script() {
+ case "$B" in
+ http://127.0.0.1:*|http://localhost:*|http://[::1]:*) ;;
+ *) die "device commands edit the LOCAL allowlist (~/.mso/auth-devices.json) and cannot reach $B.
+ Run them ON that host, or over ssh: ssh <host> mso device $*" ;;
+ esac
+ node "$ROOT/scripts/approve-device.js" "$@"
+}
+
+# ── auth ────────────────────────────────────────────────────────────────────
+PASS="${MSO_PASSWORD:-${OS_PASSWORD:-${OS_LOGIN_PASSWORD:-}}}"
+DEV="${MSO_DEVICE:-${OS_DEVICE:-}}"
+# A stable per-host CLI device id, so `mso approve` only ever has to run once.
+DEVF="${MSO_DEVICE_FILE:-$HOME/.mso/cli.device.id}"
+cli_device() {
+ [ -n "$DEV" ] && { printf '%s' "$DEV"; return; }
+ [ -s "$DEVF" ] || { mkdir -p "$(dirname "$DEVF")"; head -c16 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$DEVF"; chmod 600 "$DEVF"; }
+ cat "$DEVF"
+}
+
+# Jar is per-base as well as per-user: switching --base must not reuse a cookie
+# minted for a different origin. Live bearer material belongs only in an owner-only
+# directory, never a predictable shared /tmp name.
+PRIVATE_STATE_ROOT="${MSO_PRIVATE_STATE_DIR:-$HOME/.mso/private}"
+BASE_KEY=$(printf '%s' "$B" | sha256sum | cut -c1-32)
+JAR_REQUESTED="${MSO_JAR:-$PRIVATE_STATE_ROOT/cli/cookies/$BASE_KEY.jar}"
+JAR=$(mso_private_state_ensure_file "$JAR_REQUESTED") || die "refusing unsafe cookie jar: $JAR_REQUESTED"
+
+# proxy.ts blocks mutating /api requests that can't prove same-origin. A browser
+# proves it with Sec-Fetch-Site; the documented fallback for non-browser clients
+# is an Origin whose host matches the Host header — which is exactly what $B is.
+# Sent on every call so `login` works before any session cookie exists.
+ORIGIN=(-H "origin: $B")
+
+login() {
+ local d out code body; d=$(cli_device)
+ [ -n "$PASS" ] || die "no OS_LOGIN_PASSWORD in $ENVF (or export MSO_PASSWORD)"
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ out=$(jq -n --arg p "$PASS" --arg d "$d" '{password:$p,deviceId:$d,deviceLabel:"mso cli"}' \
+ | curl -sS -w $'\n%{http_code}' -c "$JAR" -X POST "$B/api/auth/login" \
+ "${ORIGIN[@]}" -H 'content-type: application/json' -d @- 2>/dev/null || true)
+ code="${out##*$'\n'}"; body="${out%$'\n'*}"
+ [ "$code" = "200" ] && return 0
+ case "$code" in
+ 000|"") die "MSO runtime is not reachable at $B. Run: mso web (local UI) or mso gateway start (temporary public HTTPS)" ;;
+ 403) die "device is not approved by the running MSO instance. Check: mso device pending ; then approve the exact id with: mso device approve $d \"mso cli\"" ;;
+ 401) die "login password was rejected by the running MSO instance" ;;
+ 429) die "login is rate-limited; retry after the server window resets" ;;
+ 500) die "running MSO auth is not configured correctly; run: mso doctor" ;;
+ *) die "login failed ($code): ${body:-no response body}; run: mso doctor" ;;
+ esac
+}
+
+# Request with the cached cookie; on 401/403 (expired) log in once and retry.
+# Login is lazy on purpose: `mso -h`, `mso device …` and `mso service …` are
+# local-only and must keep working while the service is down or unapproved.
+req() {
+ local out code body
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ [ -s "$JAR" ] || login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
+ code="${out##*$'\n'}"; body="${out%$'\n'*}"
+ if [ "$code" = "401" ] || [ "$code" = "403" ]; then
+ login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
+ code="${out##*$'\n'}"; body="${out%$'\n'*}"
+ fi
+ case "$code" in 2*) printf '%s' "$body" ;; *) die "request failed ($code): $body" ;; esac
+}
+# Binary-safe variant: streams straight to stdout, no capture, no code check.
+reqraw() {
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ [ -s "$JAR" ] || login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ curl -fsS -b "$JAR" "${ORIGIN[@]}" "$@"
+}
+
+enc() { jq -rn --arg v "$1" '$v|@uri'; }
+jget() { req "$B$1"; }
+jpost() { req -H 'content-type: application/json' -d "${2:-{\}}" "$B$1"; }
+jdel() { req -X DELETE -H 'content-type: application/json' -d "${2:-{\}}" "$B$1"; }
+# Build a JSON object from k=v pairs (numbers + booleans coerced).
+kv_args() { local j='{}' kv k v; for kv in "$@"; do k="${kv%%=*}"; v="${kv#*=}"
+ if [[ "$v" =~ ^-?[0-9]+([.][0-9]+)?$ || "$v" == "true" || "$v" == "false" ]]; then
+ j=$(jq -c --arg k "$k" --argjson v "$v" '.+{($k):$v}' <<<"$j")
+ else j=$(jq -c --arg k "$k" --arg v "$v" '.+{($k):$v}' <<<"$j"); fi; done; printf '%s' "$j"; }
+json_arg() { jq -e . >/dev/null 2>&1 <<<"${1-}" || die "not valid JSON: ${1-}"; printf '%s' "$1"; }
+
+# POST a JSON value that may contain a credential without putting the JSON in
+# curl's argv. We force a fresh login first so there is no retry that would need to
+# replay consumed stdin. The body exists only in this shell process and the pipe.
+secret_post() {
+ local route="$1" body="$2" out code payload
+ login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ out=$(printf '%s' "$body" | curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' \
+ -H 'content-type: application/json' -d @- "$B$route" || true)
+ code="${out##*$'\n'}"; payload="${out%$'\n'*}"
+ case "$code" in 2*) printf '%s' "$payload" ;; *) die "request failed ($code): $payload" ;; esac
+}
+
+# Build an outbound A2A credential JSON body while keeping the secret off process argv.
+# Non-secret metadata travels in env vars; the secret is read only from stdin.
+a2a_credential_body() {
+ local agent_id="$1" label="$2" kind="$3" header_name="${4-}" scheme_name="${5-}"
+ A2A_AGENT_ID="$agent_id" A2A_LABEL="$label" A2A_KIND="$kind" A2A_HEADER_NAME="$header_name" A2A_SCHEME_NAME="$scheme_name" node -e '
+ let secret=""; process.stdin.setEncoding("utf8"); process.stdin.on("data",d=>secret+=d); process.stdin.on("end",()=>{
+ const body={action:"credential-create",agentId:process.env.A2A_AGENT_ID,label:process.env.A2A_LABEL,kind:process.env.A2A_KIND,secret,activate:true};
+ if(process.env.A2A_HEADER_NAME) body.headerName=process.env.A2A_HEADER_NAME;
+ if(process.env.A2A_SCHEME_NAME) body.schemeName=process.env.A2A_SCHEME_NAME;
+ process.stdout.write(JSON.stringify(body));
+ });'
+}
+
+a2a_agent_id() {
+ local ref="$1" found
+ found="$(jget "/api/v1/a2a" | jq -r --arg q "${ref,,}" '[.agents[] | select((.id|ascii_downcase)==$q or (.alias|ascii_downcase)==$q or (.card.name|ascii_downcase)==$q)] | if length==1 then .[0].id else empty end')"
+ [ -n "$found" ] || die "A2A peer not found or ambiguous: $ref"
+ printf '%s' "$found"
+}
+
+a2a_agent_schemes() {
+ local agent_id="$1"
+ jget "/api/v1/a2a" | jq -r --arg id "$agent_id" '.agents[] | select(.id==$id) | .card.securitySchemeNames[]?'
+}
+
+a2a_agent_scheme_json() {
+ local agent_id="$1" scheme_name="$2"
+ jget "/api/v1/a2a" | jq -c --arg id "$agent_id" --arg scheme "$scheme_name" '.agents[] | select(.id==$id) | (.card.securitySchemes[$scheme] // {})'
+}
diff --git a/scripts/mso-a2a-cli-contract.test.ts b/scripts/mso-a2a-cli-contract.test.ts
index 1fe2dfe8..bd3c9b62 100644
--- a/scripts/mso-a2a-cli-contract.test.ts
+++ b/scripts/mso-a2a-cli-contract.test.ts
@@ -2,7 +2,12 @@ import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
-const cli = readFileSync(path.join(process.cwd(), "bin", "mso"), "utf8");
+const root = process.cwd();
+const cli = [
+ "scripts/cli/commands.sh",
+ "scripts/cli/commands-state.sh",
+ "scripts/cli/transport.sh",
+].map((rel) => readFileSync(path.join(root, rel), "utf8")).join("\n");
describe("MSO A2A CLI contract", () => {
it("exposes authenticated inbound, peer auth, and streaming commands", () => {
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index 104f41d5..f483cba3 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest";
const root = path.resolve(__dirname, "..");
const cli = fs.readFileSync(path.join(root, "bin/mso"), "utf8");
+const commandOwner = fs.readFileSync(path.join(root, "scripts/cli/commands.sh"), "utf8");
const agentCli = fs.readFileSync(
path.join(__dirname, "mso-cli-agent.sh"),
"utf8",
@@ -25,7 +26,7 @@ const picker = fs.readFileSync(
"utf8",
);
-const all = [cli, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
+const all = [cli, commandOwner, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
@@ -75,7 +76,7 @@ describe("MSO model/provider/session CLI contract", () => {
it("accepts yolo as a global Agent startup flag instead of treating it as a command", () => {
expect(cli).toContain('--yolo|-yolo) AGENT_START_ARGS+=("--yolo")');
- expect(cli).toContain(
+ expect(commandOwner).toContain(
"agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo]",
);
});