Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent): add interactive permissions and a2a v1
Rahman2ce14362bbb6
diff --git a/.env.example b/.env.exampleindex 95ef32dd..c97f3b54 100644--- a/.env.example+++ b/.env.example@@ -205,6 +205,7 @@ 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+# OS_A2A_STORE=~/.mso/private/a2a-agents.json # public A2A Agent Card registry; no credentials# Session context is estimated provider-neutrally and compacted when it reaches this# threshold. Raw/older context is first written as a SANITIZED gzip backup; secrets# are recursively redacted before archival. Defaults: 700k threshold, 140k recent.diff --git a/app/api/v1/a2a/route.test.ts b/app/api/v1/a2a/route.test.tsnew file mode 100644index 00000000..6a997fcf--- /dev/null+++ b/app/api/v1/a2a/route.test.ts@@ -0,0 +1,31 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const mocks = vi.hoisted(() => ({+ list: vi.fn(), discover: vi.fn(), register: vi.fn(), remove: vi.fn(), resolve: vi.fn(), send: vi.fn(), get: vi.fn(), cancel: vi.fn(), handoff: vi.fn(), audit: vi.fn(), rate: vi.fn(),+}));+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: vi.fn(async () => ({ role: "owner", session: { device_id: "cli-test" } })) }));+vi.mock("@/lib/a2a", () => ({ listA2AAgents: mocks.list, discoverA2AAgent: mocks.discover, registerA2AAgent: mocks.register, removeA2AAgent: mocks.remove, resolveA2AAgent: mocks.resolve, sendA2AMessage: mocks.send, getA2ATask: mocks.get, cancelA2ATask: mocks.cancel, handoffA2A: mocks.handoff }));+vi.mock("@/lib/host", () => ({ audit: mocks.audit, rateLimited: mocks.rate, readJson: async (req: Request) => req.json().catch(() => null) }));++const { GET, POST } = await import("./route");+const post = (body: object) => new NextRequest("http://localhost/api/v1/a2a", { method: "POST", body: JSON.stringify(body), headers: { "content-type": "application/json" } });++beforeEach(() => { vi.clearAllMocks(); mocks.rate.mockReturnValue(false); mocks.resolve.mockResolvedValue({ card: { name: "Peer" } }); });++describe("A2A CLI API", () => {+ it("lists and discovers agents", async () => {+ mocks.list.mockResolvedValue([{ alias: "peer" }]); mocks.discover.mockResolvedValue({ card: { name: "Peer" } });+ expect(await (await GET(new NextRequest("http://localhost/api/v1/a2a"))).json()).toEqual({ agents: [{ alias: "peer" }] });+ const found = await (await GET(new NextRequest("http://localhost/api/v1/a2a?action=discover&url=https%3A%2F%2Fpeer.example"))).json(); expect(found.card.name).toBe("Peer");+ });+ it("routes register/send/task/cancel/handoff without adding hidden context", async () => {+ mocks.register.mockResolvedValue({ alias: "peer" }); mocks.send.mockResolvedValue({ task: { id: "t1" } }); mocks.get.mockResolvedValue({ id: "t1" }); mocks.cancel.mockResolvedValue({ id: "t1" }); mocks.handoff.mockResolvedValue({ handoff: {}, response: { task: { id: "t2" } } });+ expect((await POST(post({ action: "register", url: "https://peer.example", alias: "peer" }))).status).toBe(200);+ expect((await POST(post({ action: "send", target: "peer", message: "hello" }))).status).toBe(200); expect(mocks.send.mock.calls[0][1]).toBe("hello");+ const task = await GET(new NextRequest("http://localhost/api/v1/a2a?action=task&target=peer&taskId=t1")); expect(task.status).toBe(200);+ expect((await POST(post({ action: "cancel", target: "peer", taskId: "t1" }))).status).toBe(200);+ expect((await POST(post({ action: "handoff", target: "peer", objective: "research", context: "only this" }))).status).toBe(200);+ expect(mocks.handoff.mock.calls[0][1]).toBe("research"); expect(mocks.handoff.mock.calls[0][2]).toBe("only this");+ });+});diff --git a/app/api/v1/a2a/route.ts b/app/api/v1/a2a/route.tsnew file mode 100644index 00000000..b7898752--- /dev/null+++ b/app/api/v1/a2a/route.ts@@ -0,0 +1,86 @@+import { createHash } from "node:crypto";+import { NextRequest, NextResponse } from "next/server";+import { cancelA2ATask, discoverA2AAgent, getA2ATask, handoffA2A, listA2AAgents, registerA2AAgent, removeA2AAgent, resolveA2AAgent, sendA2AMessage } from "@/lib/a2a";+import { getSessionContext } from "@/lib/auth/require-session";+import { audit, rateLimited, readJson } from "@/lib/host";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++async function ownerContext() {+ const context = await getSessionContext();+ return context?.role === "owner" ? context : null;+}+function error(error: unknown): NextResponse {+ const message = error instanceof Error ? error.message : "A2A 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 hash(value?: string): string | undefined {+ return value ? createHash("sha256").update(value).digest("hex").slice(0, 24) : undefined;+}+function limited(actor: string, action: string, max: number): boolean {+ return rateLimited(`a2a:${action}:${actor}`, max, 60_000);+}++export async function GET(req: NextRequest) {+ const context = await ownerContext(); if (!context) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });+ const action = req.nextUrl.searchParams.get("action") || "list"; const actor = context.session.device_id || "owner";+ try {+ if (action === "list") return NextResponse.json({ agents: await listA2AAgents() });+ if (action === "discover") {+ if (limited(actor, action, 20)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 });+ const url = req.nextUrl.searchParams.get("url") || ""; if (!url) return NextResponse.json({ error: "url_required" }, { status: 400 });+ return NextResponse.json(await discoverA2AAgent(url));+ }+ if (action === "task") {+ if (limited(actor, action, 60)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 });+ const target = req.nextUrl.searchParams.get("target") || ""; const taskId = req.nextUrl.searchParams.get("taskId") || "";+ const historyLength = Math.max(0, Math.min(100, Number(req.nextUrl.searchParams.get("historyLength")) || 10));+ if (!target || !taskId) return NextResponse.json({ error: "target_and_taskId_required" }, { status: 400 });+ return NextResponse.json(await getA2ATask(await resolveA2AAgent(target), taskId, historyLength));+ }+ return NextResponse.json({ error: "unknown_action" }, { status: 400 });+ } catch (e) { return error(e); }+}++export async function POST(req: NextRequest) {+ const context = await ownerContext(); if (!context) return NextResponse.json({ error: "owner_role_required" }, { status: 403 });+ const actor = context.session.device_id || "owner"; const body = await readJson(req) as Record<string, unknown> | null; const action = String(body?.action || "");+ const target = typeof body?.target === "string" ? body.target : "";+ try {+ if (action === "register") {+ if (limited(actor, action, 20)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 });+ const url = typeof body?.url === "string" ? body.url : ""; if (!url) return NextResponse.json({ error: "url_required" }, { status: 400 });+ const agent = await registerA2AAgent(url, typeof body?.alias === "string" ? body.alias : undefined);+ void audit({ action: "a2a.registry", actor, target: url, ok: true, detail: "agent.register" }); return NextResponse.json({ agent });+ }+ if (action === "remove") {+ if (limited(actor, action, 20)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 }); if (!target) return NextResponse.json({ error: "target_required" }, { status: 400 });+ const ok = await removeA2AAgent(target); void audit({ action: "a2a.registry", actor, target, ok, detail: "agent.remove" }); return NextResponse.json({ ok });+ }+ if (action === "send") {+ if (limited(actor, action, 30)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 });+ const message = typeof body?.message === "string" ? body.message : ""; if (!target || !message) return NextResponse.json({ error: "target_and_message_required" }, { status: 400 });+ const response = await sendA2AMessage(await resolveA2AAgent(target), message, { contextId: typeof body?.contextId === "string" ? body.contextId : undefined, taskId: typeof body?.taskId === "string" ? body.taskId : undefined, returnImmediately: body?.returnImmediately !== false });+ void audit({ action: "a2a.send", actor, target, ok: true, detail: "message.send" }); return NextResponse.json({ response });+ }+ if (action === "cancel") {+ if (limited(actor, action, 30)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 });+ const taskId = typeof body?.taskId === "string" ? body.taskId : ""; if (!target || !taskId) return NextResponse.json({ error: "target_and_taskId_required" }, { status: 400 });+ const response = await cancelA2ATask(await resolveA2AAgent(target), taskId); void audit({ action: "a2a.cancel", actor, target: taskId, ok: true, detail: `target=${target.slice(0, 120)}` }); return NextResponse.json({ response });+ }+ if (action === "handoff") {+ if (limited(actor, action, 30)) return NextResponse.json({ error: "too_many_requests" }, { status: 429 });+ const objective = typeof body?.objective === "string" ? body.objective : ""; if (!target || !objective) return NextResponse.json({ error: "target_and_objective_required" }, { status: 400 });+ const result = await handoffA2A(await resolveA2AAgent(target), objective, typeof body?.context === "string" ? body.context : undefined, { returnImmediately: body?.returnImmediately !== false, sourceSessionHash: hash(`cli:${actor}`) });+ void audit({ action: "a2a.send", actor, target, ok: true, detail: "handoff" }); return NextResponse.json(result);+ }+ return NextResponse.json({ error: "unknown_action" }, { status: 400 });+ } catch (e) {+ if (action === "register" || action === "remove") void audit({ action: "a2a.registry", actor, target: target || String(body?.url || ""), ok: false, detail: String((e as Error).message).slice(0, 160) });+ else if (action === "cancel") void audit({ action: "a2a.cancel", actor, target, ok: false, detail: String((e as Error).message).slice(0, 160) });+ else if (action === "send" || action === "handoff") void audit({ action: "a2a.send", actor, target, ok: false, detail: String((e as Error).message).slice(0, 160) });+ return error(e);+ }+}diff --git a/bin/mso b/bin/msoindex ef467ea3..a6b976ca 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+# 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# prefs * UI preferences: show | set@@ -126,7 +127,7 @@# Docs: https://github.com/rahmanef63/msoset -euo pipefail-VERSION="1.6.2"+VERSION="1.7.0"ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"die() { echo "mso: $*" >&2; exit 1; }@@ -683,6 +684,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_a2a="a2a list|discover <url>|add <url> [alias]|rm <target>|send <target> <message> [--wait]|task <target> <taskId> [history]|cancel <target> <taskId>|handoff <target> <objective> [context] [--wait]"U_memory="memory list|add <text>|rm <id>"U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"U_prefs="prefs show|set <json>"@@ -947,6 +949,31 @@ case "$cmd" increate) jpost "/api/v1/agent-sessions" "$(jq -n --arg title "${2:-MSO Agent session}" '{action:"create",title:$title}')" ;;*) die "usage: mso $U_agent_sessions" ;;esac ;;+ a2a)+ sub="${1:-list}"; shift || true+ case "$sub" in+ list) jget "/api/v1/a2a" ;;+ discover) jget "/api/v1/a2a?action=discover&url=$(enc "${1:?url}")" ;;+ add|register)+ url="${1:?url}"; alias="${2:-}"+ jpost "/api/v1/a2a" "$(jq -n --arg url "$url" --arg alias "$alias" '{action:"register",url:$url} + (if $alias == "" then {} else {alias:$alias} end)')" ;;+ rm|remove) jpost "/api/v1/a2a" "$(jq -n --arg target "${1:?target}" '{action:"remove",target:$target}')" ;;+ send)+ target="${1:?target}"; message="${2:?message}"; wait="${3:-}"+ [ "$wait" = "" ] || [ "$wait" = "--wait" ] || die "usage: mso $U_a2a"+ jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg message "$message" --arg wait "$wait" '{action:"send",target:$target,message:$message,returnImmediately:($wait != "--wait")}')" ;;+ task|status)+ target="${1:?target}"; task_id="${2:?taskId}"; history="${3:-10}"+ [[ "$history" =~ ^[0-9]+$ ]] || die "history must be 0-100"; [ "$history" -le 100 ] || die "history must be 0-100"+ jget "/api/v1/a2a?action=task&target=$(enc "$target")&taskId=$(enc "$task_id")&historyLength=$history" ;;+ cancel) jpost "/api/v1/a2a" "$(jq -n --arg target "${1:?target}" --arg taskId "${2:?taskId}" '{action:"cancel",target:$target,taskId:$taskId}')" ;;+ handoff|delegate)+ target="${1:?target}"; objective="${2:?objective}"; context="${3:-}"; wait="${4:-}"+ if [ "$context" = "--wait" ]; then wait="--wait"; context=""; fi+ [ "$wait" = "" ] || [ "$wait" = "--wait" ] || die "usage: mso $U_a2a"+ jpost "/api/v1/a2a" "$(jq -n --arg target "$target" --arg objective "$objective" --arg context "$context" --arg wait "$wait" '{action:"handoff",target:$target,objective:$objective,returnImmediately:($wait != "--wait")} + (if $context == "" then {} else {context:$context} end)')" ;;+ *) die "usage: mso $U_a2a" ;;+ esac ;;memory)case "${1:-list}" inlist) jget "/api/memory" ;;diff --git a/docs/A2A.md b/docs/A2A.mdnew file mode 100644index 00000000..0114dbe5--- /dev/null+++ b/docs/A2A.md@@ -0,0 +1,115 @@+# A2A — Agent-to-Agent interoperability++MSO implements **A2A v1** as the agent-to-agent layer beside MCP. MCP remains the+agent-to-tools/data control plane for this host; A2A is for delegating explicit work to+another agent that publishes an A2A Agent Card.++The current MSO release is an **outbound A2A client**. It can discover a peer, register its+public Agent Card, send a message, hand off an objective, read task state, and request task+cancellation. MSO does **not** publish an unauthenticated inbound A2A endpoint in this phase.++## Security boundary++A remote agent is a separate trust domain. MSO therefore keeps the A2A boundary deliberately+narrow:++- Agent discovery follows the standard `/.well-known/agent-card.json` path.+- Only public **HTTPS** Agent Card and interface URLs are accepted.+- MSO reuses the host SSRF guard, including public-address validation, DNS re-resolution,+ connect-time IP pinning, and redirect refusal. Loopback/private/link-local/metadata targets+ are rejected.+- The local registry stores only sanitized public Agent Card metadata plus a local alias in+ `~/.mso/private/a2a-agents.json` (`0700` parent / `0600` file, atomic writes).+- Security requirements from an Agent Card are persisted only as scheme names. A card never+ supplies usable credentials.+- This phase intentionally supports anonymous peers only. If a card requires OAuth/API-key+ authentication, MSO detects that and fails closed instead of putting credentials in an A2A+ message or guessing an auth flow.+- Normal `send` transmits only the explicit message and optional A2A `contextId` / `taskId`.+- `handoff` transmits only the explicit objective and optional context supplied by the caller.+ MSO does not copy hidden transcript history, durable memory, Skills, tool state, or raw MSO+ session/workflow identifiers. Internal identifiers may be represented only by one-way opaque+ hashes in metadata.+- A2A writes still pass through the normal MCP/terminal `write` scope, exact-call approval,+ audit trail, and per-operation rate limits. `yolo` bypasses the human prompt only; it does not+ bypass exact-payload binding or server authorization.++## Supported A2A v1 transport surface++MSO currently supports the v1 Agent Card `supportedInterfaces` entries for:++- `JSONRPC` — `SendMessage`, `GetTask`, `CancelTask`.+- `HTTP+JSON` — `POST message:send`, `GET tasks/{id}`, `POST tasks/{id}:cancel`.++An advertised interface must use protocol version `1.x`. The selected interface's optional+`tenant` is preserved according to the binding. Responses are bounded to 1 MiB at the core+transport and model-visible MCP results are compacted further when necessary.++Not yet exposed: authenticated peer credential profiles, extended authenticated Agent Cards,+streaming/SSE, push notifications, gRPC, or an inbound MSO A2A server. These belong to the next+phase because they expand the network/auth boundary and should not be silently enabled merely+by installing the CLI.++## CLI++```bash+# inspect a public peer without persisting it+mso a2a discover https://agent.example++# register/refresh a public Agent Card under a local alias+mso a2a add https://agent.example research+mso a2a list++# explicit peer message; returns quickly by default when the peer creates a task+mso a2a send research "Find the latest implementation notes"++# read/cancel an A2A task returned by that peer+mso a2a task research <taskId>+mso a2a cancel research <taskId>++# delegate an explicit objective; optional third argument is explicit context only+mso a2a handoff research "Compare the two approaches" "Use only these acceptance criteria..."++# ask a peer to wait for completion instead of returning immediately+mso a2a send research "Do the work" --wait+mso a2a handoff research "Do the work" --wait++# forget local registry metadata (does not modify the peer)+mso a2a rm research+```++Inside interactive MSO Agent:++- `/agents` lists registered A2A peers.+- `/delegate <peer> <objective>` uses the same explicit-context handoff boundary.+- Natural prompts containing A2A/delegate/handoff intent cause the per-turn tool router to load+ the relevant A2A tools plus their discovery/status companions; A2A tools are not kept in every+ model turn by default.++## MCP tools++The provider-neutral MCP catalog exposes:++| Tool | Scope | Purpose |+|---|---|---|+| `a2a_agents_list` | read | List registered public peers |+| `a2a_agent_discover` | read | Validate/discover a public v1 Agent Card |+| `a2a_agent_register` | write | Register or refresh public Agent Card metadata |+| `a2a_agent_remove` | write | Remove local registry metadata |+| `a2a_message_send` | write | Send one explicit A2A message |+| `a2a_task_get` | read | Read remote A2A task state/history |+| `a2a_task_cancel` | write | Request remote task cancellation |+| `a2a_handoff` | write | Delegate an explicit objective/context |++This is intentionally a stable generic catalog. Registering another remote agent does not add+new dynamic MCP tool names; the target is data (`alias`/id/Agent Card URL), just as project+functions remain data behind `project_function_call`.++## Next phase++The safe next expansion is a dedicated private A2A credential-profile store and explicit+per-peer auth configuration, followed by authenticated inbound MSO Agent Card/endpoint support.+Streaming and push should be added only after task ownership, callback validation, credential+rotation, and inbound rate/authorization policy are defined and tested.++Official protocol reference: <https://a2a-protocol.org/latest/>.diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e61d2a77..d3794bf1 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -158,11 +158,11 @@ park a visible Approve/Deny card. The complete semantic contract is**MCP** is for external clients such as ChatGPT, Claude.ai and Cursor. Its catalog lives in`lib/mcp/`; access is controlled by the OAuth token scope rather than Alfa approval cards.-At the current toolset it exposes 47 transport tools: 46 model/operator tools (24 read, 17 write, 5 exec) plus the app-only `workflow_status` progress bridge. Project-specific+At the current toolset it exposes 56 transport tools: 55 model/operator tools (28 read, 22 write, 5 exec) plus the app-only `workflow_status` progress bridge. Project-specificfunction names remain data behind `project_capabilities` / `project_function_call`, so oneproject cannot dynamically rewrite the global MCP tool prefix.-See `docs/MCP.md` for protocol/security internals and `docs/CHATGPT-PLUGIN.md` for the+See `docs/MCP.md` for protocol/security internals, `docs/A2A.md` for peer-agent delegation, and `docs/CHATGPT-PLUGIN.md` for theChatGPT-facing setup and diagrams.## 7. Project and skill discoverydiff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 259ab982..ba0168d7 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,6 +4,12 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → About shows as “What's new”.+## 2026-09-02++**Added**++- `agent` add interactive permissions and a2a v1+## 2026-09-01**Added**diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdindex c2011098..5cf14436 100644--- a/docs/CHATGPT-PLUGIN.md+++ b/docs/CHATGPT-PLUGIN.md@@ -12,10 +12,10 @@> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>> and <https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex>.-<!-- mcp-toolset: server=1.6.0 version=2026.09.02.2 tools=47 read=25 write=17 exec=5 -->+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.3 tools=55 read=28 write=22 exec=5 -->-MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.2**: **48 transport tools** total; **47 model/operator tools**-(25 read, 17 write, 5 exec) plus app-only `workflow_status` for the progress widget. Use `GET /mcp` or Settings → MCP as the live authority if+MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.3**: **56 transport tools** total; **55 model/operator tools**+(28 read, 22 write, 5 exec) plus app-only `workflow_status` for the progress widget. Use `GET /mcp` or Settings → MCP as the live authority ifthis document and a deployed instance ever disagree.## 1. What this connection does@@ -141,8 +141,11 @@ A token sees a scope prefix; there is no per-project or per-agent hidden tool fi`tools/list` filters the catalog and `tools/call` independently re-checks the requiredscope.-### `read` — 25 model/operator tools+### `read` — 28 model/operator tools+- `a2a_agent_discover`+- `a2a_agents_list`+- `a2a_task_get`- `agent_memory_read`- `agent_memory_search`- `agent_session_current`@@ -168,8 +171,13 @@ scope.- `skills_search`- `sys_processes`- `sys_stats`-### `write` — read + 17 tools+### `write` — read + 22 tools+- `a2a_agent_register`+- `a2a_agent_remove`+- `a2a_message_send`+- `a2a_task_cancel`+- `a2a_handoff`- `agent_memory_forget`- `agent_memory_remember`- `agent_session_note`@@ -211,6 +219,16 @@ snapshot; unrelated rows are never included in the mutation payload and ambiguoustill deserves the same scrutiny as any external infrastructure mutation. Configure providerslocally with `mso provider set <id>` rather than pasting credentials into a ChatGPT message.++### A2A peer delegation++ChatGPT can use `a2a_agent_discover`/`a2a_agents_list` to find peers, then the write-scope+`a2a_message_send` or `a2a_handoff` to delegate explicit work. `a2a_task_get` polls the remote+task and `a2a_task_cancel` requests cancellation; register/remove only mutate MSO's local public+Agent Card registry. MSO never auto-forwards this ChatGPT conversation, private agent memory, or+raw MSO session/workflow ids to a peer. Current A2A is outbound/public-HTTPS/anonymous only and+fails closed for Agent Cards that require credentials. See [`A2A.md`](./A2A.md).+## 6. Tool-snapshot refresh: the part most often missedChatGPT scans and caches the MCP action definitions. If MSO adds/removes/changes tools, a@@ -222,9 +240,9 @@ Settings → MCP:```textserver: 1.6.0-toolset: 2026.09.02.2+toolset: 2026.09.02.3hash: <live schema hash>-count: 46 model/operator tools (+ 1 app-only bridge)+count: 55 model/operator tools (+ 1 app-only bridge)```Use this sequence after an MSO MCP change:diff --git a/docs/CLI.md b/docs/CLI.mdindex 42285949..a972bd66 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -104,6 +104,7 @@ Commands:ai <prompt…> One turn with the assistantthreads * Conversation history: list | show | rmagent-sessions * Durable MSO Agent sessions: list | show | create+ a2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoffmemory * Assistant memories: list | add | rmconfig * Advanced raw AI config compatibility surfaceprefs * UI preferences: show | setdiff --git a/docs/COGNITIVE-RUNTIME.md b/docs/COGNITIVE-RUNTIME.mdindex fb93e2b4..00a5cc43 100644--- a/docs/COGNITIVE-RUNTIME.md+++ b/docs/COGNITIVE-RUNTIME.md@@ -136,17 +136,17 @@ probe. Overall product superiority also cannot be inferred from a prompt-size remust add equivalent task-success, tool-error, token-per-success, latency-per-success, and policy-compliancescenarios before making that claim.-## Current P1 baseline+## Current P1 + A2A baselineOn the development host after P1 implementation:| Metric | MSO P1 | Hermes local baseline ||---|---:|---:|-| Full MSO transport catalog | 48 tools | — |-| Full MSO schema bytes | 32,969 | — |-| Average MSO active tools / turn | 14.5 | — |-| Average active schema bytes / turn | 11,125 | 44,758 tool-schema bytes |-| MSO schema reduction vs full catalog | 66.3% | — |+| Full MSO transport catalog | 56 tools | — |+| Full MSO schema bytes | 37,904 | — |+| Average MSO active tools / turn | 15.5 | — |+| Average active schema bytes / turn | 11,582 | 44,758 tool-schema bytes |+| MSO schema reduction vs full catalog | 69.4% | — || Required-tool routing recall | 100% | not the same benchmark || Typed-memory fixture accuracy | 100% (8/8) | not implemented in this harness || Deterministic routing / memory resolution | yes / yes | not the same benchmark |diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.mdindex 921457c3..fa3f488e 100644--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md@@ -4,10 +4,10 @@> can evolve independently, so do not claim its mapping count is current without checking> that repository at the time of the change.-<!-- mcp-toolset: server=1.6.0 version=2026.09.02.2 tools=47 read=25 write=17 exec=5 -->+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.3 tools=55 read=28 write=22 exec=5 -->-MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.2**: **48 transport tools** total; **47 model/operator tools**-(25 read, 17 write, 5 exec) plus app-only `workflow_status`. `GET /mcp` exposes the live names, version/hash and scoped+MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.3**: **56 transport tools** total; **55 model/operator tools**+(28 read, 22 write, 5 exec) plus app-only `workflow_status`. `GET /mcp` exposes the live names, version/hash and scopedmanifest and is the machine-readable parity source.## Why this contract matters@@ -33,16 +33,17 @@ Before changing an MCP tool name:## Current MSO catalog-### Read (25 model/operator)+### Read (28 model/operator)-`agent_memory_read`, `agent_memory_search`, `agent_session_current`, `agent_session_resume`, `agent_sessions_list`,+`a2a_agent_discover`, `a2a_agents_list`, `a2a_task_get`, `agent_memory_read`, `agent_memory_search`, `agent_session_current`, `agent_session_resume`, `agent_sessions_list`,`apps_list`, `apps_logs`, `browser_status`, `cloudflare_zones_list`, `dokploy_projects_list`,`exec_job_status`, `fs_list`, `fs_read`, `fs_search`, `fs_usage`, `infra_provider_doctor`,`infra_providers_list`, `project_capabilities`, `projects_list`, `screen_capture`, `skills_list`,`skills_read`, `skills_search`, `sys_processes`, `sys_stats`.-### Write (17 beyond read)+### Write (22 beyond read)+`a2a_agent_register`, `a2a_agent_remove`, `a2a_message_send`, `a2a_task_cancel`, `a2a_handoff`,`agent_memory_forget`, `agent_memory_remember`, `agent_session_note`, `agent_session_rename`,`apps_power`, `cloudflare_dns_upsert`, `dokploy_project_ensure`, `fs_copy`, `fs_delete`,`fs_mkdir`, `fs_move`, `fs_upload_file`, `fs_write`, `hostinger_dns_upsert`,@@ -56,6 +57,11 @@ Before changing an MCP tool name:`workflow_status` is exposed for the MCP Apps progress widget and is not part of the model/operator action catalog.+A2A adds eight stable generic action names rather than one action per peer. A gateway should pass+the registered alias/id or public Agent Card URL as the `target`; it must not synthesize hidden+conversation context. Current MSO A2A is outbound, public-HTTPS, anonymous-only and rejects peers+whose Agent Card requires credentials. Full semantics live in [`A2A.md`](./A2A.md).+## Scope and workflow compatibilityThe MSO scope ladder (`read < write < exec`) is the server permission boundary. A gatewaydiff --git a/docs/MCP.md b/docs/MCP.mdindex 46118f72..54257d18 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -75,8 +75,8 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe| Scope | Tools ||---|---|-| `read` | `agent_memory_read` `agent_memory_search` `agent_session_current` `agent_session_resume` `agent_sessions_list` `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` `exec_job_status` `infra_providers_list` `infra_provider_doctor` `dokploy_projects_list` `cloudflare_zones_list` |-| `write` | + `agent_memory_forget` `agent_memory_remember` `agent_session_note` `agent_session_rename` `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` `dokploy_project_ensure` `cloudflare_dns_upsert` `hostinger_dns_upsert` |+| `read` | `a2a_agent_discover` `a2a_agents_list` `a2a_task_get` `agent_memory_read` `agent_memory_search` `agent_session_current` `agent_session_resume` `agent_sessions_list` `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` `exec_job_status` `infra_providers_list` `infra_provider_doctor` `dokploy_projects_list` `cloudflare_zones_list` |+| `write` | + `a2a_agent_register` `a2a_agent_remove` `a2a_message_send` `a2a_task_cancel` `a2a_handoff` `agent_memory_forget` `agent_memory_remember` `agent_session_note` `agent_session_rename` `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` `dokploy_project_ensure` `cloudflare_dns_upsert` `hostinger_dns_upsert` || `exec` | + `project_function_call` `exec_run` `exec_job_start` `exec_job_cancel` `browser_power` |Alfa — the in-app assistant — overlaps the same host capabilities under dot.case names,@@ -124,10 +124,10 @@ The catalog has a stable server version plus a schema-derived toolset signature.Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.-<!-- mcp-toolset: server=1.6.0 version=2026.09.02.2 tools=47 read=25 write=17 exec=5 -->+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.3 tools=55 read=28 write=22 exec=5 -->-Current transport catalog: **48 tools**, server `1.6.0` / toolset `2026.09.02.2`.-The model/operator catalog is **47 tools** (25 read, 17 write, 5 exec); `workflow_status` is the+Current transport catalog: **56 tools**, server `1.6.0` / toolset `2026.09.02.3`.+The model/operator catalog is **55 tools** (28 read, 22 write, 5 exec); `workflow_status` is theone app-only MCP Apps bridge used by the progress widget and is documented separately.`agent_memory_search` is the typed-memory retrieval surface. It resolves semantic/episodic/procedural claims at an optional point in time, returns confidence/provenance and competing effective claims, and can expose superseded/retracted history when explicitly requested. `agent_memory_remember` remains the write surface and now accepts typed metadata; raw ChatGPT conversation ids are never stored as provenance.@@ -135,6 +135,19 @@ Session/memory tools add durable conversation context without creatingdynamic per-project tool names; `project_capabilities` and `project_function_call` remain thestable project-automation seam.+### Agent-to-Agent (A2A) peers++The eight `a2a_*` tools are the provider-neutral remote-agent seam: `a2a_agents_list`,+`a2a_agent_discover`, `a2a_agent_register`, `a2a_agent_remove`, `a2a_message_send`,+`a2a_task_get`, `a2a_task_cancel`, and `a2a_handoff`. Discovery and task reads are read scope;+registry mutations, messages, cancellation, and handoff are write scope and therefore keep the+normal exact-call approval/audit boundary. Registered peers are data, not dynamic MCP names.++MSO's current A2A client accepts only public HTTPS v1 peers, blocks SSRF/DNS rebinding, and+fails closed when an Agent Card requires credentials. A normal message transmits only explicit+message/context/task arguments; a handoff never auto-attaches the caller's hidden transcript,+memory or raw session/workflow ids. See [`A2A.md`](./A2A.md) for the transport and trust contract.+## Opt-in project MCP/function capabilitiesMSO itself stays generic. A project opts into extra automation by placing files insidediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 3dc664ea..ff7ddb38 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,6 +2,14 @@Running log of what shipped each phase. Newest at top.+## 2026-09-02 — Interactive permission badge + outbound A2A v1 — SHIPPED++MSO CLI **1.7.0** makes permission state part of the interactive prompt instead of terminal scrollback. The bottom-left prompt is now a persistent color-coded badge (`ask` cyan, `auto` amber, `yolo` red); Tab on an empty prompt cycles `ask → auto → yolo` by repainting the same row with zero added LF/newline. The compact status line no longer duplicates permission. `/permission` remains the explicit picker/command surface, and the existing exact-call digest/server authorization semantics are unchanged. A live PTY regression proves three Tab transitions emit no scrollback line.++The same release adds a provider-neutral **A2A v1 outbound client** beside MCP. MSO discovers the standard well-known Agent Card, validates v1 `supportedInterfaces`, supports JSONRPC and HTTP+JSON `SendMessage` / `GetTask` / `CancelTask`, preserves optional tenant routing, bounds remote responses, and exposes a private host registry plus `mso a2a` / `/agents` / `/delegate`. MCP adds eight stable `a2a_*` tools for discovery/registry/message/task/handoff instead of dynamic per-peer tool names, and the per-turn router loads them only for A2A/delegation intent.++A2A is deliberately fail-closed at the trust boundary: only public HTTPS peers are accepted; the existing SSRF/DNS-rebinding pinned transport is reused; Agent Card security requirements are reduced to scheme names; authenticated peers are detected but not contacted until a dedicated credential profile exists. Normal messages carry only explicit A2A message/context/task arguments, while `a2a_handoff` carries only objective/context supplied by the caller plus optional one-way hashes—never hidden MSO history, memory, Skills, tool state, or raw session/workflow ids. Inbound MSO A2A serving, auth profiles, streaming/push and gRPC remain a later explicit phase rather than opening a network listener implicitly.+## 2026-09-02 — Full-store session resume resolution — SHIPPEDMSO CLI **1.6.2** moves direct resume resolution to the server-side durable session store instead of first truncating the candidate set to 100 recent summaries in the terminal client. `--continue`, `--resume`, `/session <query>`, and `/resume <query>` now resolve `latest`, modified-order index, full/short id, exact/prefix/fuzzy title against every owner-visible durable session; the interactive picker intentionally remains a bounded newest-first view for fast navigation. Empty default CLI shells are excluded from index/latest selection, matching the human picker. Ambiguity errors use human titles rather than exposing internal ids. Regression coverage includes a target beyond 275 synthetic recent rows so the 100-row regression cannot return.diff --git a/docs/README.md b/docs/README.mdindex 06f68a06..aae670bd 100644--- a/docs/README.md+++ b/docs/README.md@@ -30,6 +30,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`SECURITY-ASSURANCE.md`](./SECURITY-ASSURANCE.md) | Repeatable security verification lanes, public evidence, and claim boundaries || [`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 || [`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/a2a/client.test.ts b/lib/a2a/client.test.tsnew file mode 100644index 00000000..a46966f4--- /dev/null+++ b/lib/a2a/client.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import { cancelA2ATask, discoverA2AAgent, getA2ATask, sendA2AMessage } from "./client";++const card = (binding = "JSONRPC") => ({+ name: "Research Agent", description: "Finds concise answers", version: "1.2.0", capabilities: { streaming: false },+ supportedInterfaces: [{ url: "https://agent.example.test/a2a", protocolBinding: binding, protocolVersion: "1.0", tenant: "research" }],+ defaultInputModes: ["text/plain"], defaultOutputModes: ["text/plain"], skills: [{ id: "research", name: "Research", description: "Research topics", tags: ["web"] }],+});+function response(value: unknown) { return new Response(JSON.stringify(value), { status: 200, headers: { "content-type": "application/json" } }); }++it("discovers the standard well-known v1 Agent Card and selects JSONRPC", async () => {+ let seen = "";+ const agent = await discoverA2AAgent("https://agent.example.test/a2a", async (input) => { seen = String(input); return response(card()); });+ expect(seen).toBe("https://agent.example.test/.well-known/agent-card.json");+ expect(agent.card.name).toBe("Research Agent"); expect(agent.selectedInterface.protocolBinding).toBe("JSONRPC");+});++it("sends v1 JSONRPC SendMessage with tenant and member-discriminated text parts", async () => {+ const calls: Array<{ url: string; init?: RequestInit }> = [];+ const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => { calls.push({ url: String(input), init }); return calls.length === 1 ? response(card()) : response({ jsonrpc: "2.0", id: "x", result: { task: { id: "t-1" } } }); };+ const agent = await discoverA2AAgent("https://agent.example.test", fetcher);+ const result = await sendA2AMessage(agent, "Do the research", { returnImmediately: true }, fetcher) as { task: { id: string } };+ const body = JSON.parse(String(calls[1].init?.body));+ expect(body.method).toBe("SendMessage"); expect(body.params.tenant).toBe("research");+ expect(body.params.message.role).toBe("ROLE_USER"); expect(body.params.message.parts).toEqual([{ text: "Do the research", mediaType: "text/plain" }]);+ expect(body.params.message.parts[0]).not.toHaveProperty("kind"); expect(result.task.id).toBe("t-1");+});++it("uses v1 HTTP+JSON operation paths for send/get/cancel including tenant", async () => {+ const calls: Array<{ url: string; init?: RequestInit }> = [];+ const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => { calls.push({ url: String(input), init }); return calls.length === 1 ? response(card("HTTP+JSON")) : response({ task: { id: "t-1" } }); };+ const agent = await discoverA2AAgent("https://agent.example.test", fetcher);+ await sendA2AMessage(agent, "go", {}, fetcher); await getA2ATask(agent, "t-1", 4, fetcher); await cancelA2ATask(agent, "t-1", fetcher);+ expect(calls[1].url).toBe("https://agent.example.test/a2a/research/message:send");+ expect(calls[2].url).toBe("https://agent.example.test/a2a/research/tasks/t-1?historyLength=4");+ expect(calls[3].url).toBe("https://agent.example.test/a2a/research/tasks/t-1:cancel");+});++it("fails closed when the Agent Card requires authentication", async () => {+ const secured = { ...card(), securityRequirements: [{ oauth: { scopes: ["agent"] } }], securitySchemes: { oauth: { oauth2SecurityScheme: {} } } };+ const fetcher = async () => response(secured); const agent = await discoverA2AAgent("https://agent.example.test", fetcher);+ await expect(sendA2AMessage(agent, "secret work", {}, fetcher)).rejects.toThrow("credential profiles are not configured");+});diff --git a/lib/a2a/client.ts b/lib/a2a/client.tsnew file mode 100644index 00000000..4fa468b5--- /dev/null+++ b/lib/a2a/client.ts@@ -0,0 +1,195 @@+import { randomUUID } from "node:crypto";+import { assertSafeUrl, safeProviderFetch } from "@/lib/host/ssrf";+import type { A2AAgentCard, A2AAgentInterface, A2ADiscoveredAgent, A2ASendOptions, A2AStandardBinding } from "./types";++export const MAX_A2A_RESPONSE_BYTES = 1024 * 1024;+export const MAX_A2A_MESSAGE_BYTES = 24 * 1024;+export const A2A_TIMEOUT_MS = 20_000;++function assertA2AUrl(raw: string | URL): URL {+ const url = assertSafeUrl(String(raw));+ if (url.protocol !== "https:") throw new Error("A2A endpoints must use HTTPS");+ return url;+}++type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;+const transport: FetchLike = (input, init) => safeProviderFetch(input, init);++function obj(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};+}+function text(value: unknown, field: string, max = 500): string {+ const out = typeof value === "string" ? value.replace(/[\r\n\t]+/g, " ").trim() : "";+ if (!out) throw new Error(`A2A Agent Card is missing ${field}`);+ return [...out].slice(0, max).join("");+}+function strings(value: unknown, max = 100): string[] {+ return Array.isArray(value) ? value.filter((row): row is string => typeof row === "string" && Boolean(row.trim()))+ .map((row) => row.trim().slice(0, 200)).slice(0, max) : [];+}+function normalizeBinding(value: string): A2AStandardBinding | null {+ const normalized = value.toUpperCase().replace(/[^A-Z0-9]/g, "");+ if (normalized === "JSONRPC") return "JSONRPC";+ if (normalized === "HTTPJSON") return "HTTP+JSON";+ return null;+}+function supportsV1(value: string): boolean { return /^1(?:\.|$)/.test(value.trim()); }++export function a2aAgentCardUrl(source: string): string {+ const url = assertA2AUrl(source);+ if (!/\.json$/i.test(url.pathname)) {+ url.pathname = "/.well-known/agent-card.json";+ url.search = "";+ }+ return url.toString();+}++function normalizeInterface(value: unknown): A2AAgentInterface {+ const row = obj(value);+ const url = assertA2AUrl(text(row.url, "supportedInterfaces[].url", 2048)).toString();+ return {+ url,+ protocolBinding: text(row.protocolBinding, "supportedInterfaces[].protocolBinding", 160),+ protocolVersion: text(row.protocolVersion, "supportedInterfaces[].protocolVersion", 40),+ ...(typeof row.tenant === "string" && row.tenant.trim() ? { tenant: row.tenant.trim().slice(0, 160) } : {}),+ };+}++export function normalizeA2AAgentCard(value: unknown): A2AAgentCard {+ const raw = obj(value);+ const interfaces = Array.isArray(raw.supportedInterfaces) ? raw.supportedInterfaces.map(normalizeInterface).slice(0, 20) : [];+ if (!interfaces.length) throw new Error("A2A Agent Card must declare supportedInterfaces");+ const capabilities = Object.fromEntries(Object.entries(obj(raw.capabilities))+ .filter(([, v]) => typeof v === "boolean").slice(0, 30)) as Record<string, boolean>;+ const requirementsRaw = Array.isArray(raw.securityRequirements) ? raw.securityRequirements+ : Array.isArray(raw.security) ? raw.security : [];+ // Agent Cards are public metadata, but a malicious peer could still stuff arbitrary+ // nested values into a security requirement. Persist only scheme NAMES; actual+ // credentials are always acquired/stored out of band and never copied from a card.+ const securityRequirements = requirementsRaw.slice(0, 20).map((entry) => {+ const row = obj(entry);+ return Object.fromEntries(Object.keys(row).filter((key) => /^[A-Za-z0-9._-]{1,120}$/.test(key)).slice(0, 20).map((key) => [key, {}]));+ });+ const requiresAuthentication = securityRequirements.length > 0 && !securityRequirements.some((row) => Object.keys(row).length === 0);+ const skills = (Array.isArray(raw.skills) ? raw.skills : []).slice(0, 200).map((entry) => {+ const row = obj(entry);+ return {+ id: text(row.id, "skills[].id", 160), name: text(row.name, "skills[].name", 160),+ description: text(row.description, "skills[].description", 600), tags: strings(row.tags, 30),+ inputModes: strings(row.inputModes, 30), outputModes: strings(row.outputModes, 30),+ };+ });+ return {+ name: text(raw.name, "name", 160), description: text(raw.description, "description", 1000), version: text(raw.version, "version", 80),+ supportedInterfaces: interfaces, capabilities,+ defaultInputModes: strings(raw.defaultInputModes, 30), defaultOutputModes: strings(raw.defaultOutputModes, 30), skills,+ securityRequirements, securitySchemeNames: Object.keys(obj(raw.securitySchemes)).slice(0, 30), requiresAuthentication,+ };+}++export function selectA2AInterface(card: A2AAgentCard): A2AAgentInterface {+ const selected = card.supportedInterfaces.find((row) => supportsV1(row.protocolVersion) && normalizeBinding(row.protocolBinding));+ if (!selected) {+ const advertised = card.supportedInterfaces.map((row) => `${row.protocolBinding}@${row.protocolVersion}`).join(", ");+ throw new Error(`A2A agent has no supported v1 JSONRPC or HTTP+JSON interface${advertised ? `; advertised: ${advertised}` : ""}`);+ }+ return selected;+}++async function boundedJson(response: Response): Promise<unknown> {+ const declared = Number(response.headers.get("content-length"));+ if (Number.isFinite(declared) && declared > MAX_A2A_RESPONSE_BYTES) {+ await response.body?.cancel().catch(() => undefined);+ throw new Error(`A2A response exceeds ${MAX_A2A_RESPONSE_BYTES} bytes`);+ }+ if (!response.body) return null;+ const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let total = 0;+ try {+ while (true) {+ const { done, value } = await reader.read(); if (done) break; if (!value?.byteLength) continue;+ total += value.byteLength;+ if (total > MAX_A2A_RESPONSE_BYTES) { await reader.cancel().catch(() => undefined); throw new Error(`A2A response exceeds ${MAX_A2A_RESPONSE_BYTES} bytes`); }+ chunks.push(value);+ }+ } finally { reader.releaseLock(); }+ const all = new Uint8Array(total); let offset = 0; for (const chunk of chunks) { all.set(chunk, offset); offset += chunk.byteLength; }+ const raw = new TextDecoder().decode(all);+ try { return raw ? JSON.parse(raw) : null; } catch { throw new Error("A2A endpoint returned invalid JSON"); }+}++async function fetchJson(url: string, init: RequestInit, fetchImpl: FetchLike): Promise<unknown> {+ const safe = assertA2AUrl(url).toString();+ const response = await fetchImpl(safe, { ...init, redirect: "error", signal: init.signal ?? AbortSignal.timeout(A2A_TIMEOUT_MS) });+ const body = await boundedJson(response);+ if (!response.ok) throw new Error(`A2A endpoint returned HTTP ${response.status}`);+ return body;+}++export async function discoverA2AAgent(source: string, fetchImpl: FetchLike = transport): Promise<A2ADiscoveredAgent> {+ const cardUrl = a2aAgentCardUrl(source);+ const raw = await fetchJson(cardUrl, { headers: { accept: "application/a2a+json, application/json" } }, fetchImpl);+ const card = normalizeA2AAgentCard(raw);+ return { cardUrl, card, selectedInterface: selectA2AInterface(card) };+}++function assertAnonymous(card: A2AAgentCard): void {+ if (card.requiresAuthentication) {+ throw new Error(`A2A agent ${card.name} requires authentication; credential profiles are not configured yet`);+ }+}+function assertMessage(value: string): string {+ const message = String(value ?? "").trim(); if (!message) throw new Error("A2A message must not be empty");+ if (Buffer.byteLength(message, "utf8") > MAX_A2A_MESSAGE_BYTES) throw new Error(`A2A message exceeds ${MAX_A2A_MESSAGE_BYTES} bytes`);+ return message;+}+function restOperationUrl(iface: A2AAgentInterface, operation: string): string {+ const url = assertA2AUrl(iface.url); const base = url.pathname.endsWith("/") ? url.pathname : `${url.pathname}/`;+ const tenant = iface.tenant ? `${encodeURIComponent(iface.tenant)}/` : "";+ url.pathname = `${base}${tenant}${operation}`.replace(/\/{2,}/g, "/"); url.search = "";+ return url.toString();+}+function requestParams(iface: A2AAgentInterface, params: Record<string, unknown>): Record<string, unknown> {+ return iface.tenant ? { tenant: iface.tenant, ...params } : params;+}+function headers(iface: A2AAgentInterface, contentType: string): HeadersInit {+ return { "content-type": contentType, accept: "application/a2a+json, application/json", "a2a-version": iface.protocolVersion };+}++async function invoke(target: A2ADiscoveredAgent, method: "SendMessage" | "GetTask" | "CancelTask", params: Record<string, unknown>, fetchImpl: FetchLike): Promise<unknown> {+ assertAnonymous(target.card); const iface = target.selectedInterface; const binding = normalizeBinding(iface.protocolBinding);+ if (!binding) throw new Error(`unsupported A2A binding: ${iface.protocolBinding}`);+ const rpcParams = requestParams(iface, params);+ if (binding === "JSONRPC") {+ const rpcId = randomUUID();+ const response = obj(await fetchJson(iface.url, { method: "POST", headers: headers(iface, "application/json"), body: JSON.stringify({ jsonrpc: "2.0", id: rpcId, method, params: rpcParams }) }, fetchImpl));+ if (response.error) { const err = obj(response.error); throw new Error(`A2A ${method} failed: ${String(err.message || "JSON-RPC error")}`); }+ return response.result;+ }+ if (method === "GetTask") {+ const taskId = encodeURIComponent(String(params.id)); const url = new URL(restOperationUrl(iface, `tasks/${taskId}`));+ if (params.historyLength !== undefined) url.searchParams.set("historyLength", String(params.historyLength));+ return fetchJson(url.toString(), { headers: headers(iface, "application/a2a+json") }, fetchImpl);+ }+ const path = method === "SendMessage" ? "message:send" : `tasks/${encodeURIComponent(String(params.id))}:cancel`;+ const body = { ...params }; if (iface.tenant) delete body.tenant;+ return fetchJson(restOperationUrl(iface, path), { method: "POST", headers: headers(iface, "application/a2a+json"), body: JSON.stringify(body) }, fetchImpl);+}++export async function sendA2AMessage(target: A2ADiscoveredAgent, message: string, options: A2ASendOptions = {}, fetchImpl: FetchLike = transport): Promise<unknown> {+ const content = assertMessage(message);+ const msg = { messageId: randomUUID(), role: "ROLE_USER", parts: [{ text: content, mediaType: "text/plain" }],+ ...(options.contextId ? { contextId: options.contextId } : {}), ...(options.taskId ? { taskId: options.taskId } : {}) };+ const configuration = { acceptedOutputModes: target.card.defaultOutputModes.length ? target.card.defaultOutputModes.slice(0, 20) : ["text/plain", "application/json"],+ ...(options.historyLength !== undefined ? { historyLength: Math.max(0, Math.min(100, Math.trunc(options.historyLength))) } : {}),+ ...(options.returnImmediately !== undefined ? { returnImmediately: options.returnImmediately } : {}) };+ return invoke(target, "SendMessage", { message: msg, configuration, ...(options.metadata ? { metadata: options.metadata } : {}) }, fetchImpl);+}++export function getA2ATask(target: A2ADiscoveredAgent, taskId: string, historyLength = 10, fetchImpl: FetchLike = transport): Promise<unknown> {+ const id = String(taskId || "").trim(); if (!id) throw new Error("A2A task id is required");+ return invoke(target, "GetTask", { id, historyLength: Math.max(0, Math.min(100, Math.trunc(historyLength))) }, fetchImpl);+}+export function cancelA2ATask(target: A2ADiscoveredAgent, taskId: string, fetchImpl: FetchLike = transport): Promise<unknown> {+ const id = String(taskId || "").trim(); if (!id) throw new Error("A2A task id is required");+ return invoke(target, "CancelTask", { id }, fetchImpl);+}diff --git a/lib/a2a/handoff.ts b/lib/a2a/handoff.tsnew file mode 100644index 00000000..76a03904--- /dev/null+++ b/lib/a2a/handoff.ts@@ -0,0 +1,28 @@+import type { A2ADiscoveredAgent } from "./types";+import { sendA2AMessage } from "./client";++export const MAX_A2A_HANDOFF_OBJECTIVE_BYTES = 8 * 1024;+export const MAX_A2A_HANDOFF_CONTEXT_BYTES = 8 * 1024;++function bounded(value: string, bytes: number, label: string): string {+ const out = String(value || "").trim();+ if (!out) throw new Error(`${label} must not be empty`);+ if (Buffer.byteLength(out, "utf8") > bytes) throw new Error(`${label} exceeds ${bytes} bytes`);+ return out;+}++export async function handoffA2A(+ agent: A2ADiscoveredAgent,+ objectiveRaw: string,+ suppliedContextRaw?: string,+ options: { returnImmediately?: boolean; sourceSessionHash?: string; sourceWorkflowHash?: string } = {},+): Promise<{ handoff: { objectiveBytes: number; contextBytes: number }; response: unknown }> {+ const objective = bounded(objectiveRaw, MAX_A2A_HANDOFF_OBJECTIVE_BYTES, "A2A handoff objective");+ const suppliedContext = suppliedContextRaw?.trim() ? bounded(suppliedContextRaw, MAX_A2A_HANDOFF_CONTEXT_BYTES, "A2A handoff context") : undefined;+ const message = `Objective:\n${objective}${suppliedContext ? `\n\nContext explicitly supplied by caller:\n${suppliedContext}` : ""}`;+ const response = await sendA2AMessage(agent, message, {+ returnImmediately: options.returnImmediately !== false,+ metadata: { "mso.a2a": { type: "handoff", source: "MSO", ...(options.sourceSessionHash ? { sourceSessionHash: options.sourceSessionHash } : {}), ...(options.sourceWorkflowHash ? { sourceWorkflowHash: options.sourceWorkflowHash } : {}) } },+ });+ return { handoff: { objectiveBytes: Buffer.byteLength(objective), contextBytes: Buffer.byteLength(suppliedContext || "") }, response };+}diff --git a/lib/a2a/index.ts b/lib/a2a/index.tsnew file mode 100644index 00000000..5b77890a--- /dev/null+++ b/lib/a2a/index.ts@@ -0,0 +1,4 @@+export * from "./types";+export * from "./client";+export * from "./store";+export * from "./handoff";diff --git a/lib/a2a/store.test.ts b/lib/a2a/store.test.tsnew file mode 100644index 00000000..68a9736f--- /dev/null+++ b/lib/a2a/store.test.ts@@ -0,0 +1,17 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import os from "node:os";+import { afterEach, describe, expect, it, vi } from "vitest";++const dirs: string[] = [];+afterEach(async () => { vi.resetModules(); delete process.env.OS_A2A_STORE; await Promise.all(dirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); });++it("stores registered public Agent Cards in a private atomic registry", async () => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-a2a-")); dirs.push(dir); process.env.OS_A2A_STORE = path.join(dir, "private", "agents.json");+ const client = await import("./client");+ vi.spyOn(client, "discoverA2AAgent").mockResolvedValue({ cardUrl: "https://agent.example/.well-known/agent-card.json", selectedInterface: { url: "https://agent.example/a2a", protocolBinding: "JSONRPC", protocolVersion: "1.0" }, card: { name: "Research Agent", description: "Research", version: "1", supportedInterfaces: [{ url: "https://agent.example/a2a", protocolBinding: "JSONRPC", protocolVersion: "1.0" }], capabilities: {}, defaultInputModes: ["text/plain"], defaultOutputModes: ["text/plain"], skills: [], securityRequirements: [], securitySchemeNames: [], requiresAuthentication: false } });+ const store = await import("./store"); const registered = await store.registerA2AAgent("https://agent.example", "research");+ expect(registered.alias).toBe("research"); expect(await store.listA2AAgents()).toHaveLength(1);+ const stat = await fs.stat(process.env.OS_A2A_STORE); expect(stat.mode & 0o777).toBe(0o600); expect((await fs.stat(path.dirname(process.env.OS_A2A_STORE))).mode & 0o777).toBe(0o700);+ expect(await store.removeA2AAgent("research")).toBe(true); expect(await store.listA2AAgents()).toHaveLength(0);+});diff --git a/lib/a2a/store.ts b/lib/a2a/store.tsnew file mode 100644index 00000000..4addac59--- /dev/null+++ b/lib/a2a/store.ts@@ -0,0 +1,78 @@+import { createHash, randomUUID } from "node:crypto";+import { constants as fsConstants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { discoverA2AAgent } from "./client";+import type { A2ADiscoveredAgent, A2ARegisteredAgent } from "./types";++export const A2A_STORE_PATH = process.env.OS_A2A_STORE ?? path.join(os.homedir(), ".mso", "private", "a2a-agents.json");+const MAX_STORE_BYTES = 1024 * 1024;+type A2AStore = { version: 1; agents: A2ARegisteredAgent[] };++function slug(value: string): string {+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "agent";+}+function idFor(cardUrl: string): string { return createHash("sha256").update(cardUrl).digest("hex").slice(0, 16); }+function validAlias(value: string): string {+ const alias = String(value || "").trim().toLowerCase();+ if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(alias)) throw new Error("A2A alias must be 1-64 lowercase letters, digits, dot, underscore, or dash");+ return alias;+}++async function readUnlocked(): Promise<A2AStore> {+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;+ try {+ handle = await fs.open(A2A_STORE_PATH, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW); const stat = await handle.stat();+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_STORE_BYTES) throw new Error("A2A registry has an invalid file shape");+ if ((stat.mode & 0o077) !== 0) throw new Error("A2A registry permissions are too broad; expected 0600");+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("A2A registry is not owned by the MSO user");+ const data = JSON.parse(await handle.readFile("utf8")) as A2AStore;+ if (data?.version !== 1 || !Array.isArray(data.agents)) throw new Error("A2A registry has an invalid shape");+ return data;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, agents: [] };+ throw error;+ } finally { await handle?.close().catch(() => undefined); }+}++async function writeUnlocked(store: A2AStore): Promise<void> {+ const body = JSON.stringify(store, null, 2); if (Buffer.byteLength(body, "utf8") > MAX_STORE_BYTES) throw new Error("A2A registry exceeds 1 MiB");+ const dir = path.dirname(A2A_STORE_PATH); await fs.mkdir(dir, { recursive: true, mode: 0o700 }); await fs.chmod(dir, 0o700).catch(() => undefined);+ const tmp = `${A2A_STORE_PATH}.${randomUUID()}.tmp`; await fs.writeFile(tmp, body, { encoding: "utf8", mode: 0o600 }); await fs.chmod(tmp, 0o600);+ await fs.rename(tmp, A2A_STORE_PATH); await fs.chmod(A2A_STORE_PATH, 0o600);+}++export async function listA2AAgents(): Promise<A2ARegisteredAgent[]> {+ return (await readUnlocked()).agents.slice().sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));+}++export async function registerA2AAgent(source: string, requestedAlias?: string): Promise<A2ARegisteredAgent> {+ const discovered = await discoverA2AAgent(source); const now = new Date().toISOString(); const id = idFor(discovered.cardUrl);+ return withSecurityStoreLock(A2A_STORE_PATH, async () => {+ const store = await readUnlocked(); const existing = store.agents.find((row) => row.id === id);+ const alias = validAlias(requestedAlias || existing?.alias || slug(discovered.card.name));+ const collision = store.agents.find((row) => row.alias === alias && row.id !== id);+ if (collision) throw new Error(`A2A alias ${alias} is already used by ${collision.card.name}`);+ const record: A2ARegisteredAgent = { id, alias, cardUrl: discovered.cardUrl, card: discovered.card, registeredAt: existing?.registeredAt || now, updatedAt: now };+ store.agents = [...store.agents.filter((row) => row.id !== id), record]; await writeUnlocked(store); return record;+ });+}++export async function removeA2AAgent(ref: string): Promise<boolean> {+ return withSecurityStoreLock(A2A_STORE_PATH, async () => {+ const store = await readUnlocked(); const q = String(ref || "").trim().toLowerCase(); const before = store.agents.length;+ store.agents = store.agents.filter((row) => row.id.toLowerCase() !== q && row.alias.toLowerCase() !== q);+ if (store.agents.length !== before) await writeUnlocked(store); return store.agents.length !== before;+ });+}++export async function resolveA2AAgent(ref: string): Promise<A2ADiscoveredAgent> {+ const raw = String(ref || "").trim(); if (!raw) throw new Error("A2A target is required");+ if (/^https?:\/\//i.test(raw)) return discoverA2AAgent(raw);+ const q = raw.toLowerCase(); const agents = await listA2AAgents();+ const exact = agents.filter((row) => row.id.toLowerCase() === q || row.alias.toLowerCase() === q || row.card.name.toLowerCase() === q);+ if (!exact.length) throw new Error(`A2A agent not found: ${raw}; register it first or pass a public Agent Card URL`);+ if (exact.length > 1) throw new Error(`A2A target is ambiguous: ${exact.map((row) => row.alias).join(", ")}`);+ return discoverA2AAgent(exact[0].cardUrl);+}diff --git a/lib/a2a/types.ts b/lib/a2a/types.tsnew file mode 100644index 00000000..fef91bca--- /dev/null+++ b/lib/a2a/types.ts@@ -0,0 +1,54 @@+export type A2AStandardBinding = "JSONRPC" | "HTTP+JSON";++export type A2AAgentInterface = {+ url: string;+ protocolBinding: string;+ protocolVersion: string;+ tenant?: string;+};++export type A2AAgentSkill = {+ id: string;+ name: string;+ description: string;+ tags: string[];+ inputModes: string[];+ outputModes: string[];+};++export type A2AAgentCard = {+ name: string;+ description: string;+ version: string;+ supportedInterfaces: A2AAgentInterface[];+ capabilities: Record<string, boolean>;+ defaultInputModes: string[];+ defaultOutputModes: string[];+ skills: A2AAgentSkill[];+ securityRequirements: Array<Record<string, unknown>>;+ securitySchemeNames: string[];+ requiresAuthentication: boolean;+};++export type A2ADiscoveredAgent = {+ cardUrl: string;+ card: A2AAgentCard;+ selectedInterface: A2AAgentInterface;+};++export type A2ARegisteredAgent = {+ id: string;+ alias: string;+ cardUrl: string;+ card: A2AAgentCard;+ registeredAt: string;+ updatedAt: string;+};++export type A2ASendOptions = {+ contextId?: string;+ taskId?: string;+ returnImmediately?: boolean;+ historyLength?: number;+ metadata?: Record<string, unknown>;+};diff --git a/lib/host/audit.ts b/lib/host/audit.tsindex 4a13e000..eb121ddf 100644--- a/lib/host/audit.ts+++ b/lib/host/audit.ts@@ -35,6 +35,9 @@ export type AuditAction =| "workflow.finish"| "agent.session"| "agent.memory"+ | "a2a.registry"+ | "a2a.send"+ | "a2a.cancel"/** An MCP token asked for a tool above its scope. Not an error — it is the* signal that matters: a `read` connector repeatedly reaching for `exec_run`* is what a prompt-injected model looks like from the outside. */diff --git a/lib/mcp/activity.ts b/lib/mcp/activity.tsindex 13dacc05..0d859fa1 100644--- a/lib/mcp/activity.ts+++ b/lib/mcp/activity.ts@@ -48,7 +48,7 @@ export function newActivityId(): string {export function activityTarget(args: Record<string, unknown>): string | undefined {// Never serialize fs_write.content or arbitrary payloads. Prefer the one field// that explains what the tool is acting on without leaking the body.- for (const key of ["path", "id", "query", "intent", "project", "from", "command", "on", "workflow_id"] as const) {+ for (const key of ["path", "id", "target", "query", "intent", "project", "from", "command", "on", "workflow_id"] as const) {const v = args[key];if (typeof v === "string" && v) return trunc(safeActivityText(v));if (typeof v === "boolean") return String(v);diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex 0b94ac9d..e64e6f9a 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -61,6 +61,14 @@ 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",+ "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",+ "a2a.agent.remove": "paired with the MCP/terminal A2A registry and therefore intentionally absent from Alfa",+ "a2a.message.send": "A2A peer messaging is a provider-neutral external-agent capability; Alfa remains an in-shell assistant rather than a network agent orchestrator",+ "a2a.task.get": "A2A task polling exists only for remote tasks created through the MCP/terminal A2A client",+ "a2a.task.cancel": "A2A remote task cancellation stays approval-gated in the external agent harness",+ "a2a.handoff": "explicit agent-to-agent delegation is intentionally MCP/terminal-only until Alfa receives its own scoped orchestration model",};describe("Alfa ↔ MCP capability parity", () => {@@ -139,6 +147,12 @@ describe("MCP rate limits mirror the routes", () => {"infra.dokploy": 20,"infra.cloudflare": 20,"infra.hostinger": 10,+ "a2a.read": 30,+ "a2a.discovery": 20,+ "a2a.registry": 20,+ "a2a.send": 30,+ "a2a.task": 60,+ "a2a.cancel": 30,};for (const t of TOOLS) {if (!t.limit) continue;diff --git a/lib/mcp/tools-a2a.test.ts b/lib/mcp/tools-a2a.test.tsnew file mode 100644index 00000000..5c362636--- /dev/null+++ b/lib/mcp/tools-a2a.test.ts@@ -0,0 +1,65 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ list: vi.fn(), discover: vi.fn(), register: vi.fn(), remove: vi.fn(), resolve: vi.fn(), send: vi.fn(), get: vi.fn(), cancel: vi.fn(), handoff: vi.fn(),+}));+vi.mock("@/lib/a2a", () => ({+ listA2AAgents: mocks.list, discoverA2AAgent: mocks.discover, registerA2AAgent: mocks.register, removeA2AAgent: mocks.remove,+ resolveA2AAgent: mocks.resolve, sendA2AMessage: mocks.send, getA2ATask: mocks.get, cancelA2ATask: mocks.cancel, handoffA2A: mocks.handoff,+}));++const { A2A_TOOLS } = await import("./tools-a2a");+const byName = new Map(A2A_TOOLS.map((tool) => [tool.name, tool]));+const peer = {+ cardUrl: "https://peer.example/.well-known/agent-card.json",+ selectedInterface: { url: "https://peer.example/a2a", protocolBinding: "JSONRPC", protocolVersion: "1.0" },+ card: { name: "Peer", description: "peer agent", version: "1", supportedInterfaces: [{ url: "https://peer.example/a2a", protocolBinding: "JSONRPC", protocolVersion: "1.0" }], capabilities: {}, defaultInputModes: ["text/plain"], defaultOutputModes: ["text/plain"], skills: [], securityRequirements: [], securitySchemeNames: [], requiresAuthentication: false },+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.resolve.mockResolvedValue(peer);+ mocks.handoff.mockResolvedValue({ handoff: { objectiveBytes: 8, contextBytes: 4 }, response: { task: { id: "t-1" } } });+});++describe("MCP A2A tools", () => {+ it("exports the complete read/write A2A v1 surface with write approval semantics", () => {+ expect([...byName]).toHaveLength(8);+ expect(byName.get("a2a_agents_list")?.scope).toBe("read");+ expect(byName.get("a2a_agent_discover")?.scope).toBe("read");+ expect(byName.get("a2a_task_get")?.scope).toBe("read");+ for (const name of ["a2a_agent_register", "a2a_agent_remove", "a2a_message_send", "a2a_task_cancel", "a2a_handoff"]) {+ expect(byName.get(name)?.scope, name).toBe("write");+ expect(byName.get(name)?.limit?.max, `${name} rate limit`).toBeGreaterThan(0);+ }+ });++ it("hands off only explicit objective/context and hashes caller ids before crossing the A2A boundary", async () => {+ const tool = byName.get("a2a_handoff");+ const sessionId = "session-raw-super-secret-id";+ const workflowId = "workflow-raw-super-secret-id";+ const out = await tool!.run({ target: "peer", objective: "research", context: "facts only" }, {+ principal: "mcp-client:test", sessionId, workflowId, scope: "write", actor: "test",+ });+ expect(mocks.resolve).toHaveBeenCalledWith("peer");+ expect(mocks.handoff).toHaveBeenCalledWith(peer, "research", "facts only", expect.objectContaining({+ sourceSessionHash: expect.stringMatching(/^[a-f0-9]{24}$/),+ sourceWorkflowHash: expect.stringMatching(/^[a-f0-9]{24}$/),+ }));+ const serialized = JSON.stringify(mocks.handoff.mock.calls[0]);+ expect(serialized).not.toContain(sessionId);+ expect(serialized).not.toContain(workflowId);+ expect(JSON.stringify(out)).toContain("t-1");+ });++ it("does not synthesize hidden context when sending a normal A2A message", async () => {+ mocks.send.mockResolvedValue({ task: { id: "t-2" } });+ await byName.get("a2a_message_send")!.run({ target: "peer", message: "explicit only" }, {+ principal: "mcp-client:test", sessionId: "hidden-session", scope: "write", actor: "test",+ });+ expect(mocks.send).toHaveBeenCalledWith(peer, "explicit only", {+ contextId: undefined, taskId: undefined, returnImmediately: true,+ });+ expect(JSON.stringify(mocks.send.mock.calls[0])).not.toContain("hidden-session");+ });+});diff --git a/lib/mcp/tools-a2a.ts b/lib/mcp/tools-a2a.tsnew file mode 100644index 00000000..a36948e8--- /dev/null+++ b/lib/mcp/tools-a2a.ts@@ -0,0 +1,101 @@+import { createHash } from "node:crypto";+import { cancelA2ATask, discoverA2AAgent, getA2ATask, handoffA2A, listA2AAgents, registerA2AAgent, removeA2AAgent, resolveA2AAgent, sendA2AMessage } from "@/lib/a2a";+import type { A2ADiscoveredAgent, A2ARegisteredAgent } from "@/lib/a2a";+import { type McpTool, S, str } from "./tool-kit";++function optionalString(a: Record<string, unknown>, key: string): string | undefined {+ const value = a[key]; return typeof value === "string" && value.trim() ? value.trim() : undefined;+}+function anonymousHash(value?: string): string | undefined {+ return value ? createHash("sha256").update(value).digest("hex").slice(0, 24) : undefined;+}+function cardSummary(row: A2ADiscoveredAgent | A2ARegisteredAgent) {+ const card = row.card; const selectedInterface = "selectedInterface" in row ? row.selectedInterface : undefined;+ return {+ ...(row.cardUrl ? { cardUrl: row.cardUrl } : {}), ...( "id" in row ? { id: row.id, alias: row.alias } : {}),+ name: card.name, description: card.description, version: card.version,+ interface: selectedInterface ?? card.supportedInterfaces[0], requiresAuthentication: card.requiresAuthentication,+ capabilities: card.capabilities, inputModes: card.defaultInputModes, outputModes: card.defaultOutputModes,+ skills: card.skills.map((skill) => ({ id: skill.id, name: skill.name, description: skill.description, tags: skill.tags })),+ };+}+async function target(ref: string) { return resolveA2AAgent(ref); }++export const A2A_TOOLS: McpTool[] = [+ {+ name: "a2a_agents_list",+ description: "List A2A v1 agents registered on this MSO host. The registry stores only public Agent Card metadata, never agent credentials or private conversation context.",+ scope: "read", annotations: { readOnlyHint: true, idempotentHint: true }, limit: { key: "a2a.read", max: 30, windowMs: 60_000 }, inputSchema: S({}),+ run: async () => (await listA2AAgents()).map(cardSummary),+ },+ {+ name: "a2a_agent_discover",+ description: "Discover and validate a public A2A v1 Agent Card using the standard /.well-known/agent-card.json path. Only public HTTPS endpoints are allowed; private/loopback targets and DNS rebinding are blocked.",+ scope: "read", annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true }, limit: { key: "a2a.discovery", max: 20, windowMs: 60_000 },+ inputSchema: S({ url: { type: "string", description: "Public agent origin or direct Agent Card URL." } }, ["url"]),+ run: async (a) => cardSummary(await discoverA2AAgent(str(a, "url"))),+ },+ {+ name: "a2a_agent_register",+ description: "Register or refresh one public A2A v1 agent in MSO's private host registry. This stores the Agent Card and alias only; credentials are deliberately unsupported in this phase.",+ scope: "write", annotations: { openWorldHint: true }, limit: { key: "a2a.registry", max: 20, windowMs: 60_000 }, audit: { action: "a2a.registry", targetArg: "url" },+ inputSchema: S({ url: { type: "string", description: "Public agent origin or direct Agent Card URL." }, alias: { type: "string", description: "Optional local alias (lowercase letters/digits/._-)." } }, ["url"]),+ run: async (a) => cardSummary(await registerA2AAgent(str(a, "url"), optionalString(a, "alias"))),+ },+ {+ name: "a2a_agent_remove",+ description: "Remove one registered A2A agent alias/id from MSO. This does not contact or modify the remote agent.",+ scope: "write", annotations: { idempotentHint: true }, limit: { key: "a2a.registry", max: 20, windowMs: 60_000 }, audit: { action: "a2a.registry", targetArg: "target" },+ inputSchema: S({ target: { type: "string", description: "Registered A2A alias or id." } }, ["target"]),+ run: async (a) => ({ ok: await removeA2AAgent(str(a, "target")), target: a.target }),+ },+ {+ name: "a2a_message_send",+ description: "Send one text message to a public A2A v1 agent via its advertised JSONRPC or HTTP+JSON interface. Does not expose this MSO session history; only the explicit message and optional A2A context/task ids are transmitted.",+ scope: "write", annotations: { openWorldHint: true }, limit: { key: "a2a.send", max: 30, windowMs: 60_000 }, audit: { action: "a2a.send", targetArg: "target" },+ result: { maxTextBytes: 64 * 1024, overflowHint: "A2A response was compacted; use a2a_task_get with the returned task id for focused status." },+ inputSchema: S({+ target: { type: "string", description: "Registered alias/id or public Agent Card URL." }, message: { type: "string", description: "Explicit message to the remote agent, max 24 KiB." },+ context_id: { type: "string", description: "Optional A2A contextId supplied by that remote agent." }, task_id: { type: "string", description: "Optional A2A taskId to continue." },+ return_immediately: { type: "boolean", description: "Default true: return the task quickly instead of blocking for completion." },+ }, ["target", "message"]),+ run: async (a) => {+ const agent = await target(str(a, "target")); const result = await sendA2AMessage(agent, str(a, "message"), {+ contextId: optionalString(a, "context_id"), taskId: optionalString(a, "task_id"), returnImmediately: a.return_immediately !== false,+ }); return { agent: cardSummary(agent), response: result };+ },+ },+ {+ name: "a2a_task_get",+ description: "Read the latest state of a task previously returned by an A2A v1 agent. This is the A2A status/poll operation.",+ scope: "read", annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true }, limit: { key: "a2a.task", max: 60, windowMs: 60_000 },+ result: { maxTextBytes: 64 * 1024, overflowHint: "A2A task response was compacted; request less history." },+ inputSchema: S({ target: { type: "string" }, task_id: { type: "string" }, history_length: { type: "number", description: "0-100, default 10." } }, ["target", "task_id"]),+ run: async (a) => getA2ATask(await target(str(a, "target")), str(a, "task_id"), Math.max(0, Math.min(100, Number(a.history_length) || 10))),+ },+ {+ name: "a2a_task_cancel",+ description: "Request cancellation of one in-progress A2A v1 task. The remote agent remains authoritative about whether cancellation is allowed.",+ scope: "write", annotations: { destructiveHint: true, openWorldHint: true }, limit: { key: "a2a.cancel", max: 30, windowMs: 60_000 }, audit: { action: "a2a.cancel", targetArg: "task_id" },+ inputSchema: S({ target: { type: "string" }, task_id: { type: "string" } }, ["target", "task_id"]),+ run: async (a) => cancelA2ATask(await target(str(a, "target")), str(a, "task_id")),+ },+ {+ name: "a2a_handoff",+ description: "Delegate an explicit objective plus optional caller-supplied context to another A2A v1 agent. Hidden MSO history, memory and tool state are NEVER copied; the handoff includes only these arguments and anonymous source hashes.",+ scope: "write", annotations: { openWorldHint: true }, limit: { key: "a2a.send", max: 30, windowMs: 60_000 }, audit: { action: "a2a.send", targetArg: "target" },+ result: { maxTextBytes: 64 * 1024, overflowHint: "A2A handoff response was compacted; poll the returned task with a2a_task_get." },+ inputSchema: S({+ target: { type: "string", description: "Registered alias/id or public Agent Card URL." }, objective: { type: "string", description: "Delegated objective, max 8 KiB." },+ context: { type: "string", description: "Optional explicit handoff context, max 8 KiB. No hidden session state is added." },+ return_immediately: { type: "boolean", description: "Default true." },+ }, ["target", "objective"]),+ run: async (a, context) => {+ const agent = await target(str(a, "target"));+ const result = await handoffA2A(agent, str(a, "objective"), optionalString(a, "context"), {+ returnImmediately: a.return_immediately !== false, sourceSessionHash: anonymousHash(context.sessionId), sourceWorkflowHash: anonymousHash(context.workflowId),+ });+ return { agent: cardSummary(agent), ...result };+ },+ },+];diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 2a7ddc84..caea6169 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -7,6 +7,7 @@ import { LEARNING_TOOLS } from "./tools-learning";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 { withWorkflowContext } from "./tool-context";// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,@@ -216,4 +217,4 @@ const MUTATE_TOOLS: McpTool[] = [},];-export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_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, ...A2A_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/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex 996de57e..891ac327 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -3,8 +3,8 @@ import type { Scope } from "./scope";import type { McpTool } from "./tool-kit";export const MCP_SERVER_VERSION = "1.6.0";-export const MCP_TOOLSET_VERSION = "2026.09.02.2";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-01T20:10:00Z";+export const MCP_TOOLSET_VERSION = "2026.09.02.3";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-02T05:24:00Z";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/skills/catalog-nofollow.test.ts b/lib/skills/catalog-nofollow.test.tsindex a140105e..fb6078d2 100644--- a/lib/skills/catalog-nofollow.test.ts+++ b/lib/skills/catalog-nofollow.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { mkdir, mkdtemp, rm, symlink, writeFile } from "fs/promises";import os from "os";import path from "path";@@ -108,11 +108,19 @@ describe("the overall project-skill cap is enforced inside the loop", () => {projects.push(projectRefFor(dir, workspace));}- const { skills, scan } = await catalogSkillsDetailed({ appDir: await temp(), homeDir: await temp(), projects });- const projectSkills = skills.filter((s) => s.project);- expect(projectSkills.length).toBeLessThanOrEqual(SKILL_SCAN_LIMITS.maxProjectSkills);- expect(scan.truncated).toBe(true);- expect(scan.truncationReasons).toContain("maxProjectSkills");+ // This test targets the deterministic project-skill CAP, not the independent+ // wall-clock deadline. Freeze the clock while cataloguing so low-priority CI+ // cannot turn a maxProjectSkills assertion into a scheduler-speed assertion.+ const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now());+ try {+ const { skills, scan } = await catalogSkillsDetailed({ appDir: await temp(), homeDir: await temp(), projects });+ const projectSkills = skills.filter((s) => s.project);+ expect(projectSkills.length).toBeLessThanOrEqual(SKILL_SCAN_LIMITS.maxProjectSkills);+ expect(scan.truncated).toBe(true);+ expect(scan.truncationReasons).toContain("maxProjectSkills");+ } finally {+ clock.mockRestore();+ }});});diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjsindex f2568439..18619188 100755--- a/scripts/check-docs.mjs+++ b/scripts/check-docs.mjs@@ -22,6 +22,7 @@ const toolFiles = ["lib/mcp/tools-infra.ts","lib/mcp/tools-power.ts","lib/mcp/tools-agent.ts",+ "lib/mcp/tools-a2a.ts",];const tools = new Map();for (const file of toolFiles) {diff --git a/scripts/install-runtime-lifecycle.test.ts b/scripts/install-runtime-lifecycle.test.tsindex 2340d437..d79869a1 100644--- a/scripts/install-runtime-lifecycle.test.ts+++ b/scripts/install-runtime-lifecycle.test.ts@@ -74,7 +74,10 @@ afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursivdescribe("installer runtime lifecycle", () => {it("adopts a transaction lock acquired before checkout instead of reacquiring it", () => {const f = fixture(false, 1, true);- const out = spawnSync(f.runner, [], { encoding: "utf8", timeout: 5_000 });+ // This is a deadlock/correctness assertion, not a 5-second performance SLA.+ // Low-priority full-suite CI can legitimately delay the fixture shell; keep a+ // bounded timeout while leaving enough headroom to distinguish delay from lock recursion.+ const out = spawnSync(f.runner, [], { encoding: "utf8", timeout: 15_000 });expect(out.status).toBe(0);expect(out.error).toBeUndefined();expect(fs.readFileSync(f.capture, "utf8")).toContain("MUTATE");diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjsindex 0c90c66d..617a1518 100644--- a/scripts/mso-agent-commands.mjs+++ b/scripts/mso-agent-commands.mjs@@ -47,6 +47,8 @@ function printHelp() {" /provider <id> configure dokploy|cloudflare|hostinger"," /doctor run mso doctor"," /tools list agent tools",+ " /agents list registered A2A v1 peer agents",+ " /delegate <peer> <job> handoff explicit objective; no hidden context"," /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",@@ -61,6 +63,7 @@ function printHelp() {" ↑/↓ or Ctrl+P/N prompt history (durable after resume)"," Ctrl+A/E · Ctrl+B/F line start/end · left/right"," Alt+B/F · Ctrl+←/→ move by word",+ " Tab (empty prompt) cycle permission in place: ask → auto → yolo",].join("\n"));}@@ -104,6 +107,11 @@ export async function handleSlash(rl, line, session, { runTurn }) {session.state = await state(); return "refresh";case "/doctor": runCli(["doctor"]); return "handled";case "/tools": for (const tool of session.state.tools) console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`); return "handled";+ case "/agents": runCli(["a2a", "list"]); return "handled";+ case "/delegate":+ if (!args[0] || args.length < 2) console.log("usage: /delegate <agent> <objective>");+ else runCli(["a2a", "handoff", args[0], args.slice(1).join(" ")]);+ return "handled";case "/skills": printSkills(session, C, args.join(" ")); return "handled";case "/skill":if (!args[0]) { console.log("usage: /skill <name-or-exact-id> [prompt]"); return "handled"; }diff --git a/scripts/mso-agent-composer-session.test.ts b/scripts/mso-agent-composer-session.test.tsindex 82160b09..5a5895aa 100644--- a/scripts/mso-agent-composer-session.test.ts+++ b/scripts/mso-agent-composer-session.test.ts@@ -52,13 +52,17 @@ describe("MSO Agent session/history composer UX", () => {composer.close();});- it("uses Tab on an empty normal prompt as a mode-cycle hook without polluting history", async () => {+ it("repaints a dynamic permission prompt on empty Tab without adding a scrollback line", async () => {const { input, output, composer } = composerFixture();- let cycles = 0;- const answer = composer.question("› ", { onTab: () => { cycles++; return "permission → yolo"; } } as never);+ let mode = "ask", cycles = 0;+ const answer = composer.question(() => `[${mode}] › `, { onTab: () => { cycles++; mode = "yolo"; } } as never);+ const before = output.chunks.join("");input.emit("keypress", "\t", { name: "tab", sequence: "\t" });+ const after = output.chunks.join("");expect(cycles).toBe(1);- expect(output.chunks.join("")).toContain("permission → yolo");+ expect(after).toContain("[yolo] › ");+ expect(after.slice(before.length)).not.toMatch(/[\r]?\n/);+ expect(after).not.toContain("permission →");for (const ch of "go") input.emit("keypress", ch, { name: ch, sequence: ch });input.emit("keypress", "\r", { name: "return", sequence: "\r" });await expect(answer).resolves.toBe("go");diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjsindex 1b081e9a..07226c7f 100644--- a/scripts/mso-agent-composer.mjs+++ b/scripts/mso-agent-composer.mjs@@ -24,6 +24,7 @@ export class AgentComposer {return new Promise((resolve) => {let value = "", cursor = 0, selected = 0, reservedMenuRows = 0;let dismissed = false, historyIndex = null, draft = "", settled = false;+ const promptText = () => String(typeof prompt === "function" ? prompt() : prompt);const wasRaw = Boolean(input.isRaw);const matches = () => dismissed || !complete ? [] : complete(value) || [];@@ -42,17 +43,18 @@ export class AgentComposer {if (reservedMenuRows) output.write(`${CURSOR_UP(reservedMenuRows)}\r`);};const render = () => {- const maxInput = Math.max(8, Number(output.columns || 100) - width(prompt) - 2);+ const currentPrompt = promptText();+ const maxInput = Math.max(8, Number(output.columns || 100) - width(currentPrompt) - 2);const viewport = inputViewport(value, cursor, maxInput);const items = matches();selected = items.length ? clamp(selected, 0, items.length - 1) : 0;const menu = menuLines(items, selected, output.columns, C, panelLabel);reserve(menu.length);erase();- output.write(`${prompt}${viewport.display}`);+ output.write(`${currentPrompt}${viewport.display}`);for (const row of menu) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}${row}`);if (menu.length) output.write(CURSOR_UP(menu.length));- output.write(`\r${CURSOR_RIGHT(width(prompt) + viewport.cursor)}`);+ output.write(`\r${CURSOR_RIGHT(width(currentPrompt) + viewport.cursor)}`);};const cleanup = () => {input.off("keypress", onKey);@@ -64,7 +66,7 @@ export class AgentComposer {if (settled) return;settled = true;erase();- if (echo) output.write(`${prompt}${displayValue}\r\n`);+ if (echo) output.write(`${promptText()}${displayValue}\r\n`);cleanup();if (history && result?.trim()) {this.history.unshift(result);@@ -126,11 +128,9 @@ export class AgentComposer {return apply(items[selected]);}if (key.name === "tab" && !value && typeof onTab === "function") {- const notice = onTab();- if (notice) {- erase(); reservedMenuRows = 0; output.write(`${notice}\r\n`); render();- }- return;+ onTab();+ dismissed = false; selected = 0;+ return render();}if (key.name === "return" || key.name === "enter") {if (selectOnEnter && items[selected]) {diff --git a/scripts/mso-agent-permissions.mjs b/scripts/mso-agent-permissions.mjsindex 1c903542..efa19f41 100644--- a/scripts/mso-agent-permissions.mjs+++ b/scripts/mso-agent-permissions.mjs@@ -16,6 +16,13 @@ export function nextPermissionMode(current) {return PERMISSION_MODES[(index + 1) % PERMISSION_MODES.length];}++export function permissionPrompt(mode, C) {+ const current = permissionMode(mode) || PERMISSION_MODES[0];+ const tone = current.id === "yolo" ? C.err : current.id === "auto" ? C.warn : C.cyan;+ return `${tone}${C.bold}[${current.id}]${C.reset} ${C.blue}${C.bold}›${C.reset} `;+}+export function approvesTool(mode, scope) {if (scope === "read") return true;if (mode === "yolo") return true;diff --git a/scripts/mso-agent-permissions.test.ts b/scripts/mso-agent-permissions.test.tsindex 4e4726eb..0b858374 100644--- a/scripts/mso-agent-permissions.test.ts+++ b/scripts/mso-agent-permissions.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { approvesTool, nextPermissionMode, permissionCompletionItems, permissionMode } from "./mso-agent-permissions.mjs";+import { approvesTool, nextPermissionMode, permissionCompletionItems, permissionMode, permissionPrompt } from "./mso-agent-permissions.mjs";describe("MSO Agent permission modes", () => {it("parses stable human aliases without numeric-only UX", () => {diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjsindex 1ec7b1e5..42b95d1e 100644--- a/scripts/mso-agent-slash.mjs+++ b/scripts/mso-agent-slash.mjs@@ -17,6 +17,8 @@ export const BUILTIN_SLASH_ITEMS = [{ text: "/provider", meta: "Configure Dokploy, Cloudflare, or Hostinger", kind: "command" },{ text: "/doctor", meta: "Run MSO diagnostics", kind: "command" },{ text: "/tools", meta: "List available agent tools", kind: "command" },+ { text: "/agents", meta: "List registered A2A v1 peer agents", kind: "command" },+ { text: "/delegate", meta: "Handoff an explicit objective to an A2A peer", kind: "command" },{ text: "/skills", meta: "Browse and filter available skills", kind: "command" },{ text: "/skill", meta: "Select a skill by exact catalog id", kind: "command" },{ text: "/clear", meta: "Clear this session conversation", kind: "command" },diff --git a/scripts/mso-agent-slash.test.ts b/scripts/mso-agent-slash.test.tsindex 703cbb5a..ce7320b4 100644--- a/scripts/mso-agent-slash.test.ts+++ b/scripts/mso-agent-slash.test.ts@@ -16,6 +16,8 @@ describe("MSO Agent slash completion catalog", () => {expect(rows[0]).toMatchObject({ text: "/help", kind: "command" });expect(rows.map((row) => row.text)).toContain("/design");expect(rows.map((row) => row.text)).toContain("/quit");+ expect(rows.map((row) => row.text)).toContain("/agents");+ expect(rows.map((row) => row.text)).toContain("/delegate");expect(rows.map((row) => row.text)).not.toContain("/unsafe");});diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjsindex 4133cbfe..2fde48c5 100644--- a/scripts/mso-agent-status.mjs+++ b/scripts/mso-agent-status.mjs@@ -83,7 +83,6 @@ export function statusParts(session, cwd = process.cwd()) {ctx.limit ? `ctx ~${compactNumber(ctx.used)}/${compactNumber(ctx.limit)} ${ctx.percent}%` : `ctx ~${compactNumber(ctx.used)}/?`,session?.agentSession?.compactThresholdTokens ? `session ~${compactNumber(session.agentSession.estimatedTokens)}/${compactNumber(session.agentSession.compactThresholdTokens)}` : null,usage.totalTokens > 0 ? `tokens ${compactNumber(usage.totalTokens)}` : null,- `permission ${session?.permission || "ask"}`,`turns ${turns}`,elapsed > 0 ? `${(elapsed / 1000).toFixed(elapsed >= 10_000 ? 0 : 1)}s` : null,`session ${sessionTitle}`,diff --git a/scripts/mso-agent-status.test.ts b/scripts/mso-agent-status.test.tsindex 1f3c2eb7..d3f0fdce 100644--- a/scripts/mso-agent-status.test.ts+++ b/scripts/mso-agent-status.test.ts@@ -42,7 +42,7 @@ describe("MSO Agent dynamic status", () => {};const compact = statusParts(session, "/tmp").join(" · ");expect(compact).toContain("session test tui mso");- expect(compact).toContain("permission ask");+ expect(compact).not.toContain("permission ask");expect(compact).not.toContain("deadbeef");});diff --git a/scripts/mso-agent-tool-router.mjs b/scripts/mso-agent-tool-router.mjsindex 2a541e85..cc62b1b4 100644--- a/scripts/mso-agent-tool-router.mjs+++ b/scripts/mso-agent-tool-router.mjs@@ -11,6 +11,8 @@ const DEPENDENCIES = new Map([["exec_job_start", ["exec_job_status", "exec_job_cancel"]],["fs_write", ["fs_read"]],["agent_session_resume", ["agent_sessions_list"]],+ ["a2a_message_send", ["a2a_agents_list", "a2a_agent_discover"]],+ ["a2a_handoff", ["a2a_agents_list", "a2a_agent_discover", "a2a_task_get"]],]);const ALIASES = new Map([@@ -29,6 +31,7 @@ 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"]],]);function words(value) {diff --git a/scripts/mso-agent-tool-router.test.ts b/scripts/mso-agent-tool-router.test.tsindex 3c113467..439d535b 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("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"),];describe("MSO per-turn tool router", () => {@@ -35,6 +37,15 @@ describe("MSO per-turn tool router", () => {expect(selectToolsForTurn(catalog, history).selectedNames).toContain("hostinger_dns_upsert");});++ 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");+ expect(out.selectedNames).toContain("a2a_agents_list");+ expect(out.selectedNames).toContain("a2a_agent_discover");+ expect(out.selectedNames).toContain("a2a_task_get");+ });+it("keeps long-job companions when build work selects exec_job_start", () => {const out = selectToolsForTurn(catalog, [{ role: "user", text: "run the full build and test pipeline" }]);expect(out.selectedNames).toContain("exec_job_start");diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjsindex 526ccb43..839f09d3 100644--- a/scripts/mso-agent-ui.mjs+++ b/scripts/mso-agent-ui.mjs@@ -63,7 +63,7 @@ function toolCategory(name) {if (/^fs_/.test(name)) return "files";if (/^(sys_|apps_|browser_)/.test(name)) return "system";if (/^(project|projects)_/.test(name)) return "projects";- if (/^(workflow_|skills_|agent_)/.test(name)) return "agent";+ if (/^(workflow_|skills_|agent_|a2a_)/.test(name)) return "agent";if (/^(dokploy_|cloudflare_|hostinger_|infra_)/.test(name)) return "infra";return "other";}diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex 754ac451..157e9710 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -9,7 +9,7 @@ import { addUsage, renderStatusBar } from "./mso-agent-status.mjs";import { persistSession, resumeArg, startupSession, syncPromptHistory } from "./mso-agent-session-ui.mjs";import { C, api, printBanner, state, streamTurn } from "./mso-agent-runtime.mjs";import { handleSlash } from "./mso-agent-commands.mjs";-import { approvesTool, nextPermissionMode } from "./mso-agent-permissions.mjs";+import { approvesTool, nextPermissionMode, permissionPrompt } from "./mso-agent-permissions.mjs";import { oneShotApproves, oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";async function executeTool(rl, tool, call, agentSession, permission = "ask", signal = undefined, onInterrupt = null, options = {}) {@@ -187,12 +187,9 @@ async function main() {try {console.log();if (session.statusBar) console.log(renderStatusBar(session, C));- const answer = await rl.question(`${C.blue}${C.bold}›${C.reset} `, {+ const answer = await rl.question(() => permissionPrompt(session.permission, C), {complete: completeSlash,- onTab: () => {- session.permission = nextPermissionMode(session.permission).id;- return `${C.dim}permission → ${session.permission}${C.reset}`;- },+ onTab: () => { session.permission = nextPermissionMode(session.permission).id; },});if (answer === null) break;line = answer.trim();diff --git a/scripts/mso-gateway-boundaries.test.ts b/scripts/mso-gateway-boundaries.test.tsindex 45053436..34a67942 100644--- a/scripts/mso-gateway-boundaries.test.ts+++ b/scripts/mso-gateway-boundaries.test.ts@@ -5,6 +5,15 @@ import { describe, expect, it } from "vitest";import { GATEWAY, ROOT, VERSION, fixture, runGateway as run } from "./mso-gateway-test-fixture";+async function waitForFile(file: string, timeoutMs = 2_000) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (fs.existsSync(file)) return;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ throw new Error(`timed out waiting for lock-holder readiness: ${file}`);+}+describe("mso gateway scope and public identity boundaries", () => {it("isolates default gateway state by checkout and selected loopback origin", () => {const f = fixture();@@ -61,8 +70,12 @@ esacconst dir = path.join(base, key); fs.mkdirSync(dir, { recursive: true, mode: 0o700 });fs.chmodSync(base, 0o700); fs.chmodSync(dir, 0o700);const lock = path.join(dir, "runtime.lock"); fs.writeFileSync(lock, "", { mode: 0o600 });- const holder = spawn("flock", ["-x", lock, "-c", "sleep 2"], { stdio: "ignore" });- await new Promise((r) => setTimeout(r, 100));+ const ready = path.join(dir, "holder.ready");+ // `flock ... command` acquires the lock before executing the command. The ready+ // file therefore proves ownership; a fixed sleep is not a synchronization primitive+ // when the full suite is deliberately running under nice/ionice.+ const holder = spawn("flock", ["-x", lock, "sh", "-c", 'printf ready > "$1"; sleep 2', "mso-lock-holder", ready], { stdio: "ignore" });+ await waitForFile(ready);try {const out = spawnSync(GATEWAY, ["local-start"], { encoding: "utf8", env: { ...f.baseEnv,MSO_RUNTIME_EXCLUSION_DIR: base, MSO_RUNTIME_EXCLUSION_TIMEOUT_SECONDS: "0.1" } });@@ -70,7 +83,10 @@ esacexpect(out.stderr).toContain("offline update is mutating this checkout");} finally {try { holder.kill("SIGTERM"); } catch {}- await new Promise<void>((resolve) => holder.once("close", () => resolve()));+ await new Promise<void>((resolve) => {+ if (holder.exitCode !== null || holder.signalCode !== null) resolve();+ else holder.once("close", () => resolve());+ });}});diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.tsindex 3b778fd3..eb51dea5 100644--- a/scripts/mso-model-dx-contract.test.ts+++ b/scripts/mso-model-dx-contract.test.ts@@ -14,7 +14,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.6.2"');+ expect(cli).toContain('VERSION="1.7.0"');expect(cli).toContain("models * Configure AI providers/auth");expect(cli).toContain("model [ref] Select active model");expect(agentCli).toContain("run_models()");