Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(agent): add interrupt-safe terminal controls

Rahman3f2698852c68
diff --git a/README.md b/README.md
index 734ddc37..c12ceb13 100644
--- a/README.md
+++ b/README.md
@@ -211,7 +211,14 @@ Interactive model/provider menus use a native picker: **↑/↓** moves, typing
selects, and **Esc** cancels. No provider/model number has to be memorized. In the Agent slash
palette, executable skills carry lifecycle markers so their state is visible before and after use:
`◇ ready` → `◆ queued` (selected for the next message) → `✓ invoked` (actually sent with a model turn).
-The compact status line mirrors queued/invoked skill state.
+The compact status line mirrors queued/invoked skill state. 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 input history; **Ctrl+A/E** and **Ctrl+B/F** move to line boundaries or one
+character. `/quit` is an alias for `/exit`. An interrupted turn is removed from durable conversation
+history so `--continue` never resumes a half-turn. Server-side jobs that were already created retain
+their own bounded job/cancel lifecycle.
If it explicitly says the current shell cannot see the user launcher yet, run the one-line
`export PATH="$HOME/.local/bin:$PATH"` it prints; new shells use the persisted profile entry.
diff --git a/bin/mso b/bin/mso
index 516af1c4..437e12cb 100755
--- a/bin/mso
+++ b/bin/mso
@@ -126,7 +126,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.5.6"
+VERSION="1.5.7"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index c77ff470..310103f6 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `agent` add interrupt-safe terminal controls
- `agent` add arrow picker and skill states
- `agent` align model and session terminal UX
- `install` make upgrades agent-friendly
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index b5f46cf2..a868a74a 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -154,7 +154,11 @@ After an AI provider is connected, bare `mso` launches the interactive MSO Agent
uses the canonical MCP tool catalog internally: reads run directly, while write/exec calls
pause for terminal approval. Skill lifecycle is explicit in the slash palette and status line:
`◇ ready` means discoverable/executable, `◆ queued` means selected for the next user message,
-and `✓ invoked` means the skill instructions were actually attached to a model turn. See
+and `✓ invoked` means the skill instructions were actually attached to a model turn. The terminal
+composer also follows conventional controls: Ctrl+C clears a draft, exits an empty prompt, or interrupts
+an active turn; Ctrl+D deletes right/exits on empty; Ctrl+L clears the screen; Ctrl+W deletes the previous
+word; ↑/↓ or Ctrl+P/N browse history; Ctrl+A/E and Ctrl+B/F navigate the line. `/quit` aliases `/exit`.
+Interrupted model/tool turns are rolled back from durable CLI history before the session is saved. See
[`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md) for the deployment/provider boundary.
### WSL2
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 9f8a6b5f..edfdc38f 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,14 @@
Running log of what shipped each phase. Newest at top.
+## 2026-09-01 — Agent terminal control semantics + interrupt-safe history — SHIPPED
+
+MSO Agent 1.5.7 aligns terminal control behavior with mature agent harnesses. Ctrl+C now clears a non-empty draft, exits cleanly from an empty idle prompt, and aborts an active assistant/tool HTTP turn through a real `AbortController`; a quick second Ctrl+C while a turn is still stopping requests exit. Ctrl+D follows readline semantics (delete-right with text, EOF exit when empty), Ctrl+L clears/repaints, Ctrl+W deletes the previous word, Ctrl+P/N mirror history ↑/↓, and Ctrl+A/E plus Ctrl+B/F provide standard line navigation. `/quit` is now an explicit `/exit` alias.
+
+Interrupt state is split from the composer so raw-mode key handling and cooked-mode OS SIGINT cannot fight each other. Ctrl+C inside approval cancels and aborts the active turn, while Ctrl+C/Esc inside `/model`, `/models`, and `/resume` pickers cancels only that foreground picker. Assistant and agent-tool fetches receive the same turn AbortSignal. If a turn is interrupted, all user/assistant/tool history rows created by that unfinished round are rolled back before persistence; provider token usage already consumed may still be counted, but `mso --continue` never resumes a half-turn. Server-side bounded jobs already created keep their explicit job/cancel lifecycle.
+
+Regression coverage includes empty/draft Ctrl+C, active-turn double interrupt state, AbortSignal propagation to the assistant fetch, Ctrl+D/W/L/B/F/P/N editing, `/quit`, slash catalog parity, and zero-warning modularity for the new control files. Real PTY smoke covers clean idle Ctrl+C/D exits, Ctrl+L repaint, draft-clear→exit, history recall, `/resume` cancel, both stages of `/model` cancel, `/models` cancel, and a real Codex turn interrupted back to a live prompt with `historyTurns: 0`. Final repository verification passes **265 test files / 1,953 tests**, with 1 expected-fail and 7 skipped; typecheck, docs, dependency cycles and high/critical audit are clean, and the only lint findings are the six pre-existing `max-lines` warnings outside this change.
+
## 2026-09-01 — Arrow-key model/provider picker + visible skill lifecycle — SHIPPED
MSO Agent 1.5.6 removes the last numeric prompt from the AI provider/model interaction path. `mso model`, the no-argument `mso models` manager, provider connect/remove selection, and catalog-provider selection now share one dependency-free native TTY picker. The current provider/model is preselected, ↑/↓ redraw in place with zero added newline scrollback, typing filters candidates, Enter selects, and Esc cancels. Direct scriptable forms such as `mso model openai-codex/gpt-5.6-terra` and `mso models add openrouter` remain unchanged.
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
new file mode 100644
index 00000000..75497d67
--- /dev/null
+++ b/scripts/mso-agent-commands.mjs
@@ -0,0 +1,107 @@
+import { spawnSync } from "node:child_process";
+import process from "node:process";
+import { C, BASE, CLI, api, listCliSessions, state } from "./mso-agent-runtime.mjs";
+import { loadSlashSkill, printSkillChoices, printSkills, resolveSlashSkill } from "./mso-agent-skills.mjs";
+import { persistSession, printSessions, resumeInto, resumePicker } from "./mso-agent-session-ui.mjs";
+import { printDetailedStatus } from "./mso-agent-status.mjs";
+
+function runCli(args) {
+ const result = spawnSync(CLI, args, { stdio: "inherit", env: { ...process.env, MSO_BASE: BASE } });
+ if (result.error) console.error(`${C.err}${result.error.message}${C.reset}`);
+ return result.status ?? 1;
+}
+
+async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
+ const resolved = resolveSlashSkill(session.state.skills, requested, process.cwd());
+ if (!resolved.skill) {
+ printSkillChoices(resolved.ambiguous, C);
+ return resolved.ambiguous?.length ? "handled" : "unknown";
+ }
+ const loaded = await loadSlashSkill(api, session.agentSession.id, resolved.skill);
+ const scope = loaded.project?.name ? `project ${loaded.project.name}` : "global";
+ if (!prompt.trim()) {
+ session.pendingSkill = loaded;
+ console.log(`${C.warn}${C.bold}◆ /${loaded.name} queued${C.reset}${C.dim} · next message · ${scope}${C.reset}`);
+ return "handled";
+ }
+ session.history.push({ role: "user", text: prompt.trim() });
+ if (session.history.length > 48) session.history.splice(0, session.history.length - 48);
+ await runTurn(loaded);
+ return "handled";
+}
+
+function printHelp() {
+ console.log([
+ " /session show current durable MSO session id",
+ " /sessions list recent resumable sessions",
+ " /resume [query] resume latest/index/id/title; no arg opens picker",
+ " /title <name> rename the durable session",
+ " /status model/auth/context/token/session details",
+ " /context alias for /status",
+ " /statusbar [on|off] toggle compact dynamic status line",
+ " /models [args] configure AI providers/auth",
+ " /model [ref] select active model from connected providers",
+ " /setup full MSO onboarding",
+ " /providers infrastructure provider status",
+ " /provider <id> configure dokploy|cloudflare|hostinger",
+ " /doctor run mso doctor",
+ " /tools list agent tools",
+ " /skills [query] browse available slash skills",
+ " /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
+ " /<skill> [prompt] select for next message, or run prompt now",
+ " /clear clear this session conversation",
+ " /exit, /quit quit",
+ "",
+ "Keyboard",
+ " Ctrl+C clear input; empty prompt exits; active turn interrupts",
+ " Ctrl+D delete right; empty prompt exits",
+ " Ctrl+L clear/repaint terminal",
+ " Ctrl+W delete previous word",
+ " ↑/↓ or Ctrl+P/N command history",
+ " Ctrl+A/E · Ctrl+B/F line start/end · left/right",
+ ].join("\n"));
+}
+
+export async function handleSlash(rl, line, session, { runTurn }) {
+ const [cmd, ...args] = line.trim().split(/\s+/);
+ switch (cmd) {
+ case "/help": printHelp(); return "handled";
+ case "/session":
+ console.log(`${C.blue}${session.agentSession.id}${C.reset} · ${session.agentSession.title || "MSO Agent session"}`); return "handled";
+ case "/sessions":
+ printSessions(await listCliSessions(50)); return "handled";
+ case "/resume":
+ if (!args.length) await resumePicker(rl, session); else await resumeInto(session, args.join(" "));
+ return "refresh";
+ case "/title": {
+ const title = args.join(" ").trim();
+ if (!title) console.log("usage: /title <session name>");
+ else { session.titleOverride = title.slice(0, 120); await persistSession(session); console.log(`${C.c}✓ session title: ${session.titleOverride}${C.reset}`); }
+ return "handled";
+ }
+ case "/status": case "/context": printDetailedStatus(session, C); return "handled";
+ case "/statusbar": {
+ const value = String(args[0] || "").toLowerCase();
+ if (value === "off") session.statusBar = false; else if (value === "on") session.statusBar = true; else session.statusBar = !session.statusBar;
+ console.log(`status bar ${session.statusBar ? "on" : "off"}`); return "handled";
+ }
+ case "/models": runCli(["models", ...args]); session.state = await state(); return "refresh";
+ case "/model": runCli(["model", ...args]); session.state = await state(); return "refresh";
+ case "/setup": runCli(["onboard"]); session.state = await state(); return "refresh";
+ case "/providers": runCli(["provider", "list"]); session.state = await state(); return "refresh";
+ case "/provider":
+ if (!args[0]) console.log("usage: /provider dokploy|cloudflare|hostinger"); else runCli(["provider", "set", args[0]]);
+ session.state = await state(); return "refresh";
+ case "/doctor": runCli(["doctor"]); return "handled";
+ case "/tools": for (const tool of session.state.tools) console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`); return "handled";
+ case "/skills": printSkills(session, C, args.join(" ")); return "handled";
+ case "/skill":
+ if (!args[0]) { console.log("usage: /skill <name-or-exact-id> [prompt]"); return "handled"; }
+ return selectSlashSkill(rl, session, args[0], args.slice(1).join(" "), runTurn);
+ case "/clear":
+ Object.assign(session, { history: [], pendingSkill: null, activeSkill: null, lastInvokedSkill: null });
+ await persistSession(session); console.log("conversation cleared."); return "handled";
+ case "/exit": case "/quit": return "exit";
+ default: return selectSlashSkill(rl, session, cmd.slice(1), args.join(" "), runTurn);
+ }
+}
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 5ff0f8ed..416f4cbf 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -5,11 +5,28 @@ const CLEAR_LINE = "\x1b[2K";
const CURSOR_UP = (n) => n > 0 ? `\x1b[${n}A` : "";
const CURSOR_DOWN = (n) => n > 0 ? `\x1b[${n}B` : "";
const CURSOR_RIGHT = (n) => n > 0 ? `\x1b[${n}C` : "";
+const CLEAR_SCREEN = "\x1b[2J\x1b[H";
const plain = (value) => String(value ?? "").replace(/\x1b\[[0-9;]*m/g, "");
const chars = (value) => Array.from(String(value ?? ""));
const width = (value) => chars(plain(value)).length;
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
+export function wordLeftIndex(value, cursor) {
+ const row = chars(value);
+ let index = clamp(cursor, 0, row.length);
+ while (index > 0 && /\s/u.test(row[index - 1])) index--;
+ while (index > 0 && !/\s/u.test(row[index - 1])) index--;
+ return index;
+}
+
+export function wordRightIndex(value, cursor) {
+ const row = chars(value);
+ let index = clamp(cursor, 0, row.length);
+ while (index < row.length && /\s/u.test(row[index])) index++;
+ while (index < row.length && !/\s/u.test(row[index])) index++;
+ return index;
+}
+
function fit(value, max) {
const row = chars(plain(value).replace(/[\r\n\t]+/g, " "));
if (row.length <= max) return row.join("");
@@ -81,7 +98,7 @@ export class AgentComposer {
readline.emitKeypressEvents(this.input);
}
- async question(prompt, { complete = null, history = true } = {}) {
+ async question(prompt, { complete = null, history = true, onCancel = null } = {}) {
if (this.closed) return null;
const input = this.input, output = this.output, C = this.C;
return new Promise((resolve) => {
@@ -152,10 +169,13 @@ export class AgentComposer {
};
const onKey = (str, key = {}) => {
const items = matches();
- if (key.ctrl && key.name === "d" && !value) return finish(null, false);
if (key.ctrl && key.name === "c") {
if (value) return edit("", 0);
- erase(); output.write("^C\r\n"); cleanup(); return resolve("");
+ if (typeof onCancel === "function") onCancel();
+ erase(); output.write("^C\r\n"); cleanup(); return resolve(null);
+ }
+ if (key.ctrl && key.name === "l") {
+ output.write(CLEAR_SCREEN); reservedMenuRows = 0; return render();
}
if (key.name === "escape") { dismissed = true; selected = 0; return render(); }
if (items.length && (key.name === "up" || key.name === "down")) {
@@ -171,15 +191,26 @@ export class AgentComposer {
if (items.length && items[selected]?.text) return apply(items[selected]);
return finish(value);
}
- if (key.name === "up" && !items.length) return historyMove(-1);
- if (key.name === "down" && !items.length) return historyMove(1);
+ 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);
- if (key.name === "left") { cursor = Math.max(0, cursor - 1); return render(); }
- if (key.name === "right") { cursor = Math.min(row.length, cursor + 1); return render(); }
+ if (key.ctrl && key.name === "d") {
+ if (!value) return finish(null, false);
+ 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.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") {
+ const start = wordLeftIndex(value, cursor);
+ return edit([...row.slice(0, start), ...row.slice(cursor)].join(""), start);
+ }
if (key.ctrl && key.name === "u") return edit(row.slice(cursor).join(""), 0);
if (key.ctrl && key.name === "k") return edit(row.slice(0, cursor).join(""), cursor);
if (str && !key.ctrl && !key.meta && !/[\u0000-\u001f\u007f]/u.test(str)) {
diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.ts
index fef3e31b..f2b1664f 100644
--- a/scripts/mso-agent-composer.test.ts
+++ b/scripts/mso-agent-composer.test.ts
@@ -107,4 +107,71 @@ describe("MSO Agent interactive composer primitives", () => {
await answer; composer.close();
});
+
+ it("exits on Ctrl+C at an empty prompt but only clears when text exists", async () => {
+ class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }
+ class FakeOutput { columns = 88; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }
+ const colors = { blue: "", bold: "", reset: "", dim: "" };
+
+ const input1 = new FakeInput(); const output1 = new FakeOutput();
+ const composer1 = new AgentComposer({ input: input1 as never, output: output1 as never, colors });
+ const empty = composer1.question("› ");
+ input1.emit("keypress", undefined, { ctrl: true, name: "c", sequence: "\u0003" });
+ await expect(empty).resolves.toBeNull();
+ expect(input1.isRaw).toBe(false);
+ composer1.close();
+
+ const input2 = new FakeInput(); const output2 = new FakeOutput();
+ const composer2 = new AgentComposer({ input: input2 as never, output: output2 as never, colors });
+ const edited = composer2.question("› ");
+ for (const ch of "draft") input2.emit("keypress", ch, { name: ch, sequence: ch });
+ input2.emit("keypress", undefined, { ctrl: true, name: "c", sequence: "\u0003" });
+ for (const ch of "kept") input2.emit("keypress", ch, { name: ch, sequence: ch });
+ input2.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(edited).resolves.toBe("kept");
+ composer2.close();
+ });
+
+ it("matches readline Ctrl+D, Ctrl+W, Ctrl+L and Ctrl+B/F editing behavior", async () => {
+ class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }
+ class FakeOutput { columns = 88; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }
+ const input = new FakeInput(); const output = new FakeOutput();
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors: { blue: "", bold: "", reset: "", dim: "" } });
+ const answer = composer.question("› ");
+ for (const ch of "hello world") input.emit("keypress", ch, { name: ch, sequence: ch });
+ input.emit("keypress", undefined, { ctrl: true, name: "w", sequence: "\u0017" });
+ input.emit("keypress", undefined, { ctrl: true, name: "b", sequence: "\u0002" });
+ input.emit("keypress", undefined, { ctrl: true, name: "d", sequence: "\u0004" });
+ input.emit("keypress", undefined, { ctrl: true, name: "f", sequence: "\u0006" });
+ const beforeClear = output.chunks.length;
+ input.emit("keypress", undefined, { ctrl: true, name: "l", sequence: "\u000c" });
+ expect(output.chunks.slice(beforeClear).join("")).toContain("\x1b[2J\x1b[H");
+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(answer).resolves.toBe("hello");
+ composer.close();
+ });
+
+ it("uses Ctrl+P/N as history aliases and Ctrl+D exits an empty prompt", async () => {
+ class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }
+ class FakeOutput { columns = 88; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }
+ const input = new FakeInput(); const output = new FakeOutput();
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors: { blue: "", bold: "", reset: "", dim: "" } });
+ const first = composer.question("› ");
+ for (const ch of "first") input.emit("keypress", ch, { name: ch, sequence: ch });
+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(first).resolves.toBe("first");
+
+ const second = composer.question("› ");
+ input.emit("keypress", undefined, { ctrl: true, name: "p", sequence: "\u0010" });
+ input.emit("keypress", undefined, { ctrl: true, name: "n", sequence: "\u000e" });
+ input.emit("keypress", undefined, { ctrl: true, name: "p", sequence: "\u0010" });
+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });
+ await expect(second).resolves.toBe("first");
+
+ const eof = composer.question("› ");
+ input.emit("keypress", undefined, { ctrl: true, name: "d", sequence: "\u0004" });
+ await expect(eof).resolves.toBeNull();
+ composer.close();
+ });
+
});
diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.ts
index 43fd9df2..d39f86b6 100644
--- a/scripts/mso-agent-contract.test.ts
+++ b/scripts/mso-agent-contract.test.ts
@@ -31,7 +31,7 @@ describe("MSO terminal agent contract", () => {
for (const command of [
"/models", "/model", "/status", "/context", "/statusbar", "/title",
"/session", "/sessions", "/resume", "/setup", "/providers", "/provider",
- "/doctor", "/tools", "/skills", "/skill", "/<skill>", "/clear", "/exit",
+ "/doctor", "/tools", "/skills", "/skill", "/<skill>", "/clear", "/exit", "/quit",
]) expect(src).toContain(command);
expect(src).toContain("Configure AI providers and authentication");
expect(src).toContain("Select the active model from connected providers");
diff --git a/scripts/mso-agent-interrupt.mjs b/scripts/mso-agent-interrupt.mjs
new file mode 100644
index 00000000..2558ed22
--- /dev/null
+++ b/scripts/mso-agent-interrupt.mjs
@@ -0,0 +1,65 @@
+import process from "node:process";
+
+export function makeAbortError(message = "MSO Agent turn interrupted") {
+ const error = new Error(message);
+ error.name = "AbortError";
+ return error;
+}
+
+export function isAbortError(error) {
+ return Boolean(error && (error.name === "AbortError" || error.code === "ABORT_ERR"));
+}
+
+export class AgentInterruptManager {
+ constructor({ output = process.stdout, colors = {}, now = () => Date.now(), forceWindowMs = 2000 } = {}) {
+ this.output = output;
+ this.C = colors;
+ this.now = now;
+ this.forceWindowMs = forceWindowMs;
+ this.controller = null;
+ this.lastInterruptAt = 0;
+ this.exitRequested = false;
+ }
+
+ beginTurn() {
+ const controller = new AbortController();
+ this.controller = controller;
+ this.lastInterruptAt = 0;
+ return controller.signal;
+ }
+
+ endTurn(signal) {
+ if (this.controller?.signal === signal) this.controller = null;
+ this.lastInterruptAt = 0;
+ }
+
+ interruptCurrent() {
+ if (!this.controller || this.controller.signal.aborted) return false;
+ const C = this.C;
+ this.lastInterruptAt = this.now();
+ this.output.write(`\n${C.warn || ""}⚡ interrupting turn…${C.reset || ""}${C.dim || ""} Ctrl+C again to exit${C.reset || ""}\n`);
+ this.controller.abort(makeAbortError());
+ return true;
+ }
+
+ handleSigint() {
+ const C = this.C;
+ const now = this.now();
+ if (this.controller) {
+ if (!this.controller.signal.aborted) {
+ this.interruptCurrent();
+ return "interrupt";
+ }
+ if (now - this.lastInterruptAt <= this.forceWindowMs) {
+ this.exitRequested = true;
+ this.output.write(`\n${C.warn || ""}⚡ exiting MSO Agent…${C.reset || ""}\n`);
+ return "exit";
+ }
+ this.lastInterruptAt = now;
+ this.output.write(`\n${C.warn || ""}⚡ turn is still stopping…${C.reset || ""}${C.dim || ""} Ctrl+C again to exit${C.reset || ""}\n`);
+ return "interrupt";
+ }
+ this.exitRequested = true;
+ return "exit";
+ }
+}
diff --git a/scripts/mso-agent-interrupt.test.ts b/scripts/mso-agent-interrupt.test.ts
new file mode 100644
index 00000000..5c0d6ede
--- /dev/null
+++ b/scripts/mso-agent-interrupt.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { AgentInterruptManager, isAbortError, makeAbortError } from "./mso-agent-interrupt.mjs";
+
+describe("MSO Agent interrupt semantics", () => {
+ it("aborts an active turn on first Ctrl+C and requests exit on a quick second press", () => {
+ const chunks: string[] = [];
+ let now = 1000;
+ const manager = new AgentInterruptManager({
+ output: { write: (value: string) => { chunks.push(value); return true; } } as never,
+ colors: { warn: "", reset: "", dim: "" },
+ now: () => now,
+ });
+ const signal = manager.beginTurn();
+ expect(manager.handleSigint()).toBe("interrupt");
+ expect(signal.aborted).toBe(true);
+ expect(isAbortError(signal.reason)).toBe(true);
+ expect(manager.exitRequested).toBe(false);
+ now += 500;
+ expect(manager.handleSigint()).toBe("exit");
+ expect(manager.exitRequested).toBe(true);
+ expect(chunks.join("")).toContain("interrupting turn");
+ });
+
+ it("requests a clean exit when SIGINT arrives outside an active turn", () => {
+ const manager = new AgentInterruptManager({ output: { write: () => true } as never });
+ expect(manager.handleSigint()).toBe("exit");
+ expect(manager.exitRequested).toBe(true);
+ });
+
+ it("recognizes explicit abort errors", () => {
+ expect(isAbortError(makeAbortError())).toBe(true);
+ expect(isAbortError(new Error("ordinary"))).toBe(false);
+ });
+});
diff --git a/scripts/mso-agent-runtime-interrupt.test.ts b/scripts/mso-agent-runtime-interrupt.test.ts
new file mode 100644
index 00000000..4a05f6f3
--- /dev/null
+++ b/scripts/mso-agent-runtime-interrupt.test.ts
@@ -0,0 +1,20 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { makeAbortError } from "./mso-agent-interrupt.mjs";
+import { streamTurn } from "./mso-agent-runtime.mjs";
+
+const originalFetch = globalThis.fetch;
+afterEach(() => { globalThis.fetch = originalFetch; vi.restoreAllMocks(); });
+
+describe("MSO Agent assistant stream cancellation", () => {
+ it("passes the turn AbortSignal into the assistant fetch", async () => {
+ globalThis.fetch = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
+ const signal = init?.signal;
+ if (!signal) return reject(new Error("missing AbortSignal"));
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
+ })) as typeof fetch;
+ const controller = new AbortController();
+ const pending = streamTurn([], [], { id: "session-test", memorySnapshot: {} }, null, controller.signal);
+ controller.abort(makeAbortError("test interrupt"));
+ await expect(pending).rejects.toMatchObject({ name: "AbortError", message: "test interrupt" });
+ });
+});
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
index 657dd8aa..8c4ab117 100644
--- a/scripts/mso-agent-runtime.mjs
+++ b/scripts/mso-agent-runtime.mjs
@@ -105,11 +105,19 @@ function toolForModel(tool) {
return { name: tool.name, description: tool.description, input_schema: tool.inputSchema || { type: "object", properties: {} } };
}
-export async function streamTurn(messages, tools, agentSession, skillContext = null) {
+/**
+ * @param {Array<any>} messages
+ * @param {Array<any>} tools
+ * @param {any} agentSession
+ * @param {any} [skillContext]
+ * @param {AbortSignal | undefined} [signal]
+ */
+export async function streamTurn(messages, tools, agentSession, skillContext = null, signal = undefined) {
const res = await fetch(`${BASE}/api/assistant`, {
method: "POST",
headers: { origin: ORIGIN, cookie: cookieHeader(), "content-type": "application/json" },
body: JSON.stringify({ messages, tools: tools.map(toolForModel), system: sessionSystem(agentSession, skillContext) }),
+ signal,
});
if (!res.ok || !res.body) {
let body = {}; try { body = await res.json(); } catch {}
diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjs
index 6c01cb29..7b6bfc3a 100644
--- a/scripts/mso-agent-slash.mjs
+++ b/scripts/mso-agent-slash.mjs
@@ -21,6 +21,7 @@ export const BUILTIN_SLASH_ITEMS = [
{ text: "/skill", meta: "Select a skill by exact catalog id", kind: "command" },
{ text: "/clear", meta: "Clear this session conversation", kind: "command" },
{ text: "/exit", meta: "Exit MSO Agent", kind: "command" },
+ { text: "/quit", meta: "Alias for /exit", kind: "command" },
];
function skillItem(skillsData, name, cwd, session) {
diff --git a/scripts/mso-agent-slash.test.ts b/scripts/mso-agent-slash.test.ts
index be194cec..9f0feb6d 100644
--- a/scripts/mso-agent-slash.test.ts
+++ b/scripts/mso-agent-slash.test.ts
@@ -15,6 +15,7 @@ describe("MSO Agent slash completion catalog", () => {
const rows = slashCompletionItems(skills, "/", "/home/rahman");
expect(rows[0]).toMatchObject({ text: "/help", kind: "command" });
expect(rows.map((row) => row.text)).toContain("/design");
+ expect(rows.map((row) => row.text)).toContain("/quit");
expect(rows.map((row) => row.text)).not.toContain("/unsafe");
});
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 1fcfa50f..369af624 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -1,17 +1,16 @@
#!/usr/bin/env node
-import { spawnSync } from "node:child_process";
import process from "node:process";
import { canonicalAgentApproval } from "../lib/agent/approval.mjs";
-import { beginSkillInvocation, endSkillInvocation, loadSlashSkill, printSkillChoices, printSkills, resolveSlashSkill } from "./mso-agent-skills.mjs";
+import { beginSkillInvocation, endSkillInvocation } from "./mso-agent-skills.mjs";
import { AgentComposer } from "./mso-agent-composer.mjs";
+import { AgentInterruptManager, isAbortError } from "./mso-agent-interrupt.mjs";
import { slashCompletionItems } from "./mso-agent-slash.mjs";
-import { addUsage, printDetailedStatus, renderStatusBar } from "./mso-agent-status.mjs";
-import { persistSession, printSessions, resumeArg, resumeInto, resumePicker, startupSession } from "./mso-agent-session-ui.mjs";
-import {
- BASE, CLI, C, api, listCliSessions, printBanner, state, streamTurn,
-} from "./mso-agent-runtime.mjs";
+import { addUsage, renderStatusBar } from "./mso-agent-status.mjs";
+import { persistSession, resumeArg, startupSession } from "./mso-agent-session-ui.mjs";
+import { C, api, printBanner, state, streamTurn } from "./mso-agent-runtime.mjs";
+import { handleSlash } from "./mso-agent-commands.mjs";
-async function executeTool(rl, tool, call, agentSession) {
+async function executeTool(rl, tool, call, agentSession, signal = undefined, onInterrupt = null) {
if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };
let approved = tool.scope === "read";
let approval = null;
@@ -24,7 +23,8 @@ async function executeTool(rl, tool, call, agentSession) {
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 }) ?? "").trim().toLowerCase();
+ 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;
}
if (!approved) return { ok: false, result: "denied by user" };
@@ -39,21 +39,25 @@ async function executeTool(rl, tool, call, agentSession) {
sessionId: agentSession.id,
...(tool.scope === "read" ? {} : { approved: true, approvalDigest: approval.digest }),
}),
+ signal,
});
process.stdout.write(`\r${C.c} ✓ ${tool.name}${C.reset}\n`);
if (!out.ok) return { ok: false, result: out.result || "tool failed" };
return { ok: true, result: String(out.result ?? "ok") };
} catch (error) {
+ if (signal?.aborted || isAbortError(error)) throw error;
process.stdout.write(`\r${C.err} ✗ ${tool.name}${C.reset}\n`);
return { ok: false, result: (error instanceof Error ? error.message : String(error)).slice(0, 2000) };
}
}
-async function agentRound(rl, session, skillContext = null) {
- const startedAt = Date.now(); beginSkillInvocation(session, skillContext, C);
+async function agentRound(rl, session, skillContext = null, signal = undefined, onInterrupt = null) {
+ const startedAt = Date.now();
+ const historyCheckpoint = Math.max(0, session.history.length - 1);
+ beginSkillInvocation(session, skillContext, C);
try {
for (let turn = 0; turn < 10; turn++) {
- const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext); if (skillContext) session.lastInvokedSkill = skillContext;
+ const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext, signal); if (skillContext) session.lastInvokedSkill = skillContext;
session.usage = addUsage(session.usage, result.usage);
session.lastElapsedMs = Date.now() - startedAt;
session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });
@@ -61,103 +65,34 @@ async function agentRound(rl, session, skillContext = null) {
const results = [];
for (const call of result.toolUses) {
const tool = session.state.tools.find((row) => row.name === call.name);
- const outcome = await executeTool(rl, tool, call, session.agentSession);
+ const outcome = await executeTool(rl, tool, call, session.agentSession, signal, onInterrupt);
results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });
}
session.history.push({ role: "tool", results });
}
console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);
+ } catch (error) {
+ if (signal?.aborted || isAbortError(error)) session.history.splice(historyCheckpoint);
+ throw error;
} finally {
endSkillInvocation(session, skillContext);
}
}
-function runCli(args) {
- const r = spawnSync(CLI, args, { stdio: "inherit", env: { ...process.env, MSO_BASE: BASE } });
- if (r.error) console.error(`${C.err}${r.error.message}${C.reset}`);
- return r.status ?? 1;
-}
-
-async function selectSlashSkill(rl, session, requested, prompt = "") {
- const resolved = resolveSlashSkill(session.state.skills, requested, process.cwd());
- if (!resolved.skill) {
- printSkillChoices(resolved.ambiguous, C);
- return resolved.ambiguous?.length ? "handled" : "unknown";
- }
- const loaded = await loadSlashSkill(api, session.agentSession.id, resolved.skill);
- const scope = loaded.project?.name ? `project ${loaded.project.name}` : "global";
- if (!prompt.trim()) {
- session.pendingSkill = loaded;
- console.log(`${C.warn}${C.bold}◆ /${loaded.name} queued${C.reset}${C.dim} · next message · ${scope}${C.reset}`);
- return "handled";
+async function runInteractiveRound(rl, session, skillContext, interrupts) {
+ const signal = interrupts.beginTurn();
+ try {
+ await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent());
+ await persistSession(session);
+ } catch (error) {
+ if (signal.aborted || isAbortError(error)) console.log(`${C.dim}turn interrupted.${C.reset}`);
+ else console.error(`${C.err}agent error: ${error instanceof Error ? error.message : String(error)}${C.reset}`);
+ await persistSession(session).catch(() => undefined);
+ } finally {
+ interrupts.endTurn(signal);
}
- session.history.push({ role: "user", text: prompt.trim() });
- if (session.history.length > 48) session.history.splice(0, session.history.length - 48);
- await agentRound(rl, session, loaded);
- await persistSession(session);
- return "handled";
}
-async function slash(rl, line, session) {
- const [cmd, ...args] = line.trim().split(/\s+/);
- switch (cmd) {
- case "/help":
- console.log([
- " /session show current durable MSO session id",
- " /sessions list recent resumable sessions",
- " /resume [query] resume latest/index/id/title; no arg opens picker",
- " /title <name> rename the durable session",
- " /status model/auth/context/token/session details",
- " /context alias for /status",
- " /statusbar [on|off] toggle compact dynamic status line",
- " /models [args] configure AI providers/auth",
- " /model [ref] select active model from connected providers",
- " /setup full MSO onboarding",
- " /providers infrastructure provider status",
- " /provider <id> configure dokploy|cloudflare|hostinger",
- " /doctor run mso doctor",
- " /tools list agent tools",
- " /skills [query] browse available slash skills",
- " /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
- " /<skill> [prompt] select for next message, or run prompt now",
- " /clear clear this session conversation",
- " /exit quit",
- ].join("\n")); return "handled";
- case "/session":
- console.log(`${C.blue}${session.agentSession.id}${C.reset} · ${session.agentSession.title || "MSO Agent session"}`); return "handled";
- case "/sessions":
- printSessions(await listCliSessions(50)); return "handled";
- case "/resume":
- if (!args.length) await resumePicker(rl, session);
- else await resumeInto(session, args.join(" "));
- return "refresh";
- case "/title": {
- const title = args.join(" ").trim();
- if (!title) console.log("usage: /title <session name>");
- else { session.titleOverride = title.slice(0, 120); await persistSession(session); console.log(`${C.c}✓ session title: ${session.titleOverride}${C.reset}`); }
- return "handled";
- }
- case "/status": case "/context": printDetailedStatus(session, C); return "handled";
- case "/statusbar": {
- const v = String(args[0] || "").toLowerCase();
- if (v === "off") session.statusBar = false; else if (v === "on") session.statusBar = true;
- else session.statusBar = !session.statusBar;
- console.log(`status bar ${session.statusBar ? "on" : "off"}`); return "handled";
- }
- case "/models": runCli(["models", ...args]); session.state = await state(); return "refresh";
- case "/model": runCli(["model", ...args]); session.state = await state(); return "refresh";
- case "/setup": runCli(["onboard"]); session.state = await state(); return "refresh";
- case "/providers": runCli(["provider", "list"]); session.state = await state(); return "refresh";
- case "/provider": if (!args[0]) console.log("usage: /provider dokploy|cloudflare|hostinger"); else runCli(["provider", "set", args[0]]); session.state = await state(); return "refresh";
- case "/doctor": runCli(["doctor"]); return "handled";
- case "/tools": for (const tool of session.state.tools) console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`); return "handled";
- case "/skills": printSkills(session, C, args.join(" ")); return "handled";
- case "/skill": if (!args[0]) { console.log("usage: /skill <name-or-exact-id> [prompt]"); return "handled"; } return selectSlashSkill(rl, session, args[0], args.slice(1).join(" "));
- case "/clear": Object.assign(session, { history: [], pendingSkill: null, activeSkill: null, lastInvokedSkill: null }); await persistSession(session); console.log("conversation cleared."); return "handled";
- case "/exit": return "exit";
- default: return selectSlashSkill(rl, session, cmd.slice(1), args.join(" "));
- }
-}
async function main() {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
@@ -184,9 +119,13 @@ async function main() {
statusBar: true,
};
const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C });
+ const interrupts = new AgentInterruptManager({ output: process.stdout, colors: C });
+ const onSigint = () => interrupts.handleSigint();
+ process.on("SIGINT", onSigint);
const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session);
try {
while (true) {
+ if (interrupts.exitRequested) break;
let line = "";
try {
console.log();
@@ -198,27 +137,24 @@ async function main() {
if (!line) continue;
if (line.startsWith("/")) {
try {
- const result = await slash(rl, line, session);
+ const result = await handleSlash(rl, line, session, { runTurn: (skill) => runInteractiveRound(rl, session, skill, interrupts) });
if (result === "exit") break;
if (result === "unknown") console.log("unknown command; /help lists commands.");
} catch (error) {
console.error(`${C.err}${error instanceof Error ? error.message : String(error)}${C.reset}`);
}
+ if (interrupts.exitRequested) break;
continue;
}
session.history.push({ role: "user", text: line });
if (session.history.length > 48) session.history.splice(0, session.history.length - 48);
- try {
- const skillContext = session.pendingSkill;
- session.pendingSkill = null;
- await agentRound(rl, session, skillContext);
- await persistSession(session);
- } catch (error) {
- console.error(`${C.err}agent error: ${error instanceof Error ? error.message : String(error)}${C.reset}`);
- await persistSession(session).catch(() => undefined);
- }
+ const skillContext = session.pendingSkill;
+ session.pendingSkill = null;
+ await runInteractiveRound(rl, session, skillContext, interrupts);
+ if (interrupts.exitRequested) break;
}
} finally {
+ process.off("SIGINT", onSigint);
await persistSession(session).catch(() => undefined);
console.log(`${C.dim}session ${session.agentSession.id} · resume: mso --continue | mso --resume ${session.agentSession.id}${C.reset}`);
rl.close();
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index afa59b41..a055f3aa 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -14,7 +14,7 @@ const all = [cli, agentCli, configRoute, oauthRoute, slash, picker].join("\n");
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
- expect(cli).toContain('VERSION="1.5.6"');
+ expect(cli).toContain('VERSION="1.5.7"');
expect(cli).toContain("models * Configure AI providers/auth");
expect(cli).toContain("model [ref] Select active model");
expect(agentCli).toContain("run_models()");