Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(agent): add native local session messaging

Rahman566372122d66
diff --git a/.env.example b/.env.example
index 97e7eb21..42d228b8 100644
--- a/.env.example
+++ b/.env.example
@@ -207,6 +207,10 @@ OS_SESSION_SECRET=
# OS_THREADS_DIR=~/.mso/threads # Alfa assistant chat threads (one file each)
# OS_AGENT_MEMORY_DIR=~/.mso/agent-memory # isolated MSO Agent USER.md/MEMORY.md stores
# OS_AGENT_SESSIONS_DIR=~/.mso/agent-sessions # durable CLI/MCP agent session records
+# Native Local Agents use private defaults; overrides are normally unnecessary.
+# OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json # live receive leases/aliases (0600)
+# OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json # durable explicit local messages/tasks (0600)
+# OS_LOCAL_AGENT_LEASE_MS=60000 # receiver lease; CLI heartbeat is lighter than this expiry
# OS_TOOL_FORGE_DIR=~/.mso/tool-forge # private inert Tool Forge candidate/evaluation records
# OS_TOOL_FORGE_NODE_IMAGE=mso-forge-sandbox:node22-v1 # labelled cached Docker image used only for executable Forge fixtures
# OS_A2A_STORE=~/.mso/private/a2a-agents.json # public A2A Agent Card registry; no credentials
diff --git a/README.md b/README.md
index 741e49e8..5169d6ff 100644
--- a/README.md
+++ b/README.md
@@ -76,7 +76,8 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
-- **Delegate between agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or opt in to MSO's own authenticated inbound Agent Card. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](./docs/A2A.md).
+- **Message live local sessions natively** — every live same-principal MSO session is discovered automatically as `[agent-a]`, `[agent-b]`, or its manual session name. A private presence lease + durable mailbox + SSE feed gives honest `idle`/`busy`/`offline` delivery without Agent Cards, URLs, registration, refresh, or restart. See [Local Agents](./docs/LOCAL-AGENTS.md).
+- **Delegate between remote agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or expose MSO's authenticated inbound Agent Card when a public HTTPS origin is configured. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](./docs/A2A.md).
- **Keep agents efficient independently of the model provider** — the MCP-first [Cognitive Runtime](./docs/COGNITIVE-RUNTIME.md) isolates conversations from OAuth identity, budgets model context/tool output, selects a compact per-turn capability set without weakening scopes, compacts durable sessions with sanitized 30-day backup archives, and learns only verified workflow recipes. `bun run bench:cognitive` guards routing recall and context footprint.
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
@@ -218,7 +219,10 @@ current session and switches the same terminal to a fresh durable session. `/res
process replacement: it persists the current session, closes the composer, then reloads the latest CLI
and Agent modules against that exact same durable session id. Repeated restarts keep a constant process
depth. It does **not** restart the MSO service or VPS; updated code plus the latest dynamic
-skill/tool/plugin catalog are picked up without abandoning the conversation.
+skill/tool/plugin catalog are picked up without abandoning the conversation. Live same-host sessions require no
+manual refresh path: `/agents` discovers them automatically, `/message <agent> <text>` sends an explicit local
+message, `/delegate <agent> <task>` queues a local task before remote-A2A fallback, and `/inbox` shows the current
+session's native agent mailbox. Incoming events render as `[agent-name]` and keep a distinct durable `agent` role.
In the Agent slash palette, executable skills carry lifecycle markers so their state is visible before and after use:
`◇ ready` → `◆ queued` (selected for the next message) → `✓ invoked` (actually sent with a model turn).
The compact status line mirrors queued/invoked skill state and the current permission mode. MSO defaults
diff --git a/app/api/v1/local-agents/route.test.ts b/app/api/v1/local-agents/route.test.ts
new file mode 100644
index 00000000..fd1eac1e
--- /dev/null
+++ b/app/api/v1/local-agents/route.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const mocks = vi.hoisted(() => ({
+ list: vi.fn(), touch: vi.fn(), end: vi.fn(), inbox: vi.fn(), update: vi.fn(), send: vi.fn(),
+ subscribe: vi.fn(), flush: vi.fn(), audit: vi.fn(), rate: vi.fn(), getSession: vi.fn(),
+}));
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: vi.fn(async () => ({ role: "owner", session: { device_id: "cli-test" } })),
+}));
+vi.mock("@/lib/host", () => ({ audit: mocks.audit, rateLimited: mocks.rate }));
+vi.mock("@/lib/agent/session-store", () => ({ getAgentSession: mocks.getSession }));
+vi.mock("@/lib/agent/local-agent-directory", () => ({ listLocalAgents: mocks.list }));
+vi.mock("@/lib/agent/local-agent-presence", () => ({ touchLocalAgentPresence: mocks.touch, endLocalAgentPresence: mocks.end }));
+vi.mock("@/lib/agent/local-agent-mailbox", () => ({ listLocalAgentInbox: mocks.inbox, updateLocalAgentMessageState: mocks.update }));
+vi.mock("@/lib/agent/local-agent-messaging", () => ({ sendLocalAgentMessage: mocks.send, flushLocalAgentQueue: mocks.flush }));
+vi.mock("@/lib/agent/local-agent-events", () => ({ subscribeLocalAgentMessages: mocks.subscribe }));
+
+const { GET, POST } = await import("./route");
+const post = (body: object) => new NextRequest("http://localhost/api/v1/local-agents", {
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.rate.mockReturnValue(false);
+ mocks.getSession.mockResolvedValue({ id: "session-a", source: "cli" });
+ mocks.list.mockResolvedValue([{ id: "session-b", label: "[agent-b]", status: "idle" }]);
+ mocks.touch.mockResolvedValue({ sessionId: "session-a", alias: "agent-a", state: "idle" });
+ mocks.flush.mockResolvedValue(0);
+ mocks.inbox.mockResolvedValue([]);
+ mocks.update.mockResolvedValue([]);
+ mocks.send.mockResolvedValue({
+ status: "delivered", targetStatus: "idle",
+ sender: { id: "session-a", label: "[agent-a]" }, target: { id: "session-b", label: "[agent-b]" },
+ message: { id: "localmsg_1", kind: "message", text: "hello" },
+ });
+});
+
+describe("native local agent API", () => {
+ it("lists only same-principal live agents with the current session excluded", async () => {
+ const response = await GET(new NextRequest("http://localhost/api/v1/local-agents?session=session-a"));
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ agents: [{ id: "session-b", label: "[agent-b]", status: "idle" }] });
+ expect(mocks.list).toHaveBeenCalledWith("cli:cli-test", { currentSessionId: "session-a", includeOffline: false });
+ });
+
+ it("sends an explicit local payload without routing through remote A2A", async () => {
+ const response = await POST(post({ action: "send", sessionId: "session-a", target: "agent-b", message: "hello", kind: "message" }));
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ status: "delivered", target: { label: "[agent-b]" } });
+ expect(mocks.send).toHaveBeenCalledWith({
+ principal: "cli:cli-test", senderSessionId: "session-a", target: "agent-b", text: "hello", kind: "message",
+ });
+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ action: "agent.message", target: "session-b" }));
+ });
+
+ it("updates receive presence and flushes queued mail only when receivable", async () => {
+ await POST(post({ action: "presence", sessionId: "session-a", instanceId: "tty:1", state: "busy" }));
+ expect(mocks.flush).not.toHaveBeenCalled();
+ await POST(post({ action: "presence", sessionId: "session-a", instanceId: "tty:1", state: "idle" }));
+ expect(mocks.touch).toHaveBeenLastCalledWith("cli:cli-test", "session-a", "idle", "tty:1");
+ expect(mocks.flush).toHaveBeenCalledWith("cli:cli-test", "session-a");
+ });
+
+ it("acks only messages addressed to the exact current durable session", async () => {
+ mocks.update.mockResolvedValue([{ id: "localmsg_1", state: "read" }]);
+ const response = await POST(post({ action: "ack", sessionId: "session-a", messageIds: ["localmsg_1"] }));
+ expect(response.status).toBe(200);
+ expect(mocks.update).toHaveBeenCalledWith("cli:cli-test", "session-a", ["localmsg_1"], "read");
+ });
+ it("rejects oversized API bodies before JSON parsing", async () => {
+ const response = await POST(new NextRequest("http://localhost/api/v1/local-agents", {
+ method: "POST", headers: { "content-type": "application/json", "content-length": String(200 * 1024) },
+ body: JSON.stringify({ action: "send", sessionId: "session-a", target: "agent-b", message: "x" }),
+ }));
+ expect(response.status).toBe(413);
+ await expect(response.json()).resolves.toEqual({ error: "request_body_too_large" });
+ expect(mocks.send).not.toHaveBeenCalled();
+ });
+
+});
diff --git a/app/api/v1/local-agents/route.ts b/app/api/v1/local-agents/route.ts
new file mode 100644
index 00000000..a247bd4a
--- /dev/null
+++ b/app/api/v1/local-agents/route.ts
@@ -0,0 +1,205 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { audit, rateLimited } from "@/lib/host";
+import { getAgentSession } from "@/lib/agent/session-store";
+import { listLocalAgents } from "@/lib/agent/local-agent-directory";
+import { endLocalAgentPresence, touchLocalAgentPresence } from "@/lib/agent/local-agent-presence";
+import { listLocalAgentInbox, updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";
+import { flushLocalAgentQueue, sendLocalAgentMessage } from "@/lib/agent/local-agent-messaging";
+import { subscribeLocalAgentMessages } from "@/lib/agent/local-agent-events";
+import type { LocalAgentPresenceState } from "@/lib/agent/local-agent-types";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const SSE_HEARTBEAT_MS = 15_000;
+const MAX_POST_BODY_BYTES = 128 * 1024;
+
+class LocalAgentBodyTooLarge extends Error {}
+
+async function readBoundedBody(req: Request): Promise<Record<string, unknown>> {
+ const declared = Number(req.headers.get("content-length") || 0);
+ if (Number.isFinite(declared) && declared > MAX_POST_BODY_BYTES) throw new LocalAgentBodyTooLarge();
+ if (!req.body) throw new Error("invalid_request");
+ const reader = req.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let bytes = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ bytes += value.byteLength;
+ if (bytes > MAX_POST_BODY_BYTES) { await reader.cancel().catch(() => undefined); throw new LocalAgentBodyTooLarge(); }
+ chunks.push(value);
+ }
+ const raw = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
+ const value = JSON.parse(raw) as unknown;
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid_request");
+ return value as Record<string, unknown>;
+}
+
+async function ownerPrincipal(): Promise<{ principal: string; actor: string } | null> {
+ const context = await getSessionContext();
+ if (context?.role !== "owner") return null;
+ const actor = context.session.device_id || "owner";
+ return { principal: `cli:${actor}`, actor };
+}
+
+async function requireCliSession(principal: string, id: string) {
+ const session = await getAgentSession(principal, id);
+ if (!session || session.source !== "cli") throw new Error("local agent session not found");
+ return session;
+}
+
+function routeError(error: unknown) {
+ const message = error instanceof Error ? error.message : "local agent operation failed";
+ const status = /not found/i.test(message) ? 404 : /ambiguous/i.test(message) ? 409 : 400;
+ return NextResponse.json({ error: message.slice(0, 240) }, { status });
+}
+
+function presenceState(value: unknown): Exclude<LocalAgentPresenceState, "ended"> {
+ const raw = String(value || "idle");
+ if (raw === "ready" || raw === "idle" || raw === "busy") return raw;
+ throw new Error("local agent state must be ready, idle, or busy");
+}
+
+export async function GET(req: NextRequest) {
+ const owner = await ownerPrincipal();
+ if (!owner) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
+ const url = req.nextUrl;
+ const sessionId = String(url.searchParams.get("session") || "").trim();
+ try {
+ if (url.searchParams.get("stream") === "1") {
+ if (!sessionId) return NextResponse.json({ error: "session_required" }, { status: 400 });
+ await requireCliSession(owner.principal, sessionId);
+ const encoder = new TextEncoder();
+ let unsubscribe = () => {};
+ let heartbeat: ReturnType<typeof setInterval> | null = null;
+ let closed = false;
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const send = (event: string, value: unknown) => {
+ if (closed) return;
+ try {
+ controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(value)}\n\n`));
+ } catch {
+ closed = true;
+ }
+ };
+ // Subscribe before replaying the durable backlog so a send racing stream setup
+ // can be duplicated (client dedupes by message id) but can never be missed.
+ unsubscribe = subscribeLocalAgentMessages(sessionId, (message) => send("message", message));
+ const backlog = await listLocalAgentInbox(owner.principal, sessionId, { limit: 200 });
+ const pendingIds = backlog.filter((row) => row.state !== "read").map((row) => row.id);
+ if (pendingIds.length)
+ await updateLocalAgentMessageState(owner.principal, sessionId, pendingIds, "delivered");
+ for (const row of backlog) send("message", { ...row, state: row.state === "read" ? "read" : "delivered" });
+ heartbeat = setInterval(() => {
+ if (!closed) {
+ try { controller.enqueue(encoder.encode(": ping\n\n")); }
+ catch { closed = true; }
+ }
+ }, SSE_HEARTBEAT_MS);
+ req.signal.addEventListener("abort", () => {
+ closed = true;
+ unsubscribe();
+ if (heartbeat) clearInterval(heartbeat);
+ }, { once: true });
+ },
+ cancel() {
+ closed = true;
+ unsubscribe();
+ if (heartbeat) clearInterval(heartbeat);
+ },
+ });
+ return new Response(stream, {
+ headers: {
+ "content-type": "text/event-stream; charset=utf-8",
+ "cache-control": "no-cache, no-transform",
+ "x-accel-buffering": "no",
+ connection: "keep-alive",
+ },
+ });
+ }
+
+ if (url.searchParams.get("inbox") === "1") {
+ if (!sessionId) return NextResponse.json({ error: "session_required" }, { status: 400 });
+ return NextResponse.json({
+ messages: await listLocalAgentInbox(owner.principal, sessionId, {
+ includeRead: url.searchParams.get("includeRead") === "1",
+ limit: Number(url.searchParams.get("limit")) || 100,
+ }),
+ });
+ }
+
+ return NextResponse.json({
+ agents: await listLocalAgents(owner.principal, {
+ currentSessionId: sessionId || undefined,
+ includeOffline: url.searchParams.get("includeOffline") === "1",
+ }),
+ });
+ } catch (error) {
+ return routeError(error);
+ }
+}
+
+export async function POST(req: NextRequest) {
+ const owner = await ownerPrincipal();
+ if (!owner) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
+ let body: Record<string, unknown>;
+ try { body = await readBoundedBody(req); }
+ catch (error) {
+ if (error instanceof LocalAgentBodyTooLarge) return NextResponse.json({ error: "request_body_too_large" }, { status: 413 });
+ return NextResponse.json({ error: "invalid_request" }, { status: 400 });
+ }
+ const action = String(body.action || "");
+ const sessionId = String(body.sessionId || "").trim();
+ try {
+ if (action === "presence") {
+ if (!sessionId) throw new Error("session_required");
+ if (rateLimited(`local-agent.presence:${sessionId}`, 120, 60_000))
+ return NextResponse.json({ error: "too_many_requests" }, { status: 429 });
+ const state = presenceState(body.state);
+ const entry = await touchLocalAgentPresence(
+ owner.principal,
+ sessionId,
+ state,
+ String(body.instanceId || ""),
+ );
+ const delivered = state === "busy" || body.flush === false ? 0 : await flushLocalAgentQueue(owner.principal, sessionId);
+ return NextResponse.json({ ok: true, presence: entry, delivered });
+ }
+ if (action === "end") {
+ if (!sessionId) throw new Error("session_required");
+ await endLocalAgentPresence(owner.principal, sessionId, String(body.instanceId || ""));
+ return NextResponse.json({ ok: true });
+ }
+ if (action === "ack") {
+ if (!sessionId) throw new Error("session_required");
+ const ids = Array.isArray(body.messageIds) ? body.messageIds.map(String) : [];
+ const messages = await updateLocalAgentMessageState(owner.principal, sessionId, ids, "read");
+ return NextResponse.json({ ok: true, messages });
+ }
+ if (action === "send") {
+ if (!sessionId) throw new Error("session_required");
+ if (rateLimited(`local-agent.send:${sessionId}`, 60, 60_000))
+ return NextResponse.json({ error: "too_many_requests" }, { status: 429 });
+ const result = await sendLocalAgentMessage({
+ principal: owner.principal,
+ senderSessionId: sessionId,
+ target: String(body.target || ""),
+ text: String(body.message || ""),
+ kind: typeof body.kind === "string" ? body.kind : undefined,
+ });
+ void audit({
+ action: "agent.message",
+ actor: owner.actor,
+ target: result.target.id,
+ detail: `${result.message.kind} ${result.status}`,
+ meta: { bytes: Buffer.byteLength(result.message.text, "utf8") },
+ });
+ return NextResponse.json(result);
+ }
+ return NextResponse.json({ error: "unknown_action" }, { status: 400 });
+ } catch (error) {
+ return routeError(error);
+ }
+}
diff --git a/bin/mso b/bin/mso
index ae4058ae..096a4c4f 100755
--- a/bin/mso
+++ b/bin/mso
@@ -64,6 +64,7 @@
# ai <prompt…> One turn with the assistant
# threads * Conversation history: list | show | rm
# agent-sessions * Durable MSO Agent sessions: list | show | create
+# agents * Native local session agents: list | send | inbox
# a2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoff
# memory * Assistant memories: list | add | rm
# config * Advanced raw AI config compatibility surface
@@ -127,7 +128,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.8.2"
+VERSION="1.9.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
@@ -714,6 +715,7 @@ U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user>
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>"
@@ -979,6 +981,23 @@ case "$cmd" in
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
diff --git a/docs/A2A.md b/docs/A2A.md
index 11138bad..b906d341 100644
--- a/docs/A2A.md
+++ b/docs/A2A.md
@@ -9,7 +9,7 @@ The implementation has four independent pieces:
3. **Streaming** — use A2A v1 `SendStreamingMessage` / SSE and keep task lifetime independent from an individual stream connection.
4. **Authenticated inbound MSO** — optionally publish MSO's Agent Card and JSON-RPC endpoint, guarded by owner-minted `read`, `write`, or `exec` bearer capabilities.
-Inbound serving is **disabled by default** and is never enabled merely by installing or upgrading MSO.
+Public inbound serving is active only when a valid explicit HTTPS `OS_PUBLIC_ORIGIN` exists; `OS_A2A_INBOUND_ENABLED=0` is the kill switch. Without a public HTTPS origin, no public A2A endpoint is advertised.
## Trust model
@@ -86,69 +86,13 @@ mso a2a inbound rm <tokenId>
The Settings → **A2A** panel exposes the same flow, shows the one-time token once, lists/revokes inbound profiles, and surfaces bounded task/audit activity.
-## Same-host local A2A between terminal sessions
+## Same-host sessions are native Local Agents, not remote A2A
-Local A2A is independent from public inbound A2A and is **enabled by default**. The environment value below documents the default; set it to `0` only when you want to disable same-host A2A:
+MSO 1.9 separates live same-host session communication from this remote interoperability protocol. `/agents`, `/message`, local `/delegate`, local inbox delivery, and the `local_agent_*` MCP tools use a private **presence lease + durable mailbox + SSE/event-bus** layer. They require no Agent Card, URL, registration, credential, refresh, or restart when another session appears or is renamed.
-```bash
-OS_A2A_ALLOW_LOOPBACK=1
-```
-
-Rebuild/restart the service after changing its environment. This flag changes only A2A discovery/register/message/handoff traffic. It does not relax the generic provider HTTP client or any other MSO HTTP surface.
-
-By default, A2A accepts HTTP only when the literal destination is exactly `127.0.0.1`, `[::1]`, or `localhost`. It still rejects RFC1918 ranges, carrier/private ranges, link-local, Docker/LAN addresses, wildcard addresses, `.local`/`.lan` style hosts, and any non-loopback hostname whose DNS resolves to a private/loopback/link-local address. Public destinations continue to use HTTPS plus DNS re-resolution, resolved-IP pinning, and redirect refusal.
-
-MSO treats each durable terminal AI session as a local A2A target. A session records its current working directory when created/resumed/updated, so another session can resolve it by:
-
-- explicit session title, e.g. `bece`;
-- full or unique session id;
-- absolute working directory, e.g. `/home/rahman/projects/mso`;
-- unique working-directory basename when unambiguous.
-
-If a title/location matches multiple sessions, resolution fails instead of guessing.
+See [Local Agents](./LOCAL-AGENTS.md) for lifecycle (`ready` / `idle` / `busy` / `offline` / `ended`), `[agent-a]` labels, duplicate-name behavior, delivery statuses, storage, TUI commands, tools, and API.
-Typical baco → bece flow on one VPS:
-
-```bash
-# Terminal A
-mso agent
-/title baco
-
-# Terminal B
-mso agent
-/title bece
-
-# From either shell, inspect local durable sessions
-mso a2a sessions
-
-# Ask the bece session-context agent to do one delegated task
-mso a2a local handoff bece "inspect the current project and report the next safe step"
-
-# Inspect tasks addressed to bece
-mso a2a inbox bece
-```
-
-Inside interactive `mso agent`, `/agents` shows remote peers plus local sessions. `/delegate bece <objective>` tries a local session name/id/cwd first and falls back to a registered remote A2A peer only when no local session matches. `/spawn [--name <name>] <objective>` creates and runs a child from the current terminal session context, while `/inbox` shows tasks addressed to the current durable session.
-
-A local handoff uses the target session's bounded durable history, memory snapshot, compacted context, and working-directory identity as context. It does **not** inject keystrokes into another TTY or impersonate that live terminal process. This avoids races with a human typing in that terminal.
-
-To spawn a same-host sub-agent from an existing session context without opening another public endpoint:
-
-```bash
-mso a2a spawn baco "audit the A2A tests and return only failures" "baco-test-subagent"
-# namespaced equivalent:
-mso a2a local spawn baco "audit the A2A tests and return only failures" "baco-test-subagent"
-```
-
-The child is a durable MSO session with `parentSessionId` and inherited cwd/context snapshot, runs the delegated objective, and returns its A2A task result to the caller. `inbox` is read-only task inspection; it does not inject a new prompt into the terminal. No credential/token needs to be copied between local sessions.
-
-For raw A2A protocol testing, each local session exposes a virtual Agent Card through the same loopback-only MSO service, for example:
-
-```text
-http://127.0.0.1:4005/.well-known/agent-card.json?session=<session-id>
-```
-
-MSO uses an owner-private internal loopback bearer automatically for this virtual-card path. It is not returned by CLI/state APIs and should not be requested or copied manually.
+The older `mso a2a local ...` and loopback virtual-card helpers remain as compatibility/protocol-testing surfaces for one-shot local delegation. They are not the native live-session transport. `OS_A2A_ALLOW_LOOPBACK=0` can disable those legacy A2A-over-loopback paths without disabling Local Agents.
## Outbound peers and credentials
@@ -211,13 +155,9 @@ Inbound task execution is rate-limited by both source IP and bearer profile, and
## Interactive Agent and MCP
-Inside interactive MSO Agent:
-
-- `/agents` lists registered A2A peers.
-- `/delegate <peer> <objective>` uses the explicit-context handoff boundary.
-- A2A/delegate/handoff intent loads A2A tools on demand instead of keeping them in every model turn.
+Inside interactive MSO Agent, `/agents` renders **Local session agents** and **Remote A2A v1 peers** as separate groups. `/delegate <target> <objective>` sends a native local task when a local session matches, then falls back to the explicit remote A2A handoff boundary only when no local target exists. `/message` is local-only. See [Local Agents](./LOCAL-AGENTS.md).
-The provider-neutral MCP catalog remains intentionally generic:
+Remote A2A/delegate/handoff intent still loads the A2A tools on demand instead of keeping them in every model turn. The provider-neutral remote A2A MCP catalog remains intentionally generic:
| Tool | Scope | Purpose |
|---|---|---|
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 6fb1e1f5..def8c3eb 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `agent` add native local session messaging
- `agent` add restart and new session
- `a2a` enable local and inbound defaults
- ship authenticated and local A2A
diff --git a/docs/CLI.md b/docs/CLI.md
index a972bd66..e445088b 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -104,6 +104,7 @@ Commands:
ai <prompt…> One turn with the assistant
threads * Conversation history: list | show | rm
agent-sessions * Durable MSO Agent sessions: list | show | create
+ agents * Native local session agents: list | send | inbox
a2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoff
memory * Assistant memories: list | add | rm
config * Advanced raw AI config compatibility surface
diff --git a/docs/LOCAL-AGENTS.md b/docs/LOCAL-AGENTS.md
new file mode 100644
index 00000000..ad67cdf4
--- /dev/null
+++ b/docs/LOCAL-AGENTS.md
@@ -0,0 +1,162 @@
+# Local Agents — native same-host session messaging
+
+MSO 1.9 separates **local session messaging** from **remote A2A v1**.
+
+Local Agents is the host-local transport for live MSO sessions. It does not use Agent Cards, peer registration, public URLs, A2A credentials, or the A2A JSON-RPC protocol. Remote agents still use the standard A2A v1 surface documented in [A2A.md](./A2A.md).
+
+## UX
+
+Open two interactive MSO Agent terminals. No setup step is required:
+
+```text
+Terminal A Terminal B
+[agent-a] [agent-b]
+```
+
+A manual durable-session rename becomes the primary local identity immediately:
+
+```text
+/title zahra /title rahman
+[zahra] [rahman]
+```
+
+No other terminal needs a refresh or restart. Directory reads resolve the current durable session title each time, while receive delivery stays attached through a host-local SSE stream.
+
+Useful TUI commands:
+
+```text
+/agents
+/message rahman please check the latest result
+/delegate rahman review this change and report risks
+/inbox
+```
+
+From the ordinary shell, the same native route has an explicit CLI group for scripting/inspection:
+
+```text
+mso agents list
+mso agents send <source-session-id> rahman "please check the latest result"
+mso agents inbox <session-id>
+```
+
+`/message` sends kind `message`. `/delegate` first sends a native local kind `task`; only when there is no matching local target does it fall back to a registered **remote** A2A v1 peer. `/agents` shows local live sessions and remote peers as separate groups.
+
+Incoming terminal events are not stored as user turns. They are rendered distinctly, for example:
+
+```text
+[agent-zahra] please check the latest result
+[agent-zahra] task review this change and report risks
+```
+
+The durable history row keeps role `agent`. When the next model turn needs conversation context, MSO projects that row to a provider-compatible user-role envelope such as `[LOCAL AGENT [zahra] · task] ...`; this preserves provider compatibility without pretending that the human sent the message.
+
+## Presence lifecycle
+
+Local Agents uses a small private lease store rather than rewriting the potentially large durable session JSON on every heartbeat.
+
+| Status | Meaning |
+|---|---|
+| `ready` | Receiver registered and can accept local events while startup/session binding completes. |
+| `idle` | Receiver is live and waiting/available. |
+| `busy` | The session is executing a model/tool turn. New messages are stored as `queued`. |
+| `offline` | The receive lease expired; this is derived, not written as a permanent state. |
+| `ended` | The current receiver explicitly released that session, e.g. clean terminal exit or switching to another durable session. |
+
+Interactive CLI sessions maintain a lightweight lease heartbeat and one SSE receive stream. There is no message polling loop. `/new` and `/resume` release the old receiver and bind the same terminal to the new durable session automatically. `/restart` keeps the exact durable session alive across process replacement and the replacement process renews its lease.
+
+MCP conversation sessions have no persistent terminal socket, so MSO refreshes their lease around bound MCP tool calls. Messages remain durable when that client is not currently connected and can be read with `local_agent_inbox` on a later call.
+
+Only `ready`, `idle`, and `busy` sessions appear in the normal active target list. An explicitly addressed known `offline`/`ended` target can still receive a durable queued message; the sender receives `target_offline` instead of a false delivered status.
+
+## Identity and duplicate names
+
+The first live unnamed session for one principal receives stable alias `agent-a`, then `agent-b`, through `agent-z`, `agent-aa`, and so on. The alias is stored with presence and does not depend on UUID display or list order.
+
+A session title is used as its local label only when the existing rename flow marks it `manual`. Automatic conversation titles do not silently replace `[agent-a]` style identity.
+
+If two active sessions are manually renamed to the same title, internal durable IDs remain unique and the UI adds the alias suffix as a light disambiguator:
+
+```text
+[zahra · a]
+[zahra · b]
+```
+
+A duplicate bare name is rejected as ambiguous. The displayed disambiguated label, stable alias, or exact durable session ID remains addressable.
+
+## Delivery semantics
+
+Local messages use a private durable mailbox plus an in-process event bus for immediate wake-up. The event bus is an optimization; the mailbox is authoritative, so a server/client disconnect does not lose accepted data.
+
+Sender-visible statuses:
+
+| Status | Meaning |
+|---|---|
+| `delivered` | Persisted and handed to a live local receiver stream. It remains replayable until acknowledged. |
+| `accepted` | Persisted for a live non-busy target, but no receive-stream listener was present at that instant. |
+| `queued` | Persisted while the target is `busy`; an idle transition flushes the queue. |
+| `target_offline` | Target is known but its receiver is offline/ended. The message remains queued for the next receiver. |
+| `failed` | Reserved for a delivery/store failure; schema/target errors are returned as request errors instead of fake delivery. |
+
+The receiver acknowledges a message only after it has appended the distinct `agent` history row and persisted the durable session. Reconnecting SSE clients replay unread mailbox entries, so an event marked delivered is not equivalent to "irreversibly consumed".
+
+## Security and isolation
+
+Local messaging is scoped to the exact durable-session principal. A sender can resolve, list, send to, and read inboxes only inside that same principal hash.
+
+For example:
+
+- CLI terminals using the same approved CLI device principal can communicate.
+- MCP conversations belonging to the same MCP client principal can communicate.
+- another MCP client/device/A2A inbound principal cannot discover or address those sessions through Local Agents.
+
+A message contains only the explicit `message` string plus minimal routing metadata (`senderSessionId`, target ID, labels, kind, timestamps). MSO does **not** copy hidden transcript history, memory snapshots, credentials, authorization headers, tool arguments, file contents, or workflow state into a local message.
+
+Payloads are limited to **16 KiB**, known secret-shaped values are redacted before persistence, terminal control bytes are stripped, and both private stores use owner-only `0700/0600`, no-follow reads, bounded size, security-store locking, and atomic replacement.
+
+Receiving a local message grants no capability. The next model turn still has exactly the session's normal tool catalog, deployment scope, and `ask` / `auto-write` / `yolo` approval behavior.
+
+## MCP tools
+
+Local messaging has explicit tools so it cannot be confused with public A2A peers:
+
+| Tool | Scope | Purpose |
+|---|---|---|
+| `local_agents_list` | read | List automatically discovered same-principal live sessions. |
+| `local_agent_message_send` | write | Send an explicit `message` or `task`; no hidden context is attached. |
+| `local_agent_inbox` | read | Read this exact durable session's mailbox and optionally acknowledge returned items. |
+
+Remote A2A tools retain their existing names (`a2a_agent_*`, `a2a_message_send`, `a2a_handoff`, etc.) and behavior.
+
+## Host-local API
+
+Interactive MSO uses the owner-authenticated API below. It is not a public A2A endpoint:
+
+```text
+GET /api/v1/local-agents?session=<current-session-id>
+GET /api/v1/local-agents?inbox=1&session=<session-id>
+GET /api/v1/local-agents?stream=1&session=<session-id> # SSE
+POST /api/v1/local-agents { action: "send", ... }
+POST /api/v1/local-agents { action: "ack", ... }
+POST /api/v1/local-agents { action: "presence", ... } # client lifecycle
+POST /api/v1/local-agents { action: "end", ... } # client lifecycle
+```
+
+The normal owner UI/CLI should use TUI commands or MCP tools rather than manually managing presence. Presence and stream operations exist for the MSO client runtime, not as user setup steps.
+
+## Storage
+
+Defaults:
+
+```text
+OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json
+OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json
+OS_LOCAL_AGENT_LEASE_MS=60000
+```
+
+No external broker, database, daemon, or framework is required.
+
+## Relationship to legacy same-host A2A helpers
+
+Older `mso a2a local ...` one-shot delegation/virtual-loopback-card helpers remain for backward compatibility and protocol testing. They are **not** the transport used by `/agents`, `/message`, local `/delegate`, the Local Agents MCP tools, or live inbox delivery in MSO 1.9.
+
+New same-host communication should use Local Agents. Public/remote interoperability should use A2A v1.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index e52a808f..835078b8 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,17 @@
Running log of what shipped each phase. Newest at top.
+## 2026-09-02 — MSO 1.9.0 native Local Agents
+
+- **Transport split:** live same-host session communication is now a native Local Agents layer, separate from remote A2A v1. No Agent Card, URL, registration, bearer, refresh, or restart is part of local discovery/delivery.
+- **Automatic presence:** interactive CLI sessions maintain a small private lease plus one SSE feed. `ready`, `idle`, `busy`, `offline`, and `ended` have explicit semantics; MCP conversation sessions refresh the same lease around bound tool calls.
+- **Readable identity:** unnamed live sessions receive stable per-principal `[agent-a]`, `[agent-b]`, … aliases. Manual `agent_session_rename`/`/title` names become primary immediately; duplicate manual names use a light alias suffix and ambiguous bare names fail instead of guessing.
+- **Durable mailbox:** explicit 16 KiB `message`/`task` payloads persist privately before notification. Idle delivery can be `delivered`/`accepted`, busy targets are `queued`, and known expired/ended targets return `target_offline` while retaining the message for a later receiver.
+- **TUI:** `/agents`, `/message`, local `/delegate`, and `/inbox` use the native layer. Incoming events redraw above an active composer without losing draft input, persist as role `agent`, and project to a provider-compatible labeled envelope only when model context is built.
+- **Tools/API:** added `local_agents_list` (read), `local_agent_message_send` (write), `local_agent_inbox` (read), plus owner-authenticated `/api/v1/local-agents`. Receiving a local message never expands tool/file/shell/network authority.
+- **Isolation:** directory/mailbox operations require the exact same durable-session principal; only explicit text plus minimal routing metadata is copied. Private stores use bounded 0600 atomic persistence and security-store locking.
+- **Remote compatibility:** public A2A v1 registry, Agent Cards, credentials, send/task/handoff, inbound serving, and loopback compatibility helpers remain intact and are no longer the path used by native live-session UX.
+
## 2026-09-02 — MSO 1.8.2 constant-depth Agent restart
- **Restart lifecycle fix:** `/restart` now uses process replacement (`execve`) instead of `spawnSync`. Repeated refreshes no longer leave prior Agent processes blocked behind their children.
diff --git a/docs/README.md b/docs/README.md
index aae670bd..ac97e356 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -31,6 +31,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`CLI.md`](./CLI.md) | Generated `mso` CLI contract |
| [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |
| [`A2A.md`](./A2A.md) | A2A v1 peer discovery, delegation/task lifecycle, CLI/MCP surface and trust boundary |
+| [`LOCAL-AGENTS.md`](./LOCAL-AGENTS.md) | Native same-host session presence, identity, mailbox delivery, TUI/tools/API and isolation |
| [`MCP-FEATURE-IMPLEMENTATION.md`](./MCP-FEATURE-IMPLEMENTATION.md) | Stepwise reverse-engineering workflow for MCP tools, trusted skills and project capabilities |
| [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup, diagrams, scopes and file bridge |
| [`CONNECTORS-GATEWAY-INTEGRATION.md`](./CONNECTORS-GATEWAY-INTEGRATION.md) | MSO ↔ connectors-gateway action-name contract |
diff --git a/lib/agent/local-agent-directory.ts b/lib/agent/local-agent-directory.ts
new file mode 100644
index 00000000..1f2c9927
--- /dev/null
+++ b/lib/agent/local-agent-directory.ts
@@ -0,0 +1,103 @@
+import path from "node:path";
+import { listAgentSessions } from "./session-store";
+import { listLocalAgentPresence, localAgentStatus } from "./local-agent-presence";
+import type { AgentSessionSummary } from "./session-types";
+import type { LocalAgentPresenceRecord, LocalAgentTarget } from "./local-agent-types";
+
+function normalizeRef(value: string): string {
+ const clean = String(value || "").trim();
+ return clean.startsWith("[") && clean.endsWith("]") ? clean.slice(1, -1).trim() : clean;
+}
+
+function cleanDisplayName(value: string): string {
+ return String(value || "")
+ .replace(/[\u0000-\u001f\u007f]/g, " ")
+ .replace(/[\[\]]/g, "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .slice(0, 80);
+}
+
+function manualName(session: AgentSessionSummary): string | null {
+ const name = session.titleSource === "manual" ? cleanDisplayName(session.title) : "";
+ return name || null;
+}
+
+function buildRows(
+ sessions: AgentSessionSummary[],
+ presence: LocalAgentPresenceRecord[],
+ now: number,
+): LocalAgentTarget[] {
+ const byId = new Map(sessions.map((row) => [row.id, row]));
+ const raw = presence.flatMap((entry) => {
+ const session = byId.get(entry.sessionId);
+ if (!session) return [];
+ return [{ session, entry, status: localAgentStatus(entry, now), manual: manualName(session) }];
+ });
+ const duplicateNames = new Map<string, number>();
+ for (const row of raw) {
+ if (!row.manual || row.status === "offline" || row.status === "ended") continue;
+ const key = row.manual.toLocaleLowerCase();
+ duplicateNames.set(key, (duplicateNames.get(key) || 0) + 1);
+ }
+ return raw.map(({ session, entry, status, manual }) => {
+ const duplicate = manual && (duplicateNames.get(manual.toLocaleLowerCase()) || 0) > 1;
+ const suffix = entry.alias.replace(/^agent-/, "");
+ const label = manual ? `[${manual}${duplicate ? ` · ${suffix}` : ""}]` : `[${entry.alias}]`;
+ return {
+ id: session.id,
+ alias: entry.alias,
+ label,
+ source: session.source,
+ title: session.title,
+ titleSource: session.titleSource,
+ status,
+ ...(session.cwd ? { cwd: session.cwd } : {}),
+ lastSeenAt: entry.lastSeenAt,
+ };
+ });
+}
+
+export async function listLocalAgents(
+ principal: string,
+ options: { currentSessionId?: string; includeOffline?: boolean; now?: number } = {},
+): Promise<LocalAgentTarget[]> {
+ const now = options.now ?? Date.now();
+ const [sessions, presence] = await Promise.all([
+ listAgentSessions(principal, 500),
+ listLocalAgentPresence(principal),
+ ]);
+ return buildRows(sessions, presence, now)
+ .filter((row) => options.includeOffline || !["offline", "ended"].includes(row.status))
+ .filter((row) => !options.currentSessionId || row.id !== options.currentSessionId)
+ .sort((a, b) => a.alias.localeCompare(b.alias, undefined, { numeric: true }));
+}
+
+function matches(row: LocalAgentTarget, ref: string): boolean {
+ const wanted = normalizeRef(ref).toLocaleLowerCase();
+ const label = normalizeRef(row.label).toLocaleLowerCase();
+ const title = row.titleSource === "manual" ? cleanDisplayName(row.title).toLocaleLowerCase() : "";
+ const cwd = row.cwd ? path.resolve(row.cwd).toLocaleLowerCase() : "";
+ const base = row.cwd ? path.basename(row.cwd).toLocaleLowerCase() : "";
+ return [row.id.toLocaleLowerCase(), row.alias.toLocaleLowerCase(), label, title, cwd, base].includes(wanted);
+}
+
+export async function resolveLocalAgent(
+ principal: string,
+ ref: string,
+ currentSessionId?: string,
+): Promise<LocalAgentTarget> {
+ const wanted = normalizeRef(ref);
+ if (!wanted) throw new Error("local agent target is required");
+ const rows = await listLocalAgents(principal, { includeOffline: true });
+ const matched = rows.filter((row) => matches(row, wanted));
+ if (!matched.length) throw new Error("local agent target not found");
+ const active = matched.filter((row) => !["offline", "ended"].includes(row.status));
+ if (active.length > 1 || (!active.length && matched.length > 1)) {
+ const choices = (active.length ? active : matched).map((row) => row.alias).join(" or ");
+ throw new Error(`local agent target is ambiguous; use ${choices}`);
+ }
+ const target = active[0] || matched[0];
+ if (target.id === currentSessionId) throw new Error("cannot send a local agent message to the same session");
+ return target;
+}
diff --git a/lib/agent/local-agent-events.ts b/lib/agent/local-agent-events.ts
new file mode 100644
index 00000000..dc6cfac0
--- /dev/null
+++ b/lib/agent/local-agent-events.ts
@@ -0,0 +1,27 @@
+import type { LocalAgentMessageView } from "./local-agent-types";
+
+type Listener = (message: LocalAgentMessageView) => void;
+const listeners = new Map<string, Set<Listener>>();
+
+export function subscribeLocalAgentMessages(sessionId: string, listener: Listener): () => void {
+ const set = listeners.get(sessionId) ?? new Set<Listener>();
+ set.add(listener);
+ listeners.set(sessionId, set);
+ return () => {
+ set.delete(listener);
+ if (!set.size) listeners.delete(sessionId);
+ };
+}
+
+export function publishLocalAgentMessage(sessionId: string, message: LocalAgentMessageView): number {
+ let delivered = 0;
+ for (const listener of listeners.get(sessionId) ?? []) {
+ try {
+ listener(message);
+ delivered += 1;
+ } catch {
+ // Durable mailbox remains authoritative when a listener disappears mid-send.
+ }
+ }
+ return delivered;
+}
diff --git a/lib/agent/local-agent-mailbox.ts b/lib/agent/local-agent-mailbox.ts
new file mode 100644
index 00000000..c77f749e
--- /dev/null
+++ b/lib/agent/local-agent-mailbox.ts
@@ -0,0 +1,110 @@
+import { randomUUID } from "node:crypto";
+import os from "node:os";
+import path from "node:path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { getAgentSession } from "./session-store";
+import { principalHash, SESSION_ID } from "./session-files";
+import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";
+import type { LocalAgentMessageView, LocalAgentStoredMessage, LocalAgentStoredMessageState } from "./local-agent-types";
+
+type MailboxStore = { version: 1; messages: LocalAgentStoredMessage[] };
+const MAX_STORE_BYTES = 4 * 1024 * 1024;
+const MAX_MESSAGES = 2000;
+const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
+const STORE_PATH = process.env.OS_LOCAL_AGENT_MESSAGE_STORE ?? path.join(os.homedir(), ".mso", "private", "local-agent-messages.json");
+const EMPTY: MailboxStore = { version: 1, messages: [] };
+
+function validMessage(value: unknown): value is LocalAgentStoredMessage {
+ if (!value || typeof value !== "object") return false;
+ const row = value as LocalAgentStoredMessage;
+ return /^localmsg_[0-9a-f-]{36}$/.test(String(row.id || "")) && /^[a-f0-9]{64}$/.test(String(row.principalHash || "")) &&
+ SESSION_ID.test(String(row.senderSessionId || "")) && SESSION_ID.test(String(row.targetSessionId || "")) &&
+ typeof row.senderLabel === "string" && row.senderLabel.length <= 200 && typeof row.targetLabel === "string" && row.targetLabel.length <= 200 &&
+ ["message", "task"].includes(String(row.kind)) && typeof row.text === "string" && Buffer.byteLength(row.text, "utf8") <= 16 * 1024 &&
+ ["accepted", "queued", "delivered", "read"].includes(String(row.state)) && Number.isFinite(Date.parse(String(row.createdAt || ""))) &&
+ (!row.deliveredAt || Number.isFinite(Date.parse(row.deliveredAt))) && (!row.readAt || Number.isFinite(Date.parse(row.readAt)));
+}
+
+function validStore(value: unknown): value is MailboxStore {
+ if (!value || typeof value !== "object") return false;
+ const row = value as MailboxStore;
+ return row.version === 1 && Array.isArray(row.messages) && row.messages.length <= MAX_MESSAGES && row.messages.every(validMessage);
+}
+
+async function readStore(): Promise<MailboxStore> {
+ return readLocalAgentStore(STORE_PATH, MAX_STORE_BYTES, EMPTY, validStore);
+}
+
+function view(row: LocalAgentStoredMessage): LocalAgentMessageView {
+ const { principalHash: _principalHash, ...safe } = row;
+ return safe;
+}
+
+function prune(messages: LocalAgentStoredMessage[], now = Date.now()): LocalAgentStoredMessage[] {
+ return messages
+ .filter((row) => {
+ const created = Date.parse(row.createdAt);
+ return Number.isFinite(created) && now - created <= RETENTION_MS;
+ })
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
+ .slice(-MAX_MESSAGES);
+}
+
+export async function enqueueLocalAgentMessage(input: Omit<LocalAgentStoredMessage, "id" | "createdAt">): Promise<LocalAgentMessageView> {
+ const now = new Date().toISOString();
+ const row: LocalAgentStoredMessage = {
+ ...input,
+ id: `localmsg_${randomUUID()}`,
+ createdAt: now,
+ };
+ return withSecurityStoreLock(STORE_PATH, async () => {
+ const store = await readStore();
+ store.messages = prune([...store.messages, row]);
+ await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);
+ return view(row);
+ });
+}
+
+export async function updateLocalAgentMessageState(
+ principal: string,
+ targetSessionId: string,
+ messageIds: string[],
+ state: LocalAgentStoredMessageState,
+): Promise<LocalAgentMessageView[]> {
+ const session = await getAgentSession(principal, targetSessionId);
+ if (!session) throw new Error("local agent target not found for this client");
+ const owner = principalHash(principal);
+ const wanted = new Set(messageIds.filter((id) => /^localmsg_[0-9a-f-]{36}$/.test(id)).slice(0, 200));
+ if (!wanted.size) return [];
+ return withSecurityStoreLock(STORE_PATH, async () => {
+ const store = await readStore();
+ const now = new Date().toISOString();
+ const changed: LocalAgentMessageView[] = [];
+ for (const row of store.messages) {
+ if (row.principalHash !== owner || row.targetSessionId !== targetSessionId || !wanted.has(row.id)) continue;
+ row.state = state;
+ if ((state === "delivered" || state === "read") && !row.deliveredAt) row.deliveredAt = now;
+ if (state === "read") row.readAt = now;
+ changed.push(view(row));
+ }
+ await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);
+ return changed;
+ });
+}
+
+export async function listLocalAgentInbox(
+ principal: string,
+ targetSessionId: string,
+ options: { includeRead?: boolean; limit?: number } = {},
+): Promise<LocalAgentMessageView[]> {
+ const session = await getAgentSession(principal, targetSessionId);
+ if (!session) throw new Error("local agent target not found for this client");
+ const owner = principalHash(principal);
+ const limit = Math.max(1, Math.min(200, Math.trunc(options.limit || 100)));
+ return (await readStore()).messages
+ .filter((row) => row.principalHash === owner && row.targetSessionId === targetSessionId)
+ .filter((row) => options.includeRead || row.state !== "read")
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
+ .slice(-limit)
+ .map(view);
+}
diff --git a/lib/agent/local-agent-messaging.test.ts b/lib/agent/local-agent-messaging.test.ts
new file mode 100644
index 00000000..95c89ff3
--- /dev/null
+++ b/lib/agent/local-agent-messaging.test.ts
@@ -0,0 +1,141 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { mkdtempSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const root = mkdtempSync(path.join(os.tmpdir(), "mso-local-agent-messaging-"));
+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");
+process.env.OS_LOCAL_AGENT_PRESENCE_STORE = path.join(root, "presence.json");
+process.env.OS_LOCAL_AGENT_MESSAGE_STORE = path.join(root, "messages.json");
+process.env.OS_LOCAL_AGENT_LEASE_MS = "15000";
+process.env.NEXT_PUBLIC_OS_DEMO = "0";
+
+const store = await import("./session-store");
+const presence = await import("./local-agent-presence");
+const directory = await import("./local-agent-directory");
+const mailbox = await import("./local-agent-mailbox");
+const messaging = await import("./local-agent-messaging");
+const events = await import("./local-agent-events");
+
+const owner = "mcp-client:alpha";
+let a: Awaited<ReturnType<typeof store.createAgentSession>>;
+let b: Awaited<ReturnType<typeof store.createAgentSession>>;
+
+beforeAll(async () => {
+ a = await store.createAgentSession(owner, "mcp");
+ b = await store.createAgentSession(owner, "mcp");
+ await presence.touchLocalAgentPresence(owner, a.id, "idle", "test:a");
+ await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b");
+});
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe("native local session agents", () => {
+ it("assigns deterministic readable placeholders to two live unnamed sessions", async () => {
+ const rows = await directory.listLocalAgents(owner);
+ expect(rows.map((row) => row.label)).toEqual(["[agent-a]", "[agent-b]"]);
+ expect(rows.map((row) => row.status)).toEqual(["idle", "idle"]);
+ });
+
+ it("manual rename changes the label without changing the durable identity", async () => {
+ const id = a.id;
+ await store.renameAgentSession(owner, a.id, "zahra");
+ const rows = await directory.listLocalAgents(owner);
+ expect(rows.find((row) => row.id === id)?.label).toBe("[zahra]");
+ expect(rows.find((row) => row.id === id)?.id).toBe(id);
+ });
+
+ it("lightly disambiguates duplicate manual names while preserving aliases", async () => {
+ await store.renameAgentSession(owner, b.id, "zahra");
+ const rows = await directory.listLocalAgents(owner);
+ expect(rows.map((row) => row.label)).toEqual(["[zahra · a]", "[zahra · b]"]);
+ expect(() => rows.map((row) => row.alias)).not.toThrow();
+ await store.renameAgentSession(owner, b.id, "rahman");
+ });
+
+ it("delivers an idle-target message to the live feed and durable inbox", async () => {
+ const received: unknown[] = [];
+ const unsubscribe = events.subscribeLocalAgentMessages(b.id, (message) => received.push(message));
+ const result = await messaging.sendLocalAgentMessage({
+ principal: owner,
+ senderSessionId: a.id,
+ target: "rahman",
+ text: "please review this",
+ kind: "message",
+ });
+ unsubscribe();
+ expect(result.status).toBe("delivered");
+ expect(result.sender.label).toBe("[zahra]");
+ expect(result.target.label).toBe("[rahman]");
+ expect(received).toHaveLength(1);
+ const inbox = await mailbox.listLocalAgentInbox(owner, b.id);
+ expect(inbox.some((row) => row.id === result.message.id && row.text === "please review this")).toBe(true);
+ });
+
+ it("queues while busy and delivers when the target becomes idle", async () => {
+ await presence.touchLocalAgentPresence(owner, b.id, "busy", "test:b");
+ const result = await messaging.sendLocalAgentMessage({
+ principal: owner,
+ senderSessionId: a.id,
+ target: "agent-b",
+ text: "queued task",
+ kind: "task",
+ });
+ expect(result.status).toBe("queued");
+ expect(result.message.state).toBe("queued");
+ const received: string[] = [];
+ const unsubscribe = events.subscribeLocalAgentMessages(b.id, (message) => received.push(message.id));
+ await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b");
+ expect(await messaging.flushLocalAgentQueue(owner, b.id)).toBeGreaterThanOrEqual(1);
+ unsubscribe();
+ expect(received).toContain(result.message.id);
+ });
+
+ it("returns target_offline for a known expired receiver while retaining the payload", async () => {
+ const old = Date.now() - 30_000;
+ await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b", old);
+ const rows = await directory.listLocalAgents(owner, { includeOffline: true });
+ expect(rows.find((row) => row.id === b.id)?.status).toBe("offline");
+ expect((await directory.listLocalAgents(owner)).some((row) => row.id === b.id)).toBe(false);
+ const result = await messaging.sendLocalAgentMessage({
+ principal: owner,
+ senderSessionId: a.id,
+ target: "rahman",
+ text: "hold until you return",
+ });
+ expect(result.status).toBe("target_offline");
+ expect(result.targetStatus).toBe("offline");
+ expect(result.message.state).toBe("queued");
+ await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b");
+ });
+
+ it("redacts secret-shaped payload values and strips terminal control bytes", async () => {
+ const result = await messaging.sendLocalAgentMessage({
+ principal: owner, senderSessionId: a.id, target: "rahman",
+ text: "\u001b[31mpassword=supersecret\u001b[0m",
+ });
+ expect(result.message.text).not.toContain("\u001b");
+ expect(result.message.text).toContain("password=[redacted]");
+ expect(result.message.text).not.toContain("supersecret");
+ });
+
+ it("rejects invalid target and oversized payload", async () => {
+ await expect(messaging.sendLocalAgentMessage({
+ principal: owner, senderSessionId: a.id, target: "does-not-exist", text: "x",
+ })).rejects.toThrow(/target not found/);
+ await expect(messaging.sendLocalAgentMessage({
+ principal: owner, senderSessionId: a.id, target: "rahman", text: "x".repeat(17 * 1024),
+ })).rejects.toThrow(/16 KiB/);
+ });
+
+ it("isolates discovery, send, and inbox by session principal", async () => {
+ const other = "mcp-client:other";
+ const foreign = await store.createAgentSession(other, "mcp", { title: "foreign", titleSource: "manual" });
+ await presence.touchLocalAgentPresence(other, foreign.id, "idle", "other:1");
+ expect((await directory.listLocalAgents(owner)).some((row) => row.id === foreign.id)).toBe(false);
+ await expect(messaging.sendLocalAgentMessage({
+ principal: owner, senderSessionId: a.id, target: "foreign", text: "nope",
+ })).rejects.toThrow(/target not found/);
+ await expect(mailbox.listLocalAgentInbox(owner, foreign.id)).rejects.toThrow(/not found/);
+ });
+});
diff --git a/lib/agent/local-agent-messaging.ts b/lib/agent/local-agent-messaging.ts
new file mode 100644
index 00000000..b565fc09
--- /dev/null
+++ b/lib/agent/local-agent-messaging.ts
@@ -0,0 +1,94 @@
+import { redactText } from "@/lib/security/redact-text";
+import { getAgentSession } from "./session-store";
+import { principalHash } from "./session-files";
+import { listLocalAgents, resolveLocalAgent } from "./local-agent-directory";
+import { enqueueLocalAgentMessage, listLocalAgentInbox, updateLocalAgentMessageState } from "./local-agent-mailbox";
+import { publishLocalAgentMessage } from "./local-agent-events";
+import type { LocalAgentDeliveryStatus, LocalAgentMessageKind, LocalAgentMessageView, LocalAgentTarget } from "./local-agent-types";
+
+export const MAX_LOCAL_AGENT_MESSAGE_BYTES = 16 * 1024;
+
+function safePayload(value: string): string {
+ const raw = String(value || "").trim();
+ if (!raw) throw new Error("local agent message is required");
+ if (Buffer.byteLength(raw, "utf8") > MAX_LOCAL_AGENT_MESSAGE_BYTES)
+ throw new Error("local agent message must be 16 KiB or smaller");
+ const text = raw
+ .replace(/\r/g, "")
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "")
+ .replace(/\t/g, " ");
+ return redactText(text, MAX_LOCAL_AGENT_MESSAGE_BYTES);
+}
+
+function messageKind(value?: string): LocalAgentMessageKind {
+ if (!value || value === "message") return "message";
+ if (value === "task") return "task";
+ throw new Error("local agent message kind must be message or task");
+}
+
+async function senderTarget(principal: string, sessionId: string): Promise<LocalAgentTarget> {
+ const session = await getAgentSession(principal, sessionId);
+ if (!session) throw new Error("local agent sender not found for this client");
+ const rows = await listLocalAgents(principal, { includeOffline: true });
+ const row = rows.find((item) => item.id === sessionId);
+ if (!row) throw new Error("local agent sender is not live");
+ return row;
+}
+
+export async function sendLocalAgentMessage(input: {
+ principal: string;
+ senderSessionId: string;
+ target: string;
+ text: string;
+ kind?: string;
+}): Promise<{
+ status: LocalAgentDeliveryStatus;
+ targetStatus: LocalAgentTarget["status"];
+ sender: LocalAgentTarget;
+ target: LocalAgentTarget;
+ message: LocalAgentMessageView;
+}> {
+ const [sender, target] = await Promise.all([
+ senderTarget(input.principal, input.senderSessionId),
+ resolveLocalAgent(input.principal, input.target, input.senderSessionId),
+ ]);
+ const text = safePayload(input.text);
+ const kind = messageKind(input.kind);
+ const owner = principalHash(input.principal);
+ const targetOffline = target.status === "offline" || target.status === "ended";
+ const busy = target.status === "busy";
+ let message = await enqueueLocalAgentMessage({
+ principalHash: owner,
+ senderSessionId: sender.id,
+ senderLabel: sender.label,
+ targetSessionId: target.id,
+ targetLabel: target.label,
+ kind,
+ text,
+ state: busy || targetOffline ? "queued" : "accepted",
+ });
+
+ let status: LocalAgentDeliveryStatus = targetOffline ? "target_offline" : busy ? "queued" : "accepted";
+ if (!targetOffline && !busy) {
+ const listeners = publishLocalAgentMessage(target.id, message);
+ if (listeners > 0) {
+ const [updated] = await updateLocalAgentMessageState(input.principal, target.id, [message.id], "delivered");
+ if (updated) message = updated;
+ status = "delivered";
+ }
+ }
+ return { status, targetStatus: target.status, sender, target, message };
+}
+
+
+export async function flushLocalAgentQueue(principal: string, targetSessionId: string): Promise<number> {
+ const pending = (await listLocalAgentInbox(principal, targetSessionId, { limit: 200 }))
+ .filter((row) => row.state === "queued" || row.state === "accepted");
+ let delivered = 0;
+ for (const message of pending) {
+ if (publishLocalAgentMessage(targetSessionId, message) <= 0) continue;
+ await updateLocalAgentMessageState(principal, targetSessionId, [message.id], "delivered");
+ delivered += 1;
+ }
+ return delivered;
+}
diff --git a/lib/agent/local-agent-presence.ts b/lib/agent/local-agent-presence.ts
new file mode 100644
index 00000000..67d0d3bf
--- /dev/null
+++ b/lib/agent/local-agent-presence.ts
@@ -0,0 +1,126 @@
+import os from "node:os";
+import path from "node:path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { getAgentSession } from "./session-store";
+import { principalHash, SESSION_ID } from "./session-files";
+import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";
+import type { LocalAgentPresenceRecord, LocalAgentPresenceState, LocalAgentStatus } from "./local-agent-types";
+
+type PresenceStore = { version: 1; entries: LocalAgentPresenceRecord[] };
+const MAX_STORE_BYTES = 512 * 1024;
+const MAX_ENTRIES = 1000;
+const OFFLINE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
+const STORE_PATH = process.env.OS_LOCAL_AGENT_PRESENCE_STORE ?? path.join(os.homedir(), ".mso", "private", "local-agent-presence.json");
+const EMPTY: PresenceStore = { version: 1, entries: [] };
+
+function validPresence(value: unknown): value is LocalAgentPresenceRecord {
+ if (!value || typeof value !== "object") return false;
+ const row = value as LocalAgentPresenceRecord;
+ return SESSION_ID.test(String(row.sessionId || "")) && /^[a-f0-9]{64}$/.test(String(row.principalHash || "")) &&
+ /^agent-[a-z]+$/.test(String(row.alias || "")) && typeof row.instanceId === "string" && row.instanceId.length > 0 && row.instanceId.length <= 160 &&
+ ["ready", "idle", "busy", "ended"].includes(String(row.state)) && Number.isFinite(Date.parse(String(row.lastSeenAt || ""))) &&
+ Number.isFinite(Date.parse(String(row.leaseUntil || ""))) && (!row.endedAt || Number.isFinite(Date.parse(row.endedAt)));
+}
+
+function validStore(value: unknown): value is PresenceStore {
+ if (!value || typeof value !== "object") return false;
+ const row = value as PresenceStore;
+ return row.version === 1 && Array.isArray(row.entries) && row.entries.length <= MAX_ENTRIES && row.entries.every(validPresence);
+}
+
+function leaseMs(): number {
+ const raw = Number(process.env.OS_LOCAL_AGENT_LEASE_MS);
+ return Number.isFinite(raw) ? Math.max(15_000, Math.min(300_000, Math.trunc(raw))) : 60_000;
+}
+
+function alphaOrdinal(index: number): string {
+ let value = Math.max(0, Math.trunc(index));
+ let out = "";
+ do {
+ out = String.fromCharCode(97 + (value % 26)) + out;
+ value = Math.floor(value / 26) - 1;
+ } while (value >= 0);
+ return out;
+}
+
+function allocateAlias(entries: LocalAgentPresenceRecord[], owner: string): string {
+ const used = new Set(entries.filter((row) => row.principalHash === owner).map((row) => row.alias));
+ for (let i = 0; i < MAX_ENTRIES * 2; i += 1) {
+ const alias = `agent-${alphaOrdinal(i)}`;
+ if (!used.has(alias)) return alias;
+ }
+ throw new Error("local agent alias space is exhausted");
+}
+
+async function readStore(): Promise<PresenceStore> {
+ return readLocalAgentStore(STORE_PATH, MAX_STORE_BYTES, EMPTY, validStore);
+}
+
+function prune(entries: LocalAgentPresenceRecord[], now: number): LocalAgentPresenceRecord[] {
+ return entries
+ .filter((row) => {
+ const last = Date.parse(row.endedAt || row.lastSeenAt);
+ return Number.isFinite(last) && now - last <= OFFLINE_RETENTION_MS;
+ })
+ .sort((a, b) => a.lastSeenAt.localeCompare(b.lastSeenAt))
+ .slice(-MAX_ENTRIES);
+}
+
+export function localAgentStatus(row: LocalAgentPresenceRecord, now = Date.now()): LocalAgentStatus {
+ if (row.state === "ended") return "ended";
+ return Date.parse(row.leaseUntil) > now ? row.state : "offline";
+}
+
+export async function touchLocalAgentPresence(
+ principal: string,
+ sessionId: string,
+ state: Exclude<LocalAgentPresenceState, "ended">,
+ instanceId: string,
+ now = Date.now(),
+): Promise<LocalAgentPresenceRecord> {
+ const session = await getAgentSession(principal, sessionId);
+ if (!session) throw new Error("local agent session not found for this client");
+ if (!instanceId || instanceId.length > 160) throw new Error("invalid local agent instance id");
+ const owner = principalHash(principal);
+ return withSecurityStoreLock(STORE_PATH, async () => {
+ const store = await readStore();
+ const current = store.entries.find((row) => row.sessionId === sessionId && row.principalHash === owner);
+ const at = new Date(now).toISOString();
+ const next: LocalAgentPresenceRecord = {
+ sessionId,
+ principalHash: owner,
+ alias: current?.alias || allocateAlias(store.entries, owner),
+ instanceId: instanceId.slice(0, 160),
+ state,
+ lastSeenAt: at,
+ leaseUntil: new Date(now + leaseMs()).toISOString(),
+ };
+ store.entries = prune(store.entries.filter((row) => !(row.sessionId === sessionId && row.principalHash === owner)), now);
+ store.entries.push(next);
+ await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);
+ return next;
+ });
+}
+
+export async function endLocalAgentPresence(
+ principal: string,
+ sessionId: string,
+ instanceId: string,
+ now = Date.now(),
+): Promise<void> {
+ const owner = principalHash(principal);
+ await withSecurityStoreLock(STORE_PATH, async () => {
+ const store = await readStore();
+ const row = store.entries.find((entry) => entry.sessionId === sessionId && entry.principalHash === owner);
+ if (!row || row.instanceId !== instanceId) return;
+ const at = new Date(now).toISOString();
+ Object.assign(row, { state: "ended", lastSeenAt: at, leaseUntil: at, endedAt: at });
+ store.entries = prune(store.entries, now);
+ await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);
+ });
+}
+
+export async function listLocalAgentPresence(principal: string): Promise<LocalAgentPresenceRecord[]> {
+ const owner = principalHash(principal);
+ return (await readStore()).entries.filter((row) => row.principalHash === owner);
+}
diff --git a/lib/agent/local-agent-private-store.ts b/lib/agent/local-agent-private-store.ts
new file mode 100644
index 00000000..5f5476e2
--- /dev/null
+++ b/lib/agent/local-agent-private-store.ts
@@ -0,0 +1,44 @@
+import { randomUUID } from "node:crypto";
+import { constants as fsConstants, promises as fs } from "node:fs";
+import path from "node:path";
+
+export async function readLocalAgentStore<T>(
+ file: string,
+ maxBytes: number,
+ fallback: T,
+ valid: (value: unknown) => value is T,
+): Promise<T> {
+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
+ try {
+ handle = await fs.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > maxBytes)
+ throw new Error("local agent store has an invalid file shape");
+ if ((stat.mode & 0o077) !== 0)
+ throw new Error("local agent store permissions are too broad; expected 0600");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid())
+ throw new Error("local agent store is not owned by the MSO user");
+ const value = JSON.parse(await handle.readFile("utf8")) as unknown;
+ if (!valid(value)) throw new Error("local agent store has an invalid schema");
+ return value;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return structuredClone(fallback);
+ throw error;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
+export async function writeLocalAgentStore(file: string, value: unknown, maxBytes: number): Promise<void> {
+ const body = JSON.stringify(value, null, 2);
+ if (Buffer.byteLength(body, "utf8") > maxBytes)
+ throw new Error("local agent store exceeds its size budget");
+ const dir = path.dirname(file);
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ await fs.chmod(dir, 0o700).catch(() => undefined);
+ const tmp = `${file}.${randomUUID()}.tmp`;
+ await fs.writeFile(tmp, body, { encoding: "utf8", mode: 0o600, flag: "wx" });
+ await fs.chmod(tmp, 0o600);
+ await fs.rename(tmp, file);
+ await fs.chmod(file, 0o600);
+}
diff --git a/lib/agent/local-agent-types.ts b/lib/agent/local-agent-types.ts
new file mode 100644
index 00000000..4cd93f82
--- /dev/null
+++ b/lib/agent/local-agent-types.ts
@@ -0,0 +1,64 @@
+import type { AgentSessionSource, AgentSessionTitleSource } from "./session-types";
+
+export type LocalAgentPresenceState = "ready" | "idle" | "busy" | "ended";
+export type LocalAgentStatus = LocalAgentPresenceState | "offline";
+export type LocalAgentMessageKind = "message" | "task";
+export type LocalAgentDeliveryStatus =
+ | "accepted"
+ | "delivered"
+ | "queued"
+ | "target_offline"
+ | "failed";
+export type LocalAgentStoredMessageState = "accepted" | "queued" | "delivered" | "read";
+
+export interface LocalAgentPresenceRecord {
+ sessionId: string;
+ principalHash: string;
+ alias: string;
+ instanceId: string;
+ state: LocalAgentPresenceState;
+ lastSeenAt: string;
+ leaseUntil: string;
+ endedAt?: string;
+}
+
+export interface LocalAgentTarget {
+ id: string;
+ alias: string;
+ label: string;
+ source: AgentSessionSource;
+ title: string;
+ titleSource: AgentSessionTitleSource;
+ status: LocalAgentStatus;
+ cwd?: string;
+ lastSeenAt: string;
+}
+
+export interface LocalAgentStoredMessage {
+ id: string;
+ principalHash: string;
+ senderSessionId: string;
+ senderLabel: string;
+ targetSessionId: string;
+ targetLabel: string;
+ kind: LocalAgentMessageKind;
+ text: string;
+ state: LocalAgentStoredMessageState;
+ createdAt: string;
+ deliveredAt?: string;
+ readAt?: string;
+}
+
+export interface LocalAgentMessageView {
+ id: string;
+ senderSessionId: string;
+ senderLabel: string;
+ targetSessionId: string;
+ targetLabel: string;
+ kind: LocalAgentMessageKind;
+ text: string;
+ state: LocalAgentStoredMessageState;
+ createdAt: string;
+ deliveredAt?: string;
+ readAt?: string;
+}
diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.ts
index 4db29588..e9195294 100644
--- a/lib/agent/session-store.ts
+++ b/lib/agent/session-store.ts
@@ -241,7 +241,7 @@ export async function listAgentSessions(
limit = 30,
): Promise<AgentSessionSummary[]> {
const owner = principalHash(principal),
- wanted = Math.max(1, Math.min(200, Math.trunc(limit) || 30));
+ wanted = Math.max(1, Math.min(500, Math.trunc(limit) || 30));
return (await listSessionRecords())
.filter((row) => row.principalHash === owner)
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index 1a4779a6..dfabb44a 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -34,6 +34,7 @@ export type AuditAction =
| "workflow.cancel"
| "workflow.finish"
| "agent.session"
+ | "agent.message"
| "agent.memory"
| "tool.forge.propose"
| "tool.forge.evaluate"
diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.ts
index 862b7557..bd0ab2c2 100644
--- a/lib/mcp/dispatch-tools.ts
+++ b/lib/mcp/dispatch-tools.ts
@@ -1,5 +1,6 @@
import { audit, rateLimited } from "@/lib/host";
import { maybeAutoTitleAgentSession } from "@/lib/agent/session-store";
+import { touchLocalAgentPresence } from "@/lib/agent/local-agent-presence";
import { activeWorkflowForActor, recordWorkflowStep } from "@/lib/skills/memory";
import { activityTarget, newActivityId, recordMcpActivity } from "./activity";
import { allows, type Scope } from "./scope";
@@ -13,6 +14,11 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
const name = String(req.params?.name ?? ""), args = req.params?.arguments ?? {};
const tool = TOOLS_BY_NAME.get(name);
if (!tool) return rpcFail(id, -32602, `unknown tool: ${name}`);
+ const mcpPresence = context?.principal?.startsWith("mcp-") && context.sessionId
+ ? { principal: context.principal, sessionId: context.sessionId, instanceId: `mcp:${context.sessionId}` }
+ : null;
+ if (mcpPresence)
+ await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "ready", mcpPresence.instanceId).catch(() => undefined);
const workflowProbe = name === "workflow_status";
const requestedWorkflowId = typeof args.workflow_id === "string" && args.workflow_id ? args.workflow_id : undefined;
@@ -67,6 +73,8 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
const activityId = newActivityId(), startedAt = Date.now();
if (!workflowProbe) void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });
try {
+ if (mcpPresence)
+ await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "busy", mcpPresence.instanceId).catch(() => undefined);
const titleHint = sessionDetail(name, args, target);
if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status"].includes(name)) {
await maybeAutoTitleAgentSession(context.principal, context.sessionId, titleHint).catch(() => undefined);
@@ -85,6 +93,8 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
await recordWorkflowStep(flowActor, completedWorkflow?.id, { id: activityId, tool: name, state: "completed", target, args, durationMs, ts: new Date().toISOString() });
await recordAgentEvent(context, name, "completed", args, completedWorkflow?.id, target);
}
+ if (mcpPresence)
+ await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "idle", mcpPresence.instanceId).catch(() => undefined);
return rpcOk(id, structuredResult(name, result));
} catch (error) {
const message = error instanceof Error ? error.message : String(error), durationMs = Date.now() - startedAt;
@@ -94,6 +104,8 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
await recordWorkflowStep(flowActor, activeWorkflow?.id, { id: activityId, tool: name, state: "failed", target, args, durationMs, ts: new Date().toISOString() });
await recordAgentEvent(context, name, "failed", args, activeWorkflow?.id, target);
}
+ if (mcpPresence)
+ await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "idle", mcpPresence.instanceId).catch(() => undefined);
return rpcOk(id, { content: [{ type: "text", text: "error: " + message.slice(0, 500) }], isError: true });
}
}
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index cb8e0963..1d16bd34 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -88,6 +88,9 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("projects_list");
expect(n).toContain("skills_list");
expect(n).toContain("skills_read");
+ expect(n).toContain("local_agents_list");
+ expect(n).toContain("local_agent_inbox");
+ expect(n).not.toContain("local_agent_message_send");
expect(n).not.toContain("workflow_start");
expect(n).not.toContain("fs_write");
expect(n).not.toContain("exec_run");
@@ -100,6 +103,7 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("workflow_start");
expect(n).toContain("workflow_cancel");
expect(n).toContain("workflow_finish");
+ expect(n).toContain("local_agent_message_send");
expect(n).not.toContain("exec_run");
expect(n).not.toContain("browser_power");
});
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 4e770424..9d1a2f9a 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -61,6 +61,9 @@ const MCP_ONLY: Record<string, string> = {
"cloudflare.zones.list": "terminal/external deployment workflows need bounded zone discovery while credentials stay server-side; in-shell Alfa has the Cloudflare feature app",
"cloudflare.dns.upsert": "DNS automation is intentionally MCP/terminal-agent-only so it inherits scope, approval, audit and workflow semantics without teaching generic in-shell Alfa to mutate public DNS",
"hostinger.dns.upsert": "external DNS mutation remains an explicitly approved deployment-agent capability; MSO sends one exact Hostinger name/type RR-set and keeps credentials server-side rather than adding a generic Alfa provider primitive",
+ "local.agents.list": "native Local Agents address durable CLI/MCP AgentSession principals; Alfa browser threads use a separate thread lifecycle and do not own a compatible durable session receiver",
+ "local.agent.message.send": "same durable-session boundary; adding this to Alfa without first unifying its browser-thread identity would let one UI thread claim another principal's local receiver",
+ "local.agent.inbox": "the inbox is keyed to the exact durable AgentSession principal/id; Alfa currently has a separate owner-thread store rather than that receiver identity",
"a2a.agents.list": "A2A is an external-agent interoperability surface for MCP/terminal agents; in-shell Alfa has no remote-agent registry yet",
"a2a.agent.discover": "public Agent Card discovery is intentionally available to the MCP/terminal agent harness and does not expose owner UI state",
"a2a.agent.register": "remote A2A registry mutation inherits MCP write approval/audit semantics; Alfa has no matching registry surface",
@@ -157,6 +160,8 @@ describe("MCP rate limits mirror the routes", () => {
"a2a.send": 30,
"a2a.task": 60,
"a2a.cancel": 30,
+ "local-agent.read": 120,
+ "local-agent.send": 60,
"tool.forge.propose": 20,
"tool.forge.evaluate": 10,
"tool.forge.promote": 6,
diff --git a/lib/mcp/tools-local-agents.test.ts b/lib/mcp/tools-local-agents.test.ts
new file mode 100644
index 00000000..b1014069
--- /dev/null
+++ b/lib/mcp/tools-local-agents.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { LOCAL_AGENT_TOOLS } from "./tools-local-agents";
+
+const local = new Map(LOCAL_AGENT_TOOLS.map((tool) => [tool.name, tool]));
+
+describe("native local session agent MCP tools", () => {
+ it("keeps local discovery/inbox read-only and message delivery below exec", () => {
+ expect(local.get("local_agents_list")?.scope).toBe("read");
+ expect(local.get("local_agent_inbox")?.scope).toBe("read");
+ expect(local.get("local_agent_message_send")?.scope).toBe("write");
+ });
+
+ it("describes local messaging without Agent Card registration", () => {
+ const description = local.get("local_agent_message_send")?.description || "";
+ expect(description).toMatch(/same-owner MSO session agent/i);
+ expect(description).toMatch(/no hidden transcript/i);
+ expect(description).not.toMatch(/Agent Card URL/i);
+ });
+});
diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.ts
new file mode 100644
index 00000000..a4fe1452
--- /dev/null
+++ b/lib/mcp/tools-local-agents.ts
@@ -0,0 +1,74 @@
+import { listLocalAgents } from "@/lib/agent/local-agent-directory";
+import { listLocalAgentInbox, updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";
+import { sendLocalAgentMessage } from "@/lib/agent/local-agent-messaging";
+import { type McpRunContext, type McpTool, S, str } from "./tool-kit";
+
+function sessionContext(context: McpRunContext): { principal: string; sessionId: string } {
+ if (!context.principal || !context.sessionId)
+ throw new Error("this tool call has no conversation-bound MSO session");
+ return { principal: context.principal, sessionId: context.sessionId };
+}
+
+export const LOCAL_AGENT_TOOLS: McpTool[] = [
+ {
+ name: "local_agents_list",
+ description: "List currently active same-owner MSO session agents on this host. Local agents are discovered automatically from live session leases; no Agent Card, URL, registration, refresh, or restart is required. Unnamed sessions use stable labels such as [agent-a].",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ limit: { key: "local-agent.read", max: 60, windowMs: 60_000 },
+ inputSchema: S({
+ include_offline: { type: "boolean", description: "Also include known sessions whose receive lease expired or explicitly ended. Default false." },
+ }),
+ run: async (a, context) => {
+ const current = sessionContext(context);
+ return listLocalAgents(current.principal, {
+ currentSessionId: current.sessionId,
+ includeOffline: a.include_offline === true,
+ });
+ },
+ },
+ {
+ name: "local_agent_message_send",
+ description: "Send one explicit text message or task to another same-owner MSO session agent on this host. The payload is durable and bounded; no hidden transcript, memory, credentials, tool arguments, file data, or additional permissions are copied. Busy targets queue the message; offline known targets return target_offline and keep it for later delivery.",
+ scope: "write",
+ limit: { key: "local-agent.send", max: 60, windowMs: 60_000 },
+ audit: { action: "agent.message", targetArg: "target" },
+ inputSchema: S({
+ target: { type: "string", description: "Active local label/name such as rahman, [rahman], agent-b, or an exact durable session id." },
+ message: { type: "string", description: "Explicit payload, maximum 16 KiB. Known secret-shaped values are redacted before persistence/delivery." },
+ kind: { type: "string", enum: ["message", "task"], description: "message (default) or task." },
+ }, ["target", "message"]),
+ run: async (a, context) => {
+ const current = sessionContext(context);
+ return sendLocalAgentMessage({
+ principal: current.principal,
+ senderSessionId: current.sessionId,
+ target: str(a, "target"),
+ text: str(a, "message"),
+ kind: typeof a.kind === "string" ? a.kind : undefined,
+ });
+ },
+ },
+ {
+ name: "local_agent_inbox",
+ description: "Read durable local agent messages addressed to this exact MSO session. Messages are agent-origin events, not user messages. By default only unread/unacknowledged items are returned.",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ limit: { key: "local-agent.read", max: 120, windowMs: 60_000 },
+ inputSchema: S({
+ include_read: { type: "boolean" },
+ limit: { type: "number", description: "1-200, default 100." },
+ acknowledge: { type: "boolean", description: "When true, mark returned messages read after retrieval." },
+ }),
+ run: async (a, context) => {
+ const current = sessionContext(context);
+ const messages = await listLocalAgentInbox(current.principal, current.sessionId, {
+ includeRead: a.include_read === true,
+ limit: Number(a.limit) || 100,
+ });
+ if (a.acknowledge === true && messages.length)
+ await updateLocalAgentMessageState(current.principal, current.sessionId, messages.map((row) => row.id), "read");
+ return messages;
+ },
+ },
+];
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 3f1f3752..204903f3 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -8,6 +8,7 @@ import { POWER_TOOLS } from "./tools-power";
import { INFRA_TOOLS } from "./tools-infra";
import { AGENT_TOOLS } from "./tools-agent";
import { A2A_TOOLS } from "./tools-a2a";
+import { LOCAL_AGENT_TOOLS } from "./tools-local-agents";
import { FORGE_TOOLS } from "./tools-forge";
import { withWorkflowContext } from "./tool-context";
@@ -218,4 +219,4 @@ const MUTATE_TOOLS: McpTool[] = [
},
];
-export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
+export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 6278ee57..92df862f 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -29,6 +29,29 @@ function runCli(args) {
return result.status ?? 1;
}
+function localAgentLine(row) {
+ const status = String(row?.status || "unknown");
+ const cwd = row?.cwd ? ` · ${row.cwd}` : "";
+ return ` ${String(row?.label || row?.alias || row?.id || "agent").padEnd(24)} ${status}${cwd}`;
+}
+
+async function listLocalAgents(session, includeOffline = false) {
+ const query = new URLSearchParams({ session: session.agentSession.id });
+ if (includeOffline) query.set("includeOffline", "1");
+ const out = await api(`/api/v1/local-agents?${query}`);
+ const rows = Array.isArray(out?.agents) ? out.agents : [];
+ if (!rows.length) console.log(" no other live local session agents");
+ else for (const row of rows) console.log(localAgentLine(row));
+ return rows;
+}
+
+async function sendLocalAgent(session, target, message, kind = "message") {
+ return api("/api/v1/local-agents", {
+ method: "POST",
+ body: JSON.stringify({ action: "send", sessionId: session.agentSession.id, target, message, kind }),
+ });
+}
+
async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
const resolved = resolveSlashSkill(
session.state.skills,
@@ -80,10 +103,11 @@ function printHelp() {
" /provider <id> configure dokploy|cloudflare|hostinger",
" /doctor run mso doctor",
" /tools list agent tools",
- " /agents list remote peers + same-host session agents",
- " /delegate <target> <job> local session name/id/cwd first, then remote peer",
+ " /agents list live local session agents + remote A2A peers",
+ " /message <target> <msg> send a native local agent message",
+ " /delegate <target> <job> queue native local task; else remote A2A peer",
" /spawn [--name N] <job> spawn same-host sub-agent from this session",
- " /inbox show A2A tasks addressed to this session",
+ " /inbox show native local agent messages for this session",
" /skills [query] browse available slash skills",
" /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
" /<skill> [prompt] select for next message, or run prompt now",
@@ -197,9 +221,22 @@ export async function handleSlash(rl, line, session, { runTurn }) {
console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`);
return "handled";
case "/agents":
+ console.log(`${C.bold}Local session agents${C.reset}`);
+ await listLocalAgents(session);
+ console.log(`${C.bold}Remote A2A v1 peers${C.reset}`);
runCli(["a2a", "list"]);
- runCli(["a2a", "sessions"]);
return "handled";
+ case "/message": {
+ if (!args[0] || args.length < 2) {
+ console.log("usage: /message <local-agent> <message>");
+ return "handled";
+ }
+ const target = args[0];
+ const message = args.slice(1).join(" ");
+ const out = await sendLocalAgent(session, target, message, "message");
+ console.log(`${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"}`);
+ return "handled";
+ }
case "/delegate": {
if (!args[0] || args.length < 2) {
console.log(
@@ -210,23 +247,11 @@ export async function handleSlash(rl, line, session, { runTurn }) {
const target = args[0];
const objective = args.slice(1).join(" ");
try {
- const out = await api("/api/v1/a2a", {
- method: "POST",
- body: JSON.stringify({
- action: "local-handoff",
- sessionRef: target,
- objective,
- }),
- });
- const text = out?.task?.artifacts?.[0]?.parts?.[0]?.text || "delegated";
- console.log(
- `${C.c}↳ ${out?.session?.title || target}${C.reset} ${text}`,
- );
+ const out = await sendLocalAgent(session, target, objective, "task");
+ console.log(`${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"}`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
- if (
- /session_not_found|session_not_found|session not found/i.test(message)
- )
+ if (/local agent target not found/i.test(message))
runCli(["a2a", "handoff", target, objective]);
else throw error;
}
@@ -259,9 +284,17 @@ export async function handleSlash(rl, line, session, { runTurn }) {
);
return "handled";
}
- case "/inbox":
- runCli(["a2a", "local", "inbox", session.agentSession.id]);
+ case "/inbox": {
+ const out = await api(`/api/v1/local-agents?inbox=1&session=${encodeURIComponent(session.agentSession.id)}&limit=100`);
+ const rows = Array.isArray(out?.messages) ? out.messages : [];
+ if (!rows.length) console.log("local agent inbox is empty");
+ else for (const row of rows) {
+ const label = String(row.senderLabel || "[agent]");
+ const prefix = label.startsWith("[agent-") ? label : `[agent-${label.replace(/^\[|\]$/g, "")}]`;
+ console.log(`${C.c}${prefix}${row.kind === "task" ? " task" : ""}${C.reset} ${row.text}`);
+ }
return "handled";
+ }
case "/skills":
printSkills(session, C, args.join(" "));
return "handled";
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 07226c7f..cc51906a 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -15,6 +15,7 @@ export class AgentComposer {
this.history = [];
this.closed = false;
this._cancelCurrent = null;
+ this._notifyCurrent = null;
readline.emitKeypressEvents(this.input);
}
@@ -59,6 +60,7 @@ export class AgentComposer {
const cleanup = () => {
input.off("keypress", onKey);
if (this._cancelCurrent === cancel) this._cancelCurrent = null;
+ if (this._notifyCurrent === notify) this._notifyCurrent = null;
if (typeof input.setRawMode === "function") input.setRawMode(wasRaw);
input.pause();
};
@@ -84,7 +86,16 @@ export class AgentComposer {
resolve(null);
return true;
};
+ const notify = (text) => {
+ if (settled) return false;
+ erase();
+ output.write(`${String(text ?? "").replace(/\r/g, "")}\r\n`);
+ reservedMenuRows = 0;
+ render();
+ return true;
+ };
this._cancelCurrent = cancel;
+ this._notifyCurrent = notify;
const edit = (next, nextCursor) => {
value = next; cursor = clamp(nextCursor, 0, chars(value).length);
selected = 0; dismissed = false; historyIndex = null;
@@ -190,6 +201,12 @@ export class AgentComposer {
return typeof this._cancelCurrent === "function" ? this._cancelCurrent(echo) : false;
}
+ notify(text) {
+ if (typeof this._notifyCurrent === "function") return this._notifyCurrent(text);
+ this.output.write(`${String(text ?? "").replace(/\r/g, "")}\r\n`);
+ return false;
+ }
+
close() {
this.closed = true;
if (typeof this.input.setRawMode === "function" && this.input.isRaw) this.input.setRawMode(false);
diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.ts
index 4286b981..86a415f7 100644
--- a/scripts/mso-agent-composer.test.ts
+++ b/scripts/mso-agent-composer.test.ts
@@ -188,5 +188,22 @@ describe("MSO Agent interactive composer primitives", () => {
composer.close();
});
+ it("prints an incoming agent event above the active prompt without losing draft input", async () => {
+ class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }
+ class FakeOutput { columns = 88; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }
+ const input = new FakeInput(); const output = new FakeOutput();
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors: { blue: "", bold: "", reset: "", dim: "" } });
+ const answer = composer.question("› ");
+ for (const ch of "draft") input.emit("keypress", ch, { name: ch, sequence: ch });
+ expect(composer.notify("[agent-zahra] hello")).toBe(true);
+ for (const ch of " kept") input.emit("keypress", ch, { name: ch, sequence: ch });
+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(answer).resolves.toBe("draft kept");
+ const rendered = output.chunks.join("");
+ expect(rendered).toContain("[agent-zahra] hello\r\n");
+ expect(rendered).toContain("draft kept");
+ composer.close();
+ });
+
});
diff --git a/scripts/mso-agent-context.mjs b/scripts/mso-agent-context.mjs
index 80b20ad1..7d6c655d 100644
--- a/scripts/mso-agent-context.mjs
+++ b/scripts/mso-agent-context.mjs
@@ -17,8 +17,15 @@ export function modelHistoryBudget(contextWindow) {
return Math.min(MAX_MODEL_HISTORY_BUDGET, Math.max(16_000, Math.floor(limit * 0.55)));
}
+export function modelHistoryRow(row) {
+ if (row?.role !== "agent") return row;
+ const sender = String(row.senderLabel || "[local-agent]").replace(/[\r\n\t]+/g, " ").slice(0, 120);
+ const kind = row.kind === "task" ? "task" : "message";
+ return { role: "user", text: `[LOCAL AGENT ${sender} · ${kind}] ${String(row.text || "").slice(0, 24_000)}` };
+}
+
function messageGroups(history) {
- const rows = Array.isArray(history) ? history : [];
+ const rows = (Array.isArray(history) ? history : []).map(modelHistoryRow);
const groups = [];
for (let i = 0; i < rows.length; i += 1) {
const row = rows[i];
diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.ts
index 992bea94..0313b3d5 100644
--- a/scripts/mso-agent-contract.test.ts
+++ b/scripts/mso-agent-contract.test.ts
@@ -31,7 +31,7 @@ describe("MSO terminal agent contract", () => {
for (const command of [
"/models", "/model", "/status", "/context", "/statusbar", "/title",
"/new", "/restart", "/session", "/resume", "/setup", "/providers", "/provider",
- "/doctor", "/tools", "/skills", "/skill", "/<skill>", "/clear", "/exit", "/quit",
+ "/doctor", "/tools", "/agents", "/message", "/delegate", "/inbox", "/skills", "/skill", "/<skill>", "/clear", "/exit", "/quit",
]) expect(src).toContain(command);
expect(src).toContain("Configure AI providers and authentication");
expect(src).toContain("Select the active model from connected providers");
diff --git a/scripts/mso-agent-local.mjs b/scripts/mso-agent-local.mjs
new file mode 100644
index 00000000..97172c3c
--- /dev/null
+++ b/scripts/mso-agent-local.mjs
@@ -0,0 +1,192 @@
+import { randomUUID } from "node:crypto";
+import process from "node:process";
+import { api, apiResponse, C } from "./mso-agent-runtime.mjs";
+import { persistSession } from "./mso-agent-session-ui.mjs";
+
+const HEARTBEAT_MS = 20_000;
+const RECONNECT_MIN_MS = 800;
+const RECONNECT_MAX_MS = 5_000;
+
+function sleep(ms, signal) {
+ return new Promise((resolve) => {
+ if (signal?.aborted) return resolve();
+ const timer = setTimeout(resolve, ms);
+ signal?.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true });
+ });
+}
+
+function agentPrefix(label) {
+ const clean = String(label || "[agent]").replace(/[\u0000-\u001f\u007f]/g, "").replace(/^\[|\]$/g, "");
+ return clean.startsWith("agent-") ? `[${clean}]` : `[agent-${clean}]`;
+}
+
+export function formatLocalAgentEvent(message, colors = C) {
+ const prefix = agentPrefix(message?.senderLabel);
+ const kind = message?.kind === "task" ? " task" : "";
+ const text = String(message?.text || "").replace(/\r/g, "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "");
+ const indented = text.replace(/\n/g, "\n ");
+ return `${colors.c}${colors.bold}${prefix}${kind}${colors.reset} ${indented}`;
+}
+
+function historyRow(message) {
+ return {
+ role: "agent",
+ text: String(message.text || ""),
+ senderSessionId: message.senderSessionId,
+ senderLabel: message.senderLabel,
+ kind: message.kind === "task" ? "task" : "message",
+ messageId: message.id,
+ createdAt: message.createdAt,
+ };
+}
+
+export class LocalAgentBridge {
+ constructor({ session, composer }) {
+ this.session = session;
+ this.composer = composer;
+ this.instanceId = `cli:${process.pid}:${randomUUID()}`;
+ this.sessionId = null;
+ this.state = "idle";
+ this.closed = false;
+ this.feedAbort = null;
+ this.heartbeat = null;
+ this.feedTask = null;
+ this.pending = [];
+ this.seen = new Set();
+ }
+
+ async start() {
+ await this.syncSession();
+ this.heartbeat = setInterval(() => void this.touch({ flush: false }).catch(() => undefined), HEARTBEAT_MS);
+ this.heartbeat.unref?.();
+ }
+
+ async syncSession() {
+ const next = String(this.session?.agentSession?.id || "").trim();
+ if (!next || next === this.sessionId) return;
+ const previous = this.sessionId;
+ if (previous) await this.end(previous).catch(() => undefined);
+ this.feedAbort?.abort();
+ this.feedAbort = null;
+ this.sessionId = next;
+ this.state = "ready";
+ this.pending = [];
+ this.seen = new Set(
+ (Array.isArray(this.session.history) ? this.session.history : [])
+ .filter((row) => row?.role === "agent" && row?.messageId)
+ .map((row) => String(row.messageId)),
+ );
+ await this.touch().catch(() => undefined);
+ this.state = "idle";
+ await this.touch().catch(() => undefined);
+ this.startFeed(next);
+ }
+
+ async setState(state) {
+ if (this.closed || !this.sessionId) return;
+ this.state = state === "busy" ? "busy" : "idle";
+ await this.touch().catch(() => undefined);
+ if (this.state === "idle" && this.pending.length) {
+ const rows = this.pending.splice(0);
+ for (const row of rows) await this.accept(row);
+ }
+ }
+
+ async touch({ flush = true } = {}) {
+ if (this.closed || !this.sessionId) return;
+ await api("/api/v1/local-agents", {
+ method: "POST",
+ body: JSON.stringify({
+ action: "presence",
+ sessionId: this.sessionId,
+ instanceId: this.instanceId,
+ state: this.state,
+ flush,
+ }),
+ });
+ }
+
+ async end(sessionId = this.sessionId) {
+ if (!sessionId) return;
+ await api("/api/v1/local-agents", {
+ method: "POST",
+ body: JSON.stringify({ action: "end", sessionId, instanceId: this.instanceId }),
+ });
+ }
+
+ startFeed(sessionId) {
+ const controller = new AbortController();
+ this.feedAbort = controller;
+ this.feedTask = this.feedLoop(sessionId, controller.signal).catch(() => undefined);
+ }
+
+ async feedLoop(sessionId, signal) {
+ let delay = RECONNECT_MIN_MS;
+ while (!this.closed && !signal.aborted && this.sessionId === sessionId) {
+ try {
+ const res = await apiResponse(`/api/v1/local-agents?stream=1&session=${encodeURIComponent(sessionId)}`, { signal });
+ if (!res.body) throw new Error("local agent event stream is unavailable");
+ await this.touch({ flush: false }).catch(() => undefined);
+ delay = RECONNECT_MIN_MS;
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (!signal.aborted) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const blocks = buffer.split("\n\n");
+ buffer = blocks.pop() || "";
+ for (const block of blocks) {
+ let event = "message", data = "";
+ for (const line of block.split("\n")) {
+ if (line.startsWith("event:")) event = line.slice(6).trim();
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
+ }
+ if (event !== "message" || !data) continue;
+ const message = JSON.parse(data);
+ if (this.state === "busy") this.pending.push(message);
+ else await this.accept(message);
+ }
+ }
+ } catch {
+ if (signal.aborted || this.closed) return;
+ }
+ if (!signal.aborted && !this.closed) {
+ await sleep(delay, signal);
+ delay = Math.min(RECONNECT_MAX_MS, delay * 2);
+ }
+ }
+ }
+
+ async accept(message) {
+ if (!message?.id || this.seen.has(String(message.id))) {
+ if (message?.id) await this.ack([String(message.id)]).catch(() => undefined);
+ return;
+ }
+ if (String(message.targetSessionId || "") !== this.sessionId) return;
+ const id = String(message.id);
+ const alreadyStored = this.session.history.some((row) => row?.role === "agent" && String(row?.messageId || "") === id);
+ if (!alreadyStored) this.session.history.push(historyRow(message));
+ await persistSession(this.session);
+ this.seen.add(id);
+ if (!alreadyStored) this.composer.notify(formatLocalAgentEvent(message));
+ await this.ack([id]).catch(() => undefined);
+ }
+
+ async ack(messageIds) {
+ if (!this.sessionId || !messageIds.length) return;
+ await api("/api/v1/local-agents", {
+ method: "POST",
+ body: JSON.stringify({ action: "ack", sessionId: this.sessionId, messageIds }),
+ });
+ }
+
+ async close({ ended = true } = {}) {
+ if (this.closed) return;
+ if (ended) await this.end().catch(() => undefined);
+ this.closed = true;
+ this.feedAbort?.abort();
+ if (this.heartbeat) clearInterval(this.heartbeat);
+ }
+}
diff --git a/scripts/mso-agent-local.test.ts b/scripts/mso-agent-local.test.ts
new file mode 100644
index 00000000..2afe2efa
--- /dev/null
+++ b/scripts/mso-agent-local.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { modelHistoryRow } from "./mso-agent-context.mjs";
+import { formatLocalAgentEvent } from "./mso-agent-local.mjs";
+
+const plain = { c: "", bold: "", reset: "", dim: "", blue: "", cyan: "", warn: "", err: "" };
+
+describe("local agent TUI projection", () => {
+ it("renders manual and placeholder senders as agent-origin events", () => {
+ expect(formatLocalAgentEvent({ senderLabel: "[zahra]", kind: "message", text: "hi" }, plain)).toBe("[agent-zahra] hi");
+ expect(formatLocalAgentEvent({ senderLabel: "[agent-b]", kind: "task", text: "review" }, plain)).toBe("[agent-b] task review");
+ });
+
+ it("stores agent as a distinct role but maps it safely to model input", () => {
+ expect(modelHistoryRow({ role: "agent", senderLabel: "[zahra]", kind: "task", text: "review" })).toEqual({
+ role: "user",
+ text: "[LOCAL AGENT [zahra] · task] review",
+ });
+ });
+});
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
index c854b7d7..4b299b10 100644
--- a/scripts/mso-agent-runtime.mjs
+++ b/scripts/mso-agent-runtime.mjs
@@ -32,7 +32,7 @@ function cookieHeader() {
return pairs.join("; ");
}
-export async function api(path, init = {}) {
+export async function apiResponse(path, init = {}) {
const headers = new Headers(init.headers || {});
headers.set("origin", ORIGIN);
const cookie = cookieHeader();
@@ -40,20 +40,21 @@ export async function api(path, init = {}) {
if (init.body && !headers.has("content-type"))
headers.set("content-type", "application/json");
const res = await fetch(`${BASE}${path}`, { ...init, headers });
- const text = await res.text();
- let body = null;
- try {
- body = text ? JSON.parse(text) : null;
- } catch {
- body = text;
- }
- if (!res.ok)
+ if (!res.ok) {
+ const text = await res.text();
+ let body = null;
+ try { body = text ? JSON.parse(text) : null; } catch { body = text; }
throw new Error(
- typeof body === "object" && body?.error
- ? String(body.error)
- : `HTTP ${res.status}`,
+ typeof body === "object" && body?.error ? String(body.error) : `HTTP ${res.status}`,
);
- return body;
+ }
+ return res;
+}
+
+export async function api(path, init = {}) {
+ const res = await apiResponse(path, init);
+ const text = await res.text();
+ try { return text ? JSON.parse(text) : null; } catch { return text; }
}
export async function state() {
diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjs
index 61ce9837..02778c51 100644
--- a/scripts/mso-agent-slash.mjs
+++ b/scripts/mso-agent-slash.mjs
@@ -62,12 +62,13 @@ export const BUILTIN_SLASH_ITEMS = [
{ text: "/tools", meta: "List available agent tools", kind: "command" },
{
text: "/agents",
- meta: "List registered A2A peers + same-host session agents",
+ meta: "List live local session agents + registered remote A2A peers",
kind: "command",
},
+ { text: "/message", meta: "Send a native local-session agent message", kind: "command" },
{
text: "/delegate",
- meta: "Handoff to a local session by name/id/cwd, else a registered peer",
+ meta: "Queue a native local task; fall back to registered remote A2A peer",
kind: "command",
},
{
@@ -77,7 +78,7 @@ export const BUILTIN_SLASH_ITEMS = [
},
{
text: "/inbox",
- meta: "Show A2A tasks addressed to this durable session",
+ meta: "Show native local-session agent inbox",
kind: "command",
},
{
diff --git a/scripts/mso-agent-slash.test.ts b/scripts/mso-agent-slash.test.ts
index 03daf4d0..b76b8c27 100644
--- a/scripts/mso-agent-slash.test.ts
+++ b/scripts/mso-agent-slash.test.ts
@@ -19,6 +19,7 @@ describe("MSO Agent slash completion catalog", () => {
expect(rows.map((row) => row.text)).toContain("/agents");
expect(rows.map((row) => row.text)).toContain("/new");
expect(rows.map((row) => row.text)).toContain("/restart");
+ expect(rows.map((row) => row.text)).toContain("/message");
expect(rows.map((row) => row.text)).toContain("/delegate");
expect(rows.map((row) => row.text)).not.toContain("/unsafe");
});
diff --git a/scripts/mso-agent-tool-router.mjs b/scripts/mso-agent-tool-router.mjs
index a08ad2bc..d6404ee8 100644
--- a/scripts/mso-agent-tool-router.mjs
+++ b/scripts/mso-agent-tool-router.mjs
@@ -11,6 +11,7 @@ const DEPENDENCIES = new Map([
["exec_job_start", ["exec_job_status", "exec_job_cancel"]],
["fs_write", ["fs_read"]],
["agent_session_resume", ["agent_sessions_list"]],
+ ["local_agent_message_send", ["local_agents_list", "local_agent_inbox"]],
["a2a_message_send", ["a2a_agents_list", "a2a_agent_discover"]],
["a2a_handoff", ["a2a_agents_list", "a2a_agent_discover", "a2a_task_get"]],
["tool_forge_evaluate", ["tool_forge_candidates"]],
@@ -33,7 +34,8 @@ const ALIASES = new Map([
["dokploy", ["dokploy", "deploy", "deployment", "project"]],
["hostinger", ["hostinger", "dns", "domain", "record"]],
["apps", ["app", "service", "hermes", "openclaw", "install", "restart", "status"]],
- ["a2a", ["a2a", "delegate", "delegation", "handoff", "peer", "collaborate"]],
+ ["localagent", ["local", "session", "agent", "message", "task", "delegate", "delegation", "collaborate", "inbox"]],
+ ["a2a", ["a2a", "remote", "agent card", "peer", "handoff"]],
["forge", ["forge", "candidate", "promotion", "promote", "self-improve", "self-improving", "generate tool", "tool creator"]],
]);
diff --git a/scripts/mso-agent-tool-router.test.ts b/scripts/mso-agent-tool-router.test.ts
index a8e35b99..836cac07 100644
--- a/scripts/mso-agent-tool-router.test.ts
+++ b/scripts/mso-agent-tool-router.test.ts
@@ -14,6 +14,8 @@ const catalog = [
tool("exec_job_status", "Read long job status"), tool("exec_job_cancel", "Cancel long job"),
tool("screen_capture", "Capture screenshot"), tool("browser_status", "Camoufox browser state"),
tool("cloudflare_zones_list", "List Cloudflare DNS zones"), tool("hostinger_dns_upsert", "Update Hostinger DNS record"),
+ tool("local_agents_list", "List active same-host local session agents"), tool("local_agent_inbox", "Read local session agent inbox"),
+ tool("local_agent_message_send", "Send message or task to a local session agent"),
tool("a2a_agents_list", "List registered A2A peer agents"), tool("a2a_agent_discover", "Discover public A2A Agent Card"),
tool("a2a_message_send", "Send a message to an A2A peer"), tool("a2a_handoff", "Delegate explicit objective to A2A peer"), tool("a2a_task_get", "Read A2A task status"),
tool("tool_forge_candidates", "List Tool Forge candidates"), tool("tool_forge_propose", "Propose a Tool Forge candidate from a repeated recipe"),
@@ -40,6 +42,13 @@ describe("MSO per-turn tool router", () => {
});
+ it("prefers native local-session messaging tools for same-host delegation", () => {
+ const out = selectToolsForTurn(catalog, [{ role: "user", text: "send a task to the local session agent rahman" }]);
+ expect(out.selectedNames).toContain("local_agent_message_send");
+ expect(out.selectedNames).toContain("local_agents_list");
+ expect(out.selectedNames).toContain("local_agent_inbox");
+ });
+
it("selects A2A companions for delegation and handoff prompts", () => {
const out = selectToolsForTurn(catalog, [{ role: "user", text: "delegate this research to the a2a peer agent and handoff the result" }]);
expect(out.selectedNames).toContain("a2a_handoff");
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 273d26f0..55cbcff1 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -12,6 +12,7 @@ import { handleSlash } from "./mso-agent-commands.mjs";
import { approvesTool, nextPermissionMode, permissionMode, permissionPrompt } from "./mso-agent-permissions.mjs";
import { consumeRestartUiState, relaunchCurrentAgentSession } from "./mso-agent-lifecycle.mjs";
import { oneShotApproves, oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";
+import { LocalAgentBridge } from "./mso-agent-local.mjs";
async function executeTool(rl, tool, call, agentSession, permission = "ask", signal = undefined, onInterrupt = null, options = {}) {
if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };
@@ -97,8 +98,9 @@ async function agentRound(rl, session, skillContext = null, signal = undefined,
}
}
-async function runInteractiveRound(rl, session, skillContext, interrupts) {
+async function runInteractiveRound(rl, session, skillContext, interrupts, localBridge = null) {
const signal = interrupts.beginTurn();
+ await localBridge?.setState("busy");
try {
await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent());
await persistSession(session);
@@ -108,6 +110,7 @@ async function runInteractiveRound(rl, session, skillContext, interrupts) {
await persistSession(session).catch(() => undefined);
} finally {
interrupts.endTurn(signal);
+ await localBridge?.setState("idle");
}
}
@@ -153,27 +156,21 @@ async function main() {
const forcedPermission = argv.some((arg) => ["--yolo", "-yolo", "-y"].includes(arg))
? "yolo"
: (permissionMode(restartUi.permission)?.id || "ask");
- const [s, agentSession] = await Promise.all([
- state(),
- startupSession(requested, restartSessionId),
- ]);
+ const [s, agentSession] = await Promise.all([state(), startupSession(requested, restartSessionId)]);
if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");
printBanner(s, agentSession);
const session = {
state: s,
agentSession,
history: Array.isArray(agentSession.history) ? agentSession.history : [],
- pendingSkill: null,
- activeSkill: null,
- lastInvokedSkill: null,
+ pendingSkill: null, activeSkill: null, lastInvokedSkill: null,
titleOverride: (requested || restartSessionId) ? (agentSession.title || null) : null,
- usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
- lastElapsedMs: 0,
- statusBar: restartUi.statusBar ?? true,
- permission: forcedPermission,
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, lastElapsedMs: 0,
+ statusBar: restartUi.statusBar ?? true, permission: forcedPermission,
};
- const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C });
- syncPromptHistory(rl, session);
+ const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C }); syncPromptHistory(rl, session);
+ const localBridge = new LocalAgentBridge({ session, composer: rl });
+ await localBridge.start();
const interrupts = new AgentInterruptManager({ output: process.stdout, colors: C });
const onSigint = () => {
const action = interrupts.handleSigint();
@@ -203,9 +200,10 @@ async function main() {
if (!line) continue;
if (line.startsWith("/")) {
try {
- const result = await handleSlash(rl, line, session, { runTurn: (skill) => runInteractiveRound(rl, session, skill, interrupts) });
+ const result = await handleSlash(rl, line, session, { runTurn: (skill) => runInteractiveRound(rl, session, skill, interrupts, localBridge) });
if (result === "exit") break;
if (result === "restart") { restartRequested = true; break; }
+ if (result === "refresh") await localBridge.syncSession();
if (result === "unknown") console.log("unknown command; /help lists commands.");
} catch (error) {
console.error(`${C.err}${error instanceof Error ? error.message : String(error)}${C.reset}`);
@@ -216,7 +214,7 @@ async function main() {
session.history.push({ role: "user", text: line });
const skillContext = session.pendingSkill;
session.pendingSkill = null;
- await runInteractiveRound(rl, session, skillContext, interrupts);
+ await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);
if (interrupts.exitRequested) break;
}
} finally {
@@ -224,6 +222,7 @@ async function main() {
await persistSession(session).catch(() => undefined);
const sessionTitle = String(session.agentSession.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").trim().slice(0, 80);
if (!restartRequested) console.log(`${C.dim}session ${sessionTitle} · resume: mso --continue · switch: /sessions${C.reset}`);
+ await localBridge.close({ ended: !restartRequested }).catch(() => undefined);
rl.close();
}
if (restartRequested) {
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index 57cdf28c..b8a4adac 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -29,7 +29,7 @@ const all = [cli, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
- expect(cli).toContain('VERSION="1.8.2"');
+ expect(cli).toContain('VERSION="1.9.0"');
expect(cli).toContain("models * Configure AI providers/auth");
expect(cli).toContain("model [ref] Select active model");
expect(agentCli).toContain("run_models()");