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(tui): @ addresses agents and MCP plugins, with / owning commands (#263)

Abdurrahman Fakhrul269b6721789e
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index bc33d9ff..b5cdc9dc 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `tui` @ addresses agents and MCP plugins, with / owning commands
- `tui` opencode batch three, from starved flags to a written contract (#258)
**Fixed**
diff --git a/docs/REA-OPENCODE-TUI.md b/docs/REA-OPENCODE-TUI.md
index 924751b1..fb55d8ad 100644
--- a/docs/REA-OPENCODE-TUI.md
+++ b/docs/REA-OPENCODE-TUI.md
@@ -224,3 +224,52 @@ grep -iE "opentui|yoga" /tmp/oc-strings.txt | head
Do not `grep` without `-o` and a bounded context: individual module lines are megabytes long and will
flood the terminal. This happened twice while writing this document.
+
+## The `@` trigger: agents and plugins
+
+`/` and `@` are two triggers with two namespaces, and the split is the same one opencode proved:
+
+| Trigger | Namespace | Position |
+|---|---|---|
+| `/` | commands and skills | only at the start of the line |
+| `@` | another agent, or an MCP server for this turn | start or after whitespace |
+
+A slash command owns the whole line, so `/find @foo` opens no `@` menu. That is not a limitation, it is
+what keeps the two from fighting over one token.
+
+**The list is mixed and every row carries its kind**, because a menu headed `commands & skills` over a
+list of agents is a small lie that teaches a user to distrust the panel:
+
+```
+╭─ agents & plugins ───────────────────────────────────────────────────╮
+│ › @retired agent · offline, message will queue │
+│ @worker agent · live │
+│ @github plugin · mcp · 12 tools │
+│ @linear plugin · mcp · 4 tools │
+╰─ ↑↓ navigate · Enter/Tab select · Esc close ─────────────────────────╯
+```
+
+An offline agent is **marked, not hidden**. Hiding it makes the agent look absent, which is a different
+and more confusing lie than one that says the message will queue.
+
+### What `@plugin` means, exactly
+
+It scopes **which servers are on the table for that turn**, not which tool is called. The model still
+chooses the tool; naming a plugin never grants one outside it, because the filter matches a name prefix
+and nothing else.
+
+If no tool carries that prefix, the scope is dropped rather than enforced. Scoping to nothing would
+disable every tool and the turn would fail for a reason nobody could see.
+
+### Refused
+
+**Files under `@`.** MSO has no file-mention consumer. A row that inserts a token nothing reads is
+decoration, and this file already argues against that.
+
+**MCP tools under `@`.** Verified across opencode, Claude Code, Cursor and Continue: all four treat
+`@` as context, never as direct tool invocation. opencode went further and deleted MCP resources from
+`@` when one server flooded the menu (issue #32098). A server is the useful unit; a tool list is noise.
+
+**An unknown `@` is not deleted from the prompt.** It stays, and it is reported, because `@ghost` is
+either a typo or an agent that has not started yet, and silently removing words sends a prompt the user
+did not write.
diff --git a/scripts/mso-agent-at.mjs b/scripts/mso-agent-at.mjs
new file mode 100644
index 00000000..f95bfff6
--- /dev/null
+++ b/scripts/mso-agent-at.mjs
@@ -0,0 +1,167 @@
+// The @ completion source for the prompt.
+//
+// Two triggers share one prompt but not one namespace:
+// / commands and skills, prefix anchored at the start of the line
+// @ the things you address: another agent, or an MCP server whose tools this turn may use
+//
+// The list is mixed and every row carries its kind, so the menu can say `agent` or `plugin` instead of
+// leaving the user to infer it. Files are deliberately absent: MSO has no file-mention consumer, and a
+// menu row that inserts a token nothing reads is decoration.
+//
+// Trigger shape follows what opencode proved: `@` opens only at the start of the line or after
+// whitespace, and the query ends at the first whitespace. That is why `/` and `@` never fight for the
+// same token, and why a trailing comma or bracket does not break matching.
+
+const TRIGGER = /(^|\s)@([^\s]*)$/;
+
+/**
+ * Locates an in-progress @ token at the cursor.
+ * @param {string} text whole prompt line
+ * @param {number} cursor caret offset
+ * @returns {{start: number, query: string} | null} start is the index of "@"
+ */
+export function atTrigger(text, cursor = String(text ?? "").length) {
+ const before = String(text ?? "").slice(0, Math.max(0, Math.min(cursor, String(text ?? "").length)));
+ const match = before.match(TRIGGER);
+ if (!match) return null;
+ // A slash command owns the line: `@` inside `/find @foo` must not open this menu.
+ if (/^\s*\//.test(before)) return null;
+ const start = before.length - match[2].length - 1;
+ return { start, query: match[2] };
+}
+
+function online(agent) {
+ return !["offline", "ended"].includes(String(agent?.status ?? "").toLowerCase());
+}
+
+/**
+ * Items for the @ menu.
+ *
+ * Agents come from the live local session directory, so the menu can say whether the target can
+ * actually receive anything. A row that would silently queue is marked, not hidden: hiding it makes the
+ * agent look absent, which is a different and more confusing lie.
+ *
+ * Plugins come from the MCP server list. Per the research, `@` addresses a *server*, never an
+ * individual tool: the model picks tools, the user picks the scope.
+ *
+ * @param {{agents?: Array<any>, mcpServers?: Array<any>}} sources
+ * @param {string} query text after the @
+ * @returns {Array<{text: string, label: string, meta: string, kind: string}>}
+ */
+export function atItems({ agents = [], mcpServers = [] } = {}, query = "") {
+ const wanted = String(query ?? "").toLowerCase();
+ const items = [];
+
+ for (const agent of Array.isArray(agents) ? agents : []) {
+ const id = String(agent?.name || agent?.label || agent?.id || "").trim();
+ if (!id) continue;
+ const live = online(agent);
+ items.push({
+ text: `@${id}`,
+ label: `@${id}`,
+ meta: live ? "agent · live" : "agent · offline, message will queue",
+ kind: "agent",
+ });
+ }
+
+ for (const server of Array.isArray(mcpServers) ? mcpServers : []) {
+ const id = String(server?.name || server?.id || "").trim();
+ if (!id) continue;
+ const count = typeof server?.toolCount === "number" ? server.toolCount : Array.isArray(server?.tools) ? server.tools.length : null;
+ const tools = count === null ? "" : ` · ${count} tool${count === 1 ? "" : "s"}`;
+ items.push({
+ text: `@${id}`,
+ label: `@${id}`,
+ meta: `plugin · mcp${tools}`,
+ kind: "plugin",
+ });
+ }
+
+ const seen = new Set();
+ return items
+ .filter((item) => {
+ if (wanted && !item.text.toLowerCase().includes(wanted)) return false;
+ // Agents win a name collision: addressing a person is the action with a side effect.
+ if (seen.has(item.text)) return false;
+ seen.add(item.text);
+ return true;
+ })
+ .sort((a, b) => (a.kind === b.kind ? a.text.localeCompare(b.text) : a.kind === "agent" ? -1 : 1));
+}
+
+const AGENT_OR_PLUGIN = /@([^\s@]+)/g;
+
+/**
+ * Splits a submitted line into the addresses it carries and the text that remains.
+ *
+ * Unknown tokens are left in the text rather than stripped: `@someone` that matches nothing is a typo or
+ * an agent that has not started yet, and silently deleting it would send a prompt the user did not write.
+ *
+ * @param {string} line submitted prompt
+ * @param {{agents?: Array<any>, mcpServers?: Array<any>}} sources
+ * @returns {{agents: Array<any>, plugins: Array<any>, unknown: string[], text: string}}
+ */
+export function resolveMentions(line, sources = {}) {
+ const known = atItems(sources, "");
+ const byText = new Map(known.map((item) => [item.text.toLowerCase(), item]));
+ const agents = [], plugins = [], unknown = [];
+ const text = String(line ?? "").replace(AGENT_OR_PLUGIN, (whole, token) => {
+ const item = byText.get(`@${token}`.toLowerCase());
+ if (!item) {
+ // Keep it in the prompt, but record it so the caller can say it matched nothing.
+ unknown.push(token);
+ return whole;
+ }
+ if (item.kind === "plugin") { plugins.push({ name: token, item }); return whole; }
+ agents.push({ name: token, item });
+ return whole;
+ });
+ return { agents, plugins, unknown, text };
+}
+
+/**
+ * Applies a completion item to the prompt line.
+ *
+ * A slash command replaces the line because it IS the line. An @ token may sit mid sentence, so it
+ * replaces only itself and keeps the words around it. Kept here, beside the trigger, so the rule is
+ * tested with the parsing that produces it rather than buried in the composer's key handler.
+ *
+ * @param {string} value current prompt
+ * @param {number} cursor caret offset
+ * @param {{text: string, replaceFrom?: number}} item chosen menu row
+ * @returns {{value: string, cursor: number}}
+ */
+export function applyCompletion(value, cursor, item) {
+ const text = String(value ?? "");
+ if (!Number.isInteger(item?.replaceFrom)) {
+ const next = String(item?.text ?? "");
+ return { value: next, cursor: Array.from(next).length };
+ }
+ const next = `${text.slice(0, item.replaceFrom)}${item.text} ${text.slice(cursor).trimStart()}`.trimEnd();
+ // The caret lands right after the inserted token, not at the end of the prompt: the user usually
+ // keeps typing where they were, and jumping to the end would move the cursor out from under them.
+ return { value: next, cursor: Array.from(`${text.slice(0, item.replaceFrom)}${item.text}`).length };
+}
+
+/**
+ * Tool filter for a turn addressed to a plugin.
+ *
+ * The model still chooses which tool to call; @plugin only decides which servers are on the table for
+ * that turn. Naming one server must never grant a tool outside it, so this filters by name prefix and
+ * returns undefined when the turn is unscoped, which the caller reads as "no restriction".
+ *
+ * @param {Array<{name: string}>} plugins servers named by @
+ * @param {Array<any>} tools tools available to the session
+ * @returns {((tool: any) => boolean) | null} predicate, or null when unscoped
+ */
+export function pluginToolFilter(plugins, tools = []) {
+ const names = (Array.isArray(plugins) ? plugins : []).map((p) => String(p?.name ?? p ?? "")).filter(Boolean);
+ if (!names.length) return null;
+ // Only claim a prefix that some tool actually carries. Otherwise @unknown would silently disable
+ // every tool and the turn would fail for a reason nobody could see.
+ const prefixes = names
+ .map((name) => `${name}__`)
+ .filter((prefix) => (Array.isArray(tools) ? tools : []).some((tool) => String(tool?.name ?? "").startsWith(prefix)));
+ if (!prefixes.length) return null;
+ return (tool) => prefixes.some((prefix) => String(tool?.name ?? "").startsWith(prefix));
+}
diff --git a/scripts/mso-agent-at.test.ts b/scripts/mso-agent-at.test.ts
new file mode 100644
index 00000000..d2fbb003
--- /dev/null
+++ b/scripts/mso-agent-at.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it } from "vitest";
+import { atItems, atTrigger, applyCompletion, pluginToolFilter, resolveMentions } from "./mso-agent-at.mjs";
+import { promptCompletion } from "./mso-agent-prompt-completion.mjs";
+
+const agents = [
+ { name: "worker", status: "active", consumerConnected: true },
+ { name: "retired", status: "offline" },
+];
+const mcpServers = [
+ { name: "github", toolCount: 12 },
+ { name: "linear", tools: ["issue_search", "issue_create"] },
+];
+
+describe("@ trigger", () => {
+ it("opens at the start of a line and after whitespace, and not mid word", () => {
+ expect(atTrigger("@wo")).toEqual({ start: 0, query: "wo" });
+ expect(atTrigger("hello @wo")).toEqual({ start: 6, query: "wo" });
+ expect(atTrigger("[email protected]")).toBeNull();
+ });
+
+ it("ends the query at the first space, so trailing prose does not break matching", () => {
+ expect(atTrigger("ask @worker about it", 11)).toEqual({ start: 4, query: "worker" });
+ });
+
+ it("stays closed inside a slash command, because the command owns the line", () => {
+ expect(atTrigger("/find @foo")).toBeNull();
+ expect(atTrigger(" /export @x")).toBeNull();
+ });
+
+ it("returns nothing when there is no @ before the cursor", () => {
+ expect(atTrigger("plain text")).toBeNull();
+ expect(atTrigger("")).toBeNull();
+ });
+});
+
+describe("@ menu items", () => {
+ it("lists agents and plugins together, each labelled with its kind", () => {
+ const items = atItems({ agents, mcpServers });
+ expect(items.map((i) => i.kind)).toEqual(["agent", "agent", "plugin", "plugin"]);
+ expect(items.every((i) => i.text.startsWith("@"))).toBe(true);
+ });
+
+ it("marks an offline agent instead of hiding it, because absent and unreachable differ", () => {
+ const offline = atItems({ agents, mcpServers }).find((i) => i.text === "@retired");
+ expect(offline?.meta).toContain("offline");
+ expect(offline?.meta).toContain("queue");
+ });
+
+ it("counts tools for a plugin from either a number or a list", () => {
+ const items = atItems({ agents: [], mcpServers });
+ expect(items.find((i) => i.text === "@github")?.meta).toContain("12 tools");
+ expect(items.find((i) => i.text === "@linear")?.meta).toContain("2 tools");
+ });
+
+ it("filters by the typed query, case insensitively", () => {
+ expect(atItems({ agents, mcpServers }, "GITH").map((i) => i.text)).toEqual(["@github"]);
+ expect(atItems({ agents, mcpServers }, "zzz")).toEqual([]);
+ });
+
+ it("lets an agent win a name collision, because addressing a person has a side effect", () => {
+ const items = atItems({ agents: [{ name: "github" }], mcpServers: [{ name: "github" }] });
+ expect(items.filter((i) => i.text === "@github")).toHaveLength(1);
+ expect(items[0].kind).toBe("agent");
+ });
+
+ it("survives empty or malformed sources without throwing", () => {
+ expect(atItems()).toEqual([]);
+ expect(atItems({ agents: null as any, mcpServers: undefined })).toEqual([]);
+ expect(atItems({ agents: [{}, { name: "" }], mcpServers: [{}] })).toEqual([]);
+ });
+});
+
+describe("mention resolution", () => {
+ it("separates plugin addresses from agent addresses", () => {
+ const out = resolveMentions("@worker look at @github issues", { agents, mcpServers });
+ expect(out.plugins.map((p) => p.name)).toEqual(["github"]);
+ expect(out.agents.map((a) => a.name)).toEqual(["worker"]);
+ });
+
+ it("keeps an unknown @ in the prompt and reports it, rather than deleting words", () => {
+ const out = resolveMentions("ping @ghost now", { agents, mcpServers });
+ expect(out.unknown).toEqual(["ghost"]);
+ expect(out.text).toBe("ping @ghost now");
+ });
+
+ it("leaves a plain prompt untouched", () => {
+ const out = resolveMentions("no mentions here", { agents, mcpServers });
+ expect(out).toEqual({ agents: [], plugins: [], unknown: [], text: "no mentions here" });
+ });
+});
+
+describe("plugin scoping", () => {
+ const tools = [
+ { name: "github__issue_search" },
+ { name: "github__issue_create" },
+ { name: "linear__issue_search" },
+ { name: "fs_read" },
+ ];
+
+ it("narrows a turn to the named server and nothing else", () => {
+ const filter = pluginToolFilter([{ name: "github" }], tools)!;
+ expect(tools.filter(filter).map((t) => t.name)).toEqual(["github__issue_search", "github__issue_create"]);
+ });
+
+ it("returns no filter when no plugin was named, which reads as unrestricted", () => {
+ expect(pluginToolFilter([], tools)).toBeNull();
+ });
+
+ it("refuses to scope to a name no tool carries, instead of disabling every tool silently", () => {
+ expect(pluginToolFilter([{ name: "unknown" }], tools)).toBeNull();
+ });
+
+ it("allows several plugins in one turn", () => {
+ const filter = pluginToolFilter([{ name: "github" }, { name: "linear" }], tools)!;
+ expect(tools.filter(filter)).toHaveLength(3);
+ });
+});
+
+describe("completion routing", () => {
+ const slash = (line: string) => (line.startsWith("/") ? [{ text: "/help", label: "/help" }] : []);
+
+ it("routes a slash line to commands", () => {
+ const complete = promptCompletion({ slash, sources: () => ({ agents, mcpServers }) });
+ expect(complete("/he")).toEqual([{ text: "/help", label: "/help" }]);
+ });
+
+ it("routes an @ line to the mixed menu, marking where the token begins", () => {
+ const complete = promptCompletion({ slash, sources: () => ({ agents, mcpServers }) });
+ const items = complete("tell @wo");
+ expect(items[0].text).toBe("@worker");
+ expect(items[0].replaceFrom).toBe(5);
+ });
+
+ it("gives no @ items inside a slash command", () => {
+ const complete = promptCompletion({ slash, sources: () => ({ agents, mcpServers }) });
+ // The line is a command, so the slash menu owns it and no @ token is offered.
+ expect(complete("/find @foo").map((i: any) => i.text)).not.toContain("@foo");
+ });
+});
+
+describe("applying a completion", () => {
+ it("treats a slash item as the whole line", () => {
+ expect(applyCompletion("/he", 3, { text: "/help" })).toEqual({ value: "/help", cursor: 5 });
+ });
+
+ it("replaces only the @ token and keeps the surrounding words", () => {
+ expect(applyCompletion("tell @wo about it", 8, { text: "@worker", replaceFrom: 5 })).toEqual({
+ value: "tell @worker about it",
+ cursor: 12,
+ });
+ });
+
+ it("works with an @ token at the start and nothing after it", () => {
+ expect(applyCompletion("@gi", 3, { text: "@github", replaceFrom: 0 })).toEqual({ value: "@github", cursor: 7 });
+ });
+});
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 83433a2c..dc5acd9d 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -2,6 +2,7 @@ import readline from "node:readline";
import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";
import process from "node:process";
import { resumeActiveActivity, suspendActiveActivity } from "./mso-agent-activity.mjs";
+import { applyCompletion } from "./mso-agent-at.mjs";
import { getKeybinds, resolveKeybind } from "./mso-agent-keybinds.mjs";
import { cursorHome, eraseFrame, frameHeight, withCursorHidden, writeFrame } from "./mso-agent-screen.mjs";
import { chars, clamp, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, footerLines, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width } from "./mso-agent-composer-ui.mjs";
@@ -40,19 +41,19 @@ export class AgentComposer {
cursorHome(output, lastCursorRow);
const currentPrompt = promptText(), promptWidth = width(currentPrompt), items = matches();
selected = items.length ? clamp(selected, 0, items.length - 1) : 0;
- const menu = menuLines(items, selected, output.columns, C, panelLabel);
+ const menu = menuLines(items, selected, output.columns, C, typeof panelLabel === "function" ? panelLabel(value) : panelLabel);
const foot = footerLines(footer);
const terminalRows = Math.max(8, Number(output.rows || 24));
const maxInputRows = Math.max(2, Math.min(12, terminalRows - menu.length - foot.length - 4, Math.floor(terminalRows * 0.32)));
const layout = inputLayout(value, cursor, { columns: output.columns, rows: terminalRows, promptWidth, maxRows: maxInputRows });
const continuation = " ".repeat(promptWidth);
const lines = [
- `${currentPrompt}${layout.lines[0] || ""}`,
- ...layout.lines.slice(1).map((row) => `${continuation}${row}`),
- ...menu,
- ...foot,
+ `${currentPrompt}${layout.lines[0] || ""}`, ...layout.lines.slice(1).map((row) => `${continuation}${row}`),
+ ...menu, ...foot,
];
- reserve(Math.max(0, frameHeight(lines) - 1));
+ // Panel mode reports height first: the panel must free the rows before this frame is written,
+ // else it keeps the old height one frame and the menu is drawn clipped under it.
+ if (rowCallback) setRows(lines.length); else reserve(Math.max(0, frameHeight(lines) - 1));
withCursorHidden(output, () => { paintedLines = writeFrame(output, paintedLines, lines); });
setRows(paintedLines.length);
if (layout.cursorRow) output.write(CURSOR_DOWN(layout.cursorRow));
@@ -107,7 +108,8 @@ export class AgentComposer {
};
const apply = (item) => {
if (!item?.text) return;
- value = item.text; cursor = chars(value).length; dismissed = true; selected = 0;
+ ({ value, cursor } = applyCompletion(value, cursor, item));
+ dismissed = true; selected = 0;
render();
};
const historyMove = (dir) => {
diff --git a/scripts/mso-agent-local-directory.mjs b/scripts/mso-agent-local-directory.mjs
new file mode 100644
index 00000000..161f4b3f
--- /dev/null
+++ b/scripts/mso-agent-local-directory.mjs
@@ -0,0 +1,25 @@
+// The live agent directory, kept separate from the command that prints it.
+//
+// The @ menu needs the same rows /agents shows, but it must never await a network call inside a
+// keystroke handler: a menu that stalls while you type is worse than a menu that is one prompt stale.
+// So the caller refreshes this between prompts and the completion source reads the snapshot.
+import { api } from "./mso-agent-api.mjs";
+
+/**
+ * @param {any} session active session, used for its id
+ * @param {{includeOffline?: boolean, request?: any}} [options]
+ * @returns {Promise<Array<any>>} agents, or an empty list when the directory is unreachable
+ */
+export async function listLocalAgents(session, { includeOffline = true, request = api } = {}) {
+ const id = session?.agentSession?.id;
+ if (!id) return [];
+ const query = new URLSearchParams({ session: id });
+ if (includeOffline) query.set("includeOffline", "1");
+ try {
+ const out = await request(`/api/v1/local-agents?${query}`);
+ return Array.isArray(out?.agents) ? out.agents : [];
+ } catch {
+ // A failed directory lookup must not break the prompt: the menu simply offers plugins only.
+ return [];
+ }
+}
diff --git a/scripts/mso-agent-prompt-completion.mjs b/scripts/mso-agent-prompt-completion.mjs
new file mode 100644
index 00000000..cd007155
--- /dev/null
+++ b/scripts/mso-agent-prompt-completion.mjs
@@ -0,0 +1,59 @@
+// Routes the prompt's single completion callback to the right trigger.
+//
+// The composer takes one `complete` function, which is why / and @ have to share it. Routing is decided
+// by position, not by preference: a slash command owns the whole line, so `@` inside `/find @foo`
+// completes nothing rather than trying to address an agent.
+import { atItems, atTrigger } from "./mso-agent-at.mjs";
+import { listLocalAgents } from "./mso-agent-local-directory.mjs";
+import { fetchMcpServers } from "./mso-agent-mcp-servers.mjs";
+
+/**
+ * @param {{ slash?: (line: string) => Array<any>, sources?: () => {agents?: Array<any>, mcpServers?: Array<any>} }} options
+ * @returns {(line: string) => Array<any>}
+ */
+export function promptCompletion({ slash, sources = () => ({}) } = {}) {
+ return (line) => {
+ const text = String(line ?? "");
+ const trigger = atTrigger(text);
+ if (!trigger) return typeof slash === "function" ? slash(text) || [] : [];
+ // A menu item is inserted as the whole token, so the completed text replaces the partial "@qu".
+ const snapshot = sources() || {};
+ return atItems(snapshot, trigger.query).map((item) => ({
+ ...item,
+ // The composer appends the chosen item's text, so the token must already carry its "@".
+ text: item.text,
+ replaceFrom: trigger.start,
+ }));
+ };
+}
+
+/**
+ * Builds the completion callback the composer takes, and the directory refresh that keeps it current.
+ *
+ * Wired here rather than inline in the entrypoint because the entrypoint is at its line ceiling, and
+ * because the two things it owns belong together: what the menu shows, and when that view is refreshed.
+ *
+ * @param {{session: any, recentSessions: () => Array<any>, slashCompletionItems: any}} deps
+ */
+export function createPromptCompletion({ session, recentSessions, slashCompletionItems }) {
+ let directory = [];
+ const complete = promptCompletion({
+ slash: (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session, { settings: true, sessions: recentSessions }),
+ sources: () => ({ agents: directory, mcpServers: session.mcpServers }),
+ });
+ // Once per prompt, before the menu can open: the agent directory is the only source that changes
+ // while the user sits here, and fetching per keystroke would make the menu stutter.
+ // Both sources are refreshed off the keystroke path. MCP servers connect and disconnect during a
+ // session, so a list captured at startup would leave @ offering a plugin that is already gone.
+ complete.refresh = async () => {
+ const [rows, servers] = await Promise.all([
+ listLocalAgents(session).catch(() => []),
+ fetchMcpServers().catch(() => null),
+ ]);
+ directory = rows;
+ if (Array.isArray(servers)) session.mcpServers = servers;
+ };
+ // A menu headed "commands & skills" over a list of agents is a small lie that teaches distrust.
+ complete.label = (v) => (String(v).trimStart().startsWith("/") ? "commands & skills" : "agents & plugins");
+ return complete;
+}
diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjs
index c6ff4db2..14b4bffa 100644
--- a/scripts/mso-agent-screen-loop.mjs
+++ b/scripts/mso-agent-screen-loop.mjs
@@ -67,11 +67,10 @@ export function mountScreenLoop({
const command = createCommandLines();
const setPromptRows = (rows) => {
- // Clamps reservation without repainting immediately; repainting while composer
- // is drawing its draft/menu would erase them before input is completed.
- const termRows = Math.max(6, Number(output.rows) || 24);
- const clamped = clampPromptRows(rows, termRows);
- if (clamped !== promptReservation) promptReservation = clamped;
+ // Repainted at once: the composer writes its frame right after this returns and needs the rows
+ // already freed. The paint leaves the cursor on the row that frame starts at.
+ const clamped = clampPromptRows(rows, Math.max(6, Number(output.rows) || 24));
+ if (clamped !== promptReservation) { promptReservation = clamped; if (output?.isTTY === true) paint(); }
};
if (composer) {
diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjs
index 8da9ab84..f0508aac 100644
--- a/scripts/mso-agent-turn.mjs
+++ b/scripts/mso-agent-turn.mjs
@@ -123,8 +123,9 @@ export async function agentRound(rl, session, skillContext = null, signal = unde
rounds = turn + 1;
// Live row while the first token is in flight: a provider wait reads as work.
activity?.waiting("thinking");
+ const scoped = options.toolFilter ? session.state.tools.filter(options.toolFilter) : session.state.tools;
const result = await turnStream(
- session.history, session.state.tools, session.agentSession, skillContext, signal, session.state.modelMeta?.context, lazyAssistantOutput(session, toolOptions),
+ session.history, scoped, session.agentSession, skillContext, signal, session.state.modelMeta?.context, lazyAssistantOutput(session, toolOptions),
);
// The current model round has consumed all prior read-tool payloads that were
// still inside its projected context. Persist only bounded replay envelopes
@@ -193,7 +194,7 @@ async function persistTurnActive(session, turnStartedAt) {
} catch { /* Bookkeeping write failure should never abort an interactive round. */ }
}
-export async function runInteractiveRound(rl, session, skillContext, interrupts, localBridge = null) {
+export async function runInteractiveRound(rl, session, skillContext, interrupts, localBridge = null, roundOptions = {}) {
const signal = interrupts.beginTurn();
await localBridge?.setState("busy");
let roundResult = null;
@@ -201,7 +202,7 @@ export async function runInteractiveRound(rl, session, skillContext, interrupts,
// Persist turn start timestamp so session list reflects active work immediately.
await persistTurnActive(session, new Date().toISOString());
try {
- roundResult = await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent(), { print });
+ roundResult = await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent(), { print, ...roundOptions });
} catch (error) {
if (signal.aborted || isAbortError(error)) print(`${C.dim}turn interrupted.${C.reset}`);
else {
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 15a92674..3ed207ab 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -8,6 +8,7 @@ import { C, printBanner } from "./mso-agent-runtime.mjs";
import { listCliSessions, state } from "./mso-agent-api.mjs";
import { fetchMcpServers } from "./mso-agent-mcp-servers.mjs";
import { handleSlash } from "./mso-agent-commands.mjs";
+import { createPromptCompletion } from "./mso-agent-prompt-completion.mjs"; import { pluginToolFilter, resolveMentions } from "./mso-agent-at.mjs";
import { nextPermissionMode, permissionMode } from "./mso-agent-permissions.mjs";
import { consumeRestartUiState, relaunchCurrentAgentSession } from "./mso-agent-lifecycle.mjs";
import { oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";
@@ -137,7 +138,7 @@ async function main() {
else if (action === "interrupt") rl.cancelCurrent({ echo: false });
};
process.on("SIGINT", onSigint);
- const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session, { settings: true, sessions: () => recentSessions });
+ const completeSlash = createPromptCompletion({ session, recentSessions: () => recentSessions, slashCompletionItems });
while (true) {
if (interrupts.exitRequested) break;
if (inboundRequestQueued) {
@@ -148,9 +149,9 @@ async function main() {
}
let line = "";
try {
- screenLoop.paint();
+ screenLoop.paint(); await completeSlash.refresh();
const answer = await rl.question(() => composerPrompt(session, C), {
- complete: completeSlash,
+ complete: completeSlash, panelLabel: completeSlash.label,
onTab: () => { session.permission = nextPermissionMode(session.permission).id; },
// The panel already draws the separator and the footer above the prompt, so drawing
// them twice would push the prompt off the reserved rows.
@@ -185,8 +186,7 @@ async function main() {
continue;
}
if (await handleLocalAgentMentionInput(session, line, C)) { screenLoop.sync(); continue; }
- // Attached images belong to the NEXT prompt only. Format them into the user
- // message once, then clear, so a stale image can never ride along silently.
+ // Images belong to this prompt only: format once then clear, so a stale one never rides along.
const images = Array.isArray(session.pendingImages) ? session.pendingImages : [];
const imageBlock = images.length ? pendingImageBlock(images) : "";
session.history.push({ role: "user", text: imageBlock ? `${imageBlock}${line}` : line });
@@ -194,7 +194,8 @@ async function main() {
const skillContext = session.pendingSkill;
session.pendingSkill = null;
screenLoop.sync();
- await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);
+ const tools = pluginToolFilter(resolveMentions(line, { mcpServers: session.mcpServers }).plugins, session.state.tools);
+ await runInteractiveRound(rl, session, skillContext, interrupts, localBridge, { toolFilter: tools });
screenLoop.sync();
if (interrupts.exitRequested) break;
if (!lastTurnInterrupted) await drainQueue();
@@ -215,5 +216,4 @@ async function main() {
}
}
-const direct = Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
-if (direct) main().catch((error) => { console.error(`${C.err}mso agent: ${error instanceof Error ? error.message : String(error)}${C.reset}`); process.exit(1); });
+if (Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href) main().catch((error) => { console.error(`${C.err}mso agent: ${error instanceof Error ? error.message : String(error)}${C.reset}`); process.exit(1); });