Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(agent): name sessions and wrap composer

Rahman0cc43ef162b1
diff --git a/.env.example b/.env.example
index 42d228b8..ad108612 100644
--- a/.env.example
+++ b/.env.example
@@ -207,6 +207,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_SUBAGENT_MAX_TURNS=12 # server policy cap for one foreground subagent; default 12, absolute max 48 (each child still defaults to 6)
# Native Local Agents use private defaults; overrides are normally unnecessary.
# OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json # live receive leases/aliases (0600)
# OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json # durable explicit local messages/tasks (0600)
diff --git a/README.md b/README.md
index 29dd8907..29c53acd 100644
--- a/README.md
+++ b/README.md
@@ -76,7 +76,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
-- **Message live local sessions natively** — every live same-principal MSO session is discovered automatically as `[agent-a]`, `[agent-b]`, or its manual session name. `@agent-b …` and local `/delegate` create explicitly correlated requests; replies can relay deterministically back into the originating conversation, while notify-only events remain passive. A private presence lease + durable mailbox + SSE feed gives honest `idle`/`busy`/`offline` delivery without Agent Cards, URLs, registration, refresh, or restart. See [Local Agents](./docs/LOCAL-AGENTS.md).
+- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves active agents only and creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. See [Local Agents](./docs/LOCAL-AGENTS.md).
- **Spawn focused same-session subagents** — `/spawn` and `agent_subagent_run` create bounded foreground workers with isolated context, explicit delegated scope, turn/timeout caps, no recursive spawn, and final-result-only return. They are not Local Agent peers and do not run autonomously after the parent call returns. See [Subagents](./docs/SUBAGENTS.md).
- **Delegate between remote agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or expose MSO's authenticated inbound Agent Card when a public HTTPS origin is configured. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](./docs/A2A.md).
- **Keep agents efficient independently of the model provider** — the MCP-first [Cognitive Runtime](./docs/COGNITIVE-RUNTIME.md) isolates conversations from OAuth identity, budgets model context/tool output, selects a compact per-turn capability set without weakening scopes, compacts durable sessions with sanitized 30-day backup archives, and learns only verified workflow recipes. `bun run bench:cognitive` guards routing recall and context footprint.
@@ -213,15 +213,15 @@ mso skills install ponytail caveman rtk -y
Interactive model/provider menus use a native picker: **↑/↓** moves, typing filters, **Enter**
selects, and **Esc** cancels. No provider/model number has to be memorized. `/session` and bare
-`/resume` open one recent-session picker directly: newest modified session first, human session title
-as the primary label, and compact `modified …` metadata. Durable session IDs stay hidden in the normal
-picker UI but remain accepted by scriptable `--resume`/`/resume` queries. `/new [name]` persists the
+`/resume` open one recent-session picker directly: newest modified session first, short `@name`
+as the primary label, with the longer human session title and compact `modified …` metadata. Durable session IDs stay hidden in the normal
+picker UI but remain accepted by scriptable `--resume`/`/resume` queries. `/new [title]` persists the
current session and switches the same terminal to a fresh durable session. `/restart` is a soft Agent
process replacement: it persists the current session, closes the composer, then reloads the latest CLI
and Agent modules against that exact same durable session id. Repeated restarts keep a constant process
depth. It does **not** restart the MSO service or VPS; updated code plus the latest dynamic
skill/tool/plugin catalog are picked up without abandoning the conversation. Live same-host sessions require no
-manual refresh path: `/agents` discovers them automatically, `@agent-b <prompt>` dispatches a correlated request,
+manual refresh path: `/agents` discovers them automatically, `@milo <prompt>` dispatches a correlated request only when `milo` is active,
`/message <agent> <text>` sends notify-only data, `/delegate <agent> <task>` sends a correlated local task before
remote-A2A fallback, and `/inbox` shows the current session's native agent mailbox. Correlated replies relay as a
durable synthetic assistant response; notify-only events remain passive peer events. `/spawn` is a separate foreground
@@ -231,13 +231,13 @@ In the Agent slash palette, executable skills carry lifecycle markers so their s
The compact status line mirrors queued/invoked skill state and the current permission mode. MSO defaults
to `ask`; use `mso --yolo` or `mso -yolo` when you explicitly want write+exec calls auto-approved for
that Agent process. YOLO still computes and sends the canonical exact-payload approval digest; it only
-skips the interactive `y/N` prompt. `/permission` opens the same arrow-key style selector for
+skips the interactive compact approval prompt. `/permission` opens the same arrow-key style selector for
`ask` / `auto-write` / `yolo`, and Tab on an empty prompt cycles those modes. `auto-write` approves
writes but still asks before exec. Permission mode is intentionally process-local and is not persisted
into a resumed session. Terminal controls follow familiar agent/shell conventions: **Ctrl+C** clears a non-empty draft, exits from an empty idle prompt, and
interrupts an active model/tool turn; **Ctrl+D** deletes the character to the right or exits on an
empty prompt; **Ctrl+L** clears/repaints; **Ctrl+W** deletes the previous word; **↑/↓** or
-**Ctrl+P/N** browse prompt history, including durable user prompts restored by `--continue`/`/resume`;
+**Ctrl+P/N** browse prompt history, including durable user prompts restored by `--continue`/`/resume`. Long drafts wrap dynamically to terminal width/height; **↑/↓** move between visual wrapped rows before falling through to history navigation;
**Ctrl+A/E** and **Ctrl+B/F** move to line boundaries or one character, **Ctrl+U/K** delete to the
start/end of the line, and **Alt+B/F** or **Ctrl+←/→** move by word. `/quit` is an alias for `/exit`.
An interrupted turn is removed from durable conversation
@@ -366,7 +366,7 @@ mso -h # grouped command list; `mso <command> --help` per
mso models # configure AI provider/API/OAuth connections
mso model # arrow-key model picker / switch active model
mso --continue # resume the latest MSO Agent session
-mso --resume "session title" # resume by index/id/short id/title query
+mso --resume "@milo" # resume by @name; index/id/title queries remain supported
mso doctor # includes HTTPS/login-origin diagnosis
mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
mso onboard # guided AI/app/infrastructure/skill setup
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index be90a9f7..96b9b7f6 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -3,6 +3,7 @@ import { getSessionContext } from "@/lib/auth/require-session";
import {
createAgentSession,
renameAgentSession,
+ renameAgentSessionName,
updateAgentSessionHistory,
updateAgentSessionLocation,
} from "@/lib/agent/session-store";
@@ -66,6 +67,7 @@ export async function POST(req: NextRequest) {
action?: string;
id?: string;
ref?: string;
+ name?: string;
title?: string;
history?: unknown[];
cwd?: string;
@@ -117,6 +119,16 @@ export async function POST(req: NextRequest) {
session: await resumeAgentSessionForOwner(principal, ref, body.cwd),
});
}
+ if (body.action === "rename-name") {
+ if (!body.id || !body.name)
+ return NextResponse.json(
+ { error: "id_and_name_required" },
+ { status: 400 },
+ );
+ return NextResponse.json({
+ session: await renameAgentSessionName(principal, body.id, body.name),
+ });
+ }
if (body.action === "rename") {
if (!body.id || !body.title)
return NextResponse.json(
diff --git a/app/api/v1/local-agents/route.test.ts b/app/api/v1/local-agents/route.test.ts
index 0ff505b7..996b5fe6 100644
--- a/app/api/v1/local-agents/route.test.ts
+++ b/app/api/v1/local-agents/route.test.ts
@@ -56,7 +56,7 @@ describe("native local agent API", () => {
expect(await response.json()).toMatchObject({ status: "delivered", target: { label: "[agent-b]" } });
expect(mocks.send).toHaveBeenCalledWith({
principal: "cli:cli-test", senderSessionId: "session-a", target: "agent-b", text: "hello", kind: "message",
- intent: undefined, correlationId: undefined, requiresUserRelay: false,
+ intent: undefined, correlationId: undefined, requiresUserRelay: false, requireActiveTarget: false,
});
expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ action: "agent.message", target: "session-b" }));
});
diff --git a/app/api/v1/local-agents/route.ts b/app/api/v1/local-agents/route.ts
index a72b2a55..24eb88fb 100644
--- a/app/api/v1/local-agents/route.ts
+++ b/app/api/v1/local-agents/route.ts
@@ -191,6 +191,7 @@ export async function POST(req: NextRequest) {
intent: typeof body.intent === "string" ? body.intent : undefined,
correlationId: typeof body.correlationId === "string" ? body.correlationId : undefined,
requiresUserRelay: body.requiresUserRelay === true,
+ requireActiveTarget: body.activeOnly === true,
});
void audit({
action: "agent.message",
diff --git a/bin/mso b/bin/mso
index 28930511..1b35c650 100755
--- a/bin/mso
+++ b/bin/mso
@@ -128,7 +128,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.10.0"
+VERSION="1.11.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
diff --git a/docs/A2A.md b/docs/A2A.md
index b906d341..35e84e3c 100644
--- a/docs/A2A.md
+++ b/docs/A2A.md
@@ -90,7 +90,7 @@ The Settings → **A2A** panel exposes the same flow, shows the one-time token o
MSO 1.9 separates live same-host session communication from this remote interoperability protocol. `/agents`, `/message`, local `/delegate`, local inbox delivery, and the `local_agent_*` MCP tools use a private **presence lease + durable mailbox + SSE/event-bus** layer. They require no Agent Card, URL, registration, credential, refresh, or restart when another session appears or is renamed.
-See [Local Agents](./LOCAL-AGENTS.md) for lifecycle (`ready` / `idle` / `busy` / `offline` / `ended`), `[agent-a]` labels, duplicate-name behavior, delivery statuses, storage, TUI commands, tools, and API.
+See [Local Agents](./LOCAL-AGENTS.md) for lifecycle (`ready` / `idle` / `busy` / `offline` / `ended`), short `@name` handles, receiver-subscription observability, delivery statuses, storage, TUI commands, tools, and API.
The older `mso a2a local ...` and loopback virtual-card helpers remain as compatibility/protocol-testing surfaces for one-shot local delegation. They are not the native live-session transport. `OS_A2A_ALLOW_LOOPBACK=0` can disable those legacy A2A-over-loopback paths without disabling Local Agents.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index fdeb5f0a..e49c3878 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `agent` name sessions and wrap composer
- `agent` correlate local replies and add subagents
- `agent` add native local session messaging
- `agent` add restart and new session
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index ac511321..1f5f8734 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -12,15 +12,15 @@
> <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.6 tools=64 read=31 write=22 exec=11 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.7 tools=66 read=32 write=22 exec=12 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.6**: **65 transport tools** total; **64 model/operator tools**
-(31 read, 22 write, 11 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.7**: **67 transport tools** total; **66 model/operator tools**
+(32 read, 22 write, 12 exec) plus app-only `workflow_status` for the progress widget. Use `GET /mcp` or Settings → MCP as the live authority if
this document and a deployed instance ever disagree.
### Local-agent and subagent tools
-The current catalog also exposes `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, and `local_agent_inbox` for explicitly correlated same-principal session messaging, plus `agent_subagent_run` for one bounded foreground isolated worker. The local messaging tools do not turn an MCP connection into a remote A2A peer, and the subagent tool does not create another durable session or background process. A client should use `local_agent_reply` for an exact inbox request instead of reconstructing correlation from text.
+The current catalog exposes `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_request_wait`, `local_agent_inbox`, and `local_agent_request` for same-principal session collaboration, plus `agent_subagent_run` for one bounded foreground isolated worker. `local_agents_list` separates lease status from receiver subscription; `local_agent_request_wait` gives a bounded no-resend mailbox outcome; `local_agent_request` is an exec-gated fresh worker from a durable session context and never claims to wake/control the original ChatGPT/terminal process. The local tools do not turn an MCP connection into a remote A2A peer, and the subagent tool does not create another durable session or background process. A client should use `local_agent_reply` for an exact inbox request instead of reconstructing correlation from text.
## 1. What this connection does
diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
index b9647a37..e50bf377 100644
--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md
+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
@@ -4,15 +4,15 @@
> 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.6 tools=64 read=31 write=22 exec=11 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.7 tools=66 read=32 write=22 exec=12 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.09.02.6**: **65 transport tools** total; **64 model/operator tools**
-(31 read, 22 write, 11 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.7**: **67 transport tools** total; **66 model/operator tools**
+(32 read, 22 write, 12 exec) plus app-only `workflow_status`. `GET /mcp` exposes the live names, version/hash and scoped
manifest and is the machine-readable parity source.
## Local collaboration additions
-Toolset `2026.09.02.6` adds/now tracks `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_inbox`, and `agent_subagent_run`. A gateway should preserve these literal names if it chooses to expose them. The first four address durable same-principal MSO sessions; `agent_subagent_run` is a foreground same-session worker and must not be modeled as a remote A2A registration or long-lived peer.
+Toolset `2026.09.02.7` tracks `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_request_wait`, `local_agent_inbox`, `local_agent_request`, and `agent_subagent_run`. A gateway should preserve these literal names if it chooses to expose them. The six `local_agent_*`/`local_agents_list` tools address durable same-principal MSO sessions; `agent_subagent_run` is a foreground same-session worker and must not be modeled as a remote A2A registration or long-lived peer.
## Why this contract matters
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index b5e64d4b..a6d44582 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -136,16 +136,14 @@ ChatGPT/Codex subscription path), while `mso model list [provider]` shows select
Interactive `mso model` / `mso models` menus are arrow-key pickers: **↑/↓** moves, typing filters,
**Enter** selects, and **Esc** cancels; numeric provider/model prompts are not part of the UX.
Agent sessions are durable: `mso --continue` resumes the latest session and
-`mso --resume <index|id|title>` resolves a prior session without weakening principal isolation. Inside
+`mso --resume <@name|index|id|title>` resolves a prior session without weakening principal isolation. Inside
the Agent, `/session` and bare `/resume` open a single newest-first picker directly—there is no second
-printed recent list. Rows show the human session title plus `modified …`; IDs are hidden in the normal UI
-and retained only as an exact automation/debug escape hatch. Explicit `/title` renames use the durable
-rename lifecycle, while new CLI sessions remain auto-titleable from their first real user prompt.
+printed recent list. Rows show the short durable `@name` first, with the longer human session title plus `modified …`; IDs are hidden in the normal UI and retained only as an exact automation/debug escape hatch. Every fresh session receives a familiar unique name automatically. `/rename <name>` changes only this mention handle; `/title <text>` changes the longer durable description/topic, while new CLI titles remain auto-titleable from their first real user prompt.
Agent permission mode defaults to `ask`. `mso --yolo` and `mso -yolo` are global Agent startup flags, so
they work without spelling `agent` (`mso --continue --yolo` is valid too). YOLO auto-approves write and
exec calls for that process only; MSO still canonicalizes the exact payload and sends its approval digest
-to the server, but the interactive `allow this exact call? [y/N]` step is skipped. `/permission` opens a
+to the server, but the interactive compact approval flow is skipped. In normal `ask` mode MSO shows one safe `Approval needed: <tool> — <action>` line; Enter opens redacted-safe exact-call details and the canonical digest, then a separate explicit `allow` or `deny` decision is required. `/permission` opens a
native picker for `ask`, `auto-write`, or `yolo`; Tab on an empty Agent prompt cycles the same modes.
`auto-write` approves writes only and retains exec confirmation. The mode is deliberately not persisted
across Agent restarts/resumes.
diff --git a/docs/LOCAL-AGENTS.md b/docs/LOCAL-AGENTS.md
index 7ba89376..ada3c4da 100644
--- a/docs/LOCAL-AGENTS.md
+++ b/docs/LOCAL-AGENTS.md
@@ -1,26 +1,33 @@
# Local Agents — native same-host session messaging
-MSO 1.10 keeps **local session messaging** separate from **remote A2A v1** and adds explicit request/reply correlation plus mention routing.
+MSO 1.11 keeps **local session messaging** separate from **remote A2A v1** and adds explicit request/reply correlation plus mention routing.
Local Agents is the host-local transport for live MSO sessions. It does not use Agent Cards, peer registration, public URLs, A2A credentials, or the A2A JSON-RPC protocol. Remote agents still use the standard A2A v1 surface documented in [A2A.md](./A2A.md).
## UX
-Open two interactive MSO Agent terminals. No setup step is required:
+Every durable session has two distinct human-facing fields:
+
+- `name` — a short unique handle such as `milo`, `luna`, or `nara`; this is what `@mention` uses;
+- `title` — a longer auto/manual description of what the session is about.
+
+Fresh sessions receive a familiar short name automatically. Open two terminals and they may look like:
```text
Terminal A Terminal B
-[agent-a] [agent-b]
+[milo] [luna]
+
+Title: Debug auth Title: Review API
```
-A manual durable-session rename becomes the primary local identity immediately:
+Rename the short handle independently from the description:
```text
-/title zahra /title rahman
-[zahra] [rahman]
+/rename zahra /rename rahman
+/title frontend debugging /title security review
```
-No other terminal needs a refresh or restart. Directory reads resolve the current durable session title each time, while receive delivery stays attached through a host-local SSE stream.
+`/rename` is immediately durable and does not change the session id/title. `/title` remains the description/topic lifecycle and does not change the `@name`. Names are unique per principal.
Useful TUI commands:
@@ -32,6 +39,8 @@ Useful TUI commands:
/inbox
```
+A leading `@rahman …` resolves **active agents only**. If `rahman` is offline/ended, the mention fails clearly and does not silently queue a new request. This prevents a typo/stale handle from becoming a delayed surprise response. The lower-level `local_agent_message_send`/`mso agents send` compatibility surface may still explicitly address a known offline session and retain durable queued delivery.
+
From the ordinary shell, the same native route has an explicit CLI group for scripting/inspection:
```text
@@ -40,23 +49,32 @@ mso agents send <source-session-id> rahman "please check the latest result"
mso agents inbox <session-id>
```
-`@agent-b …` is an explicit correlated `request` with `requiresUserRelay=true`. The client acknowledges dispatch immediately; it does **not** start an idle target in the background. When that target later performs an explicit turn and answers with `local_agent_reply`, the exact correlated reply is relayed to the originating user-facing conversation without another user prompt or model call. `/message` remains backward-compatible notify-only messaging. `/delegate` creates a correlated local task; only when there is no matching local target does it fall back to a registered **remote** A2A v1 peer. `/agents` shows local live sessions and remote peers separately.
+`@rahman …` is an explicit correlated `request` with `requiresUserRelay=true`. The client acknowledges dispatch immediately; it does **not** start an idle target in the background. When that target later performs an explicit turn and answers with `local_agent_reply`, the exact correlated reply is relayed to the originating user-facing conversation without another user prompt or model call. `/message` remains backward-compatible notify-only messaging. `/delegate` creates a correlated local task; only when there is no matching active local name does it fall back to a registered **remote** A2A v1 peer. `/agents` shows local live sessions and remote peers separately.
Incoming peer data is never stored as a human user turn. Notify-only and request events remain visually distinct:
```text
-[agent-zahra] FYI: deploy finished
-[agent-zahra] task review this change and report risks
+[rahman] FYI: deploy finished
+[rahman] task review this change and report risks
```
A correlated reply that matches an outstanding source request renders user-facing immediately:
```text
-[agent-zahra] → user Review looks safe; one migration needs a backup.
+[rahman] → user Review looks safe; one migration needs a backup.
```
MSO persists both the raw role `agent` row and, only for a valid user-relay correlation, a synthetic `assistant` relay row. No model call rewrites the peer answer. For later model context, raw peer rows are projected as `[LOCAL_AGENT_DATA …]` so their text is explicitly treated as peer data rather than higher-authority user instructions.
+### Which local delegation path to use
+
+| Goal | Primitive | Behavior |
+|---|---|---|
+| Talk to another **currently active** Agent session | `@name …` / correlated mailbox request | Immediate acknowledgement, durable queue, target processes only on its own explicit turn, async reply relays by correlation. |
+| Send passive information | `/message` / `local_agent_message_send` | Notify-only by default; no synthetic assistant reply. Explicit low-level callers may queue to known offline sessions. |
+| Need a result now from another durable session context | `local_agent_request` | `exec`-gated fresh bounded worker using that saved session context. It does **not** wake/control the original terminal or ChatGPT conversation. |
+| Observe one mailbox request without polling forever | `local_agent_request_wait` | Foreground bounded wait/status check (0–30s): `replied`, `target_offline`, `consumer_absent`, or `timeout`. Never resends or starts a background worker. |
+
## Request/reply correlation
Mailbox messages carry schema-validated metadata instead of relying on text parsing:
@@ -80,26 +98,21 @@ Local Agents uses a small private lease store rather than rewriting the potentia
| `offline` | The receive lease expired; this is derived, not written as a permanent state. |
| `ended` | The current receiver explicitly released that session, e.g. clean terminal exit or switching to another durable session. |
-Interactive CLI sessions maintain a lightweight lease heartbeat and one SSE receive stream. There is no message polling loop. `/new` and `/resume` release the old receiver and bind the same terminal to the new durable session automatically. `/restart` keeps the exact durable session alive across process replacement and the replacement process renews its lease.
+Interactive CLI sessions maintain a lightweight lease heartbeat and one SSE receive stream. There is no message polling loop. **Presence and consumption are separate signals:** `idle` means the lease is current; it does not by itself prove that an SSE receiver is subscribed. Directory rows therefore also expose `consumerConnected` and `consumerCount`. `/new` and `/resume` release the old receiver and bind the same terminal to the new durable session automatically. `/restart` keeps the exact durable session alive across process replacement and the replacement process renews its lease.
MCP conversation sessions have no persistent terminal socket, so MSO refreshes their lease around bound MCP tool calls. Messages remain durable when that client is not currently connected and can be read with `local_agent_inbox` on a later call.
-Only `ready`, `idle`, and `busy` sessions appear in the normal active target list. An explicitly addressed known `offline`/`ended` target can still receive a durable queued message; the sender receives `target_offline` instead of a false delivered status.
-
-## Identity and duplicate names
+Only `ready`, `idle`, and `busy` sessions appear in the normal active target list. `@mention` is stricter and only resolves this active list. An explicit lower-level send to a known `offline`/`ended` target can still retain a durable queued message; the sender receives `target_offline` instead of a false delivered status.
-The first live unnamed session for one principal receives stable alias `agent-a`, then `agent-b`, through `agent-z`, `agent-aa`, and so on. The alias is stored with presence and does not depend on UUID display or list order.
+## Session names, titles and legacy aliases
-A session title is used as its local label only when the existing rename flow marks it `manual`. Automatic conversation titles do not silently replace `[agent-a]` style identity.
+A session's public `name` is deliberately separate from its title. New sessions allocate a familiar, easy-to-type name from a bounded pool (`milo`, `luna`, `nara`, etc.) and serialize only the name-allocation boundary per principal so parallel session creation cannot create duplicate handles.
-If two active sessions are manually renamed to the same title, internal durable IDs remain unique and the UI adds the alias suffix as a light disambiguator:
+Names normalize to `^[a-z][a-z0-9-]{1,23}$`, are unique for the same principal, and are changed with `/rename <name>`. Duplicate names are rejected instead of decorated or guessed. The durable session id never changes.
-```text
-[zahra · a]
-[zahra · b]
-```
+Older persisted sessions that predate the `name` field are read compatibly and receive a deterministic stable fallback such as `luna-a3f2`; they do not need a destructive migration. The old presence alias (`agent-a`, `agent-b`, …) remains internal/backward-compatible for explicit API/CLI targeting, but new human `@mention` UX intentionally resolves only the public session name.
-A duplicate bare name is rejected as ambiguous. The displayed disambiguated label, stable alias, or exact durable session ID remains addressable.
+The longer `title` remains the human description/topic, may still auto-title from the first prompt, and can be changed independently with `/title <text>`. It is not an `@mention` identity.
## Delivery semantics
@@ -110,7 +123,7 @@ Sender-visible statuses:
| Status | Meaning |
|---|---|
| `delivered` | Persisted and handed to a live local receiver stream. It remains replayable until acknowledged. |
-| `accepted` | Persisted for a live non-busy target, but no receive-stream listener was present at that instant. |
+| `accepted` | Persisted for a live non-busy lease, but no receive-stream listener was present at that instant. Inspect `consumerConnected=false`; the durable inbox is authoritative. |
| `queued` | Persisted while the target is `busy`; an idle transition flushes the queue. |
| `target_offline` | Target is known but its receiver is offline/ended. The message remains queued for the next receiver. |
| `failed` | Reserved for a delivery/store failure; schema/target errors are returned as request errors instead of fake delivery. |
@@ -139,10 +152,12 @@ Local messaging has explicit tools so it cannot be confused with public A2A peer
| Tool | Scope | Purpose |
|---|---|---|
-| `local_agents_list` | read | List automatically discovered same-principal sessions; optionally include known offline/ended targets. |
-| `local_agent_message_send` | write | Backward-compatible send. Default `intent=notify`; set `intent=request` for an expected reply. |
+| `local_agents_list` | read | List same-principal sessions, including short public names plus lease status and `consumerConnected` / `consumerCount`; optionally include offline/ended targets. |
+| `local_agent_message_send` | write | Backward-compatible explicit send. Default `intent=notify`; can create a durable request and may explicitly queue to known offline targets. |
| `local_agent_reply` | write | Reply to one exact request message ID; target, correlation ID, and relay policy are inherited. |
+| `local_agent_request_wait` | read | Bounded 0–30s foreground wait/status for one exact sent request; returns replied/offline/no-consumer/timeout without resend. |
| `local_agent_inbox` | read | Read this exact durable session's mailbox with explicit intent/correlation metadata. |
+| `local_agent_request` | exec | Run a fresh bounded worker from another same-owner durable session context and return the result even when its terminal receiver is offline; never claims to wake/control that original process. |
Remote A2A tools retain their existing names (`a2a_agent_*`, `a2a_message_send`, `a2a_handoff`, etc.) and behavior.
@@ -177,6 +192,6 @@ No external broker, database, daemon, or framework is required.
## Relationship to legacy same-host A2A helpers
-Older `mso a2a local ...` one-shot delegation/virtual-loopback-card helpers remain for backward compatibility and protocol testing. They are **not** the transport used by `/agents`, `/message`, local `/delegate`, the Local Agents MCP tools, or live inbox delivery in MSO 1.10.
+Older `mso a2a local ...` one-shot delegation/virtual-loopback-card helpers remain for backward compatibility and protocol testing. They are **not** the transport used by `/agents`, `/message`, local `/delegate`, the Local Agents MCP tools, or live inbox delivery in MSO 1.11.
New same-host communication should use Local Agents. Public/remote interoperability should use A2A v1.
diff --git a/docs/MCP.md b/docs/MCP.md
index 3f45b4bd..9fbf1f7c 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -126,10 +126,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.6 tools=64 read=31 write=22 exec=11 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.02.7 tools=66 read=32 write=22 exec=12 -->
-Current transport catalog: **65 tools**, server `1.6.0` / toolset `2026.09.02.6`.
-The model/operator catalog is **59 tools** (31 read, 22 write, 11 exec); `workflow_status` is the
+Current transport catalog: **67 tools**, server `1.6.0` / toolset `2026.09.02.7`.
+The model/operator catalog is **66 tools** (32 read, 22 write, 12 exec); `workflow_status` is the
one 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.
@@ -137,6 +137,10 @@ Session/memory tools add durable conversation context without creating
dynamic per-project tool names; `project_capabilities` and `project_function_call` remain the
stable project-automation seam.
+### Local Agent collaboration
+
+Local same-owner session collaboration is intentionally separate from public A2A. `local_agents_list` reports each durable session's short public `name`, lease status, and live receiver observability (`consumerConnected` / `consumerCount`). `local_agent_message_send` + `local_agent_reply` provide durable correlated mailbox semantics; `local_agent_request_wait` gives a bounded foreground request outcome without polling/resending; `local_agent_request` is an explicit exec-gated fresh worker from another durable session context and never claims to wake/control its original terminal/ChatGPT process. Human `@name` mentions resolve active public names only.
+
### Agent-to-Agent (A2A) peers
The eight `a2a_*` tools are the provider-neutral remote-agent seam: `a2a_agents_list`,
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index d00b0b0b..a52893ae 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,15 @@
Running log of what shipped each phase. Newest at top.
+## 2026-09-02 — MSO 1.11.0 named sessions + wrapped composer + collaboration observability
+
+- **Short session handles:** every durable session now has a public `name` separate from its longer title. Fresh sessions allocate familiar easy-to-type names such as `milo`, `luna`, or `nara`; allocation is unique under same-principal concurrency, old sessions receive deterministic backward-compatible fallback names, `/rename <name>` changes only the handle, and `/title <text>` remains the topic/description lifecycle. Internal `agent-a` presence aliases remain a compatibility detail.
+- **Active-name mentions:** leading `@milo …` resolves only currently active public names. Offline/ended targets are not mentionable; lower-level explicit mailbox sends retain backward-compatible offline queueing. The local directory reports lease status separately from `consumerConnected` / `consumerCount`, so `idle` no longer implies an SSE consumer exists.
+- **Bounded request observability:** added read-scope `local_agent_request_wait`, returning `replied`, `target_offline`, `consumer_absent`, or `timeout` in a bounded 0–30s foreground call without resend/background polling. The testing-handoff `local_agent_request` is now dispatch-covered as an exec-gated fresh bounded worker from another same-owner durable session context; it never claims to wake/control that original terminal/ChatGPT process.
+- **Responsive composer:** the interactive draft wraps to terminal width and a height-aware 2–12-row viewport. Terminal resize repaints without losing text; ↑/↓ navigate visual wrapped rows while preserving cursor column before falling through to prompt history.
+- **Compact exact approval:** default ask-mode approval is one safe status line. Tab focuses it, Enter opens redacted-safe tool/scope/args plus the unchanged canonical SHA-256 digest, and a separate explicit `allow` / `deny` decision is mandatory. Auto-write/YOLO still compute exact payload binding while skipping only the human prompt.
+- **Subagent testing capacity:** `OS_SUBAGENT_MAX_TURNS` defaults to 12 and can raise the server policy up to absolute 48; each child still defaults to 6 turns and remains foreground/context-isolated/non-recursive.
+
## 2026-09-02 — MSO 1.10.0 correlated Local Agents + same-session subagents
- **Mention UX:** leading `@agent-b …` resolves the live/known local directory, validates aliases/manual labels, dispatches a durable correlated request, and returns an immediate honest acknowledgement instead of blocking on an idle target. Unknown/ambiguous mentions fail with stable alias choices; known offline targets remain queueable.
diff --git a/docs/README.md b/docs/README.md
index 3600d79f..c28a5591 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -57,6 +57,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`CHANGELOG.md`](./CHANGELOG.md) | Git subjects via `scripts/gen-changelog.mjs`; never hand-edit |
| [`COMPARISON.md`](./COMPARISON.md) | `docs/comparison-data.json` via `scripts/gen-comparison.mjs`; never hand-edit |
| [`PROGRESS.md`](./PROGRESS.md) | Hand-written shipping rationale; newest first; canonical historical WHY |
+| [`TESTING-HANDOFF.md`](./TESTING-HANDOFF.md) | Factual manual/automated test handoff; observed issues and resolved/remaining verification, never architecture authority |
## Historical point-in-time documents
diff --git a/docs/SUBAGENTS.md b/docs/SUBAGENTS.md
index 49b05795..b877cf3f 100644
--- a/docs/SUBAGENTS.md
+++ b/docs/SUBAGENTS.md
@@ -49,7 +49,7 @@ Inside the child:
- default `max_scope` is `read`;
- requested scope cannot exceed the parent caller scope;
-- max model/tool rounds default to 6 and cap at 12;
+- max model/tool rounds default to 6; the server policy `OS_SUBAGENT_MAX_TURNS` defaults to 12 and may be raised up to the absolute cap of 48;
- timeout defaults to 60 seconds and caps at 120 seconds;
- result text is bounded to 64 KiB;
- recursive `agent_subagent_run` is unavailable;
diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.md
new file mode 100644
index 00000000..1410887d
--- /dev/null
+++ b/docs/TESTING-HANDOFF.md
@@ -0,0 +1,134 @@
+# MSO testing handoff
+
+Update this file at the end of every manual or automated test session. Keep it factual; never include tokens, cookies, prompts containing secrets, or hidden transcripts.
+
+## Current status
+
+The v1.10 findings below have been implemented in the **MSO 1.11 candidate** in this working tree. The historical session logs remain below as evidence of what was observed. Do not re-open those findings from the prose alone: reproduce against the current build first.
+
+Resolved in the candidate:
+- every durable session has a unique short public `name` (`milo`, `luna`, `nara`, …) independent from its longer `title`; `/rename` changes the handle and `/title` changes the description;
+- human `@name` mention routing resolves active agents only; internal `agent-a` aliases remain compatibility data for explicit APIs;
+- composer drafts wrap dynamically to terminal width/height, repaint on resize, and ↑/↓ navigate visual rows before history;
+- `local_agents_list` exposes lease status separately from `consumerConnected` / `consumerCount`;
+- `local_agent_request_wait` provides bounded foreground outcomes without resend/background polling;
+- `local_agent_request` has MCP-dispatch coverage and remains a fresh bounded worker, never a claim to wake/control another terminal/ChatGPT process;
+- standalone Local Agent MCP tests isolate the A2A worker import boundary instead of failing on Vitest's unresolved `server-only`;
+- exact write/exec approval defaults to one compact safe line; Enter opens redacted-safe details plus the unchanged canonical digest, and a separate explicit `allow` / `deny` decision is required.
+
+## Copy prompt for Agent Alpha
+
+```text
+You are taking over MSO testing work in /home/rahman/projects/mso.
+
+Read docs/TESTING-HANDOFF.md first. Preserve existing uncommitted changes unless they directly conflict with the requested fix.
+
+Implement and verify the open items below:
+1. Expose and exercise local_agent_request end-to-end through the MCP tool catalog. It must run a fresh bounded worker from a same-owner durable session even when its live terminal lease is offline. It must never claim to wake/control the original ChatGPT conversation or terminal process.
+2. Diagnose local-agent request/reply delivery. A target shown `idle` only means its lease is current; it does not prove a consumer is subscribed or will reply. Add explicit delivery/consumer observability and a bounded timeout/result state so requests cannot silently wait forever. Preserve durable mailbox and correlation semantics.
+3. Replace the verbose exact-approval prompt with the compact interaction below. Keep canonical full-payload approval binding unchanged.
+
+Exact-approval UX requirement:
+- Show only one changing status line while a write/exec approval is pending, e.g. `Approval needed: exec_run — run typecheck`.
+- The line must describe the current task/tool and update for the next call; do not print `[WRITE · YOLO]`, payload JSON, hash, byte count, or a multi-line confirmation by default.
+- `Tab` focuses/selects the pending approval action; `Enter` opens exact-call details (tool, redacted-safe args summary, canonical digest, scope, and allow/deny choices).
+- From details, the user can explicitly allow or deny; no approval is implied by Tab or Enter alone.
+- Preserve accessible keyboard behavior, cancellation/interrupt behavior, and the existing exact full-payload server-side digest check.
+
+Validation minimum: focused unit tests for success, offline target, absent subscriber/no reply, self-target rejection, principal isolation, compact default approval line, Tab-to-details, Enter-to-details, explicit allow/deny, and canonical approval binding; then npm run typecheck. Report changed files and exact test results.
+```
+
+## Session log
+
+### 2026-09-02 — named sessions, responsive composer, consumer observability, compact approval
+
+**Goal**
+- Apply the user's v1.10 test findings without losing the uncommitted local-agent worker/subagent changes.
+- Make session identity easy to type and separate it from session description.
+- Make long terminal input editable as a responsive wrapped draft.
+
+**Changed**
+- Added per-session familiar short names with same-principal uniqueness locking and backward-compatible legacy fallback names.
+- Added `/rename <name>`; kept `/title <text>` for the longer session topic/description.
+- Restricted human `@name` mentions to active sessions while preserving explicit offline queueing in the lower-level mailbox API.
+- Added receiver subscription observability and `local_agent_request_wait` bounded outcomes.
+- Preserved/finished `local_agent_request` and configurable subagent max-turn policy from the previous test session.
+- Reworked the composer into a terminal-size-aware wrapped input viewport with vertical cursor movement and resize repaint.
+- Replaced verbose exact-call approval output with compact status → details → explicit allow/deny UX while preserving canonical digest verification.
+
+**Verified so far**
+- Focused regression bundle: **13 test files / 97 tests passed**.
+- `npm run typecheck` passes after the changes.
+- `node scripts/check-docs.mjs` reports **53 Markdown files, 66 model MCP tools + 1 app-only bridge** and is current.
+- `local_agent_request` is exercised through the real MCP dispatcher with its worker boundary mocked, not by direct tool invocation only.
+
+**Observed**
+- The old standalone `tools-local-agents.test.ts` `server-only` failure was reproduced and fixed by isolating the A2A worker boundary in that test.
+- `idle` remains a presence-lease state by design; receiver subscription is now a separate field instead of overloading `idle`.
+
+**Repository-wide verification**
+- Full release gate PASS: `npm run typecheck`, `npm run lint`, full `npm run test`, `npm run check`, production `npm run build`, and `git diff --check`.
+- Lint: **0 errors / 9 existing max-lines warnings**; the responsive composer tests were split into a dedicated file so this change adds no new warning-only file.
+- The first full-load run exposed an overly broad per-principal session-name lock; it was replaced with per-candidate-name locking, after which unrelated conversation/session creation remained concurrent and the full suite passed.
+
+**Open work / handoff**
+- Only live post-deploy PTY smoke remains before treating 1.11 as shipped: generated `@name`, `/rename`, active-only mention, consumer subscription fields, and narrow/resized wrapped composer.
+
+
+### 2026-09-02 — local agent wake + subagent capacity
+
+**Goal**
+- Let a same-owner durable local-agent session perform work even if its live terminal receiver is offline.
+- Increase focused subagent model/tool rounds for testing.
+
+**Changes made (uncommitted)**
+- Added `local_agent_request` in `lib/mcp/tools-local-agents.ts` (exec scope).
+- Added `handoffOwnerLocalSession()` in `lib/a2a/local-session.ts`.
+- The request creates a fresh bounded worker using target durable session context; it does **not** wake or control the original terminal/ChatGPT session.
+- Added `OS_SUBAGENT_MAX_TURNS`: default `12`, configurable up to absolute cap `48`. Callers still pass `max_turns` per invocation.
+
+**Verification**
+- `npx vitest run lib/a2a/local-session.test.ts lib/agent/local-agent-messaging.test.ts` → 15 passing.
+- `npm run typecheck` → passing.
+- `lib/mcp/tools-local-agents.test.ts` could not load in standalone Vitest because dependency `server-only` was unresolved via the full MCP tool graph. This is a test-environment/import issue, not treated as a passing test.
+
+**Observed local-agent issue**
+- `agent-k` is currently reported `idle` with a fresh lease, but no reply arrived.
+- This status proves presence heartbeat only. It does not prove the ChatGPT-side consumer is subscribed, has read the inbox, or will execute `local_agent_reply`.
+- Do not send duplicate request messages while diagnosing. Inspect delivery/inbox state and add observability/timeout behavior first.
+
+**Open work (resolved by the 1.11 candidate)**
+- `local_agent_request` now has MCP dispatcher coverage.
+- Directory rows expose receiver subscription state and `local_agent_request_wait` gives bounded outcomes.
+- Product UX is documented: `@name`/mailbox for active-session collaboration; `local_agent_request` for an immediate fresh bounded worker from durable context; `local_agent_request_wait` for bounded mailbox observation.
+
+### 2026-09-02 — compact exact-approval UX requirement
+
+**Requested behavior**
+- One changing status/task line only for a pending exact write/exec approval.
+- `Tab`, then `Enter`, opens the exact-call details; details contain the approval controls.
+- Default display must not expose YOLO/auto-write labels or payload/hash noise.
+
+**Handoff (resolved by the 1.11 candidate)**
+- Compact approval runtime and focused regression coverage are implemented; canonical exact full-payload digest binding is unchanged.
+
+### Template — append for every later session
+
+```md
+### YYYY-MM-DD — short title
+
+**Goal**
+- ...
+
+**Changed**
+- files / behavior
+
+**Verified**
+- exact commands and results
+
+**Observed**
+- reproducible facts only
+
+**Open work / handoff**
+- ...
+```
diff --git a/lib/a2a/local-session.test.ts b/lib/a2a/local-session.test.ts
index a68d6d8d..43d2485f 100644
--- a/lib/a2a/local-session.test.ts
+++ b/lib/a2a/local-session.test.ts
@@ -17,6 +17,7 @@ vi.mock("./inbound-agent", () => ({ runInboundA2AAgent: runner }));
const { createAgentSession } = await import("@/lib/agent/session-store");
const {
handoffA2ALocalSession,
+ handoffOwnerLocalSession,
listA2ALocalSessions,
resolveA2ALocalSession,
spawnA2ALocalSubagent,
@@ -76,6 +77,19 @@ describe("same-host A2A durable-session agents", () => {
expect(result.task.artifacts[0].parts[0].text).toBe("bece result");
});
+ it("runs an offline same-owner session as a bounded fresh worker", async () => {
+ const session = await bece();
+ runner.mockImplementationOnce(async ({ session: target, principal }) => {
+ expect(target.id).toBe(session.id);
+ expect(principal).toBe(`a2a:local:${session.id}`);
+ return { text: "offline worker result", rounds: 1, toolCalls: [] };
+ });
+ const result = await handoffOwnerLocalSession("cli:owner", session.id, "answer this");
+ expect(result.session.id).toBe(session.id);
+ expect(result.task.artifacts[0].parts[0].text).toBe("offline worker result");
+ await expect(handoffOwnerLocalSession("cli:owner", session.id, "answer this", session.id)).rejects.toThrow(/same session/);
+ });
+
it("spawns a durable child agent that inherits context/cwd but has its own id", async () => {
const source = await bece();
runner.mockImplementationOnce(async ({ session: child, principal }) => {
diff --git a/lib/a2a/local-session.ts b/lib/a2a/local-session.ts
index dad57f1a..3be38259 100644
--- a/lib/a2a/local-session.ts
+++ b/lib/a2a/local-session.ts
@@ -6,6 +6,7 @@ import {
import {
ownerSessionSummaries,
resolveAgentSessionOwnerRef,
+ resolveAgentSessionRef,
} from "@/lib/agent/session-query";
import type { AgentSession } from "@/lib/agent/session-types";
import { a2aLoopbackOrigin } from "./network";
@@ -72,6 +73,17 @@ export async function handoffA2ALocalSession(ref: string, objective: string) {
};
}
+/** Execute against a same-owner durable session without requiring its terminal
+ * process to be present. This is a fresh bounded agent run, never a TTY wake. */
+export async function handoffOwnerLocalSession(principal: string, ref: string, objective: string, currentSessionId?: string) {
+ const session = await resolveAgentSessionRef(principal, ref);
+ if (session.id === currentSessionId) throw new Error("cannot run a local agent request against the same session");
+ return {
+ session: agentSessionSummary(session),
+ task: await runLocalSessionTask(session, objective),
+ };
+}
+
export async function spawnA2ALocalSubagent(input: {
ownerPrincipal: string;
sourceSessionRef: string;
diff --git a/lib/agent/local-agent-directory.ts b/lib/agent/local-agent-directory.ts
index 1f2c9927..b24f9d2e 100644
--- a/lib/agent/local-agent-directory.ts
+++ b/lib/agent/local-agent-directory.ts
@@ -1,6 +1,7 @@
import path from "node:path";
import { listAgentSessions } from "./session-store";
import { listLocalAgentPresence, localAgentStatus } from "./local-agent-presence";
+import { localAgentSubscriberCount } from "./local-agent-events";
import type { AgentSessionSummary } from "./session-types";
import type { LocalAgentPresenceRecord, LocalAgentTarget } from "./local-agent-types";
@@ -18,43 +19,32 @@ function cleanDisplayName(value: string): string {
.slice(0, 80);
}
-function manualName(session: AgentSessionSummary): string | null {
- const name = session.titleSource === "manual" ? cleanDisplayName(session.title) : "";
- return name || null;
-}
-
function buildRows(
sessions: AgentSessionSummary[],
presence: LocalAgentPresenceRecord[],
now: number,
): LocalAgentTarget[] {
const byId = new Map(sessions.map((row) => [row.id, row]));
- const raw = presence.flatMap((entry) => {
+ return presence.flatMap((entry) => {
const session = byId.get(entry.sessionId);
if (!session) return [];
- return [{ session, entry, status: localAgentStatus(entry, now), manual: manualName(session) }];
- });
- const duplicateNames = new Map<string, number>();
- for (const row of raw) {
- if (!row.manual || row.status === "offline" || row.status === "ended") continue;
- const key = row.manual.toLocaleLowerCase();
- duplicateNames.set(key, (duplicateNames.get(key) || 0) + 1);
- }
- return raw.map(({ session, entry, status, manual }) => {
- const duplicate = manual && (duplicateNames.get(manual.toLocaleLowerCase()) || 0) > 1;
- const suffix = entry.alias.replace(/^agent-/, "");
- const label = manual ? `[${manual}${duplicate ? ` · ${suffix}` : ""}]` : `[${entry.alias}]`;
- return {
+ const name = cleanDisplayName(session.name).toLocaleLowerCase();
+ if (!name) return [];
+ const consumerCount = localAgentSubscriberCount(session.id);
+ return [{
id: session.id,
+ name,
alias: entry.alias,
- label,
+ label: `[${name}]`,
source: session.source,
title: session.title,
titleSource: session.titleSource,
- status,
+ status: localAgentStatus(entry, now),
+ consumerConnected: consumerCount > 0,
+ consumerCount,
...(session.cwd ? { cwd: session.cwd } : {}),
lastSeenAt: entry.lastSeenAt,
- };
+ }];
});
}
@@ -70,7 +60,7 @@ export async function listLocalAgents(
return buildRows(sessions, presence, now)
.filter((row) => options.includeOffline || !["offline", "ended"].includes(row.status))
.filter((row) => !options.currentSessionId || row.id !== options.currentSessionId)
- .sort((a, b) => a.alias.localeCompare(b.alias, undefined, { numeric: true }));
+ .sort((a, b) => a.name.localeCompare(b.name));
}
function matches(row: LocalAgentTarget, ref: string): boolean {
@@ -79,7 +69,7 @@ function matches(row: LocalAgentTarget, ref: string): boolean {
const title = row.titleSource === "manual" ? cleanDisplayName(row.title).toLocaleLowerCase() : "";
const cwd = row.cwd ? path.resolve(row.cwd).toLocaleLowerCase() : "";
const base = row.cwd ? path.basename(row.cwd).toLocaleLowerCase() : "";
- return [row.id.toLocaleLowerCase(), row.alias.toLocaleLowerCase(), label, title, cwd, base].includes(wanted);
+ return [row.id.toLocaleLowerCase(), row.name.toLocaleLowerCase(), row.alias.toLocaleLowerCase(), label, title, cwd, base].includes(wanted);
}
export async function resolveLocalAgent(
diff --git a/lib/agent/local-agent-events.ts b/lib/agent/local-agent-events.ts
index dc6cfac0..e275789f 100644
--- a/lib/agent/local-agent-events.ts
+++ b/lib/agent/local-agent-events.ts
@@ -25,3 +25,11 @@ export function publishLocalAgentMessage(sessionId: string, message: LocalAgentM
}
return delivered;
}
+
+export function localAgentSubscriberCount(sessionId: string): number {
+ return listeners.get(sessionId)?.size ?? 0;
+}
+
+export function localAgentConsumerConnected(sessionId: string): boolean {
+ return localAgentSubscriberCount(sessionId) > 0;
+}
diff --git a/lib/agent/local-agent-mailbox.ts b/lib/agent/local-agent-mailbox.ts
index 6201947b..1113091b 100644
--- a/lib/agent/local-agent-mailbox.ts
+++ b/lib/agent/local-agent-mailbox.ts
@@ -110,6 +110,38 @@ export async function updateLocalAgentMessageState(
});
}
+
+export async function getLocalAgentSentMessage(
+ principal: string,
+ senderSessionId: string,
+ messageId: string,
+): Promise<LocalAgentMessageView | null> {
+ const session = await getAgentSession(principal, senderSessionId);
+ if (!session) throw new Error("local agent sender not found for this client");
+ if (!/^localmsg_[0-9a-f-]{36}$/.test(messageId)) throw new Error("invalid local agent message id");
+ const owner = principalHash(principal);
+ const row = (await readStore()).messages.find((message) =>
+ message.principalHash === owner && message.senderSessionId === senderSessionId && message.id === messageId,
+ );
+ return row ? view(row) : null;
+}
+
+export async function findLocalAgentReply(
+ principal: string,
+ targetSessionId: string,
+ replyToMessageId: string,
+): Promise<LocalAgentMessageView | null> {
+ const session = await getAgentSession(principal, targetSessionId);
+ if (!session) throw new Error("local agent target not found for this client");
+ if (!/^localmsg_[0-9a-f-]{36}$/.test(replyToMessageId)) throw new Error("invalid local agent message id");
+ const owner = principalHash(principal);
+ const row = (await readStore()).messages
+ .filter((message) => message.principalHash === owner && message.targetSessionId === targetSessionId &&
+ message.intent === "reply" && message.replyToMessageId === replyToMessageId)
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
+ return row ? view(row) : null;
+}
+
export async function listLocalAgentInbox(
principal: string,
targetSessionId: string,
diff --git a/lib/agent/local-agent-messaging.test.ts b/lib/agent/local-agent-messaging.test.ts
index 127ef116..e42c2aca 100644
--- a/lib/agent/local-agent-messaging.test.ts
+++ b/lib/agent/local-agent-messaging.test.ts
@@ -31,31 +31,36 @@ beforeAll(async () => {
afterAll(() => rmSync(root, { recursive: true, force: true }));
describe("native local session agents", () => {
- it("assigns deterministic readable placeholders to two live unnamed sessions", async () => {
+ it("assigns short familiar unique public names to two live sessions", async () => {
const rows = await directory.listLocalAgents(owner);
- expect(rows.map((row) => row.label)).toEqual(["[agent-a]", "[agent-b]"]);
+ expect(rows).toHaveLength(2);
+ expect(rows.every((row) => /^[a-z][a-z0-9-]{1,23}$/.test(row.name))).toBe(true);
+ expect(new Set(rows.map((row) => row.name)).size).toBe(2);
+ expect(rows.every((row) => row.label === `[${row.name}]`)).toBe(true);
expect(rows.map((row) => row.status)).toEqual(["idle", "idle"]);
+ expect(rows.every((row) => row.consumerConnected === false && row.consumerCount === 0)).toBe(true);
});
- it("manual rename changes the label without changing the durable identity", async () => {
- const id = a.id;
- await store.renameAgentSession(owner, a.id, "zahra");
+ it("session-name rename changes only the public handle and keeps durable identity/title", async () => {
+ const id = a.id, title = a.title;
+ a = await store.renameAgentSessionName(owner, a.id, "zahra");
const rows = await directory.listLocalAgents(owner);
- expect(rows.find((row) => row.id === id)?.label).toBe("[zahra]");
- expect(rows.find((row) => row.id === id)?.id).toBe(id);
+ expect(rows.find((row) => row.id === id)).toMatchObject({ id, name: "zahra", label: "[zahra]", title });
});
- it("lightly disambiguates duplicate manual names while preserving aliases", async () => {
- await store.renameAgentSession(owner, b.id, "zahra");
+ it("rejects duplicate public handles, then accepts a unique rename", async () => {
+ await expect(store.renameAgentSessionName(owner, b.id, "zahra")).rejects.toThrow(/already in use/i);
+ b = await store.renameAgentSessionName(owner, b.id, "rahman");
const rows = await directory.listLocalAgents(owner);
- expect(rows.map((row) => row.label)).toEqual(["[zahra · a]", "[zahra · b]"]);
- expect(() => rows.map((row) => row.alias)).not.toThrow();
- await store.renameAgentSession(owner, b.id, "rahman");
+ expect(rows.map((row) => row.name).sort()).toEqual(["rahman", "zahra"]);
+ expect(rows.find((row) => row.id === b.id)?.alias).toBe("agent-b");
});
it("delivers an idle-target message to the live feed and durable inbox", async () => {
const received: unknown[] = [];
const unsubscribe = events.subscribeLocalAgentMessages(b.id, (message) => received.push(message));
+ const subscribed = await directory.listLocalAgents(owner);
+ expect(subscribed.find((row) => row.id === b.id)).toMatchObject({ consumerConnected: true, consumerCount: 1 });
const result = await messaging.sendLocalAgentMessage({
principal: owner,
senderSessionId: a.id,
@@ -66,7 +71,7 @@ describe("native local session agents", () => {
unsubscribe();
expect(result.status).toBe("delivered");
expect(result.sender.label).toBe("[zahra]");
- expect(result.target.label).toBe("[rahman]");
+ expect(result.target).toMatchObject({ label: "[rahman]", consumerConnected: true, consumerCount: 1 });
expect(received).toHaveLength(1);
const inbox = await mailbox.listLocalAgentInbox(owner, b.id);
expect(inbox.some((row) => row.id === result.message.id && row.text === "please review this")).toBe(true);
@@ -90,6 +95,10 @@ describe("native local session agents", () => {
expect(reply.target.id).toBe(a.id);
const original = await mailbox.getLocalAgentInboxMessage(owner, b.id, request.message.id);
expect(original?.state).toBe("read");
+ const waited = await messaging.waitForLocalAgentReply({
+ principal: owner, senderSessionId: a.id, requestMessageId: request.message.id, timeoutMs: 0,
+ });
+ expect(waited).toMatchObject({ state: "replied", reply: { id: reply.message.id } });
});
it("defaults ordinary sends to notify-only semantics", async () => {
@@ -117,6 +126,18 @@ describe("native local session agents", () => {
expect(received).toContain(result.message.id);
});
+ it("returns consumer_absent for a bounded request wait when lease is active but no receiver is subscribed", async () => {
+ await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b");
+ const request = await messaging.sendLocalAgentMessage({
+ principal: owner, senderSessionId: a.id, target: "rahman", text: "wait status", intent: "request",
+ });
+ const waited = await messaging.waitForLocalAgentReply({
+ principal: owner, senderSessionId: a.id, requestMessageId: request.message.id, timeoutMs: 0,
+ });
+ expect(waited.state).toBe("consumer_absent");
+ expect(waited.target).toMatchObject({ id: b.id, status: "idle", consumerConnected: false, consumerCount: 0 });
+ });
+
it("returns target_offline for a known expired receiver while retaining the payload", async () => {
const old = Date.now() - 30_000;
await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b", old);
@@ -132,6 +153,13 @@ describe("native local session agents", () => {
expect(result.status).toBe("target_offline");
expect(result.targetStatus).toBe("offline");
expect(result.message.state).toBe("queued");
+ const request = await messaging.sendLocalAgentMessage({
+ principal: owner, senderSessionId: a.id, target: "rahman", text: "offline request", intent: "request",
+ });
+ const waited = await messaging.waitForLocalAgentReply({
+ principal: owner, senderSessionId: a.id, requestMessageId: request.message.id, timeoutMs: 100,
+ });
+ expect(waited.state).toBe("target_offline");
await presence.touchLocalAgentPresence(owner, b.id, "idle", "test:b");
});
@@ -160,7 +188,7 @@ describe("native local session agents", () => {
await presence.touchLocalAgentPresence(other, foreign.id, "idle", "other:1");
expect((await directory.listLocalAgents(owner)).some((row) => row.id === foreign.id)).toBe(false);
await expect(messaging.sendLocalAgentMessage({
- principal: owner, senderSessionId: a.id, target: "foreign", text: "nope",
+ principal: owner, senderSessionId: a.id, target: foreign.name, text: "nope",
})).rejects.toThrow(/target not found/);
await expect(mailbox.listLocalAgentInbox(owner, foreign.id)).rejects.toThrow(/not found/);
});
diff --git a/lib/agent/local-agent-messaging.ts b/lib/agent/local-agent-messaging.ts
index 175c014b..7252ec6e 100644
--- a/lib/agent/local-agent-messaging.ts
+++ b/lib/agent/local-agent-messaging.ts
@@ -3,7 +3,7 @@ import { redactText } from "@/lib/security/redact-text";
import { getAgentSession } from "./session-store";
import { principalHash } from "./session-files";
import { listLocalAgents, resolveLocalAgent } from "./local-agent-directory";
-import { enqueueLocalAgentMessage, getLocalAgentInboxMessage, listLocalAgentInbox, updateLocalAgentMessageState } from "./local-agent-mailbox";
+import { enqueueLocalAgentMessage, findLocalAgentReply, getLocalAgentInboxMessage, getLocalAgentSentMessage, listLocalAgentInbox, updateLocalAgentMessageState } from "./local-agent-mailbox";
import { publishLocalAgentMessage } from "./local-agent-events";
import type { LocalAgentDeliveryStatus, LocalAgentMessageIntent, LocalAgentMessageKind, LocalAgentMessageView, LocalAgentTarget } from "./local-agent-types";
@@ -55,6 +55,7 @@ export async function sendLocalAgentMessage(input: {
correlationId?: string;
replyToMessageId?: string;
requiresUserRelay?: boolean;
+ requireActiveTarget?: boolean;
}): Promise<{
status: LocalAgentDeliveryStatus;
targetStatus: LocalAgentTarget["status"];
@@ -73,6 +74,8 @@ export async function sendLocalAgentMessage(input: {
const correlationId = correlation(input.correlationId) ?? (intent === "request" ? `localcorr_${randomUUID()}` : undefined);
const owner = principalHash(input.principal);
const targetOffline = target.status === "offline" || target.status === "ended";
+ if (input.requireActiveTarget && targetOffline)
+ throw new Error(`local agent @${target.name} is no longer active; no message was sent`);
const busy = target.status === "busy";
let message = await enqueueLocalAgentMessage({
principalHash: owner,
@@ -135,3 +138,31 @@ export async function flushLocalAgentQueue(principal: string, targetSessionId: s
}
return delivered;
}
+
+
+export async function waitForLocalAgentReply(input: {
+ principal: string;
+ senderSessionId: string;
+ requestMessageId: string;
+ timeoutMs?: number;
+}) {
+ const request = await getLocalAgentSentMessage(input.principal, input.senderSessionId, input.requestMessageId);
+ if (!request || request.intent !== "request" || !request.correlationId)
+ throw new Error("correlated local agent request not found for this session");
+ const timeoutMs = Math.max(0, Math.min(30_000, Math.trunc(input.timeoutMs ?? 5_000)));
+ const startedAt = Date.now();
+ while (true) {
+ const reply = await findLocalAgentReply(input.principal, input.senderSessionId, request.id);
+ const target = (await listLocalAgents(input.principal, { includeOffline: true }))
+ .find((row) => row.id === request.targetSessionId) ?? null;
+ const elapsedMs = Date.now() - startedAt;
+ if (reply) return { state: "replied" as const, elapsedMs, request, reply, target };
+ if (target && ["offline", "ended"].includes(target.status))
+ return { state: "target_offline" as const, elapsedMs, request, reply: null, target };
+ if (elapsedMs >= timeoutMs) {
+ const state = target?.consumerConnected === false ? "consumer_absent" as const : "timeout" as const;
+ return { state, elapsedMs, request, reply: null, target };
+ }
+ await new Promise((resolve) => setTimeout(resolve, Math.min(100, Math.max(1, timeoutMs - elapsedMs))));
+ }
+}
diff --git a/lib/agent/local-agent-types.ts b/lib/agent/local-agent-types.ts
index f8b732a0..735de411 100644
--- a/lib/agent/local-agent-types.ts
+++ b/lib/agent/local-agent-types.ts
@@ -25,12 +25,15 @@ export interface LocalAgentPresenceRecord {
export interface LocalAgentTarget {
id: string;
+ name: string;
alias: string;
label: string;
source: AgentSessionSource;
title: string;
titleSource: AgentSessionTitleSource;
status: LocalAgentStatus;
+ consumerConnected: boolean;
+ consumerCount: number;
cwd?: string;
lastSeenAt: string;
}
diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.ts
index 45d8343d..aa882b0c 100644
--- a/lib/agent/session-files.ts
+++ b/lib/agent/session-files.ts
@@ -4,6 +4,7 @@ import os from "node:os";
import path from "node:path";
import { compactThresholdTokens, inferredTitleSource, MAX_EVENTS, MAX_HISTORY, safeTitle, sessionContextTokens } from "./session-policy";
import type { AgentSession } from "./session-types";
+import { legacyAgentSessionName, normalizeAgentSessionName } from "./session-name";
const ROOT = path.resolve((process.env.OS_AGENT_SESSIONS_DIR || path.join(os.homedir(), ".mso", "agent-sessions")).replace(/^~(?=$|\/)/, os.homedir()));
const LOCK_ROOT = path.join(ROOT, ".locks");
@@ -28,6 +29,12 @@ export function sessionLockTarget(id: string): string {
return path.join(LOCK_ROOT, "sessions", id);
}
+export function sessionNameLockTarget(ownerHash: string, name: string): string {
+ if (!HASH64.test(ownerHash)) throw new Error("invalid agent session owner hash");
+ if (!/^[a-z][a-z0-9-]{1,23}$/.test(name)) throw new Error("invalid agent session name lock");
+ return path.join(LOCK_ROOT, "names", ownerHash, name);
+}
+
function conversationRefFile(ownerHash: string, conversationHash: string): string {
if (!HASH64.test(ownerHash) || !HASH64.test(conversationHash)) throw new Error("invalid agent conversation index key");
return path.join(CONVERSATION_ROOT, ownerHash.slice(0, 2), ownerHash, `${conversationHash}.ref`);
@@ -106,6 +113,7 @@ export function normalizeSession(raw: AgentSession): AgentSession {
const threshold = Number(raw.compactThresholdTokens) || compactThresholdTokens();
const base = {
...raw,
+ name: normalizeAgentSessionName((raw as AgentSession & { name?: string }).name) || legacyAgentSessionName(raw.id),
title,
titleSource: inferredTitleSource(title, raw.titleSource),
history: Array.isArray(raw.history) ? raw.history.slice(-MAX_HISTORY) : [],
diff --git a/lib/agent/session-name.ts b/lib/agent/session-name.ts
new file mode 100644
index 00000000..d6fbb5e6
--- /dev/null
+++ b/lib/agent/session-name.ts
@@ -0,0 +1,58 @@
+import { createHash, randomInt } from "node:crypto";
+
+const FAMILIAR_NAMES = [
+ "milo", "luna", "nara", "rio", "rafi", "niko", "maya", "zara", "leo", "kira",
+ "bimo", "tara", "naya", "ari", "dino", "sora", "lio", "mira", "noah", "nino",
+ "riko", "sana", "theo", "vivi", "yuki", "zeno", "coco", "ruby", "olive", "hazel",
+ "max", "sam", "ben", "eli", "kai", "ivy", "joy", "finn", "hugo", "lily",
+ "nico", "remi", "tobi", "nova", "alma", "cora", "dara", "ezra", "faye", "gabi",
+ "hana", "iris", "juno", "luca", "mika", "nala", "omar", "piko", "raya", "suki",
+ "timo", "vera", "wren", "yara", "zane", "adit", "bela", "cali", "dika", "eko",
+ "fara", "gino", "hadi", "ika", "jaka", "kano", "lani", "miko", "navi", "raka",
+] as const;
+
+export const AGENT_SESSION_NAME_RE = /^[a-z][a-z0-9-]{1,23}$/;
+
+export function normalizeAgentSessionName(value: unknown): string {
+ const raw = String(value ?? "")
+ .trim()
+ .replace(/^@/, "")
+ .replace(/^\[|\]$/g, "")
+ .normalize("NFKD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/-+/g, "-")
+ .replace(/^-|-$/g, "")
+ .slice(0, 24)
+ .replace(/-$/g, "");
+ return AGENT_SESSION_NAME_RE.test(raw) ? raw : "";
+}
+
+export function requireAgentSessionName(value: unknown): string {
+ const name = normalizeAgentSessionName(value);
+ if (!name) throw new Error("session name must be 2-24 lowercase letters/numbers/hyphens, starting with a letter");
+ return name;
+}
+
+export function legacyAgentSessionName(id: string): string {
+ const digest = createHash("sha256").update(String(id)).digest();
+ const base = FAMILIAR_NAMES[digest.readUInt16BE(0) % FAMILIAR_NAMES.length]!;
+ const suffix = createHash("sha256").update(`legacy:${id}`).digest("hex").slice(0, 4);
+ return `${base}-${suffix}`;
+}
+
+export function allocateAgentSessionName(usedNames: Iterable<string>): string {
+ const used = new Set(Array.from(usedNames, (value) => normalizeAgentSessionName(value)).filter(Boolean));
+ const start = randomInt(FAMILIAR_NAMES.length);
+ for (let i = 0; i < FAMILIAR_NAMES.length; i += 1) {
+ const candidate = FAMILIAR_NAMES[(start + i) % FAMILIAR_NAMES.length]!;
+ if (!used.has(candidate)) return candidate;
+ }
+ for (let suffix = 2; suffix < 10_000; suffix += 1) {
+ const base = FAMILIAR_NAMES[(start + suffix) % FAMILIAR_NAMES.length]!;
+ const candidate = `${base}-${suffix}`;
+ if (candidate.length <= 24 && !used.has(candidate)) return candidate;
+ }
+ throw new Error("session name space is exhausted");
+}
diff --git a/lib/agent/session-query.test.ts b/lib/agent/session-query.test.ts
index ba686a02..26078307 100644
--- a/lib/agent/session-query.test.ts
+++ b/lib/agent/session-query.test.ts
@@ -4,7 +4,7 @@ import type { AgentSession } from "./session-types";
function row(n: number, title: string, updatedAt: string, overrides: Partial<AgentSession> = {}): AgentSession {
return {
- id: `20260901_120000_${n.toString(16).padStart(8, "0")}`, principalHash: "p", source: "cli",
+ id: `20260901_120000_${n.toString(16).padStart(8, "0")}`, principalHash: "p", source: "cli", name: `test-${n}`,
title, titleSource: "auto", createdAt: updatedAt, updatedAt, memorySnapshot: { user: "", memory: "", capturedAt: updatedAt },
history: [{ role: "user", text: title }], events: [], estimatedTokens: 1, lifetimeEstimatedTokens: 1,
compactThresholdTokens: 700000, compactionCount: 0, archiveCount: 0, ...overrides,
diff --git a/lib/agent/session-query.ts b/lib/agent/session-query.ts
index 638279a8..d25a9b68 100644
--- a/lib/agent/session-query.ts
+++ b/lib/agent/session-query.ts
@@ -36,6 +36,10 @@ export function chooseAgentSessionRecord(
if (!ref || q === "latest" || q === "continue") return resumable[0]!;
const exactId = resumable.find((row) => row.id === ref);
if (exactId) return exactId;
+ const wantedName = q.replace(/^@/, "");
+ const exactName = resumable.filter((row) => row.name.toLowerCase() === wantedName);
+ if (exactName.length === 1) return exactName[0]!;
+ if (exactName.length > 1) throw new Error(`session name is ambiguous: ${exactName.map((row) => `@${row.name}`).join(" | ")}`);
if (/^[1-9]\d{0,3}$/.test(ref)) {
const indexed = resumable[Number(ref) - 1];
if (indexed) return indexed;
diff --git a/lib/agent/session-store.test.ts b/lib/agent/session-store.test.ts
index dd679b0d..bffefbfe 100644
--- a/lib/agent/session-store.test.ts
+++ b/lib/agent/session-store.test.ts
@@ -70,6 +70,18 @@ describe("durable agent session context policy", () => {
expect(renamed.updatedAt.localeCompare(before)).toBeGreaterThan(0);
});
+ it("allocates unique short names and renames the handle without changing the title", async () => {
+ const principal = "principal:session-name";
+ const first = await store.createAgentSession(principal, "cli", { title: "Keep this title", titleSource: "manual" });
+ const second = await store.createAgentSession(principal, "cli");
+ expect(first.name).toMatch(/^[a-z][a-z0-9-]{1,23}$/);
+ expect(second.name).toMatch(/^[a-z][a-z0-9-]{1,23}$/);
+ expect(first.name).not.toBe(second.name);
+ const renamed = await store.renameAgentSessionName(principal, first.id, "milo-test");
+ expect(renamed).toMatchObject({ name: "milo-test", title: "Keep this title", titleSource: "manual" });
+ await expect(store.renameAgentSessionName(principal, second.id, "milo-test")).rejects.toThrow(/already in use/i);
+ });
+
it("repairs the legacy CLI default that was incorrectly stored as a manual title", async () => {
const session = await store.createAgentSession("principal:legacy-title", "cli", { title: "MSO Agent session", titleSource: "manual" });
const updated = await store.updateAgentSessionHistory("principal:legacy-title", session.id, [{ role: "user", text: "Deploy Control Room" }], "Deploy Control Room", "auto");
@@ -104,6 +116,7 @@ describe("durable agent session context policy", () => {
store.findOrCreateAgentSessionForConversation(principal, hash, `Conversation ${hash.slice(-2)}`),
));
expect(new Set(rows.map((row) => row.id)).size).toBe(hashes.length);
+ expect(new Set(rows.map((row) => row.name)).size).toBe(hashes.length);
expect(await store.listAgentSessions(principal, 100)).toHaveLength(hashes.length);
});
diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.ts
index e9195294..168cae28 100644
--- a/lib/agent/session-store.ts
+++ b/lib/agent/session-store.ts
@@ -15,6 +15,7 @@ import {
readConversationSession,
readSessionFile,
sessionLockTarget,
+ sessionNameLockTarget,
writeConversationRef,
writeSessionFile,
} from "./session-files";
@@ -28,6 +29,7 @@ import {
safeTitle,
sessionContextTokens,
} from "./session-policy";
+import { allocateAgentSessionName, requireAgentSessionName } from "./session-name";
import type {
AgentSession,
AgentSessionEvent,
@@ -46,6 +48,7 @@ export type {
interface CreateOptions {
id?: string;
+ name?: string;
title?: string;
titleSource?: AgentSessionTitleSource;
resumedFrom?: string;
@@ -61,6 +64,7 @@ function summary(record: AgentSession): AgentSessionSummary {
return {
id: record.id,
source: record.source,
+ name: record.name,
title: record.title,
titleSource: record.titleSource,
createdAt: record.createdAt,
@@ -90,6 +94,12 @@ async function buildRecord(
options: CreateOptions,
): Promise<AgentSession> {
const now = new Date().toISOString();
+ const owner = principalHash(principal);
+ const usedNames = (await listSessionRecords())
+ .filter((row) => row.principalHash === owner)
+ .map((row) => row.name);
+ const name = options.name ? requireAgentSessionName(options.name) : allocateAgentSessionName(usedNames);
+ if (usedNames.includes(name)) throw new Error(`session name @${name} is already in use`);
const memorySnapshot =
options.memorySnapshot ?? (await snapshotAgentMemory(principal));
const created: AgentSessionEvent = {
@@ -103,6 +113,7 @@ async function buildRecord(
id: options.id ?? newAgentSessionId(),
principalHash: principalHash(principal),
source,
+ name,
title: safeTitle(options.title),
titleSource: options.titleSource ?? "default",
...(options.conversationHash
@@ -137,6 +148,33 @@ async function buildRecord(
};
}
+async function withUniqueSessionName<T>(
+ principal: string,
+ source: AgentSessionSource,
+ options: CreateOptions,
+ commit: (record: AgentSession) => Promise<T>,
+): Promise<T> {
+ const owner = principalHash(principal);
+ const requested = options.name ? requireAgentSessionName(options.name) : undefined;
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ const used = (await listSessionRecords())
+ .filter((row) => row.principalHash === owner)
+ .map((row) => row.name);
+ const name = requested ?? allocateAgentSessionName(used);
+ try {
+ return await withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
+ const record = await buildRecord(principal, source, { ...options, name });
+ return commit(record);
+ });
+ } catch (error) {
+ const duplicate = error instanceof Error && /session name @.+ is already in use/.test(error.message);
+ if (!requested && duplicate) continue;
+ throw error;
+ }
+ }
+ throw new Error("could not allocate a unique session name");
+}
+
async function compactIfNeeded(
record: AgentSession,
reason: string,
@@ -177,13 +215,14 @@ export async function createAgentSession(
source: AgentSessionSource,
options: CreateOptions = {},
): Promise<AgentSession> {
- const record = await buildRecord(principal, source, options);
- return withSecurityStoreLock(sessionLockTarget(record.id), async () => {
- if (await readSessionFile(record.id))
- throw new Error("agent session id already exists");
- await writeSessionFile(record);
- return record;
- });
+ return withUniqueSessionName(principal, source, options, async (record) =>
+ withSecurityStoreLock(sessionLockTarget(record.id), async () => {
+ if (await readSessionFile(record.id))
+ throw new Error("agent session id already exists");
+ await writeSessionFile(record);
+ return record;
+ }),
+ );
}
export async function findOrCreateAgentSessionForConversation(
@@ -216,14 +255,15 @@ export async function findOrCreateAgentSessionForConversation(
return legacy;
}
}
- const record = await buildRecord(principal, "mcp", {
+ return withUniqueSessionName(principal, "mcp", {
title,
titleSource: "default",
conversationHash: hash,
+ }, async (record) => {
+ await writeSessionFile(record);
+ await writeConversationRef(owner, hash, record.id);
+ return record;
});
- await writeSessionFile(record);
- await writeConversationRef(owner, hash, record.id);
- return record;
},
);
}
@@ -312,6 +352,28 @@ export async function maybeAutoTitleAgentSession(
});
}
+export async function renameAgentSessionName(
+ principal: string,
+ id: string,
+ value: string,
+): Promise<AgentSession> {
+ const name = requireAgentSessionName(value);
+ const owner = principalHash(principal);
+ return withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
+ const duplicate = (await listSessionRecords()).find((row) =>
+ row.principalHash === owner && row.id !== id && row.name === name,
+ );
+ if (duplicate) throw new Error(`session name @${name} is already in use`);
+ return withSecurityStoreLock(sessionLockTarget(id), async () => {
+ const record = await requireOwned(principal, id);
+ record.name = name;
+ record.updatedAt = new Date().toISOString();
+ await writeSessionFile(record);
+ return record;
+ });
+ });
+}
+
export async function renameAgentSession(
principal: string,
id: string,
diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.ts
index 2d4da2b6..22b2bde8 100644
--- a/lib/agent/session-types.ts
+++ b/lib/agent/session-types.ts
@@ -23,6 +23,7 @@ export interface AgentSession {
id: string;
principalHash: string;
source: AgentSessionSource;
+ name: string;
title: string;
titleSource: AgentSessionTitleSource;
conversationHash?: string;
@@ -47,6 +48,7 @@ export interface AgentSession {
export interface AgentSessionSummary {
id: string;
source: AgentSessionSource;
+ name: string;
title: string;
titleSource: AgentSessionTitleSource;
createdAt: string;
diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.ts
index 0ee1241c..77ad9a14 100644
--- a/lib/agent/subagent-runner.ts
+++ b/lib/agent/subagent-runner.ts
@@ -6,7 +6,13 @@ import { allows, parseScope, type Scope } from "@/lib/mcp/scope";
const MAX_RESULT_BYTES = 64 * 1024;
const DEFAULT_TURNS = 6;
-const MAX_TURNS = 12;
+const ABSOLUTE_MAX_TURNS = 48;
+function maxTurnsLimit(): number {
+ const configured = Number(process.env.OS_SUBAGENT_MAX_TURNS);
+ return Number.isFinite(configured)
+ ? Math.max(1, Math.min(ABSOLUTE_MAX_TURNS, Math.trunc(configured)))
+ : 12;
+}
const DEFAULT_TIMEOUT_MS = 60_000;
const MAX_TIMEOUT_MS = 120_000;
const DENY_PREFIXES = ["agent_session_", "agent_memory_", "local_agent_", "a2a_"];
@@ -60,7 +66,7 @@ export async function runSessionSubagent(input: {
if (Buffer.byteLength(objective, "utf8") > 24 * 1024) throw new Error("subagent objective must be 24 KiB or smaller");
const name = String(input.name || "worker").trim().replace(/[\r\n\t]+/g, " ").slice(0, 60) || "worker";
const maxScope = parseScope(input.maxScope || "read");
- const maxTurns = Math.max(1, Math.min(MAX_TURNS, Math.trunc(input.maxTurns || DEFAULT_TURNS)));
+ const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || DEFAULT_TURNS)));
const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));
const subagentId = `subagent_${randomUUID()}`;
const [{ TOOLS }, { dispatch }] = await Promise.all([import("@/lib/mcp/tools"), import("@/lib/mcp/dispatch")]);
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index 1d16bd34..cbcbb859 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -3,6 +3,8 @@ import { beforeEach, describe, it, expect, vi } from "vitest";
// Next aliases that specifier internally; vitest does not, so stub it — same
// pattern as lib/managed-apps/manager.test.ts.
vi.mock("server-only", () => ({}));
+const localSessionMock = vi.hoisted(() => ({ handoffOwnerLocalSession: vi.fn() }));
+vi.mock("@/lib/a2a/local-session", () => localSessionMock);
// Spy on the trail without writing to ~/.mso/audit.log. Everything else in
// @/lib/host stays REAL — the point of these cases is that the dispatcher, not
@@ -90,7 +92,9 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("skills_read");
expect(n).toContain("local_agents_list");
expect(n).toContain("local_agent_inbox");
+ expect(n).toContain("local_agent_request_wait");
expect(n).not.toContain("local_agent_message_send");
+ expect(n).not.toContain("local_agent_request");
expect(n).not.toContain("workflow_start");
expect(n).not.toContain("fs_write");
expect(n).not.toContain("exec_run");
@@ -104,6 +108,7 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("workflow_cancel");
expect(n).toContain("workflow_finish");
expect(n).toContain("local_agent_message_send");
+ expect(n).not.toContain("local_agent_request");
expect(n).not.toContain("exec_run");
expect(n).not.toContain("browser_power");
});
@@ -113,6 +118,23 @@ describe("tools/list is scope-filtered", () => {
});
});
+
+describe("local agent request dispatch", () => {
+ it("dispatches local_agent_request through the MCP catalog with the conversation-bound session context", async () => {
+ localSessionMock.handoffOwnerLocalSession.mockResolvedValueOnce({
+ session: { id: "20260902_120000_11111111", name: "milo" },
+ task: { state: "completed", artifacts: [{ parts: [{ text: "worker result" }] }] },
+ });
+ const context = { principal: "cli:test-dispatch", sessionId: "20260902_120001_22222222" };
+ const r = await dispatch(call("local_agent_request", { target: "milo", objective: "inspect this" }), "exec", "tester", context);
+ expect(r.error).toBeUndefined();
+ expect(localSessionMock.handoffOwnerLocalSession).toHaveBeenCalledWith(
+ context.principal, "milo", "inspect this", context.sessionId,
+ );
+ expect(JSON.stringify(r.result)).toContain("worker result");
+ });
+});
+
describe("tools/call enforces scope even when the tool was never listed", () => {
it("refuses exec_run for a write token, and says how to fix it", async () => {
const r = await dispatch(call("exec_run", { command: "id" }), "write");
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 0da5ae9d..40fec9a2 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -74,6 +74,8 @@ const MCP_ONLY: Record<string, string> = {
"a2a.handoff": "explicit agent-to-agent delegation is intentionally MCP/terminal-only until Alfa receives its own scoped orchestration model",
"agent.subagent.run": "same-session isolated subagent orchestration belongs to the terminal/MCP agent runtime; Alfa browser threads do not yet share durable AgentSession identity or its approval boundary",
"local.agent.reply": "correlated replies belong to the durable Local Agents session mailbox; Alfa browser threads do not share that session identity or inbox",
+ "local.agent.request.wait": "bounded request observation is tied to the durable Local Agents mailbox/correlation ledger; Alfa browser threads do not own that AgentSession sender identity",
+ "local.agent.request": "fresh-worker execution from another durable AgentSession context belongs to the terminal/MCP orchestration runtime; Alfa browser threads neither share that isolated session store nor its exec delegation boundary",
"tool.forge.candidates": "Tool Forge is the external/terminal cognitive-runtime promotion pipeline; Alfa has a separate in-app lifecycle and must not implicitly expose generated project capabilities",
"tool.forge.propose": "same Forge boundary; creating an inert candidate depends on learned external workflow recipes rather than Alfa owner recall",
"tool.forge.evaluate": "Forge evaluation may execute project-owned fixtures only inside the dedicated sandbox and therefore stays on the scoped external/terminal automation surface",
@@ -165,6 +167,8 @@ describe("MCP rate limits mirror the routes", () => {
"a2a.cancel": 30,
"local-agent.read": 120,
"local-agent.send": 60,
+ "local-agent.wait": 30,
+ "local-agent.request": 12,
"tool.forge.propose": 20,
"tool.forge.evaluate": 10,
"tool.forge.promote": 6,
diff --git a/lib/mcp/tools-local-agents.test.ts b/lib/mcp/tools-local-agents.test.ts
index b0fb5577..4e3e2f0d 100644
--- a/lib/mcp/tools-local-agents.test.ts
+++ b/lib/mcp/tools-local-agents.test.ts
@@ -1,21 +1,29 @@
-import { describe, expect, it } from "vitest";
-import { LOCAL_AGENT_TOOLS } from "./tools-local-agents";
+import { describe, expect, it, vi } from "vitest";
+vi.mock("@/lib/a2a/local-session", () => ({
+ handoffOwnerLocalSession: vi.fn(async () => ({ session: { id: "target" }, task: { state: "completed" } })),
+}));
+
+const { LOCAL_AGENT_TOOLS } = await import("./tools-local-agents");
const local = new Map(LOCAL_AGENT_TOOLS.map((tool) => [tool.name, tool]));
describe("native local session agent MCP tools", () => {
- it("keeps local discovery/inbox read-only and message delivery below exec", () => {
+ it("keeps discovery/wait/inbox read-only, mailbox delivery below exec, and fresh-worker request explicit exec", () => {
expect(local.get("local_agents_list")?.scope).toBe("read");
expect(local.get("local_agent_inbox")?.scope).toBe("read");
+ expect(local.get("local_agent_request_wait")?.scope).toBe("read");
expect(local.get("local_agent_message_send")?.scope).toBe("write");
expect(local.get("local_agent_reply")?.scope).toBe("write");
+ expect(local.get("local_agent_request")?.scope).toBe("exec");
});
- it("describes local messaging without Agent Card registration", () => {
+ it("describes local collaboration without Agent Card registration", () => {
const description = local.get("local_agent_message_send")?.description || "";
expect(description).toMatch(/same-owner MSO session agent/i);
expect(description).toMatch(/no hidden transcript/i);
expect(description).not.toMatch(/Agent Card URL/i);
expect(local.get("local_agent_reply")?.description).toMatch(/correlation/i);
+ expect(local.get("local_agent_request_wait")?.description).toMatch(/bounded foreground/i);
+ expect(local.get("local_agent_request")?.description).toMatch(/fresh bounded worker/i);
});
});
diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.ts
index bc1f5606..769aa4e1 100644
--- a/lib/mcp/tools-local-agents.ts
+++ b/lib/mcp/tools-local-agents.ts
@@ -1,6 +1,7 @@
import { listLocalAgents } from "@/lib/agent/local-agent-directory";
import { listLocalAgentInbox, updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";
-import { replyLocalAgentMessage, sendLocalAgentMessage } from "@/lib/agent/local-agent-messaging";
+import { replyLocalAgentMessage, sendLocalAgentMessage, waitForLocalAgentReply } from "@/lib/agent/local-agent-messaging";
+import { handoffOwnerLocalSession } from "@/lib/a2a/local-session";
import { type McpRunContext, type McpTool, S, str } from "./tool-kit";
function sessionContext(context: McpRunContext): { principal: string; sessionId: string } {
@@ -12,7 +13,7 @@ function sessionContext(context: McpRunContext): { principal: string; sessionId:
export const LOCAL_AGENT_TOOLS: McpTool[] = [
{
name: "local_agents_list",
- description: "List currently active same-owner MSO session agents on this host. Local agents are discovered automatically from live session leases; no Agent Card, URL, registration, refresh, or restart is required. Unnamed sessions use stable labels such as [agent-a].",
+ description: "List same-owner MSO session agents on this host. Every session has a short public name such as milo or luna for @mention UX. status reflects the presence lease; consumerConnected/consumerCount separately report whether this MSO runtime currently has an inbound receiver subscribed. No Agent Card, URL, registration, refresh, or restart is required.",
scope: "read",
annotations: { readOnlyHint: true, idempotentHint: true },
limit: { key: "local-agent.read", max: 60, windowMs: 60_000 },
@@ -29,7 +30,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [
limit: { key: "local-agent.send", max: 60, windowMs: 60_000 },
audit: { action: "agent.message", targetArg: "target" },
inputSchema: S({
- target: { type: "string", description: "Local label/name such as rahman, [rahman], agent-b, or exact durable session id." },
+ target: { type: "string", description: "Local public name such as milo, [milo], legacy internal alias such as agent-b, or exact durable session id." },
message: { type: "string", description: "Explicit payload, maximum 16 KiB." },
kind: { type: "string", enum: ["message", "task"], description: "message (default) or task." },
intent: { type: "string", enum: ["notify", "request"], description: "notify (default) or request. Replies must use local_agent_reply." },
@@ -48,6 +49,43 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [
});
},
},
+ {
+ name: "local_agent_request",
+ description: "Run an explicit objective against another same-owner durable MSO session and return its result. Unlike mailbox delivery, it works when that session's terminal receiver is offline: MSO starts a fresh bounded worker using the target session's saved context. It never wakes or controls a ChatGPT/terminal process, and it copies no hidden live transcript.",
+ scope: "exec",
+ limit: { key: "local-agent.request", max: 12, windowMs: 60_000 },
+ audit: { action: "agent.message", targetArg: "target" },
+ result: { maxTextBytes: 64 * 1024, overflowHint: "Local-agent result was compacted; rerun with a narrower objective." },
+ inputSchema: S({
+ target: { type: "string", description: "Same-owner durable session id, @name/name, title, or working-directory reference." },
+ objective: { type: "string", description: "Explicit task for the target session worker, maximum 24 KiB." },
+ }, ["target", "objective"]),
+ run: async (a, context) => {
+ const current = sessionContext(context);
+ const result = await handoffOwnerLocalSession(current.principal, str(a, "target"), str(a, "objective"), current.sessionId);
+ return { mode: "durable_session_worker", ...result };
+ },
+ },
+ {
+ name: "local_agent_request_wait",
+ description: "Wait a bounded foreground interval for the correlated reply to one exact request previously sent by this session. Returns replied, target_offline, consumer_absent, or timeout with current receiver observability. This never starts a background loop and never resends the request.",
+ scope: "read",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ limit: { key: "local-agent.wait", max: 30, windowMs: 60_000 },
+ inputSchema: S({
+ request_message_id: { type: "string", description: "Exact localmsg_... id returned for the original request." },
+ timeout_ms: { type: "number", minimum: 0, maximum: 30000, description: "Foreground wait budget in milliseconds. Default 5000; max 30000. Zero performs a status-only check." },
+ }, ["request_message_id"]),
+ run: async (a, context) => {
+ const current = sessionContext(context);
+ return waitForLocalAgentReply({
+ principal: current.principal,
+ senderSessionId: current.sessionId,
+ requestMessageId: str(a, "request_message_id"),
+ timeoutMs: a.timeout_ms === undefined ? undefined : Number(a.timeout_ms),
+ });
+ },
+ },
{
name: "local_agent_reply",
description: "Reply to one exact correlated local-agent request in this session's inbox. The original sender, correlation id, and user-relay requirement are inherited from the request, preventing replies from being attached to the wrong turn. Use this instead of local_agent_message_send when answering an inbox item with intent=request.",
diff --git a/lib/mcp/tools-subagents.ts b/lib/mcp/tools-subagents.ts
index b9b2daf3..614b6203 100644
--- a/lib/mcp/tools-subagents.ts
+++ b/lib/mcp/tools-subagents.ts
@@ -12,7 +12,7 @@ export const SUBAGENT_TOOLS: McpTool[] = [{
objective: { type: "string", description: "Exact focused task for the worker, maximum 24 KiB." },
name: { type: "string", description: "Optional short display name, e.g. reviewer or researcher." },
max_scope: { type: "string", enum: ["read", "write", "exec"], description: "Maximum host-tool authority delegated to the child. Default read. The parent call itself is exec-gated as the delegation approval boundary." },
- max_turns: { type: "number", description: "1-12 model/tool rounds; default 6." },
+ max_turns: { type: "number", description: "1 to the server-configured OS_SUBAGENT_MAX_TURNS limit (default 12, absolute max 48); default 6." },
timeout_ms: { type: "number", description: "1000-120000 ms; default 60000." },
context: { type: "string", description: "Optional explicit parent context. Hidden parent transcript is never copied automatically." },
}, ["objective"]),
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index be635110..214950b6 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.6";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-02T14:52:00Z";
+export const MCP_TOOLSET_VERSION = "2026.09.02.7";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-02T16:23:00Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/scripts/mso-agent-approval-ui.mjs b/scripts/mso-agent-approval-ui.mjs
new file mode 100644
index 00000000..d7137897
--- /dev/null
+++ b/scripts/mso-agent-approval-ui.mjs
@@ -0,0 +1,71 @@
+const SECRET_KEY = /(api[_-]?key|token|secret|password|passwd|credential|cookie|authorization|private[_-]?key)/i;
+const SECRET_TEXT = /((?:api[_-]?key|token|secret|password|passwd|credential|authorization)\s*[=:]\s*)[^\s,;]+|\bBearer\s+[^\s,;]+/gi;
+
+function oneLine(value, max = 100) {
+ const clean = String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();
+ const safe = clean.replace(SECRET_TEXT, (match, prefix) => prefix ? `${prefix}[redacted]` : "Bearer [redacted]");
+ return Array.from(safe).length <= max ? safe : `${Array.from(safe).slice(0, Math.max(1, max - 1)).join("")}…`;
+}
+
+function safeValue(value, key = "", depth = 0) {
+ if (SECRET_KEY.test(key)) return "[redacted]";
+ if (depth > 3) return "[…]";
+ if (value === null || typeof value === "boolean" || typeof value === "number") return value;
+ if (typeof value === "string") return oneLine(value, 180);
+ if (Array.isArray(value)) return value.slice(0, 8).map((item) => safeValue(item, "", depth + 1));
+ if (value && typeof value === "object") {
+ const out = {};
+ for (const [childKey, child] of Object.entries(value).slice(0, 16)) out[childKey] = safeValue(child, childKey, depth + 1);
+ return out;
+ }
+ return String(value ?? "");
+}
+
+export function approvalActionSummary(tool, input = {}) {
+ const name = String(tool?.name || "tool");
+ if (name === "exec_run" || name === "exec_job_start") return `run ${oneLine(input.command || "command", 72)}`;
+ if (name === "fs_write") return `write ${oneLine(input.path || "file", 72)}`;
+ if (name === "fs_delete") return `delete ${oneLine(input.path || "path", 72)}`;
+ if (name === "fs_move") return `move ${oneLine(input.from || "source", 32)} → ${oneLine(input.to || "target", 32)}`;
+ if (name === "fs_copy") return `copy ${oneLine(input.from || "source", 32)} → ${oneLine(input.to || "target", 32)}`;
+ if (name === "apps_power") return `${oneLine(input.action || "change", 20)} ${oneLine(input.id || "app", 48)}`;
+ if (name === "local_agent_message_send") return `message ${oneLine(input.target || "agent", 48)}`;
+ return oneLine(name.replaceAll("_", " "), 80);
+}
+
+export function approvalArgsSummary(input = {}) {
+ try { return JSON.stringify(safeValue(input)); }
+ catch { return "{…}"; }
+}
+
+export function approvalStatusLine(tool, input, focused = false) {
+ return `${focused ? "▸ " : ""}Approval needed: ${String(tool?.name || "tool")} — ${approvalActionSummary(tool, input)}`;
+}
+
+export function approvalDetailLines(tool, input, approval) {
+ return [
+ "Approval details",
+ ` tool ${String(tool?.name || "tool")}`,
+ ` scope ${String(tool?.scope || "write")}`,
+ ` args ${approvalArgsSummary(input)}`,
+ ` digest sha256 ${approval.digest}`,
+ " choose allow or deny",
+ ];
+}
+
+export async function requestExactToolApproval(rl, { tool, input = {}, approval, onCancel = null, signal = null, colors = {}, print = console.log }) {
+ let focused = false;
+ const dim = colors.dim || "", reset = colors.reset || "", blue = colors.blue || "", bold = colors.bold || "";
+ const status = () => `${blue}${bold}${approvalStatusLine(tool, input, focused)}${reset}${dim} · Tab focus · Enter details${reset} `;
+ const opened = await rl.question(status, {
+ history: false,
+ onCancel,
+ onTab: () => { focused = true; },
+ });
+ if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
+ if (opened === null) return false;
+ for (const line of approvalDetailLines(tool, input, approval)) print(line);
+ const decision = String(await rl.question(" decision [allow/deny] › ", { history: false, onCancel }) ?? "").trim().toLowerCase();
+ if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
+ return decision === "allow";
+}
diff --git a/scripts/mso-agent-approval-ui.test.ts b/scripts/mso-agent-approval-ui.test.ts
new file mode 100644
index 00000000..c42a4b3b
--- /dev/null
+++ b/scripts/mso-agent-approval-ui.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from "vitest";
+import { canonicalAgentApproval, matchesAgentApproval } from "../lib/agent/approval.mjs";
+import { approvalActionSummary, approvalArgsSummary, approvalDetailLines, approvalStatusLine, requestExactToolApproval } from "./mso-agent-approval-ui.mjs";
+
+describe("compact exact-call approval UX", () => {
+ const tool = { name: "exec_run", scope: "exec" };
+ const input = { command: "npm run typecheck", password: "supersecret" };
+ const approval = canonicalAgentApproval(tool.name, input);
+
+ it("keeps the default status to one safe line without payload, digest, bytes, or YOLO noise", () => {
+ const line = approvalStatusLine(tool, input);
+ expect(line).toBe("Approval needed: exec_run — run npm run typecheck");
+ expect(line).not.toContain("supersecret");
+ expect(line).not.toContain(approval.digest);
+ expect(line).not.toMatch(/bytes|yolo|\{.*\}/i);
+ });
+
+ it("opens redacted exact-call details and preserves the canonical digest", () => {
+ expect(approvalArgsSummary(input)).toContain('"password":"[redacted]"');
+ expect(approvalArgsSummary(input)).not.toContain("supersecret");
+ const details = approvalDetailLines(tool, input, approval).join("\n");
+ expect(details).toContain("exec_run");
+ expect(details).toContain("npm run typecheck");
+ expect(details).toContain(approval.digest);
+ expect(matchesAgentApproval(tool.name, approval.payload.input, approval.digest)).toBe(true);
+ });
+
+ it("lets Tab focus the pending action but requires a separate explicit allow decision", async () => {
+ const prompts: string[] = [], printed: string[] = [];
+ let calls = 0;
+ const rl = { question: vi.fn(async (prompt: string | (() => string), options: { onTab?: () => void }) => {
+ calls += 1;
+ prompts.push(typeof prompt === "function" ? prompt() : prompt);
+ if (calls === 1) {
+ options.onTab?.();
+ prompts.push(typeof prompt === "function" ? prompt() : prompt);
+ return "";
+ }
+ return "allow";
+ }) };
+ await expect(requestExactToolApproval(rl, { tool, input, approval, print: (line: string) => printed.push(line) })).resolves.toBe(true);
+ expect(prompts[0]).toContain("Approval needed: exec_run");
+ expect(prompts[1]).toContain("▸ Approval needed: exec_run");
+ expect(calls).toBe(2);
+ expect(printed.join("\n")).toContain("choose allow or deny");
+ });
+
+ it("does not approve Enter/details alone and supports explicit deny", async () => {
+ let calls = 0;
+ const rl = { question: vi.fn(async () => (++calls === 1 ? "" : "deny")) };
+ await expect(requestExactToolApproval(rl, { tool, input, approval, print: () => {} })).resolves.toBe(false);
+ expect(calls).toBe(2);
+ });
+});
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index c6b8100c..364f8280 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -10,6 +10,7 @@ import {
import {
persistSession,
renameCurrentSession,
+ renameCurrentSessionName,
resumeInto,
startNewSession,
resumePicker,
@@ -98,11 +99,12 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
function printHelp() {
console.log(
[
- " /new [name] create and switch to a fresh durable session",
+ " /new [title] create and switch to a fresh durable session",
" /restart soft-reload Agent runtime; keep this session",
- " /session [query] open picker or resume latest/index/id/title",
+ " /session [query] open picker or resume latest/index/id/@name/title",
" /resume [query] alias-style resume command; bare opens same picker",
- " /title <name> rename the durable session",
+ " /rename <name> rename the short @agent handle",
+ " /title <text> rename the session title/description",
" /status model/auth/context/token/session details",
" /permission [mode] choose ask | auto-write | yolo",
" /context alias for /status",
@@ -115,7 +117,7 @@ function printHelp() {
" /doctor run mso doctor",
" /tools list agent tools",
" /agents list live local session agents + remote A2A peers",
- " @agent-b <prompt> correlated local request; relay its reply here",
+ " @milo <prompt> message an active local agent by its short @name",
" /message <target> <msg> send notify-only local agent data",
" /delegate <target> <job> correlated local task; else remote A2A peer",
" /spawn [--name N] [--scope S] <job> run foreground isolated subagent in this session",
@@ -157,6 +159,15 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
if (!args.length) await resumePicker(rl, session);
else await resumeInto(rl, session, args.join(" "));
return "refresh";
+ case "/rename": {
+ const name = args.join(" ").trim();
+ if (!name) console.log("usage: /rename <short-name>");
+ else {
+ const renamed = await renameCurrentSessionName(session, name);
+ console.log(`${C.c}✓ session name: @${renamed}${C.reset}`);
+ }
+ return "handled";
+ }
case "/title": {
const title = args.join(" ").trim();
if (!title) console.log("usage: /title <session name>");
diff --git a/scripts/mso-agent-composer-ui.mjs b/scripts/mso-agent-composer-ui.mjs
index db75daec..97c676b3 100644
--- a/scripts/mso-agent-composer-ui.mjs
+++ b/scripts/mso-agent-composer-ui.mjs
@@ -21,6 +21,50 @@ export function inputViewport(value, cursor, maxWidth) {
return { display: `${prefix}${row.slice(start, end).join("")}${suffix}`, cursor: width(prefix) + clamp(cursor - start, 0, end - start) };
}
+export function inputLayout(value, cursor, options = {}) {
+ const row = chars(value);
+ const columns = Math.max(20, Number(options.columns || 100));
+ const promptWidth = Math.max(0, Number(options.promptWidth || 0));
+ const terminalRows = Math.max(8, Number(options.rows || 24));
+ const lineWidth = Math.max(8, columns - promptWidth - 2);
+ const safeCursor = clamp(cursor, 0, row.length);
+ const totalLines = Math.max(1, Math.floor(row.length / lineWidth) + 1);
+ const absoluteCursorRow = Math.floor(safeCursor / lineWidth);
+ const cursorCol = safeCursor % lineWidth;
+ const requestedMaxRows = Number(options.maxRows || Math.floor(terminalRows * 0.32));
+ const maxRows = Math.max(2, Math.min(12, terminalRows - 4, requestedMaxRows || 2));
+ const visibleCount = Math.min(totalLines, maxRows);
+ const startLine = clamp(absoluteCursorRow - Math.floor(visibleCount / 2), 0, Math.max(0, totalLines - visibleCount));
+ const lines = Array.from({ length: visibleCount }, (_, offset) => {
+ const line = startLine + offset;
+ return row.slice(line * lineWidth, (line + 1) * lineWidth).join("");
+ });
+ return {
+ lines,
+ cursorRow: absoluteCursorRow - startLine,
+ cursorCol,
+ lineWidth,
+ totalLines,
+ startLine,
+ clippedTop: startLine > 0,
+ clippedBottom: startLine + visibleCount < totalLines,
+ };
+}
+
+export function verticalCursor(value, cursor, lineWidth, direction, preferredColumn = /** @type {number|null} */ (null)) {
+ const row = chars(value);
+ const width = Math.max(1, Number(lineWidth || 1));
+ const current = clamp(cursor, 0, row.length);
+ const currentRow = Math.floor(current / width);
+ const totalRows = Math.max(1, Math.floor(row.length / width) + 1);
+ const targetRow = currentRow + (direction < 0 ? -1 : 1);
+ const column = preferredColumn === null ? current % width : Math.max(0, Number(preferredColumn) || 0);
+ if (targetRow < 0 || targetRow >= totalRows) return { moved: false, cursor: current, column };
+ const start = targetRow * width;
+ const end = Math.min(row.length, start + width);
+ return { moved: true, cursor: Math.min(start + column, end), column };
+}
+
export function completionWindow(items, selected, size = 8) {
const rows = Array.isArray(items) ? items : [];
if (!rows.length) return { start: 0, items: [] };
diff --git a/scripts/mso-agent-composer-wrap.test.ts b/scripts/mso-agent-composer-wrap.test.ts
new file mode 100644
index 00000000..bca9ff0b
--- /dev/null
+++ b/scripts/mso-agent-composer-wrap.test.ts
@@ -0,0 +1,44 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it } from "vitest";
+import { AgentComposer, inputLayout, verticalCursor } from "./mso-agent-composer.mjs";
+
+describe("MSO Agent responsive wrapped composer", () => {
+ it("wraps the active draft to terminal width and scales visible rows with terminal height", () => {
+ const source = "abcdefghijklmnopqrstuvwxyz".repeat(4);
+ const short = inputLayout(source, source.length, { columns: 30, rows: 12, promptWidth: 2 });
+ const tall = inputLayout(source, source.length, { columns: 30, rows: 40, promptWidth: 2 });
+ expect(short.totalLines).toBeGreaterThan(1);
+ expect(short.lines.length).toBeGreaterThanOrEqual(2);
+ expect(short.lines.length).toBeLessThanOrEqual(tall.lines.length);
+ expect(short.lines.every((line) => Array.from(line).length <= short.lineWidth)).toBe(true);
+ });
+
+ it("moves the cursor vertically across wrapped visual rows while preserving its column", () => {
+ const source = "0123456789abcdefghijKLMNOPQRST";
+ const down = verticalCursor(source, 3, 10, 1);
+ expect(down).toMatchObject({ moved: true, cursor: 13, column: 3 });
+ const downAgain = verticalCursor(source, down.cursor, 10, 1, down.column);
+ expect(downAgain.cursor).toBe(23);
+ const up = verticalCursor(source, downAgain.cursor, 10, -1, downAgain.column);
+ expect(up.cursor).toBe(13);
+ });
+
+ it("repaints a wrapped draft on terminal resize without losing the submitted value", async () => {
+ class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }
+ class FakeOutput extends EventEmitter {
+ columns = 24; rows = 16; chunks: string[] = [];
+ write(value: string) { this.chunks.push(String(value)); return true; }
+ }
+ const input = new FakeInput(), output = new FakeOutput();
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors: { blue: "", warn: "", c: "", cyan: "", err: "", bold: "", reset: "", dim: "" } });
+ const answer = composer.question("› ");
+ const value = "resize keeps this long draft intact";
+ for (const ch of value) input.emit("keypress", ch, { name: ch, sequence: ch });
+ const before = output.chunks.length;
+ output.columns = 18; output.rows = 24; output.emit("resize");
+ expect(output.chunks.length).toBeGreaterThan(before);
+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(answer).resolves.toBe(value);
+ composer.close();
+ });
+});
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index cc51906a..e41d32da 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -3,9 +3,9 @@ import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";
import process from "node:process";
import {
- chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, inputViewport, menuLines, width,
+ chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, inputLayout, inputViewport, menuLines, verticalCursor, width,
} from "./mso-agent-composer-ui.mjs";
-export { completionWindow, inputViewport } from "./mso-agent-composer-ui.mjs";
+export { completionWindow, inputLayout, inputViewport, verticalCursor } from "./mso-agent-composer-ui.mjs";
export class AgentComposer {
constructor({ input = process.stdin, output = process.stdout, colors }) {
@@ -23,8 +23,8 @@ export class AgentComposer {
if (this.closed) return null;
const input = this.input, output = this.output, C = this.C;
return new Promise((resolve) => {
- let value = "", cursor = 0, selected = 0, reservedMenuRows = 0;
- let dismissed = false, historyIndex = null, draft = "", settled = false;
+ let value = "", cursor = 0, selected = 0, reservedRows = 0;
+ let dismissed = false, historyIndex = null, draft = "", settled = false, verticalColumn = null;
const promptText = () => String(typeof prompt === "function" ? prompt() : prompt);
const wasRaw = Boolean(input.isRaw);
@@ -32,35 +32,43 @@ export class AgentComposer {
// Reserve physical rows only when the dropdown first grows. Selection changes then
// redraw with cursor movement only — no LF/CRLF — so ↑/↓ never create scrollback rows.
const reserve = (rows) => {
- if (rows <= reservedMenuRows) return;
- if (reservedMenuRows) output.write(CURSOR_DOWN(reservedMenuRows));
- for (let i = reservedMenuRows; i < rows; i++) output.write("\r\n");
+ if (rows <= reservedRows) return;
+ if (reservedRows) output.write(CURSOR_DOWN(reservedRows));
+ for (let i = reservedRows; i < rows; i++) output.write("\r\n");
output.write(`${CURSOR_UP(rows)}\r`);
- reservedMenuRows = rows;
+ reservedRows = rows;
};
const erase = () => {
output.write(`\r${CLEAR_LINE}`);
- for (let i = 0; i < reservedMenuRows; i++) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}`);
- if (reservedMenuRows) output.write(`${CURSOR_UP(reservedMenuRows)}\r`);
+ for (let i = 0; i < reservedRows; i++) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}`);
+ if (reservedRows) output.write(`${CURSOR_UP(reservedRows)}\r`);
};
const render = () => {
const currentPrompt = promptText();
- const maxInput = Math.max(8, Number(output.columns || 100) - width(currentPrompt) - 2);
- const viewport = inputViewport(value, cursor, maxInput);
+ const promptWidth = width(currentPrompt);
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);
+ const terminalRows = Math.max(8, Number(output.rows || 24));
+ const maxInputRows = Math.max(2, Math.min(12, terminalRows - menu.length - 4, Math.floor(terminalRows * 0.32)));
+ const layout = inputLayout(value, cursor, { columns: output.columns, rows: terminalRows, promptWidth, maxRows: maxInputRows });
+ const inputExtraRows = Math.max(0, layout.lines.length - 1);
+ const below = inputExtraRows + menu.length;
+ reserve(below);
erase();
- output.write(`${currentPrompt}${viewport.display}`);
+ const continuation = " ".repeat(promptWidth);
+ output.write(`${currentPrompt}${layout.lines[0] || ""}`);
+ for (const row of layout.lines.slice(1)) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}${continuation}${row}`);
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(currentPrompt) + viewport.cursor)}`);
+ const backUp = menu.length + (layout.lines.length - 1 - layout.cursorRow);
+ if (backUp) output.write(CURSOR_UP(backUp));
+ output.write(`\r${CURSOR_RIGHT(promptWidth + layout.cursorCol)}`);
};
const cleanup = () => {
input.off("keypress", onKey);
if (this._cancelCurrent === cancel) this._cancelCurrent = null;
if (this._notifyCurrent === notify) this._notifyCurrent = null;
+ if (typeof output.off === "function") output.off("resize", onResize);
if (typeof input.setRawMode === "function") input.setRawMode(wasRaw);
input.pause();
};
@@ -90,7 +98,7 @@ export class AgentComposer {
if (settled) return false;
erase();
output.write(`${String(text ?? "").replace(/\r/g, "")}\r\n`);
- reservedMenuRows = 0;
+ reservedRows = 0;
render();
return true;
};
@@ -98,7 +106,7 @@ export class AgentComposer {
this._notifyCurrent = notify;
const edit = (next, nextCursor) => {
value = next; cursor = clamp(nextCursor, 0, chars(value).length);
- selected = 0; dismissed = false; historyIndex = null;
+ selected = 0; dismissed = false; historyIndex = null; verticalColumn = null;
render();
};
const apply = (item) => {
@@ -112,8 +120,9 @@ export class AgentComposer {
else historyIndex = dir < 0 ? Math.min(this.history.length - 1, historyIndex + 1) : historyIndex - 1;
if (historyIndex === null || historyIndex < 0) { historyIndex = null; value = draft; }
else value = this.history[historyIndex] || "";
- cursor = chars(value).length; dismissed = true; render();
+ cursor = chars(value).length; dismissed = true; verticalColumn = null; render();
};
+ const onResize = () => { if (!settled) render(); };
const onKey = (str, key = {}) => {
const items = matches();
if (key.ctrl && key.name === "c") {
@@ -121,7 +130,7 @@ export class AgentComposer {
return cancel(true);
}
if (key.ctrl && key.name === "l") {
- output.write(CLEAR_SCREEN); reservedMenuRows = 0; return render();
+ output.write(CLEAR_SCREEN); reservedRows = 0; return render();
}
if (key.name === "escape") {
if (escapeCancels) return cancel(false);
@@ -155,6 +164,12 @@ export class AgentComposer {
if (items.length && items[selected]?.text) return apply(items[selected]);
return finish(value);
}
+ if (!items.length && (key.name === "up" || key.name === "down") && value) {
+ const currentPrompt = promptText();
+ const layout = inputLayout(value, cursor, { columns: output.columns, rows: output.rows, promptWidth: width(currentPrompt) });
+ const moved = verticalCursor(value, cursor, layout.lineWidth, key.name === "up" ? -1 : 1, verticalColumn);
+ if (moved.moved) { cursor = moved.cursor; verticalColumn = moved.column; return render(); }
+ }
if ((key.name === "up" && !items.length) || (key.ctrl && key.name === "p")) return historyMove(-1);
if ((key.name === "down" && !items.length) || (key.ctrl && key.name === "n")) return historyMove(1);
const row = chars(value);
@@ -163,12 +178,12 @@ export class AgentComposer {
if (cursor < row.length) return edit([...row.slice(0, cursor), ...row.slice(cursor + 1)].join(""), cursor);
return render();
}
- if (((key.ctrl || key.meta) && key.name === "left") || (key.meta && key.name === "b")) { cursor = wordLeftIndex(value, cursor); return render(); }
- if (((key.ctrl || key.meta) && key.name === "right") || (key.meta && key.name === "f")) { cursor = wordRightIndex(value, cursor); return render(); }
- if (key.name === "left" || (key.ctrl && key.name === "b")) { cursor = Math.max(0, cursor - 1); return render(); }
- if (key.name === "right" || (key.ctrl && key.name === "f")) { cursor = Math.min(row.length, cursor + 1); return render(); }
- if (key.name === "home" || (key.ctrl && key.name === "a")) { cursor = 0; return render(); }
- if (key.name === "end" || (key.ctrl && key.name === "e")) { cursor = row.length; return render(); }
+ if (((key.ctrl || key.meta) && key.name === "left") || (key.meta && key.name === "b")) { cursor = wordLeftIndex(value, cursor); verticalColumn = null; return render(); }
+ if (((key.ctrl || key.meta) && key.name === "right") || (key.meta && key.name === "f")) { cursor = wordRightIndex(value, cursor); verticalColumn = null; return render(); }
+ if (key.name === "left" || (key.ctrl && key.name === "b")) { cursor = Math.max(0, cursor - 1); verticalColumn = null; return render(); }
+ if (key.name === "right" || (key.ctrl && key.name === "f")) { cursor = Math.min(row.length, cursor + 1); verticalColumn = null; return render(); }
+ if (key.name === "home" || (key.ctrl && key.name === "a")) { cursor = 0; verticalColumn = null; return render(); }
+ if (key.name === "end" || (key.ctrl && key.name === "e")) { cursor = row.length; verticalColumn = null; return render(); }
if (key.name === "backspace" && cursor > 0) return edit([...row.slice(0, cursor - 1), ...row.slice(cursor)].join(""), cursor - 1);
if (key.name === "delete" && cursor < row.length) return edit([...row.slice(0, cursor), ...row.slice(cursor + 1)].join(""), cursor);
if (key.ctrl && key.name === "w") {
@@ -184,6 +199,7 @@ export class AgentComposer {
};
input.on("keypress", onKey);
+ if (typeof output.on === "function") output.on("resize", onResize);
input.resume();
if (typeof input.setRawMode === "function") input.setRawMode(true);
render();
diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.ts
index 86a415f7..17c91947 100644
--- a/scripts/mso-agent-composer.test.ts
+++ b/scripts/mso-agent-composer.test.ts
@@ -22,6 +22,7 @@ describe("MSO Agent interactive composer primitives", () => {
expect(Array.from(atStart.display).length).toBeLessThanOrEqual(10);
expect(atStart.cursor).toBe(0);
});
+
it("redraws arrow-key selection in place without emitting new lines", async () => {
class FakeInput extends EventEmitter {
isRaw = false;
diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.ts
index 0313b3d5..999bb2b3 100644
--- a/scripts/mso-agent-contract.test.ts
+++ b/scripts/mso-agent-contract.test.ts
@@ -2,7 +2,7 @@ import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
-const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.mjs", "mso-agent-slash.mjs", "mso-agent-status.mjs", "mso-agent-sessions.mjs", "mso-agent-session-ui.mjs", "mso-agent-lifecycle.mjs", "mso-agent-commands.mjs", "mso-agent-composer.mjs", "mso-agent-permissions.mjs"].map((name) => path.join(__dirname, name));
+const files = ["mso-agent.mjs", "mso-agent-runtime.mjs", "mso-agent-ui.mjs", "mso-agent-slash.mjs", "mso-agent-status.mjs", "mso-agent-sessions.mjs", "mso-agent-session-ui.mjs", "mso-agent-lifecycle.mjs", "mso-agent-commands.mjs", "mso-agent-composer.mjs", "mso-agent-permissions.mjs", "mso-agent-approval-ui.mjs"].map((name) => path.join(__dirname, name));
const src = files.map((file) => fs.readFileSync(file, "utf8")).join("\n");
describe("MSO terminal agent contract", () => {
@@ -29,7 +29,7 @@ describe("MSO terminal agent contract", () => {
expect(src).toContain("MSO_TITLE_ART");
expect(src).toContain("MSO_TITLE_COLORS");
for (const command of [
- "/models", "/model", "/status", "/context", "/statusbar", "/title",
+ "/models", "/model", "/status", "/context", "/statusbar", "/rename", "/title",
"/new", "/restart", "/session", "/resume", "/setup", "/providers", "/provider",
"/doctor", "/tools", "/agents", "/message", "/delegate", "/inbox", "/skills", "/skill", "/<skill>", "/clear", "/exit", "/quit",
]) expect(src).toContain(command);
@@ -47,8 +47,9 @@ describe("MSO terminal agent contract", () => {
it("keeps infrastructure secrets out of model messages and binds write/exec approval to the exact full payload", () => {
expect(src).toContain("never ask the user to paste API tokens into chat");
expect(src).toContain('tool.scope === "read"');
- expect(src).toContain("exact tool call");
- expect(src).toContain("allow this exact call? [y/N]");
+ expect(src).toContain("Approval needed:");
+ expect(src).toContain("decision [allow/deny]");
+ expect(src).toContain("requestExactToolApproval");
expect(src).toContain("canonicalAgentApproval");
expect(src).toContain("approvalDigest");
expect(src).not.toContain("redactedPreview");
@@ -63,6 +64,8 @@ describe("MSO terminal agent contract", () => {
it("keeps session picker titles human-first and rename explicit", () => {
expect(src).toContain("recent sessions");
+ expect(src).toContain("renameCliSessionName");
+ expect(src).toContain('action: "rename-name"');
expect(src).toContain("renameCliSession");
expect(src).toContain('action: "rename"');
expect(src).toContain("syncPromptHistory");
diff --git a/scripts/mso-agent-mentions.mjs b/scripts/mso-agent-mentions.mjs
index 087b6750..60021bd9 100644
--- a/scripts/mso-agent-mentions.mjs
+++ b/scripts/mso-agent-mentions.mjs
@@ -15,18 +15,15 @@ export function parseLocalAgentMention(line) {
export function resolveLocalAgentMention(rows, token) {
const wanted = clean(token);
- const matches = (Array.isArray(rows) ? rows : []).filter((row) => {
- const names = [row?.alias, row?.label, row?.titleSource === "manual" ? row?.title : ""]
- .map(clean).filter(Boolean);
- return names.includes(wanted);
- });
+ const activeRows = (Array.isArray(rows) ? rows : []).filter((row) => !["offline", "ended"].includes(String(row?.status || "")));
+ const matches = activeRows.filter((row) => [row?.name, row?.label].map(clean).filter(Boolean).includes(wanted));
if (!matches.length) {
- const available = (Array.isArray(rows) ? rows : []).map((row) => `@${row.alias}`).slice(0, 12).join(", ");
+ const available = activeRows.map((row) => `@${row.name}`).slice(0, 12).join(", ");
throw new Error(`local agent mention @${wanted} not found${available ? `; available: ${available}` : ""}`);
}
if (matches.length > 1) {
- const aliases = matches.map((row) => `@${row.alias}`).join(" or ");
- throw new Error(`local agent mention @${wanted} is ambiguous; use ${aliases}`);
+ const names = matches.map((row) => `@${row.name}`).join(" or ");
+ throw new Error(`local agent mention @${wanted} is ambiguous; use ${names}`);
}
return matches[0];
}
@@ -37,6 +34,7 @@ export function mentionAck(result) {
if (status === "target_offline") return `${label} queued · target offline · correlated reply will relay here after it returns`;
if (status === "queued") return `${label} queued · target busy · correlated reply will relay here`;
if (status === "delivered") return `${label} delivered · correlated reply will relay here`;
+ if (status === "accepted" && result?.target?.consumerConnected === false) return `${label} queued · active lease, but no receiver is subscribed · durable inbox will wait`;
if (status === "accepted") return `${label} accepted · waiting for an explicit target turn; correlated reply will relay here`;
return `${label} ${status}`;
}
@@ -48,7 +46,7 @@ export async function dispatchLocalAgentMention(session, line, deps = {}) {
const save = deps.persist || persistSession;
let directory;
try {
- directory = await request(`/api/v1/local-agents?session=${encodeURIComponent(session.agentSession.id)}&includeOffline=1`, {
+ directory = await request(`/api/v1/local-agents?session=${encodeURIComponent(session.agentSession.id)}`, {
signal: AbortSignal.timeout(5_000),
});
} catch (error) {
@@ -69,6 +67,7 @@ export async function dispatchLocalAgentMention(session, line, deps = {}) {
kind: "message",
intent: "request",
requiresUserRelay: true,
+ activeOnly: true,
}),
});
} catch (error) {
diff --git a/scripts/mso-agent-mentions.test.ts b/scripts/mso-agent-mentions.test.ts
index cd49d199..c3e3b859 100644
--- a/scripts/mso-agent-mentions.test.ts
+++ b/scripts/mso-agent-mentions.test.ts
@@ -2,19 +2,22 @@ import { describe, expect, it, vi } from "vitest";
import { dispatchLocalAgentMention, mentionAck, parseLocalAgentMention, resolveLocalAgentMention } from "./mso-agent-mentions.mjs";
const rows = [
- { id: "session-b", alias: "agent-b", label: "[agent-b]", title: "Session B", titleSource: "auto", status: "idle" },
- { id: "session-z", alias: "agent-c", label: "[zahra]", title: "zahra", titleSource: "manual", status: "idle" },
+ { id: "session-b", name: "milo", alias: "agent-b", label: "[milo]", title: "Session B", titleSource: "auto", status: "idle" },
+ { id: "session-z", name: "zahra", alias: "agent-c", label: "[zahra]", title: "Design review", titleSource: "manual", status: "idle" },
+ { id: "session-o", name: "luna", alias: "agent-d", label: "[luna]", title: "Offline", titleSource: "auto", status: "offline" },
];
describe("local agent @mention routing", () => {
- it("parses and resolves valid aliases/manual labels", () => {
- expect(parseLocalAgentMention("@agent-b tebak: apa yang punya banyak kunci?")).toEqual({ target: "agent-b", prompt: "tebak: apa yang punya banyak kunci?" });
- expect(resolveLocalAgentMention(rows, "agent-b").id).toBe("session-b");
+ it("parses and resolves active public names only", () => {
+ expect(parseLocalAgentMention("@milo tebak: apa yang punya banyak kunci?")).toEqual({ target: "milo", prompt: "tebak: apa yang punya banyak kunci?" });
+ expect(resolveLocalAgentMention(rows, "milo").id).toBe("session-b");
expect(resolveLocalAgentMention(rows, "zahra").id).toBe("session-z");
+ expect(() => resolveLocalAgentMention(rows, "agent-b")).toThrow(/not found/i);
+ expect(() => resolveLocalAgentMention(rows, "luna")).toThrow(/not found/i);
});
- it("fails unknown mentions with available stable aliases", () => {
- expect(() => resolveLocalAgentMention(rows, "missing")).toThrow(/@missing not found.*@agent-b.*@agent-c/i);
+ it("fails unknown mentions with active public names only", () => {
+ expect(() => resolveLocalAgentMention(rows, "missing")).toThrow(/@missing not found.*@milo.*@zahra/i);
});
it("dispatches a mention as a correlated request and persists the parent request", async () => {
@@ -23,27 +26,31 @@ describe("local agent @mention routing", () => {
const api = vi.fn(async (path: string, init?: RequestInit) => {
if (!init?.method) return { agents: rows };
const body = JSON.parse(String(init.body));
- expect(body).toMatchObject({ target: "session-b", intent: "request", requiresUserRelay: true });
+ expect(body).toMatchObject({ target: "session-b", intent: "request", requiresUserRelay: true, activeOnly: true });
return {
status: "delivered", target: rows[0],
message: { id: "localmsg_11111111-1111-1111-1111-111111111111", correlationId: "localcorr_22222222-2222-2222-2222-222222222222", createdAt: new Date().toISOString() },
};
});
const persist = vi.fn(async () => {});
- const out = await dispatchLocalAgentMention(session, "@agent-b tebak ini", { api, persist });
+ const out = await dispatchLocalAgentMention(session, "@milo tebak ini", { api, persist });
expect(out?.result.status).toBe("delivered");
expect(history).toEqual(expect.arrayContaining([expect.objectContaining({ role: "local_request", targetSessionId: "session-b", requiresUserRelay: true })]));
expect(persist).toHaveBeenCalledOnce();
});
it("reports offline/queued UX without pretending the target ran", () => {
- expect(mentionAck({ target: { label: "[agent-b]" }, status: "target_offline" })).toMatch(/queued · target offline/i);
- expect(mentionAck({ target: { label: "[agent-b]" }, status: "queued" })).toMatch(/target busy/i);
+ expect(mentionAck({ target: { label: "[milo]" }, status: "target_offline" })).toMatch(/queued · target offline/i);
+ expect(mentionAck({ target: { label: "[milo]" }, status: "queued" })).toMatch(/target busy/i);
+ });
+
+ it("explains an active lease with no subscribed receiver instead of pretending it ran", () => {
+ expect(mentionAck({ target: { label: "[milo]", consumerConnected: false }, status: "accepted" })).toMatch(/no receiver is subscribed/i);
});
it("reports bounded lookup timeout without sending anything", async () => {
const timeout = new Error("timeout"); timeout.name = "TimeoutError";
- await expect(dispatchLocalAgentMention({ agentSession: { id: "session-a" }, history: [] }, "@agent-b hi", {
+ await expect(dispatchLocalAgentMention({ agentSession: { id: "session-a" }, history: [] }, "@milo hi", {
api: vi.fn(async () => { throw timeout; }), persist: vi.fn(),
})).rejects.toThrow(/lookup timed out; no message was sent/i);
});
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
index cf323437..6b009066 100644
--- a/scripts/mso-agent-runtime.mjs
+++ b/scripts/mso-agent-runtime.mjs
@@ -124,6 +124,13 @@ export async function renameCliSession(session, title) {
});
return out.session;
}
+export async function renameCliSessionName(session, name) {
+ const out = await api("/api/v1/agent-sessions", {
+ method: "POST",
+ body: JSON.stringify({ action: "rename-name", id: session.id, name }),
+ });
+ return out.session;
+}
export function printBanner(s, agentSession) {
return printAgentBanner(s, agentSession, { base: BASE, version: VERSION });
diff --git a/scripts/mso-agent-session-ui.mjs b/scripts/mso-agent-session-ui.mjs
index 705532a3..3b098775 100644
--- a/scripts/mso-agent-session-ui.mjs
+++ b/scripts/mso-agent-session-ui.mjs
@@ -1,4 +1,4 @@
-import { C, createCliSession, listCliSessions, loadCliSession, renameCliSession, resumeCliSession, saveCliSession } from "./mso-agent-runtime.mjs";
+import { C, createCliSession, listCliSessions, loadCliSession, renameCliSession, renameCliSessionName, resumeCliSession, saveCliSession } from "./mso-agent-runtime.mjs";
import { sessionCompletionItems, sessionPromptHistory, visibleSessionRows } from "./mso-agent-sessions.mjs";
function autoTitle(history) {
@@ -26,6 +26,14 @@ export async function renameCurrentSession(session, title) {
return session.titleOverride;
}
+export async function renameCurrentSessionName(session, value) {
+ const requested = String(value || "").trim();
+ if (!requested) throw new Error("session name is required");
+ const saved = await renameCliSessionName(session.agentSession, requested);
+ session.agentSession = { ...session.agentSession, ...saved };
+ return saved?.name || requested;
+}
+
export function applyNewSessionState(session, loaded, requestedTitle = "") {
Object.assign(session, {
@@ -48,7 +56,7 @@ export async function startNewSession(rl, session, title = "") {
if (!loaded || loaded.source !== "cli") throw new Error("could not create a new CLI MSO Agent session");
applyNewSessionState(session, loaded, requestedTitle);
syncPromptHistory(rl, session);
- console.log(`${C.c}new session ${loaded.title || "MSO Agent session"}${C.reset}`);
+ console.log(`${C.c}new session @${loaded.name} · ${loaded.title || "MSO Agent session"}${C.reset}`);
return true;
}
@@ -66,7 +74,7 @@ export async function resumeInto(rl, session, query) {
lastElapsedMs: 0,
});
syncPromptHistory(rl, session);
- console.log(`${C.c}resumed ${loaded.title || "MSO Agent session"}${C.reset} · ${session.history.length} history rows`);
+ console.log(`${C.c}resumed @${loaded.name} · ${loaded.title || "MSO Agent session"}${C.reset} · ${session.history.length} history rows`);
return true;
}
@@ -89,7 +97,7 @@ export function resumeArg(argv) {
if (index < 0) index = argv.indexOf("-r");
if (index < 0) return null;
const value = argv[index + 1];
- if (!value || value.startsWith("-")) throw new Error("--resume requires latest, an index, session id, or title query");
+ if (!value || value.startsWith("-")) throw new Error("--resume requires latest, an index, session id, @name, or title query");
return value;
}
diff --git a/scripts/mso-agent-sessions.mjs b/scripts/mso-agent-sessions.mjs
index 6bcc9a49..bed562ec 100644
--- a/scripts/mso-agent-sessions.mjs
+++ b/scripts/mso-agent-sessions.mjs
@@ -36,6 +36,10 @@ export function resolveSessionQuery(rows, query) {
const lower = raw.toLowerCase();
const exactId = sessions.find((row) => String(row.id) === raw);
if (exactId) return { session: exactId, ambiguous: [] };
+ const wantedName = lower.replace(/^@/, "");
+ const exactName = sessions.filter((row) => clean(row.name).toLowerCase() === wantedName);
+ if (exactName.length === 1) return { session: exactName[0], ambiguous: [] };
+ if (exactName.length > 1) return { session: null, ambiguous: exactName, reason: "ambiguous" };
const idPrefix = sessions.filter((row) => String(row.id).toLowerCase().startsWith(lower) || String(row.id).toLowerCase().endsWith(lower));
if (idPrefix.length === 1) return { session: idPrefix[0], ambiguous: [] };
if (idPrefix.length > 1) return { session: null, ambiguous: idPrefix, reason: "ambiguous" };
@@ -62,10 +66,12 @@ export function sessionCompletionItems(rows, input, now = Date.now(), currentId
.slice()
.sort((a, b) => modifiedMs(b) - modifiedMs(a))
.map((row) => {
- const text = clean(row.title) || "MSO Agent session";
+ const title = clean(row.title) || "MSO Agent session";
+ const name = clean(row.name) || "agent";
+ const text = `@${name}`;
const modified = `modified ${formatSessionModified(row.updatedAt || row.createdAt, now)}`;
- const meta = String(row.id) === String(currentId) ? `current · ${modified}` : modified;
- return { text, value: String(row.id), meta, search: `${text} ${row.id} ${meta}`.toLowerCase() };
+ const meta = `${title} · ${String(row.id) === String(currentId) ? `current · ${modified}` : modified}`;
+ return { text, value: String(row.id), meta, search: `${text} ${title} ${row.id} ${meta}`.toLowerCase() };
})
.filter((item) => !q || item.search.includes(q))
.slice(0, 20)
diff --git a/scripts/mso-agent-sessions.test.ts b/scripts/mso-agent-sessions.test.ts
index 603bf27e..122e44d4 100644
--- a/scripts/mso-agent-sessions.test.ts
+++ b/scripts/mso-agent-sessions.test.ts
@@ -2,18 +2,19 @@ import { describe, expect, it } from "vitest";
import { formatSessionModified, resolveSessionQuery, sessionCompletionItems, sessionPromptHistory, visibleSessionRows } from "./mso-agent-sessions.mjs";
const rows = [
- { id: "20260901_120000_aaaaaaaa", title: "Deploy Baton", source: "cli", historyTurns: 10, createdAt: "2026-09-01T11:50:00.000Z", updatedAt: "2026-09-01T12:00:00.000Z" },
- { id: "20260901_110000_bbbbbbbb", title: "Audit MSO", source: "cli", historyTurns: 4, createdAt: "2026-09-01T10:50:00.000Z", updatedAt: "2026-09-01T11:00:00.000Z" },
- { id: "20260901_100000_cccccccc", title: "Older Baton notes", source: "cli", historyTurns: 2, createdAt: "2026-09-01T09:50:00.000Z", updatedAt: "2026-09-01T10:00:00.000Z" },
+ { id: "20260901_120000_aaaaaaaa", name: "milo", title: "Deploy Baton", source: "cli", historyTurns: 10, createdAt: "2026-09-01T11:50:00.000Z", updatedAt: "2026-09-01T12:00:00.000Z" },
+ { id: "20260901_110000_bbbbbbbb", name: "luna", title: "Audit MSO", source: "cli", historyTurns: 4, createdAt: "2026-09-01T10:50:00.000Z", updatedAt: "2026-09-01T11:00:00.000Z" },
+ { id: "20260901_100000_cccccccc", name: "nara", title: "Older Baton notes", source: "cli", historyTurns: 2, createdAt: "2026-09-01T09:50:00.000Z", updatedAt: "2026-09-01T10:00:00.000Z" },
];
describe("MSO Agent session resolver", () => {
- it("resumes newest, list index, exact id, short id and unique title", () => {
+ it("resumes newest, list index, exact id, short id, @name and unique title", () => {
const unordered = [rows[2], rows[0], rows[1]];
expect(resolveSessionQuery(unordered, "latest").session?.id).toBe(rows[0].id);
expect(resolveSessionQuery(unordered, "2").session?.id).toBe(rows[1].id);
expect(resolveSessionQuery(rows, rows[1].id).session?.id).toBe(rows[1].id);
expect(resolveSessionQuery(rows, "bbbbbbbb").session?.id).toBe(rows[1].id);
+ expect(resolveSessionQuery(rows, "@luna").session?.id).toBe(rows[1].id);
expect(resolveSessionQuery(rows, "Audit MSO").session?.id).toBe(rows[1].id);
});
@@ -23,14 +24,15 @@ describe("MSO Agent session resolver", () => {
expect(result.ambiguous).toHaveLength(2);
});
- it("builds a newest-first title picker with hidden ids and last-modified metadata", () => {
+ it("builds a newest-first @name picker with hidden ids, title and last-modified metadata", () => {
const now = Date.parse("2026-09-01T12:05:00.000Z");
const items = sessionCompletionItems([rows[1], rows[0], rows[2]], "", now);
- expect(items.map((item) => item.text)).toEqual(["Deploy Baton", "Audit MSO", "Older Baton notes"]);
- expect(items[0]).toMatchObject({ text: "Deploy Baton", value: rows[0].id, meta: "modified 5m ago" });
+ expect(items.map((item) => item.text)).toEqual(["@milo", "@luna", "@nara"]);
+ expect(items[0]).toMatchObject({ text: "@milo", value: rows[0].id, meta: "Deploy Baton · modified 5m ago" });
expect(`${items[0].text} ${items[0].meta}`).not.toContain(rows[0].id);
expect(sessionCompletionItems(rows, "audit", now)).toHaveLength(1);
- expect(sessionCompletionItems(rows, "bbbbbbbb", now)[0]?.text).toBe("Audit MSO");
+ expect(sessionCompletionItems(rows, "bbbbbbbb", now)[0]?.text).toBe("@luna");
+ expect(sessionCompletionItems(rows, "luna", now)[0]?.text).toBe("@luna");
});
it("formats last-modified time compactly", () => {
@@ -51,12 +53,12 @@ describe("MSO Agent session resolver", () => {
});
it("hides empty default CLI clutter but keeps named and non-CLI sessions", () => {
- const clutter = { id: "empty", source: "cli", title: "MSO Agent session", titleSource: "default", historyTurns: 0, updatedAt: "2026-09-02T10:00:00Z" };
- const named = { id: "named", source: "cli", title: "Deploy MSO", titleSource: "manual", historyTurns: 0, updatedAt: "2026-09-02T09:00:00Z" };
- const mcp = { id: "mcp", source: "mcp", title: "ChatGPT task", titleSource: "auto", historyTurns: 0, updatedAt: "2026-09-02T08:00:00Z" };
+ const clutter = { id: "empty", name: "milo", source: "cli", title: "MSO Agent session", titleSource: "default", historyTurns: 0, updatedAt: "2026-09-02T10:00:00Z" };
+ const named = { id: "named", name: "luna", source: "cli", title: "Deploy MSO", titleSource: "manual", historyTurns: 0, updatedAt: "2026-09-02T09:00:00Z" };
+ const mcp = { id: "mcp", name: "nara", source: "mcp", title: "ChatGPT task", titleSource: "auto", historyTurns: 0, updatedAt: "2026-09-02T08:00:00Z" };
expect(visibleSessionRows([clutter, named, mcp]).map((row) => row.id)).toEqual(["named", "mcp"]);
const items = sessionCompletionItems([clutter, named, mcp], "", Date.parse("2026-09-02T10:05:00Z"), "named");
- expect(items.map((row) => row.text)).toEqual(["Deploy MSO", "ChatGPT task"]);
+ expect(items.map((row) => row.text)).toEqual(["@luna", "@nara"]);
expect(items[0].meta).toContain("current");
});
diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjs
index 669837f0..b9a24040 100644
--- a/scripts/mso-agent-slash.mjs
+++ b/scripts/mso-agent-slash.mjs
@@ -26,7 +26,8 @@ export const BUILTIN_SLASH_ITEMS = [
meta: "Resume a session; no arg opens the same picker",
kind: "command",
},
- { text: "/title", meta: "Rename the durable session", kind: "command" },
+ { text: "/rename", meta: "Rename the short @agent handle", kind: "command" },
+ { text: "/title", meta: "Rename the session title/description", kind: "command" },
{
text: "/status",
meta: "Show model, auth, context, tokens, session",
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
index 2fde48c5..e0790371 100644
--- a/scripts/mso-agent-status.mjs
+++ b/scripts/mso-agent-status.mjs
@@ -74,6 +74,7 @@ export function statusParts(session, cwd = process.cwd()) {
const ctx = contextStatus(session?.history, session?.state?.modelMeta);
const turns = (session?.history || []).filter((row) => row?.role === "user").length;
const sessionTitle = compactLabel(session?.agentSession?.title || "MSO Agent session");
+ const sessionName = String(session?.agentSession?.name || "agent");
const usage = session?.usage || { totalTokens: 0 };
const elapsed = Number(session?.lastElapsedMs || 0);
const skill = skillStatus(session);
@@ -85,6 +86,7 @@ export function statusParts(session, cwd = process.cwd()) {
usage.totalTokens > 0 ? `tokens ${compactNumber(usage.totalTokens)}` : null,
`turns ${turns}`,
elapsed > 0 ? `${(elapsed / 1000).toFixed(elapsed >= 10_000 ? 0 : 1)}s` : null,
+ `@${sessionName}`,
`session ${sessionTitle}`,
homeShort(cwd),
].filter(Boolean);
@@ -116,6 +118,7 @@ export function detailedStatus(session, cwd = process.cwd()) {
skill: skillStatus(session),
turns: (session?.history || []).filter((row) => row?.role === "user").length,
session: session?.agentSession?.id || null,
+ name: session?.agentSession?.name || null,
title: session?.agentSession?.title || null,
permission: session?.permission || "ask",
cwd: homeShort(cwd),
@@ -136,6 +139,7 @@ export function printDetailedStatus(session, C, cwd = process.cwd()) {
console.log(` permission ${row.permission}`);
console.log(` turns ${row.turns}`);
console.log(` session ${row.session}`);
+ console.log(` name @${row.name || "agent"}`);
console.log(` title ${row.title || "MSO Agent session"}`);
console.log(` cwd ${row.cwd}`);
}
diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjs
index 839f09d3..9f24729f 100644
--- a/scripts/mso-agent-ui.mjs
+++ b/scripts/mso-agent-ui.mjs
@@ -117,7 +117,8 @@ export function printAgentBanner(s, agentSession, { base, version }) {
const skills = groupedSkillLines(s.skills?.skills, 5);
const model = `${s.config?.provider ?? "—"}/${s.config?.model ?? "—"}`;
const sessionTitle = fit(agentSession?.title || "MSO Agent session", 52);
- const title = fit(`MSO Agent${version ? ` v${version}` : ""} · ${sessionTitle}`, inner - 2);
+ const sessionName = `@${agentSession?.name || "agent"}`;
+ const title = fit(`MSO Agent${version ? ` v${version}` : ""} · ${sessionName} · ${sessionTitle}`, inner - 2);
console.log(panelTitle(title, inner));
if (totalWidth >= 94) {
@@ -125,7 +126,7 @@ export function printAgentBanner(s, agentSession, { base, version }) {
const leftWidth = Math.max(30, Math.floor((inner - gap) * 0.37));
const rightWidth = inner - gap - leftWidth;
const left = [
- `${C.bold}Runtime${C.reset}`, kv("model", model, leftWidth), kv("session", sessionTitle, leftWidth),
+ `${C.bold}Runtime${C.reset}`, kv("model", model, leftWidth), kv("name", sessionName, leftWidth), kv("session", sessionTitle, leftWidth),
kv("endpoint", base, leftWidth), "", `${C.bold}Capabilities${C.reset}`,
fit(`${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec`, leftWidth),
fit("write/exec approval-gated", leftWidth), "", `${C.bold}Infrastructure${C.reset}`,
@@ -140,7 +141,7 @@ export function printAgentBanner(s, agentSession, { base, version }) {
for (let i = 0; i < rows; i++) console.log(panelLine(left[i] || "", right[i] || "", leftWidth, rightWidth, gap));
} else {
const lines = [
- `${C.bold}Runtime${C.reset}`, kv("model", model, inner), kv("session", sessionTitle, inner), kv("endpoint", base, inner), "",
+ `${C.bold}Runtime${C.reset}`, kv("model", model, inner), kv("name", sessionName, inner), kv("session", sessionTitle, inner), kv("endpoint", base, inner), "",
`${C.bold}Available Tools${C.reset}`, ...tools.map((row) => kv(row.label, row.value, inner)), "",
`${C.bold}Available Skills${C.reset}`, ...skills.map((row) => kv(row.label, row.value, inner)), "",
`${C.bold}Capabilities${C.reset}`, `${byScope.read} read · ${byScope.write} write · ${byScope.exec} exec · write/exec approval-gated`,
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 925d6a43..256fb653 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import process from "node:process";
import { canonicalAgentApproval } from "../lib/agent/approval.mjs";
+import { requestExactToolApproval } from "./mso-agent-approval-ui.mjs";
import { beginSkillInvocation, endSkillInvocation } from "./mso-agent-skills.mjs";
import { AgentComposer } from "./mso-agent-composer.mjs";
import { AgentInterruptManager, isAbortError } from "./mso-agent-interrupt.mjs";
@@ -30,15 +31,12 @@ async function executeTool(rl, tool, call, agentSession, permission = "ask", sig
// Its default approval scope is read, so write/exec fail closed unless the
// caller explicitly chose --approve-scope write|exec.
if (options.approvalScope) return { ok: false, result: "denied by user" };
- console.log(`${C.warn}${C.bold}[${tool.scope.toUpperCase()}] exact tool call${C.reset}`);
- console.log(approval.display);
- console.log(`${C.dim}sha256 ${approval.digest} · ${approval.bytes} bytes${C.reset}`);
- const answer = String(await rl.question(" allow this exact call? [y/N]: ", { history: false, onCancel: onInterrupt }) ?? "").trim().toLowerCase();
- if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
- if (answer === "y" || answer === "yes") approved = true;
+ approved = await requestExactToolApproval(rl, {
+ tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C,
+ });
} else if (needsApprovalDigest && !options.quiet && !options.approvalScope) {
- const mode = permission === "yolo" ? "YOLO" : "AUTO-WRITE";
- console.log(`${C.c}${C.bold}[${tool.scope.toUpperCase()} · ${mode}]${C.reset} ${tool.name}`);
+ // Keep autonomous approval mode out of the transcript: scope + tool is enough.
+ console.log(`${C.c}${C.bold}[${tool.scope}]${C.reset} ${tool.name}`);
}
if (!approved) return { ok: false, result: "denied by user" };
if (!options.quiet) process.stdout.write(`${C.dim} ↳ ${tool.name}…${C.reset}`);
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index 02cc2a27..5710841f 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -29,7 +29,7 @@ const all = [cli, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
- expect(cli).toContain('VERSION="1.10.0"');
+ expect(cli).toContain('VERSION="1.11.0"');
expect(cli).toContain("models * Configure AI providers/auth");
expect(cli).toContain("model [ref] Select active model");
expect(agentCli).toContain("run_models()");