Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent): section terminal and recover API errors
Rahmaneeaaa2753b94
diff --git a/README.md b/README.mdindex 1e6586e4..5fb4a126 100644--- a/README.md+++ b/README.md@@ -228,13 +228,18 @@ durable synthetic assistant response; notify-only events remain passive peer evesame-session subagent primitive with isolated context and final-result-only return.In the Agent slash palette, executable skills carry lifecycle markers so their state is visible before and after use:`◇ ready` → `◆ queued` (selected for the next message) → `✓ invoked` (actually sent with a model turn).-The compact status line mirrors queued/invoked skill state and the current permission mode. MSO defaults-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 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+The interactive transcript is sectioned by full-width `Assistant`, `Agent work`, `Local agent`, and `Error`+dividers. The composer stays in its own bottom `Input · @name` area: the short session handle is the input+identity (`@milo ›`), while permission is shown separately in the bottom footer as `mode ask|auto|yolo`.+Tab on an empty prompt cycles that footer in place without adding scrollback. 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 compact approval prompt. `/permission` opens the same arrow-key style selector; `auto-write`+approves writes but still asks before exec. Permission mode is process-local and is not persisted into a+resumed session. Recoverable HTTP/API failures render a bounded `Error` section instead of silently+ending the interaction. If a write/exec delivery is uncertain, MSO stops that turn and never retries the+mutation automatically; if an earlier mutation completed, the error section says so and instructs the+user/client to continue from that result rather than repeat it. Terminal controls follow familiar agent/shell conventions: **Ctrl+C** clears a non-empty draft, exits from an empty idle prompt, andinterrupts an active model/tool turn; **Ctrl+D** deletes the character to the right or exits on anempty 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`. Long drafts wrap dynamically to terminal width/height; **↑/↓** move between visual wrapped rows before falling through to history navigation;diff --git a/bin/mso b/bin/msoindex 22b1d0ea..1ce4deab 100755--- a/bin/mso+++ b/bin/mso@@ -128,7 +128,7 @@# Docs: https://github.com/rahmanef63/msoset -euo pipefail-VERSION="1.11.1"+VERSION="1.12.0"ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"die() { echo "mso: $*" >&2; exit 1; }diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex d2b87e3d..b6f46367 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` section terminal and recover API errors- `agent` name sessions and wrap composer- `agent` correlate local replies and add subagents- `agent` add native local session messagingdiff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex a6d44582..cb84d388 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -165,7 +165,11 @@ uses the canonical MCP tool catalog internally: reads run directly, while write/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. The terminal-composer also follows conventional controls: Ctrl+C clears a draft, exits an empty prompt, or interrupts+transcript uses full-width dividers for Assistant, Agent work, Local agent, and recoverable Error sections.+The bottom composer is separated by an `Input · @name` divider, uses `@name ›` as its identity prompt, and+keeps `mode ask|auto|yolo` in the footer; Tab cycles that mode in place. Recoverable HTTP/API errors keep+the interaction/session intact and never auto-repeat an uncertain write/exec call. The composer also+follows conventional controls: Ctrl+C clears a draft, exits an empty prompt, or interruptsan active turn; Ctrl+D deletes right/exits on empty; Ctrl+L clears the screen; Ctrl+W deletes the previousword; ↑/↓ or Ctrl+P/N browse prompt history and are seeded from durable user prompts after resume;Ctrl+A/E and Ctrl+B/F navigate the line, Ctrl+U/K delete to the start/end, and Alt+B/F or Ctrl+←/→ movediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex a52893ae..8811d203 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,6 +2,14 @@Running log of what shipped each phase. Newest at top.+## 2026-09-02 — MSO 1.12.0 sectioned Agent TUI + recoverable API failures++- **Identity-first bottom composer:** the old `[ask] ›` prompt is replaced by the short durable handle (`@milo ›`). A full-width `Input · @milo` divider separates transcript from editing state; permission moves to the dynamic footer as `mode ask|auto|yolo`, and empty-prompt Tab repaints only that footer. Wrapped input, resize redraw, prompt history, and keyboard editing remain intact.+- **Unambiguous transcript streams:** streamed model text opens an `Assistant` section lazily on the first text delta, tool/subagent execution opens `Agent work`, and Local Agent send/receive/inbox output uses `Local agent`. Sections are full-width and content is not duplicated merely to label a stream.+- **Recoverable error state:** terminal API/transport failures carry bounded status/path/method/dispatch metadata and render a redacted `Error` section. The turn journal distinguishes `not_started`, `completed`, and `uncertain` mutation outcomes. A successful mutation is never repeated just because a later assistant request failed; an uncertain write/exec transport failure stops the turn before the model can retry it.+- **State preservation:** recoverable failures keep the durable session/transcript/correlation rows, active draft redraw, and pending exact-approval metadata. Exact approval still binds the canonical full payload/digest; transport error rendering never prints request bodies, hidden transcript, credentials, or secret-shaped error values.+- **Cleanup:** turn/tool orchestration moved out of the CLI entrypoint into a focused module; the obsolete internal `permissionPrompt` and `renderStatusBar` helpers were removed instead of retained as compatibility shims.+## 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.diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.mdindex 2a3c0528..5f8dc536 100644--- a/docs/TESTING-HANDOFF.md+++ b/docs/TESTING-HANDOFF.md@@ -4,7 +4,7 @@ Update this file at the end of every manual or automated test session. Keep it f## 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.+The v1.10 findings below are implemented and deployed in **MSO 1.11.1** (`3e06c70`). The historical session logs remain below as evidence of what was observed. Do not re-open resolved findings from prose alone: reproduce against the current build first. The current open work is the sectioned terminal conversation layout and recoverable HTTP/API error UX described below.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;@@ -27,6 +27,12 @@ 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.+4. Improve the terminal conversation layout, drawing from Claude Code/Codex CLI ergonomics:+ - Render a full-width horizontal divider before each distinct section: agent work/progress, normal assistant response, and local-agent discussion/inbound or outbound messages. Dividers must make the three streams visually unambiguous without duplicating content.+ - Keep the input composer in a dedicated bottom area separated from transcript output by a full-width horizontal divider.+ - Move the current permission mode (`yolo`, auto-write, ask, etc.) into the bottom composer/status area below that input divider, not among transcript headers.+ - Put the current agent's short public name/handle in the header slot currently used for permission mode, matching the identity-forward layout familiar from Claude Code/Codex CLI. Preserve clear indication of the active permission mode in the new bottom location.+ - Preserve keyboard accessibility, resize redraw behavior, compact output, exact approval semantics, and existing local-agent correlation/inbox behavior.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`.@@ -35,11 +41,38 @@ Exact-approval UX requirement:- 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.+Validation minimum: focused unit tests for success, offline target, absent subscriber/no reply, self-target rejection, principal isolation, transcript section dividers, input divider, agent-name header placement, permission-mode bottom placement, 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 — sectioned terminal + recoverable API failures++**Goal**+- Separate Assistant, Agent work, Local Agent, Error, and Input streams without buffering model output or duplicating content.+- Move permission mode to the bottom composer area while keeping the short public `@name` as the terminal identity.+- Make HTTP/API transport failures recoverable and explicit without automatically repeating an uncertain mutation.++**Changed**+- Added full-width `Assistant`, `Agent work`, `Local agent`, `Error`, and `Input · @name` section dividers.+- Replaced the old `[ask] ›` identity prompt with `@name ›`; the bottom footer now shows `mode ask|auto|yolo` and Tab cycles that mode in place.+- Preserved wrapped composer editing, vertical cursor navigation, resize repaint, and incoming-event draft redraw.+- Added structured Agent API errors plus a per-turn mutation journal with `not_started`, `completed`, and `uncertain` outcomes.+- A write/exec transport failure with uncertain delivery now stops the turn before the model can retry the mutation. A later assistant/API error after a completed mutation reports the mutation as completed and tells the client not to repeat it.+- Recoverable errors are redacted, rendered as a bounded `Error` section, persisted as safe durable context, and keep session/correlation state. Pending exact-approval metadata is retained if the approval interaction itself fails before a decision.+- Moved turn/tool orchestration out of `mso-agent.mjs`; removed obsolete internal `permissionPrompt` and `renderStatusBar` helpers rather than keeping compatibility shims.++**Verified**+- Focused Local Agent/layout/error/approval/dispatcher regression bundle: **13 test files / 91 tests passed**.+- Additional composer/layout/error focused suites passed after extracting composer row-reservation helpers to keep lint line budgets unchanged.+- Pre-release PTY smoke PASS: `@smoke-a` showed `mode yolo`, one `Assistant` section for model output, one `Agent work` section for `/spawn`, one `Local agent` section for outbound collaboration, and a bounded `Error` section for an unknown mention. `@smoke-b` received `LOCAL_LAYOUT_SMOKE` under a `Local agent · [smoke-a]` divider and its Input area/draft was redrawn correctly. Temporary PTYs were closed.+- Full release gate PASS with exit 0: `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**; no new warning-only file remains after the composer extraction.+- MCP toolset remains `2026.09.02.7` because this release changes Agent/TUI runtime semantics but adds no MCP tool.++**Open work / handoff**+- Commit/push/deploy CLI 1.12.0, then repeat a small PTY smoke against the deployed build and record the final live build SHA.+### 2026-09-02 — named sessions, responsive composer, consumer observability, compact approval**Goal**@@ -82,8 +115,10 @@ Validation minimum: focused unit tests for success, offline target, absent subsc- Final full release gate PASS with exit 0: `npm run typecheck`, `npm run lint`, full `npm run test`, `npm run check`, production `npm run build`, and `git diff --check`.- Lint remains **0 errors / 9 existing max-lines warnings**. Full-load session-store concurrency and gateway exclusion both pass in the final run.-**Open work / handoff**-- Commit/push/deploy 1.11.1, then repeat the close-target mention smoke: immediately after receiver disconnect, the target may still have an `idle` lease but `consumerConnected=false`; human `@name` must be rejected and the mailbox marker count must remain unchanged.+**1.11.1 release/live verification**+- Released as commit `3e06c70` with `HEAD == origin/main`; live `mso.service` reported `buildSha=3e06c70` and CLI `1.11.1`.+- Close-target race smoke PASS: after target PTY disconnect the lease could still report `idle`, but `consumerConnected=false`; human `@name` was rejected immediately and the target mailbox marker count stayed unchanged.+- Temporary PTYs were closed. Durable smoke session records were not manually deleted because MSO does not yet expose a supported AgentSession delete API and direct store-file deletion could leave indexes/mailbox references inconsistent.### 2026-09-02 — local agent wake + subagent capacity@@ -123,6 +158,18 @@ Validation minimum: focused unit tests for success, offline target, absent subsc**Handoff (resolved by the 1.11 candidate)**- Compact approval runtime and focused regression coverage are implemented; canonical exact full-payload digest binding is unchanged.+### 2026-09-02 — terminal HTTP/API error resilience++**Observed**+- During a documentation-only update, the file write succeeded, but the next tool/UI step surfaced an HTTP 400 and interrupted the visible flow before the assistant could confirm completion.++**Required follow-up**+- Treat recoverable transport/API failures (including HTTP 400) as a visible, bounded UI state rather than silently terminating the active interaction.+- Preserve the user draft, session identity, transcript, pending permission state, and correlation IDs across a recoverable failure; do not duplicate a mutation automatically.+- Render a concise error section/divider with a safe error summary, whether the preceding operation completed, and a clear retry/continue action. Never expose secrets, raw request bodies, or hidden transcripts.+- The assistant/client must still emit a user-facing completion, partial-result, or failure message after a tool/API error. If status is uncertain, say so and verify before retrying any write/exec mutation.+- Add focused tests for: HTTP 400 after a successful mutation, HTTP 400 before dispatch, draft preservation, no duplicate write on retry, pending approval preservation, and a visible user-facing error/result message.+### Template — append for every later session```mddiff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjsindex 364f8280..15faafc0 100644--- a/scripts/mso-agent-commands.mjs+++ b/scripts/mso-agent-commands.mjs@@ -21,6 +21,7 @@ import {permissionMode,} from "./mso-agent-permissions.mjs";import { parseSubagentArgs, SUBAGENT_USAGE } from "./mso-agent-subagent.mjs";+import { sectionBlock, printSection } from "./mso-agent-layout.mjs";function runCli(args) {const result = spawnSync(CLI, args, {@@ -257,7 +258,9 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {const target = args[0];const message = args.slice(1).join(" ");const out = await sendLocalAgent(session, target, message, "message");- console.log(`${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"}`);+ console.log(sectionBlock("local", `${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"}`, {+ columns: process.stdout.columns, detail: out?.target?.label || target, colors: C,+ }));return "handled";}case "/delegate": {@@ -272,7 +275,9 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {try {const out = await sendLocalAgent(session, target, objective, "task", { intent: "request", requiresUserRelay: true });await trackLocalRequest(session, out, objective);- console.log(`${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"} · correlated reply will relay here`);+ console.log(sectionBlock("local", `${C.c}↳ ${out?.target?.label || target}${C.reset} ${out?.status || "accepted"} · correlated reply will relay here`, {+ columns: process.stdout.columns, detail: out?.target?.label || target, colors: C,+ }));} catch (error) {const message = error instanceof Error ? error.message : String(error);if (/local agent target not found/i.test(message))@@ -294,10 +299,13 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {const out = await api(`/api/v1/local-agents?inbox=1&session=${encodeURIComponent(session.agentSession.id)}&limit=100`);const rows = Array.isArray(out?.messages) ? out.messages : [];if (!rows.length) console.log("local agent inbox is empty");- else for (const row of rows) {- const label = String(row.senderLabel || "[agent]");- const prefix = label.startsWith("[agent-") ? label : `[agent-${label.replace(/^\[|\]$/g, "")}]`;- console.log(`${C.c}${prefix}${row.kind === "task" ? " task" : ""}${C.reset} ${row.text}`);+ else {+ printSection("local", { detail: "inbox", colors: C });+ for (const row of rows) {+ const label = String(row.senderLabel || "[agent]");+ const prefix = label.startsWith("[agent-") ? label : `[agent-${label.replace(/^\[|\]$/g, "")}]`;+ console.log(`${C.c}${prefix}${row.kind === "task" ? " task" : ""}${C.reset} ${row.text}`);+ }}return "handled";}diff --git a/scripts/mso-agent-composer-session.test.ts b/scripts/mso-agent-composer-session.test.tsindex 5a5895aa..b82308e0 100644--- a/scripts/mso-agent-composer-session.test.ts+++ b/scripts/mso-agent-composer-session.test.ts@@ -1,6 +1,7 @@import { EventEmitter } from "node:events";import { describe, expect, it } from "vitest";import { AgentComposer } from "./mso-agent-composer.mjs";+import { composerFooter, composerPrompt } from "./mso-agent-layout.mjs";class FakeInput extends EventEmitter {isRaw = false;@@ -52,17 +53,26 @@ describe("MSO Agent session/history composer UX", () => {composer.close();});- it("repaints a dynamic permission prompt on empty Tab without adding a scrollback line", async () => {+ it("keeps @name in the prompt while Tab repaints permission only in the bottom footer", async () => {const { input, output, composer } = composerFixture();- let mode = "ask", cycles = 0;- const answer = composer.question(() => `[${mode}] › `, { onTab: () => { cycles++; mode = "yolo"; } } as never);+ const session: any = {+ permission: "ask", statusBar: false, history: [], agentSession: { name: "milo" },+ state: { config: {}, modelMeta: null }, usage: { totalTokens: 0 },+ };+ let cycles = 0;+ const answer = composer.question(() => composerPrompt(session, colors), {+ footer: () => composerFooter(session, colors, output.columns),+ onTab: () => { cycles++; session.permission = "yolo"; },+ } as never);const before = output.chunks.join("");+ expect(before).toContain("@milo › ");+ expect(before).toContain("mode ask");input.emit("keypress", "\t", { name: "tab", sequence: "\t" });const after = output.chunks.join("");expect(cycles).toBe(1);- expect(after).toContain("[yolo] › ");+ expect(after).toContain("@milo › ");+ expect(after).toContain("mode yolo");expect(after.slice(before.length)).not.toMatch(/[\r]?\n/);- expect(after).not.toContain("permission →");for (const ch of "go") input.emit("keypress", ch, { name: ch, sequence: ch });input.emit("keypress", "\r", { name: "return", sequence: "\r" });await expect(answer).resolves.toBe("go");diff --git a/scripts/mso-agent-composer-ui.mjs b/scripts/mso-agent-composer-ui.mjsindex 97c676b3..16a63718 100644--- a/scripts/mso-agent-composer-ui.mjs+++ b/scripts/mso-agent-composer-ui.mjs@@ -10,6 +10,20 @@ export const chars = (value) => Array.from(String(value ?? ""));export const width = (value) => chars(plain(value)).length;export const clamp = (value, min, max) => Math.min(Math.max(value, min), max);+export function reserveComposerRows(output, reservedRows, rows) {+ if (rows <= reservedRows) return reservedRows;+ if (reservedRows) output.write(CURSOR_DOWN(reservedRows));+ for (let i = reservedRows; i < rows; i++) output.write("\r\n");+ output.write(`${CURSOR_UP(rows)}\r`);+ return rows;+}++export function eraseComposerRows(output, reservedRows) {+ output.write(`\r${CLEAR_LINE}`);+ for (let i = 0; i < reservedRows; i++) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}`);+ if (reservedRows) output.write(`${CURSOR_UP(reservedRows)}\r`);+}+export function inputViewport(value, cursor, maxWidth) {const row = chars(value), max = Math.max(1, maxWidth);if (row.length <= max) return { display: row.join(""), cursor: clamp(cursor, 0, row.length) };diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjsindex e41d32da..cd64acb1 100644--- a/scripts/mso-agent-composer.mjs+++ b/scripts/mso-agent-composer.mjs@@ -3,7 +3,7 @@ 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, inputLayout, inputViewport, menuLines, verticalCursor, width,+ chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, eraseComposerRows, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width,} from "./mso-agent-composer-ui.mjs";export { completionWindow, inputLayout, inputViewport, verticalCursor } from "./mso-agent-composer-ui.mjs";@@ -19,48 +19,43 @@ export class AgentComposer {readline.emitKeypressEvents(this.input);}- async question(prompt, { complete = null, history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false } = {}) {+ async question(prompt, { complete = null, history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false, footer = null, separator = null } = {}) {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, reservedRows = 0;let dismissed = false, historyIndex = null, draft = "", settled = false, verticalColumn = null;const promptText = () => String(typeof prompt === "function" ? prompt() : prompt);+ const footerText = () => String(typeof footer === "function" ? footer() : (footer || ""));+ const separatorText = () => String(typeof separator === "function" ? separator() : (separator || ""));const wasRaw = Boolean(input.isRaw);const matches = () => dismissed || !complete ? [] : complete(value) || [];// 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 <= 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`);- reservedRows = rows;- };- const erase = () => {- output.write(`\r${CLEAR_LINE}`);- for (let i = 0; i < reservedRows; i++) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}`);- if (reservedRows) output.write(`${CURSOR_UP(reservedRows)}\r`);- };+ const reserve = (rows) => { reservedRows = reserveComposerRows(output, reservedRows, rows); };+ const erase = () => eraseComposerRows(output, reservedRows);const render = () => {const currentPrompt = promptText();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);+ const footerRow = footerText();+ const footerRows = footerRow ? 1 : 0;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 maxInputRows = Math.max(2, Math.min(12, terminalRows - menu.length - footerRows - 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;+ const below = inputExtraRows + menu.length + footerRows;reserve(below);erase();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}`);- const backUp = menu.length + (layout.lines.length - 1 - layout.cursorRow);+ if (footerRow) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}${footerRow}`);+ const backUp = menu.length + footerRows + (layout.lines.length - 1 - layout.cursorRow);if (backUp) output.write(CURSOR_UP(backUp));output.write(`\r${CURSOR_RIGHT(promptWidth + layout.cursorCol)}`);};@@ -98,6 +93,8 @@ export class AgentComposer {if (settled) return false;erase();output.write(`${String(text ?? "").replace(/\r/g, "")}\r\n`);+ const separatorRow = separatorText();+ if (separatorRow) output.write(`${separatorRow}\r\n`);reservedRows = 0;render();return true;@@ -202,6 +199,8 @@ export class AgentComposer {if (typeof output.on === "function") output.on("resize", onResize);input.resume();if (typeof input.setRawMode === "function") input.setRawMode(true);+ const separatorRow = separatorText();+ if (separatorRow) output.write(`${separatorRow}\r\n`);render();});}diff --git a/scripts/mso-agent-context.mjs b/scripts/mso-agent-context.mjsindex b956d307..ca95e194 100644--- a/scripts/mso-agent-context.mjs+++ b/scripts/mso-agent-context.mjs@@ -26,6 +26,10 @@ export function modelHistoryRow(row) {const target = String(row.targetLabel || "[local-agent]").replace(/[\r\n\t]+/g, " ").slice(0, 120);return { role: "assistant", text: `[LOCAL DISPATCH ${target}] ${String(row.text || "").slice(0, 24_000)}` };}+ if (row?.role === "recoverable_error") {+ const mutation = ["completed", "uncertain", "not_started"].includes(row.mutationState) ? row.mutationState : "not_started";+ return { role: "assistant", text: `[RECOVERABLE ERROR · mutation ${mutation}] ${String(row.text || "").slice(0, 2_000)}` };+ }if (row?.role !== "agent") return row;const sender = String(row.senderLabel || "[local-agent]").replace(/[\r\n\t]+/g, " ").slice(0, 120);const kind = row.kind === "task" ? "task" : "message";diff --git a/scripts/mso-agent-contract.test.ts b/scripts/mso-agent-contract.test.tsindex 999bb2b3..4592b088 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", "mso-agent-approval-ui.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", "mso-agent-turn.mjs", "mso-agent-layout.mjs", "mso-agent-errors.mjs", "mso-agent-local.mjs"].map((name) => path.join(__dirname, name));const src = files.map((file) => fs.readFileSync(file, "utf8")).join("\n");describe("MSO terminal agent contract", () => {@@ -40,8 +40,13 @@ describe("MSO terminal agent contract", () => {expect(src).toContain("lastInvokedSkill");expect(src).toContain("AgentComposer");expect(src).toContain("slashCompletionItems");- expect(src).toContain("renderStatusBar");expect(src).toContain("resolveSessionQuery");+ expect(src).toContain("composerPrompt");+ expect(src).toContain("composerFooter");+ expect(src).toContain("composerSeparator");+ expect(src).toContain("sectionDivider");+ expect(src).toContain("Agent work");+ expect(src).toContain("Local agent");});it("keeps infrastructure secrets out of model messages and binds write/exec approval to the exact full payload", () => {@@ -55,6 +60,10 @@ describe("MSO terminal agent contract", () => {expect(src).not.toContain("redactedPreview");expect(src).not.toContain("allowedForSession");expect(src).toContain("approved: true");+ expect(src).toContain("AgentMutationUncertainError");+ expect(src).toContain("recoverableTurnState");+ expect(src).toContain("pendingApproval");+ expect(src).toContain("will not retry it automatically");});it("reads the authenticated cookie jar instead of accepting a bearer/token argument", () => {diff --git a/scripts/mso-agent-error-ux.test.ts b/scripts/mso-agent-error-ux.test.tsnew file mode 100644index 00000000..ce4c486f--- /dev/null+++ b/scripts/mso-agent-error-ux.test.ts@@ -0,0 +1,103 @@+import { EventEmitter } from "node:events";+import { describe, expect, it, vi } from "vitest";+import { AgentApiError, AgentMutationUncertainError, recoverableErrorLines, recoverableTurnState } from "./mso-agent-errors.mjs";+import { sectionBlock } from "./mso-agent-layout.mjs";+import { AgentComposer } from "./mso-agent-composer.mjs";+import { agentRound, executeTool } from "./mso-agent-turn.mjs";++const colors = { blue: "", bold: "", reset: "", dim: "", c: "", cyan: "", warn: "", err: "" };++describe("MSO Agent recoverable API/tool error UX", () => {+ it("reports HTTP 400 after a successful mutation as completed, never as a reason to repeat it", () => {+ const error = new AgentApiError("assistant rejected follow-up", { status: 400, path: "/api/assistant", method: "POST", requestDispatched: true });+ const state = recoverableTurnState(error, { calls: [{ name: "fs_write", scope: "write", ok: true }] });+ expect(state).toMatchObject({ mutationState: "completed", mutationTool: "fs_write", status: 400 });+ expect(state.action).toMatch(/do not repeat/i);+ });++ it("reports HTTP 400 before any mutation as not started", () => {+ const error = new AgentApiError("bad assistant request", { status: 400, path: "/api/assistant", method: "POST", requestDispatched: true });+ expect(recoverableTurnState(error, { calls: [] })).toMatchObject({ mutationState: "not_started", status: 400 });+ });++ it("stops an uncertain write API failure after exactly one dispatch instead of returning it to the model for retry", async () => {+ const request = vi.fn(async () => { throw new AgentApiError("HTTP 400", { status: 400, path: "/api/v1/agent-tools", method: "POST", requestDispatched: true }); });+ const tool = { name: "fs_write", scope: "write" };+ await expect(executeTool(null, tool, { name: "fs_write", input: { path: "/tmp/x", text: "x" } }, { id: "session-a" }, "yolo", undefined, null, {+ quiet: true, apiRequest: request,+ })).rejects.toBeInstanceOf(AgentMutationUncertainError);+ expect(request).toHaveBeenCalledTimes(1);+ });++ it("does not repeat a completed mutation when the following assistant request fails with HTTP 400", async () => {+ const session: any = {+ history: [{ role: "user", text: "write once" }], permission: "yolo",+ state: { tools: [{ name: "fs_write", scope: "write" }], modelMeta: null },+ agentSession: { id: "session-a", name: "milo" },+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, lastElapsedMs: 0,+ };+ const stream = vi.fn()+ .mockResolvedValueOnce({ text: "", toolUses: [{ id: "call-1", name: "fs_write", input: { path: "/tmp/a", text: "a" } }], usage: null })+ .mockRejectedValueOnce(new AgentApiError("follow-up bad request", { status: 400, path: "/api/assistant", method: "POST", requestDispatched: true }));+ const toolExecutor = vi.fn(async () => ({ ok: true, result: "written" }));+ let caught: any;+ try { await agentRound(null, session, null, undefined, null, { quiet: true, streamTurn: stream, executeTool: toolExecutor }); }+ catch (error) { caught = error; }+ expect(caught).toBeInstanceOf(AgentApiError);+ expect(toolExecutor).toHaveBeenCalledTimes(1);+ expect(stream).toHaveBeenCalledTimes(2);+ expect(recoverableTurnState(caught, caught.turnJournal)).toMatchObject({ mutationState: "completed", mutationTool: "fs_write" });+ });++ it("does not dispatch any tool when the assistant request fails before tool planning", async () => {+ const session: any = {+ history: [{ role: "user", text: "read" }], permission: "ask",+ state: { tools: [{ name: "fs_read", scope: "read" }], modelMeta: null },+ agentSession: { id: "session-a", name: "milo" }, usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },+ };+ const stream = vi.fn(async () => { throw new AgentApiError("bad request", { status: 400, path: "/api/assistant", method: "POST", requestDispatched: true }); });+ const toolExecutor = vi.fn();+ await expect(agentRound(null, session, null, undefined, null, { quiet: true, streamTurn: stream, executeTool: toolExecutor })).rejects.toBeInstanceOf(AgentApiError);+ expect(toolExecutor).not.toHaveBeenCalled();+ });++ it("preserves a pending exact approval if the approval interaction itself fails recoverably", async () => {+ const approvalState: any = { pendingApproval: null };+ const rl = { question: vi.fn(async () => { throw new AgentApiError("approval UI transport failed", { status: 400, path: "/approval", method: "POST", requestDispatched: false }); }) };+ await expect(executeTool(rl, { name: "fs_write", scope: "write" }, { name: "fs_write", input: { path: "/tmp/a", text: "a" } }, { id: "session-a" }, "ask", undefined, null, {+ quiet: true, approvalState,+ })).rejects.toBeInstanceOf(AgentApiError);+ expect(approvalState.pendingApproval).toMatchObject({ tool: "fs_write", scope: "write" });+ });++ it("treats a POST transport failure as uncertain even without a response", () => {+ const error = new AgentApiError("socket closed", { path: "/api/v1/agent-sessions", method: "POST", requestDispatched: false });+ expect(recoverableTurnState(error, { calls: [] })).toMatchObject({ mutationState: "uncertain", requestDispatched: false });+ });++ it("redacts secret-shaped error text from the user-facing error section", () => {+ const state = recoverableTurnState(new AgentApiError("password=supersecret failed", { status: 400, path: "/api/x", method: "GET", requestDispatched: true }));+ const rendered = recoverableErrorLines(state).join("\n");+ expect(rendered).toContain("password=[redacted]");+ expect(rendered).not.toContain("supersecret");+ });++ it("preserves an in-progress draft when a recoverable error section is rendered above the composer", async () => {+ class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(v: boolean) { this.isRaw = v; } }+ class FakeOutput extends EventEmitter { columns = 64; rows = 18; chunks: string[] = []; write(v: string) { this.chunks.push(String(v)); return true; } }+ const input = new FakeInput(), output = new FakeOutput();+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });+ const answer = composer.question("@milo › ", { footer: "mode ask · Tab cycle", separator: "── Input ──" } as never);+ for (const ch of "draft") input.emit("keypress", ch, { name: ch, sequence: ch });+ composer.notify(sectionBlock("error", "HTTP 400 · no mutation repeated", { columns: output.columns, colors }));+ for (const ch of " kept") input.emit("keypress", ch, { name: ch, sequence: ch });+ input.emit("keypress", "\r", { name: "return", sequence: "\r" });+ await expect(answer).resolves.toBe("draft kept");+ const rendered = output.chunks.join("");+ expect(rendered).toContain("Error");+ expect(rendered).toContain("HTTP 400 · no mutation repeated");+ expect(rendered).toContain("mode ask");+ expect(rendered).toContain("draft kept");+ composer.close();+ });+});diff --git a/scripts/mso-agent-errors.mjs b/scripts/mso-agent-errors.mjsnew file mode 100644index 00000000..88ba0730--- /dev/null+++ b/scripts/mso-agent-errors.mjs@@ -0,0 +1,97 @@+const SECRET_TEXT = /((?:api[_-]?key|token|secret|password|passwd|credential|authorization|cookie)\s*[=:]\s*)[^\s,;]+|\bBearer\s+[^\s,;]+/gi;++function safeOneLine(value, max = 180) {+ const clean = String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();+ const redacted = clean.replace(SECRET_TEXT, (match, prefix) => prefix ? `${prefix}[redacted]` : "Bearer [redacted]");+ return Array.from(redacted).length <= max ? redacted : `${Array.from(redacted).slice(0, max - 1).join("")}…`;+}++export class AgentApiError extends Error {+ /**+ * @param {string} message+ * @param {{ status?: number|null, path?: string, method?: string, requestDispatched?: boolean, cause?: unknown }} [meta]+ */+ constructor(message, { status = null, path = "", method = "GET", requestDispatched = false, cause = undefined } = {}) {+ super(safeOneLine(message || (status ? `HTTP ${status}` : "API request failed")));+ this.name = "AgentApiError";+ this.status = status === null || status === undefined || status === "" ? null : (Number.isFinite(Number(status)) ? Number(status) : null);+ this.path = String(path || "").slice(0, 240);+ this.method = String(method || "GET").toUpperCase();+ this.requestDispatched = requestDispatched === true;+ if (cause) this.cause = cause;+ }+}++export class AgentMutationUncertainError extends Error {+ constructor(toolName, apiError) {+ super(`delivery outcome is uncertain for ${String(toolName || "mutation")}; MSO will not retry it automatically`);+ this.name = "AgentMutationUncertainError";+ this.toolName = String(toolName || "mutation");+ this.apiError = apiError;+ this.mutationUncertain = true;+ }+}++export function isAgentApiError(error) {+ return error instanceof AgentApiError || error?.name === "AgentApiError";+}++export function isRecoverableInteractionError(error) {+ if (error?.name === "AbortError") return false;+ return isAgentApiError(error) || error?.name === "AgentMutationUncertainError" || error?.mutationUncertain === true;+}++export function safeErrorSummary(error) {+ if (error?.name === "AgentMutationUncertainError") {+ const inner = error.apiError;+ return safeOneLine(`${error.message}${inner?.status ? ` · HTTP ${inner.status}` : ""}`);+ }+ if (isAgentApiError(error)) return safeOneLine(`${error.message}${error.status && !String(error.message).includes(String(error.status)) ? ` · HTTP ${error.status}` : ""}`);+ return safeOneLine(error instanceof Error ? error.message : String(error || "interaction failed"));+}++function latestCompletedMutation(calls = []) {+ return [...(Array.isArray(calls) ? calls : [])].reverse().find((call) => call?.ok === true && ["write", "exec"].includes(call?.scope)) || null;+}++export function recoverableTurnState(error, journal = {}) {+ const calls = Array.isArray(journal?.calls) ? journal.calls : [];+ const completed = latestCompletedMutation(calls);+ const uncertainTool = error?.name === "AgentMutationUncertainError" ? String(error.toolName || "mutation") : null;+ let mutationState = "not_started";+ if (uncertainTool) mutationState = "uncertain";+ else if (completed) mutationState = "completed";+ else if (isAgentApiError(error) && error.path !== "/api/assistant" && !["GET", "HEAD"].includes(String(error.method || "GET").toUpperCase())) mutationState = "uncertain";+ return {+ summary: safeErrorSummary(error),+ status: error?.apiError?.status ?? error?.status ?? null,+ mutationState,+ mutationTool: uncertainTool || completed?.name || null,+ requestDispatched: error?.apiError?.requestDispatched ?? error?.requestDispatched ?? false,+ action: mutationState === "uncertain"+ ? "Do not retry automatically. Verify the target state first, then retry only if needed."+ : mutationState === "completed"+ ? "The previous mutation completed. Continue from the result; do not repeat it just because this later request failed."+ : "Nothing mutating is known to have run. Continue or retry the failed read/assistant step when ready.",+ };+}++export function recoverableErrorLines(state) {+ const rows = [safeOneLine(state?.summary || "recoverable interaction error")];+ if (state?.mutationState === "completed") rows.push(`mutation: completed${state.mutationTool ? ` · ${state.mutationTool}` : ""}`);+ else if (state?.mutationState === "uncertain") rows.push(`mutation: uncertain${state.mutationTool ? ` · ${state.mutationTool}` : ""}`);+ else rows.push("mutation: not started in this failed step");+ rows.push(safeOneLine(state?.action || "Continue when ready."));+ return rows;+}++export function recoverableHistoryRow(state) {+ return {+ role: "recoverable_error",+ text: safeOneLine(state?.summary || "recoverable interaction error", 500),+ mutationState: state?.mutationState || "not_started",+ mutationTool: state?.mutationTool || undefined,+ status: state?.status || undefined,+ createdAt: new Date().toISOString(),+ };+}diff --git a/scripts/mso-agent-layout.mjs b/scripts/mso-agent-layout.mjsnew file mode 100644index 00000000..d27d2f70--- /dev/null+++ b/scripts/mso-agent-layout.mjs@@ -0,0 +1,64 @@+import process from "node:process";+import { fit } from "./mso-agent-ui.mjs";+import { statusParts } from "./mso-agent-status.mjs";++const LABELS = {+ assistant: "Assistant",+ work: "Agent work",+ local: "Local agent",+ error: "Error",+ input: "Input",+};++function plain(value) { return String(value ?? "").replace(/\x1b\[[0-9;]*m/g, ""); }+function width(value) { return Array.from(plain(value)).length; }++export function tuiColumns(output = process.stdout) {+ return Math.max(24, Number(output?.columns || 100));+}++export function sectionDivider(kind, { columns = tuiColumns(), detail = "", colors = {} } = {}) {+ const total = Math.max(24, Number(columns || 100) - 1);+ const label = LABELS[kind] || String(kind || "Section");+ const suffix = String(detail || "").replace(/[\r\n\t]+/g, " ").trim();+ const center = fit(` ${label}${suffix ? ` · ${suffix}` : ""} `, Math.max(8, total - 4));+ const remaining = Math.max(0, total - width(center));+ const leftCount = Math.min(3, Math.max(1, Math.floor(remaining * 0.08)));+ const rightCount = Math.max(0, remaining - leftCount);+ const tone = kind === "error" ? (colors.err || "")+ : kind === "local" ? (colors.c || colors.cyan || "")+ : kind === "work" ? (colors.warn || "")+ : (colors.blue || "");+ return `${tone}${"─".repeat(leftCount)}${center}${"─".repeat(rightCount)}${colors.reset || ""}`;+}++export function sectionBlock(kind, text, options = {}) {+ const body = String(text ?? "").replace(/\r/g, "");+ return `${sectionDivider(kind, options)}\n${body}`;+}++export function printSection(kind, options = {}, print = console.log) {+ print(sectionDivider(kind, options));+}++export function composerPrompt(session, colors = {}) {+ const name = String(session?.agentSession?.name || "agent").replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 32) || "agent";+ return `${colors.blue || ""}${colors.bold || ""}@${name}${colors.reset || ""} ${colors.blue || ""}${colors.bold || ""}›${colors.reset || ""} `;+}++export function composerFooter(session, colors = {}, columns = tuiColumns()) {+ const permission = String(session?.permission || "ask");+ const tone = permission === "yolo" ? (colors.err || "") : permission === "auto" ? (colors.warn || "") : (colors.c || colors.cyan || "");+ const mode = `${tone}mode ${permission}${colors.reset || ""}`;+ if (session?.statusBar === false) return `${mode}${colors.dim || ""} · Tab cycle${colors.reset || ""}`;+ const parts = statusParts(session).filter((part) => !String(part).startsWith("@"));+ const raw = `mode ${permission} · ${parts.join(" · ")} · Tab cycle`;+ const fitted = fit(raw, Math.max(20, Number(columns || 100) - 2));+ const prefix = `mode ${permission}`;+ if (!fitted.startsWith(prefix)) return fitted;+ return `${tone}${prefix}${colors.reset || ""}${colors.dim || ""}${fitted.slice(prefix.length)}${colors.reset || ""}`;+}++export function composerSeparator(session, colors = {}, columns = tuiColumns()) {+ return sectionDivider("input", { columns, detail: `@${session?.agentSession?.name || "agent"}`, colors });+}diff --git a/scripts/mso-agent-layout.test.ts b/scripts/mso-agent-layout.test.tsnew file mode 100644index 00000000..0b853e46--- /dev/null+++ b/scripts/mso-agent-layout.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import { composerFooter, composerPrompt, composerSeparator, sectionBlock, sectionDivider } from "./mso-agent-layout.mjs";++const colors = { blue: "", bold: "", reset: "", dim: "", c: "", cyan: "", warn: "", err: "" };+const session = {+ permission: "ask", statusBar: true, history: [], usage: { totalTokens: 0 },+ state: { config: { provider: "openai-codex", model: "gpt-5.6-terra" }, modelMeta: { context: 128000 } },+ agentSession: { id: "session-a", name: "milo", title: "Review auth", compactThresholdTokens: 700000, estimatedTokens: 120 },+};++describe("MSO Agent sectioned terminal layout", () => {+ it("renders terminal-width dividers for assistant, work, local-agent, error, and input streams", () => {+ for (const kind of ["assistant", "work", "local", "error", "input"] as const) {+ const line = sectionDivider(kind, { columns: 60, colors });+ expect(Array.from(line)).toHaveLength(59);+ expect(line).toContain("─");+ }+ expect(sectionDivider("assistant", { columns: 60, colors })).toContain("Assistant");+ expect(sectionDivider("work", { columns: 60, colors })).toContain("Agent work");+ expect(sectionDivider("local", { columns: 60, colors })).toContain("Local agent");+ });++ it("puts the short agent handle in the composer header and permission mode only in the bottom footer", () => {+ const prompt = composerPrompt(session, colors);+ const footer = composerFooter(session, colors, 100);+ expect(prompt).toBe("@milo › ");+ expect(prompt).not.toContain("ask");+ expect(footer).toContain("mode ask");+ expect(footer).not.toContain("@milo");+ });++ it("separates the bottom input area from transcript output with a named full-width divider", () => {+ const divider = composerSeparator(session, colors, 72);+ expect(divider).toContain("Input · @milo");+ expect(Array.from(divider)).toHaveLength(71);+ });++ it("wraps local/error text as one section block without duplicating content", () => {+ const block = sectionBlock("local", "[agent-zahra] hello", { columns: 72, colors });+ expect(block.match(/Local agent/g)).toHaveLength(1);+ expect(block.match(/\[agent-zahra\] hello/g)).toHaveLength(1);+ });+});diff --git a/scripts/mso-agent-local.mjs b/scripts/mso-agent-local.mjsindex 669a8e65..89d7cc6d 100644--- a/scripts/mso-agent-local.mjs+++ b/scripts/mso-agent-local.mjs@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import process from "node:process";import { api, apiResponse, C } from "./mso-agent-runtime.mjs";import { persistSession } from "./mso-agent-session-ui.mjs";+import { sectionBlock } from "./mso-agent-layout.mjs";const HEARTBEAT_MS = 20_000;const RECONNECT_MIN_MS = 800;@@ -213,7 +214,9 @@ export class LocalAgentBridge {}await persistSession(this.session);this.seen.add(id);- if (!alreadyStored) this.composer.notify(presentation.text);+ if (!alreadyStored) this.composer.notify(sectionBlock("local", presentation.text, {+ columns: this.composer?.output?.columns, detail: String(message?.senderLabel || "peer"), colors: C,+ }));if (message?.intent !== "request") await this.ack([id]).catch(() => undefined);}diff --git a/scripts/mso-agent-mentions.mjs b/scripts/mso-agent-mentions.mjsindex f3f9a89e..88e26276 100644--- a/scripts/mso-agent-mentions.mjs+++ b/scripts/mso-agent-mentions.mjs@@ -1,10 +1,14 @@import { api } from "./mso-agent-runtime.mjs";import { persistSession } from "./mso-agent-session-ui.mjs";+import { sectionBlock } from "./mso-agent-layout.mjs";+import { safeErrorSummary } from "./mso-agent-errors.mjs";function clean(value) {return String(value || "").trim().replace(/^\[|\]$/g, "").toLocaleLowerCase();}+function parsedTarget(line) { return parseLocalAgentMention(line)?.target || "peer"; }+export function parseLocalAgentMention(line) {const match = String(line || "").match(/^@([^\s]+)\s+([\s\S]+)$/);if (!match) return null;@@ -100,10 +104,14 @@ export async function handleLocalAgentMentionInput(session, line, colors) {try {const mention = await dispatchLocalAgentMention(session, line);if (!mention) return false;- console.log(`${colors.c}↳ ${mention.acknowledgement}${colors.reset}`);+ console.log(sectionBlock("local", `${colors.c}↳ ${mention.acknowledgement}${colors.reset}`, {+ columns: process.stdout.columns, detail: mention.result?.target?.label || parsedTarget(line), colors,+ }));return true;} catch (error) {- console.error(`${colors.err}${error instanceof Error ? error.message : String(error)}${colors.reset}`);+ console.error(sectionBlock("error", `${colors.err}${safeErrorSummary(error)}${colors.reset}`, {+ columns: process.stdout.columns, detail: "local agent", colors,+ }));return true;}}diff --git a/scripts/mso-agent-permissions.mjs b/scripts/mso-agent-permissions.mjsindex efa19f41..4029f891 100644--- a/scripts/mso-agent-permissions.mjs+++ b/scripts/mso-agent-permissions.mjs@@ -17,12 +17,6 @@ export function nextPermissionMode(current) {}-export function permissionPrompt(mode, C) {- const current = permissionMode(mode) || PERMISSION_MODES[0];- const tone = current.id === "yolo" ? C.err : current.id === "auto" ? C.warn : C.cyan;- return `${tone}${C.bold}[${current.id}]${C.reset} ${C.blue}${C.bold}›${C.reset} `;-}-export function approvesTool(mode, scope) {if (scope === "read") return true;if (mode === "yolo") return true;diff --git a/scripts/mso-agent-permissions.test.ts b/scripts/mso-agent-permissions.test.tsindex 0b858374..4e4726eb 100644--- a/scripts/mso-agent-permissions.test.ts+++ b/scripts/mso-agent-permissions.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { approvesTool, nextPermissionMode, permissionCompletionItems, permissionMode, permissionPrompt } from "./mso-agent-permissions.mjs";+import { approvesTool, nextPermissionMode, permissionCompletionItems, permissionMode } from "./mso-agent-permissions.mjs";describe("MSO Agent permission modes", () => {it("parses stable human aliases without numeric-only UX", () => {diff --git a/scripts/mso-agent-runtime-error.test.ts b/scripts/mso-agent-runtime-error.test.tsnew file mode 100644index 00000000..cc90151b--- /dev/null+++ b/scripts/mso-agent-runtime-error.test.ts@@ -0,0 +1,25 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { AgentApiError } from "./mso-agent-errors.mjs";+import { api } from "./mso-agent-runtime.mjs";++afterEach(() => vi.unstubAllGlobals());++describe("MSO Agent API error metadata", () => {+ it("keeps HTTP status/path and marks an HTTP response as dispatched", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ error: "bad request" }), {+ status: 400, headers: { "content-type": "application/json" },+ })));+ let caught: any;+ try { await api("/api/test"); } catch (error) { caught = error; }+ expect(caught).toBeInstanceOf(AgentApiError);+ expect(caught).toMatchObject({ status: 400, path: "/api/test", method: "GET", requestDispatched: true });+ });++ it("marks a transport failure before a response as dispatch-unconfirmed", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("socket closed"); }));+ let caught: any;+ try { await api("/api/test", { method: "POST", body: "{}" }); } catch (error) { caught = error; }+ expect(caught).toBeInstanceOf(AgentApiError);+ expect(caught).toMatchObject({ status: null, path: "/api/test", method: "POST", requestDispatched: false });+ });+});diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjsindex 6b009066..47c9ced1 100644--- a/scripts/mso-agent-runtime.mjs+++ b/scripts/mso-agent-runtime.mjs@@ -3,6 +3,7 @@ import process from "node:process";import { selectToolsForTurn } from "./mso-agent-tool-router.mjs";import { projectHistoryForModel } from "./mso-agent-context.mjs";import { C, fit, MSO_TITLE_ART, printAgentBanner } from "./mso-agent-ui.mjs";+import { AgentApiError } from "./mso-agent-errors.mjs";export { C, MSO_TITLE_ART } from "./mso-agent-ui.mjs";export const BASE = String(@@ -39,13 +40,23 @@ export async function apiResponse(path, init = {}) {if (cookie) headers.set("cookie", cookie);if (init.body && !headers.has("content-type"))headers.set("content-type", "application/json");- const res = await fetch(`${BASE}${path}`, { ...init, headers });+ const method = String(init.method || "GET").toUpperCase();+ let res;+ try {+ res = await fetch(`${BASE}${path}`, { ...init, headers });+ } catch (error) {+ if (["AbortError", "TimeoutError"].includes(String(error?.name || ""))) throw error;+ throw new AgentApiError(error instanceof Error ? error.message : "transport failure", {+ path, method, requestDispatched: false, cause: error,+ });+ }if (!res.ok) {const text = await res.text();let body = null;try { body = text ? JSON.parse(text) : null; } catch { body = text; }- throw new Error(+ throw new AgentApiError(typeof body === "object" && body?.error ? String(body.error) : `HTTP ${res.status}`,+ { status: res.status, path, method, requestDispatched: true },);}return res;@@ -207,26 +218,34 @@ export async function streamTurn(projected.messages,skillContext,);- const res = await fetch(`${BASE}/api/assistant`, {- method: "POST",- headers: {- origin: ORIGIN,- cookie: cookieHeader(),- "content-type": "application/json",- },- body: JSON.stringify({- messages: projected.messages,- tools: activeTools.tools.map(toolForModel),- system: sessionSystem(agentSession, skillContext),- }),- signal,- });+ let res;+ try {+ res = await fetch(`${BASE}/api/assistant`, {+ method: "POST",+ headers: {+ origin: ORIGIN,+ cookie: cookieHeader(),+ "content-type": "application/json",+ },+ body: JSON.stringify({+ messages: projected.messages,+ tools: activeTools.tools.map(toolForModel),+ system: sessionSystem(agentSession, skillContext),+ }),+ signal,+ });+ } catch (error) {+ if (["AbortError", "TimeoutError"].includes(String(error?.name || ""))) throw error;+ throw new AgentApiError(error instanceof Error ? error.message : "assistant transport failure", {+ path: "/api/assistant", method: "POST", requestDispatched: false, cause: error,+ });+ }if (!res.ok || !res.body) {let body = {};- try {- body = await res.json();- } catch {}- throw new Error(body?.error || `assistant HTTP ${res.status}`);+ try { body = await res.json(); } catch {}+ throw new AgentApiError(body?.error || `assistant HTTP ${res.status}`, {+ status: res.status, path: "/api/assistant", method: "POST", requestDispatched: true,+ });}const reader = res.body.getReader();const dec = new TextDecoder();@@ -258,7 +277,13 @@ export async function streamTurn(const done = JSON.parse(data);stopReason = done?.stopReason ?? null;usage = done?.usage ?? null;- } else if (event === "error") throw new Error(JSON.parse(data));+ } else if (event === "error") {+ let message = "assistant stream error";+ try { message = String(JSON.parse(data) || message); } catch { message = String(data || message); }+ throw new AgentApiError(message, {+ path: "/api/assistant", method: "POST", requestDispatched: true,+ });+ }}}if (text && !text.endsWith("\n")) output?.write?.("\n");diff --git a/scripts/mso-agent-session-ui.mjs b/scripts/mso-agent-session-ui.mjsindex 3b098775..077cb185 100644--- a/scripts/mso-agent-session-ui.mjs+++ b/scripts/mso-agent-session-ui.mjs@@ -45,6 +45,7 @@ export function applyNewSessionState(session, loaded, requestedTitle = "") {titleOverride: requestedTitle ? (loaded.title || requestedTitle) : null,usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },lastElapsedMs: 0,+ pendingApproval: null,});return session;}@@ -72,6 +73,7 @@ export async function resumeInto(rl, session, query) {titleOverride: loaded.title || null,usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },lastElapsedMs: 0,+ pendingApproval: null,});syncPromptHistory(rl, session);console.log(`${C.c}resumed @${loaded.name} · ${loaded.title || "MSO Agent session"}${C.reset} · ${session.history.length} history rows`);diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjsindex e0790371..8ddabe82 100644--- a/scripts/mso-agent-status.mjs+++ b/scripts/mso-agent-status.mjs@@ -92,9 +92,6 @@ export function statusParts(session, cwd = process.cwd()) {].filter(Boolean);}-export function renderStatusBar(session, C, cwd = process.cwd()) {- return `${C.blue}${C.bold}◆${C.reset} ${statusParts(session, cwd).join(`${C.dim} · ${C.reset}`)}`;-}export function detailedStatus(session, cwd = process.cwd()) {const cfg = session?.state?.config || {};diff --git a/scripts/mso-agent-subagent.mjs b/scripts/mso-agent-subagent.mjsindex 64b972f9..e8c9ac27 100644--- a/scripts/mso-agent-subagent.mjs+++ b/scripts/mso-agent-subagent.mjs@@ -1,4 +1,5 @@import { persistSession } from "./mso-agent-session-ui.mjs";+import { printSection } from "./mso-agent-layout.mjs";export const SUBAGENT_USAGE = "/spawn [--name <name>] [--scope read|write|exec] [--turns 1-12] <objective>";@@ -22,7 +23,8 @@ export async function runForegroundSubagent({ rl, session, input, executeTool, cconst tool = session.state.tools.find((row) => row.name === "agent_subagent_run");if (!tool) throw new Error("agent_subagent_run is unavailable; refresh the MSO runtime/tool catalog");const call = { id: `slash_subagent_${Date.now()}`, name: "agent_subagent_run", input };- const outcome = await executeTool(rl, tool, call, session.agentSession, session.permission);+ printSection("work", { detail: `subagent ${input.name || "worker"}`, colors });+ const outcome = await executeTool(rl, tool, call, session.agentSession, session.permission, undefined, null, { approvalState: session });if (!outcome.ok) throw new Error(outcome.result || "subagent failed");let parsed = null;try { parsed = JSON.parse(outcome.result); } catch {}diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjsnew file mode 100644index 00000000..0455748d--- /dev/null+++ b/scripts/mso-agent-turn.mjs@@ -0,0 +1,154 @@+import process from "node:process";+import { canonicalAgentApproval } from "../lib/agent/approval.mjs";+import { requestExactToolApproval } from "./mso-agent-approval-ui.mjs";+import { AgentMutationUncertainError, isAgentApiError, isRecoverableInteractionError, recoverableErrorLines, recoverableHistoryRow, recoverableTurnState } from "./mso-agent-errors.mjs";+import { printSection, sectionDivider } from "./mso-agent-layout.mjs";+import { beginSkillInvocation, endSkillInvocation } from "./mso-agent-skills.mjs";+import { isAbortError } from "./mso-agent-interrupt.mjs";+import { approvesTool } from "./mso-agent-permissions.mjs";+import { api, C, streamTurn } from "./mso-agent-runtime.mjs";+import { persistSession } from "./mso-agent-session-ui.mjs";+import { addUsage } from "./mso-agent-status.mjs";+import { oneShotApproves } from "./mso-agent-oneshot.mjs";++function lazyAssistantOutput(session, options = {}) {+ if (options.quiet) return null;+ let opened = false;+ return {+ write(value) {+ if (!opened) {+ opened = true;+ printSection("assistant", { detail: `@${session?.agentSession?.name || "agent"}`, colors: C });+ }+ return process.stdout.write(String(value ?? ""));+ },+ };+}++export async function executeTool(rl, tool, call, agentSession, permission = "ask", signal = undefined, onInterrupt = null, options = {}) {+ if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };+ const needsApprovalDigest = tool.scope !== "read";+ let approval = null;+ if (needsApprovalDigest) {+ try { approval = canonicalAgentApproval(tool.name, call.input || {}); }+ catch (error) { return { ok: false, result: `cannot safely approve tool call: ${error instanceof Error ? error.message : String(error)}` }; }+ }+ let approved = options.approvalScope+ ? oneShotApproves(options.approvalScope, tool.scope)+ : approvesTool(permission, tool.scope);+ if (!approved) {+ if (options.approvalScope) return { ok: false, result: "denied by user" };+ const approvalState = options.approvalState || null;+ if (approvalState) approvalState.pendingApproval = {+ tool: tool.name, scope: tool.scope, digest: approval?.digest || null, createdAt: new Date().toISOString(),+ };+ try {+ approved = await requestExactToolApproval(rl, {+ tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C,+ });+ if (approvalState) approvalState.pendingApproval = null;+ } catch (error) {+ if (signal?.aborted || isAbortError(error)) { if (approvalState) approvalState.pendingApproval = null; }+ throw error;+ }+ } else if (needsApprovalDigest && !options.quiet && !options.approvalScope) {+ 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}`);+ const request = options.apiRequest || api;+ try {+ const input = approval ? approval.payload.input : (call.input || {});+ const out = await request("/api/v1/agent-tools", {+ method: "POST",+ body: JSON.stringify({+ name: tool.name,+ input,+ sessionId: agentSession.id,+ ...(tool.scope === "read" ? {} : { approved: true, approvalDigest: approval.digest }),+ }),+ signal,+ });+ if (!options.quiet) 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;+ if (!options.quiet) process.stdout.write(`\r${C.err} ✗ ${tool.name}${C.reset}\n`);+ if (tool.scope !== "read" && isAgentApiError(error)) throw new AgentMutationUncertainError(tool.name, error);+ return { ok: false, result: (error instanceof Error ? error.message : String(error)).slice(0, 2000) };+ }+}++export async function agentRound(rl, session, skillContext = null, signal = undefined, onInterrupt = null, options = {}) {+ const startedAt = Date.now();+ const historyCheckpoint = Math.max(0, session.history.length - 1);+ const calls = [];+ let finalText = "", rounds = 0;+ beginSkillInvocation(session, skillContext, C);+ const turnStream = options.streamTurn || streamTurn;+ const toolExecutor = options.executeTool || executeTool;+ try {+ for (let turn = 0; turn < 10; turn++) {+ rounds = turn + 1;+ const result = await turnStream(+ session.history, session.state.tools, session.agentSession, skillContext, signal,+ session.state.modelMeta?.context, lazyAssistantOutput(session, options),+ );+ if (skillContext) session.lastInvokedSkill = skillContext;+ finalText = result.text;+ session.usage = addUsage(session.usage, result.usage);+ session.lastElapsedMs = Date.now() - startedAt;+ session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });+ if (!result.toolUses.length) return { text: finalText, calls, rounds, usage: session.usage, elapsedMs: session.lastElapsedMs };+ if (!options.quiet) printSection("work", { detail: `@${session?.agentSession?.name || "agent"}`, colors: C });+ const results = [];+ for (const call of result.toolUses) {+ const tool = session.state.tools.find((row) => row.name === call.name);+ const outcome = await toolExecutor(rl, tool, call, session.agentSession, session.permission, signal, onInterrupt, {+ ...options, approvalState: options.approvalState || session,+ });+ calls.push({ name: call.name, scope: tool?.scope || "unknown", ok: outcome.ok });+ results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });+ }+ session.history.push({ role: "tool", results });+ }+ if (!options.quiet) console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);+ return { text: finalText, calls, rounds, usage: session.usage, elapsedMs: session.lastElapsedMs, turnLimitReached: true };+ } catch (error) {+ if (signal?.aborted || isAbortError(error)) session.history.splice(historyCheckpoint);+ else if (error && typeof error === "object" && !error.turnJournal) error.turnJournal = { calls: [...calls] };+ throw error;+ } finally {+ endSkillInvocation(session, skillContext);+ }+}++export function renderInteractionFailure(error, session, journal = {}, colors = C, print = console.log) {+ const state = recoverableTurnState(error, journal);+ print(sectionDivider("error", { detail: `@${session?.agentSession?.name || "agent"}`, colors }));+ for (const line of recoverableErrorLines(state)) print(`${colors.err || ""}${line}${colors.reset || ""}`);+ return state;+}++export async function runInteractiveRound(rl, session, skillContext, interrupts, localBridge = null) {+ const signal = interrupts.beginTurn();+ await localBridge?.setState("busy");+ let roundResult = null;+ try {+ roundResult = 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 {+ const journal = error?.turnJournal || { calls: roundResult?.calls || [] };+ const state = renderInteractionFailure(error, session, journal, C);+ if (isRecoverableInteractionError(error)) session.history.push(recoverableHistoryRow(state));+ }+ await persistSession(session).catch(() => undefined);+ } finally {+ interrupts.endTurn(signal);+ await localBridge?.setState("idle");+ }+}diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex 256fb653..4d909933 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -1,117 +1,18 @@#!/usr/bin/env nodeimport 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";+import { AgentInterruptManager } from "./mso-agent-interrupt.mjs";import { slashCompletionItems } from "./mso-agent-slash.mjs";-import { addUsage, renderStatusBar } from "./mso-agent-status.mjs";import { persistSession, restartSessionArg, resumeArg, startupSession, syncPromptHistory } from "./mso-agent-session-ui.mjs";-import { C, api, printBanner, state, streamTurn } from "./mso-agent-runtime.mjs";+import { C, printBanner, state } from "./mso-agent-runtime.mjs";import { handleSlash } from "./mso-agent-commands.mjs";-import { approvesTool, nextPermissionMode, permissionMode, permissionPrompt } from "./mso-agent-permissions.mjs";+import { nextPermissionMode, permissionMode } from "./mso-agent-permissions.mjs";import { consumeRestartUiState, relaunchCurrentAgentSession } from "./mso-agent-lifecycle.mjs";-import { oneShotApproves, oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";+import { oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";import { LocalAgentBridge, handleLocalAgentMentionInput, runForegroundSubagent } from "./mso-agent-collaboration.mjs";--async function executeTool(rl, tool, call, agentSession, permission = "ask", signal = undefined, onInterrupt = null, options = {}) {- if (!tool) return { ok: false, result: `unknown tool requested by model: ${call.name}` };- const needsApprovalDigest = tool.scope !== "read";- let approval = null;- if (needsApprovalDigest) {- try { approval = canonicalAgentApproval(tool.name, call.input || {}); }- catch (error) { return { ok: false, result: `cannot safely approve tool call: ${error instanceof Error ? error.message : String(error)}` }; }- }- let approved = options.approvalScope- ? oneShotApproves(options.approvalScope, tool.scope)- : approvesTool(permission, tool.scope);- if (!approved) {- // Autonomous one-shot mode must never fall back to an interactive prompt.- // 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" };- approved = await requestExactToolApproval(rl, {- tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C,- });- } else if (needsApprovalDigest && !options.quiet && !options.approvalScope) {- // 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}`);- try {- const input = approval ? approval.payload.input : (call.input || {});- const out = await api("/api/v1/agent-tools", {- method: "POST",- body: JSON.stringify({- name: tool.name,- input,- sessionId: agentSession.id,- ...(tool.scope === "read" ? {} : { approved: true, approvalDigest: approval.digest }),- }),- signal,- });- if (!options.quiet) 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;- if (!options.quiet) 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, signal = undefined, onInterrupt = null, options = {}) {- const startedAt = Date.now();- const historyCheckpoint = Math.max(0, session.history.length - 1);- const calls = [];- let finalText = "", rounds = 0;- beginSkillInvocation(session, skillContext, C);- try {- for (let turn = 0; turn < 10; turn++) {- rounds = turn + 1;- const result = await streamTurn(session.history, session.state.tools, session.agentSession, skillContext, signal, session.state.modelMeta?.context, options.quiet ? null : process.stdout); if (skillContext) session.lastInvokedSkill = skillContext;- finalText = result.text;- session.usage = addUsage(session.usage, result.usage);- session.lastElapsedMs = Date.now() - startedAt;- session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });- if (!result.toolUses.length) return { text: finalText, calls, rounds, usage: session.usage, elapsedMs: session.lastElapsedMs };- 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, session.permission, signal, onInterrupt, options);- calls.push({ name: call.name, ok: outcome.ok });- results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });- }- session.history.push({ role: "tool", results });- }- if (!options.quiet) console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);- return { text: finalText, calls, rounds, usage: session.usage, elapsedMs: session.lastElapsedMs, turnLimitReached: true };- } catch (error) {- if (signal?.aborted || isAbortError(error)) session.history.splice(historyCheckpoint);- throw error;- } finally {- endSkillInvocation(session, skillContext);- }-}--async function runInteractiveRound(rl, session, skillContext, interrupts, localBridge = null) {- const signal = interrupts.beginTurn();- await localBridge?.setState("busy");- try {- await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent());- await persistSession(session);- } 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);- await localBridge?.setState("idle");- }-}-+import { composerFooter, composerPrompt, composerSeparator } from "./mso-agent-layout.mjs";+import { agentRound, executeTool, renderInteractionFailure, runInteractiveRound } from "./mso-agent-turn.mjs";+import { pathToFileURL } from "node:url";async function runOneShot(opts) {const requested = resumeArg(process.argv.slice(2));@@ -122,7 +23,7 @@ async function runOneShot(opts) {pendingSkill: null, activeSkill: null, lastInvokedSkill: null,titleOverride: requested ? (agentSession.title || null) : null,usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, lastElapsedMs: 0, statusBar: false,- permission: "ask",+ permission: "ask", pendingApproval: null,};session.history.push({ role: "user", text: opts.prompt });const result = await agentRound(null, session, null, undefined, null, { quiet: true, approvalScope: opts.approvalScope });@@ -164,7 +65,7 @@ async function main() {pendingSkill: null, activeSkill: null, lastInvokedSkill: null,titleOverride: (requested || restartSessionId) ? (agentSession.title || null) : null,usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, lastElapsedMs: 0,- statusBar: restartUi.statusBar ?? true, permission: forcedPermission,+ statusBar: restartUi.statusBar ?? true, permission: forcedPermission, pendingApproval: null,};const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C }); syncPromptHistory(rl, session);const localBridge = new LocalAgentBridge({ session, composer: rl });@@ -186,11 +87,11 @@ async function main() {if (interrupts.exitRequested) break;let line = "";try {- console.log();- if (session.statusBar) console.log(renderStatusBar(session, C));- const answer = await rl.question(() => permissionPrompt(session.permission, C), {+ const answer = await rl.question(() => composerPrompt(session, C), {complete: completeSlash,onTab: () => { session.permission = nextPermissionMode(session.permission).id; },+ separator: () => composerSeparator(session, C, process.stdout.columns),+ footer: () => composerFooter(session, C, process.stdout.columns),});if (answer === null) break;line = answer.trim();@@ -204,7 +105,8 @@ async function main() {if (result === "refresh") await localBridge.syncSession();if (result === "unknown") console.log("unknown command; /help lists commands.");} catch (error) {- console.error(`${C.err}${error instanceof Error ? error.message : String(error)}${C.reset}`);+ renderInteractionFailure(error, session, {}, C);+ await persistSession(session).catch(() => undefined);}if (interrupts.exitRequested) break;continue;@@ -230,4 +132,5 @@ async function main() {}}-main().catch((error) => { console.error(`${C.err}mso agent: ${error instanceof Error ? error.message : String(error)}${C.reset}`); process.exit(1); });+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); });diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.tsindex 2d439201..104f41d5 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.11.1"');+ expect(cli).toContain('VERSION="1.12.0"');expect(cli).toContain("models * Configure AI providers/auth");expect(cli).toContain("model [ref] Select active model");expect(agentCli).toContain("run_models()");