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): one live activity row and env-tunable turn budgets (#154)
Abdurrahman Fakhrulda14f39c764a
diff --git a/.env.example b/.env.exampleindex fb0ab186..376de280 100644--- a/.env.example+++ b/.env.example@@ -256,7 +256,15 @@ OS_SESSION_SECRET=# Session artifacts use this same root: temp/<client-hash>/<session-id> (owner-only).# OS_AGENT_ARTIFACT_RETENTION_DAYS=7 # dormant artifacts only; clamped 1-30; active leases preserved# OS_PROJECT_AGENT_TASKS_DIR=~/.mso/project-agent-tasks # private project-agent message/status records-# OS_SUBAGENT_MAX_TURNS=12 # server policy cap for one foreground subagent; default 12, absolute max 48 (each child still defaults to 6)+# OS_SUBAGENT_MAX_TURNS=12 # server policy cap for one foreground subagent; default 12, absolute max sees OS_SUBAGENT_ABSOLUTE_MAX_TURNS+# OS_SUBAGENT_ABSOLUTE_MAX_TURNS=48 # hard ceiling OS_SUBAGENT_MAX_TURNS may reach; default 48+# OS_SUBAGENT_DEFAULT_TURNS=6 # turns a subagent gets when the caller passes none; default 6+# OS_SUBAGENT_MAX_TIMEOUT_MS=120000 # longest one foreground subagent may run; default 120000+# --- Agent turn budgets (each has a conservative default; raise deliberately) ---+# OS_AGENT_MAX_ROUNDS=1000 # interactive MSO Agent model rounds per turn (stream → tools → stream); default 1000+# OS_ASSISTANT_MAX_TURNS=8 # web Assistant tool rounds per request; default 8+# OS_AGENT_PROFILE_MAX_TURNS=6 # rounds one saved-profile read run may take; default 6+# OS_AGENT_PROFILE_MAX_TOOL_CALLS=16 # tool calls one saved-profile read run may make; default 16# Native Local Agents use private defaults; overrides are normally unnecessary.# OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json # live receive leases/aliases (0600)# OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json # durable explicit local messages/tasks (0600)diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex f86e951b..e38d5c57 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,16 +4,25 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → Account → About shows as “What's new”.-## 2026-10-24+## 2026-10-25++**Added**++- `agent` one live activity row and env-tunable turn budgets**Fixed**-- `install` bump vendored node-gyp lock undici 6.29.0 -> 6.29.1-- `deps` bump zod past GHSA-mrhx-c7xc-m3w5 (>=4.6.6)+- `settings` only grade an update after the request actually starts-**Chores**+**Docs**++- `progress` record the agent live-row and turn-budget change++## 2026-10-24-- `security` allowlist reviewed Convex 152 fixtures reachable from other open branch+**Fixed**++- `deps` clear undici + zod advisories blocking every merge (#153)## 2026-10-23@@ -1481,21 +1490,3 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- `mcp` allow ChatGPT Australia file storage- `mcp` allow ChatGPT regional file storage- `mcp` report rejected file host safely--## 2026-08-19--**Added**--- enable image generation and full access defaults-- `mcp` isolate workflows and standardize skill flows-- `mcp` streamline bootstrap and workflow visibility-- add semantic skill memory and workflow recipes-- add secure temporary screenshot links-- add MCP screenshots and live activity--**Fixed**--- `oauth` force visible ChatGPT callback-- `icons` use native macOS and Windows artwork-- `update` remove passwordless sudo requirement-- use official agent logosdiff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.mdindex 4cb24825..bdc39d94 100644--- a/docs/INFRASTRUCTURE-PROVIDERS.md+++ b/docs/INFRASTRUCTURE-PROVIDERS.md@@ -87,6 +87,15 @@ by full-width `Assistant`, `Agent work`, `Local agent`, and `Error` dividers. Renever auto-repeat an uncertain write/exec mutation; verify target state before retrying a mutation whose outcomeis reported as `uncertain`.+Inside `Agent work` the progress is one live row, not one row per tool: every round of a single request stays in+the same section, and the tools that ran are repainted in place (`⠹ fs_search · 3/7 tools · 12s`) on a single+terminal line, with the turn's model wait shown as a spinner in that same row. The turn ends with one compact+receipt (`7 tools · all ok · 1m12s`). The exchange is driven by the same cursor primitives the composer uses;+when stdout is not a TTY (piped output, CI, the PTY smoke harness) nothing is animated and each tool keeps its+own discrete `[scope] name` / `↳ name…` / `✓ name` line, so log consumers never receive cursor control. An async+Local Agent event redraws above the draft as before — the live row is suspended around that write. The round+budget for one interactive turn is `OS_AGENT_MAX_ROUNDS` (default 1000).+## 2. One tool catalog, two transports`scripts/mso-agent.mjs` does not invent a second host-tool implementation. It asks thediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 943bd7f3..2f07ce44 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,33 @@+## 2026-10-25: Agent transcript — one live row per turn, and owner-owned turn budgets++The interactive Agent printed an `Agent work` divider for every model round and a separate row+for every tool call, so a ten-round turn produced ten headers plus one row per call and pushed the+conversation off the screen. Progress now renders on a single live row below the transcript+(`⠹ fs_search · 3/7 tools · 12s`), repainted in place with the composer's own cursor primitives,+with one `Agent work` section per turn, a spinner while the first token is in flight, and a compact+receipt at the end (`3 tools · all ok · 8s`). Async Local Agent traffic suspends and repaints the+row, so a foreign write never lands inside it. Non-TTY stdout keeps the previous discrete lines, so+pipes, CI and the PTY smoke harness never receive cursor control.++The hard caps that ended work with `turn limit reached` are now owner settings instead of code+constants: `OS_AGENT_MAX_ROUNDS` (10 -> 1000 rounds per interactive turn),+`OS_ASSISTANT_MAX_TURNS`, `OS_SUBAGENT_ABSOLUTE_MAX_TURNS`, `OS_SUBAGENT_DEFAULT_TURNS`,+`OS_SUBAGENT_MAX_TIMEOUT_MS`, `OS_AGENT_PROFILE_MAX_TURNS` and+`OS_AGENT_PROFILE_MAX_TOOL_CALLS`. Defaults are the historical values, so behaviour only moves+where an operator sets the knob, and `intEnv` is exported from `session-policy` instead of copied+per caller.++A settings follow-up rides along: `UpdateSection.start()` marked the run as "seen running" before+the POST resolved, so a refused update was still graded from the log and a previous attempt's+`UPDATE OK` produced a success banner for an update that never ran. The flag is now set only after+a started response.++**Evidence.** `typecheck` 0, `lint` 0, `check-cycles` 2138 files / 0 cycles, `check-architecture`+exit 0 at 43/43 files-over-220, `check-docs` current, `gen-comparison --check` current,+`check-contrast` 0 fail, full vitest **852 files / 5535 tests passed**. A real PTY run of+`mso --yolo agent` produced one `Agent work` section, 736 in-place repaints and the receipt+`3 tools · all ok · 8s`.+## 2026-10-22: CodeQL follow-up — the taint, not the temp pathThe previous entry closed the symlink/TOCTOU concern but not `js/http-to-file-access`: the icondiff --git a/docs/SUBAGENTS.md b/docs/SUBAGENTS.mdindex b877cf3f..e1551034 100644--- a/docs/SUBAGENTS.md+++ b/docs/SUBAGENTS.md@@ -49,8 +49,8 @@ Inside the child:- default `max_scope` is `read`;- requested scope cannot exceed the parent caller scope;-- max model/tool rounds default to 6; the server policy `OS_SUBAGENT_MAX_TURNS` defaults to 12 and may be raised up to the absolute cap of 48;-- timeout defaults to 60 seconds and caps at 120 seconds;+- max model/tool rounds default to `OS_SUBAGENT_DEFAULT_TURNS` (6); the server policy `OS_SUBAGENT_MAX_TURNS` defaults to 12 and may be raised up to `OS_SUBAGENT_ABSOLUTE_MAX_TURNS` (48);+- timeout defaults to 60 seconds and caps at `OS_SUBAGENT_MAX_TIMEOUT_MS` (120 seconds);- result text is bounded to 64 KiB;- recursive `agent_subagent_run` is unavailable;- `agent_session_*`, `agent_memory_*`, `local_agent_*`, and `a2a_*` tools are unavailable.diff --git a/frontend/slices/os-settings/components/update-section.tsx b/frontend/slices/os-settings/components/update-section.tsxindex d216e181..04c6e515 100644--- a/frontend/slices/os-settings/components/update-section.tsx+++ b/frontend/slices/os-settings/components/update-section.tsx@@ -74,7 +74,7 @@ export function UpdateSection() {setBusy(true);setError(null);postRunRemoteCheck.current = false;- setSawRunning(true);+ setSawRunning(false);try {const res = await fetch("/api/v1/sys/update", {method: "POST",@@ -83,7 +83,12 @@ export function UpdateSection() {});const body = (await res.json()) as UpdateStatus & { error?: string };if (!res.ok) setError(body.error ?? `update refused (${res.status})`);- else setInfo(body);+ else {+ setInfo(body);+ // Only a started update may be graded from the log: a refusal leaves the+ // previous attempt's UPDATE OK in place and would report stale success.+ setSawRunning(true);+ }} catch {setError("could not reach the host");} finally {diff --git a/lib/agent/profile-runtime.ts b/lib/agent/profile-runtime.tsindex fbe989ad..2d6011f0 100644--- a/lib/agent/profile-runtime.ts+++ b/lib/agent/profile-runtime.ts@@ -10,6 +10,7 @@ import { requireAgentProfile } from "./profile-store";import { runBoundedAgent } from "./bounded-runner";import { runAcpAgentProfile } from "./acp-runtime";import type { AcpInstance } from "./acp-drivers";+import { intEnv } from "./session-policy";export function profileRuntimeAuthority(session: SessionPayload, profile: AgentProfile, capabilities: CapabilityRuntime, options: { signal?: AbortSignal; sessionId?: string } = {}) {if (!session.device_id) throw new AgentProfileError("profile_owner_unsupported", 403);@@ -70,7 +71,9 @@ export async function runAgentProfile(input: { session: SessionPayload; body: unconst result = await runBoundedAgent({ prepared, objective: prompt,system: `You are MSO saved profile ${profile.config.name}. Work on the requested read task. Only the saved read tools may run. Do not claim to change files or run commands. No earlier chat or owner memory is included.\n${profile.config.instructions}`,capabilities: authority.runtime, authority: authority.context, actor: principal,- tools: context => authority.runtime.list(context.scope, context), maxTurns: 6, maxToolCalls: 16, signal });+ tools: context => authority.runtime.list(context.scope, context),+ maxTurns: intEnv("OS_AGENT_PROFILE_MAX_TURNS", 6, 1, 10_000),+ maxToolCalls: intEnv("OS_AGENT_PROFILE_MAX_TOOL_CALLS", 16, 1, 100_000), signal });await updateAgentSessionHistory(principal, runId, result.messages);await appendAgentSessionEvent(principal, runId, { kind: "note", state: result.status, detail: `Profile ${profile.id}, revision ${profile.revision}` });await authority.liveAuthorization();diff --git a/lib/agent/session-policy.ts b/lib/agent/session-policy.tsindex cc39c2bd..073416ee 100644--- a/lib/agent/session-policy.ts+++ b/lib/agent/session-policy.ts@@ -10,7 +10,7 @@ const DEFAULT_COMPACT_TOKENS = 700_000;const DEFAULT_RECENT_TOKENS = 140_000;const GENERIC_TITLES = /^(MSO Agent session|ChatGPT\/MCP|ChatGPT session|MCP legacy session)/i;-function intEnv(name: string, fallback: number, min: number, max: number): number {+export function intEnv(name: string, fallback: number, min: number, max: number): number {const value = Number(process.env[name]);return Number.isFinite(value) ? Math.max(min, Math.min(max, Math.trunc(value))) : fallback;}diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.tsindex 651cf8bb..05d7bfca 100644--- a/lib/agent/subagent-runner.ts+++ b/lib/agent/subagent-runner.ts@@ -5,17 +5,30 @@ import { allows, parseScope, type Scope } from "@/lib/capabilities/scope";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import type { CapabilityRunContext } from "@/lib/capabilities/tool";import { runBoundedAgent, type BoundedAgentProgress } from "./bounded-runner";+import { intEnv } from "./session-policy";const DEFAULT_TURNS = 6;const ABSOLUTE_MAX_TURNS = 48;+// Owner-tunable ceilings (historical defaults preserved). `OS_SUBAGENT_MAX_TURNS`+// still caps one invocation; the absolute ceiling and the timeout budget can be+// raised for long delegated runs.function maxTurnsLimit(): number {const configured = Number(process.env.OS_SUBAGENT_MAX_TURNS);return Number.isFinite(configured)- ? Math.max(1, Math.min(ABSOLUTE_MAX_TURNS, Math.trunc(configured)))- : 12;+ ? Math.max(1, Math.min(absoluteMaxTurns(), Math.trunc(configured)))+ : Math.min(12, absoluteMaxTurns());+}+function absoluteMaxTurns(): number {+ return intEnv("OS_SUBAGENT_ABSOLUTE_MAX_TURNS", ABSOLUTE_MAX_TURNS, 1, 10_000);+}+function defaultTurns(): number {+ return Math.min(absoluteMaxTurns(), intEnv("OS_SUBAGENT_DEFAULT_TURNS", DEFAULT_TURNS, 1, 10_000));}const DEFAULT_TIMEOUT_MS = 60_000;const MAX_TIMEOUT_MS = 120_000;+function maxTimeoutMs(): number {+ return intEnv("OS_SUBAGENT_MAX_TIMEOUT_MS", MAX_TIMEOUT_MS, 1_000, 7_200_000);+}const DENY_PREFIXES = ["agent_session_", "agent_memory_", "local_agent_", "a2a_"];const DENY_EXACT = new Set(["agent_subagent_run", "project_agent_run"]);function allowedTool(name: string): boolean {@@ -53,8 +66,8 @@ export async function runSessionSubagent(input: {const name = String(input.name || "worker").trim().replace(/[\r\n\t]+/g, " ").slice(0, 60) || "worker";const maxScope = parseScope(input.maxScope || "read");if (!allows(input.authority.scope, maxScope)) throw new Error("subagent scope exceeds initiating authority");- const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || DEFAULT_TURNS)));- const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));+ const maxTurns = Math.max(1, Math.min(maxTurnsLimit(), Math.trunc(input.maxTurns || defaultTurns())));+ const timeoutMs = Math.max(1_000, Math.min(maxTimeoutMs(), Math.trunc(input.timeoutMs || DEFAULT_TIMEOUT_MS)));const subagentId = `subagent_${randomUUID()}`;const authority = { ...input.authority, principal: input.authority.principal ?? input.principal, scope: maxScope, capabilities: input.capabilities };const toolDefs = (context: CapabilityRunContext) => input.capabilities.list(context.scope, context).filter(tool => allows(context.scope, tool.scope) && allowedTool(tool.name) && (!context.allowedTools || context.allowedTools.includes(tool.name)));diff --git a/lib/ai/agent-loop.ts b/lib/ai/agent-loop.tsindex 9f142b19..f51f34e2 100644--- a/lib/ai/agent-loop.ts+++ b/lib/ai/agent-loop.ts@@ -1,5 +1,6 @@import { streamAgentTurn, type AgentMsg, type AiTool, type ProviderUsage } from "./stream";import { addProviderUsage } from "./provider-usage.mjs";+import { intEnv } from "@/lib/agent/session-policy";// Generic tool-execution contract. `invoke` runs one tool call and returns a// short, model-readable outcome; where the side-effect happens (a client store,@@ -33,7 +34,7 @@ export async function runToolAgent(tools: AiTool[],invoke: (call: ToolInvocation) => Promise<ToolOutcome>,ev: AgentEvents,- maxTurns = 8,+ maxTurns = intEnv("OS_ASSISTANT_MAX_TURNS", 8, 1, 10_000),system?: string,signal?: AbortSignal,): Promise<AgentLoopResult> {diff --git a/scripts/mso-agent-activity.mjs b/scripts/mso-agent-activity.mjsnew file mode 100644index 00000000..c71b7d7a--- /dev/null+++ b/scripts/mso-agent-activity.mjs@@ -0,0 +1,219 @@+import process from "node:process";++/**+ * One-line live activity region for the interactive MSO Agent.+ *+ * The transcript is append-only, so every per-tool `[scope] / ↳ / ✓` line used to+ * claim a terminal row of its own and a 10-round turn buried the conversation. This+ * module owns a SINGLE row and repaints it in place (`\r` + erase-to-end-of-line),+ * the mechanism the composer already uses for its prompt: one `Agent work` section+ * plus one advancing row (`⠹ fs_search · 3/7 tools · 12s`) instead of a wall of rows.+ * When stdout is not a TTY nothing is animated and callers keep their discrete+ * lines, so pipes and log consumers never see cursor-control characters.+ */++const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];+export const DEFAULT_ACTIVITY_INTERVAL_MS = 120;+export const CLEAR_ACTIVITY_LINE = "\x1b[2K";++// The composer can repaint above an in-progress draft (async Local Agent traffic) at+// any moment. A suspended row is cleared first so a foreign write never lands inside+// the live row, then repainted on resume.+let current = null;++/** Clear any live activity row before a foreign writer touches stdout. */+export function suspendActiveActivity() {+ current?.suspend();+}++/** Repaint the live activity row after a foreign writer is done. */+export function resumeActiveActivity() {+ current?.resume();+}++export function formatElapsed(startedAt, now) {+ const elapsed = Math.max(0, Number(now) - Number(startedAt));+ if (elapsed < 1000) return "0s";+ const total = Math.floor(elapsed / 1000);+ if (total < 60) return `${total}s`;+ return `${Math.floor(total / 60)}m${String(total % 60).padStart(2, "0")}s`;+}++/** Elapsed milliseconds as the compact `12s` / `1m04s` form used in the live row. */+export function formatDuration(ms) {+ return formatElapsed(0, ms);+}++/** Join non-empty segments with the same separator the status footer uses. */export function activityText(parts) {+ return (Array.isArray(parts) ? parts : [])+ .map((part) => String(part ?? "").trim())+ .filter(Boolean)+ .join(" · ");+}++/**+ * @typedef {object} AgentActivityOptions+ * @property {typeof process.stdout} [output] destination stream+ * @property {Record<string, string>} [colors] ANSI theme (subset of the agent palette)+ * @property {() => number} [now] clock injection for elapsed-time tests+ * @property {number} [intervalMs] spinner period+ * @property {boolean} [animate] force the live row on/off (defaults to `output.isTTY`)+ * @property {(line: string) => unknown} [print] discrete-line sink (defaults to console.log)+ * @property {typeof setInterval} [setIntervalImpl] timer injection+ * @property {typeof clearInterval} [clearIntervalImpl] timer injection+ */++export class AgentActivity {+ /** @param {AgentActivityOptions} [options] */+ constructor({+ output = process.stdout,+ colors = {},+ now = () => Date.now(),+ intervalMs = DEFAULT_ACTIVITY_INTERVAL_MS,+ animate = undefined,+ print = (line) => console.log(line),+ setIntervalImpl = setInterval,+ clearIntervalImpl = clearInterval,+ } = {}) {+ this.output = output;+ this.C = colors;+ this.now = now;+ this.intervalMs = Math.max(40, Number(intervalMs) || DEFAULT_ACTIVITY_INTERVAL_MS);+ // Explicit `animate` wins so a PTY harness can force the live path.+ this.animate = animate === undefined ? Boolean(output?.isTTY) : Boolean(animate);+ this.print = print;+ this.setIntervalImpl = setIntervalImpl;+ this.clearIntervalImpl = clearIntervalImpl;+ this.frame = 0;+ this.open = false;+ this.suspended = false;+ this.detail = "";+ this.startedAt = Number(now());+ this.timer = null;+ this.toolTotal = 0;+ this.completed = 0;+ }++ /** True when this instance owns a live terminal row (vs. discrete lines). */+ get live() { return this.animate; }++ /** Claim the live row for one agent turn. */+ begin() {+ current = this;+ this.startedAt = Number(this.now());+ this.toolTotal = 0;+ this.completed = 0;+ return this;+ }++ setToolTotal(total) {+ this.toolTotal = Math.max(0, Number(total) || 0);+ }++ /** Model is waiting: first token, or between tool rounds. */+ waiting(text = "thinking") {+ this.paint(activityText([text, formatElapsed(this.startedAt, this.now())]));+ }++ /** `[scope] tool` — discrete only; the live row already names the tool. */+ label(tool) {+ if (this.animate) return;+ this.print(`${this.C?.c || ""}${this.C?.bold || ""}[${tool?.scope}]${this.C?.reset || ""} ${String(tool?.name || "tool")}`);+ }++ toolStart(tool) {+ const name = String(tool?.name || "tool");+ if (!this.animate) {+ this.print(`${this.C?.dim || ""} ↳ ${name}…${this.C?.reset || ""}`);+ return;+ }+ this.paint(activityText([+ name,+ this.toolTotal ? `${this.completed + 1}/${this.toolTotal} tools` : null,+ formatElapsed(this.startedAt, this.now()),+ ]));+ }++ toolEnd(tool, ok) {+ const name = String(tool?.name || "tool");+ if (ok) this.completed += 1;+ if (!this.animate) {+ const tone = ok ? (this.C?.c || "") : (this.C?.err || "");+ this.print(`\r${tone} ${ok ? "✓" : "✗"} ${name}${this.C?.reset || ""}`);+ return;+ }+ this.paint(activityText([+ `${ok ? "✓" : "✗"} ${name}`,+ this.toolTotal ? `${this.completed}/${this.toolTotal} ok` : null,+ formatElapsed(this.startedAt, this.now()),+ ]));+ }++ /** Turn finished: replace the live row with a compact receipt (or nothing). */+ finish(text = "") {+ const detail = String(text || "");+ this.stopTicker();+ if (this.animate) this.clear();+ if (detail) this.print(`${this.C?.dim || ""}${detail}${this.C?.reset || ""}`);+ if (current === this) current = null;+ }++ /** Drop the live row (used before streamed model text takes the terminal). */+ clear() {+ if (this.open) {+ this.output.write(`\r${CLEAR_ACTIVITY_LINE}`);+ this.open = false;+ }+ }++ stop() {+ this.stopTicker();+ this.clear();+ if (current === this) current = null;+ }++ suspend() {+ this.clear();+ this.suspended = true;+ }++ resume() {+ if (!this.suspended) return;+ this.suspended = false;+ if (this.detail) this.paint(this.detail);+ }++ paint(text) {+ const line = String(text ?? "");+ this.detail = line;+ if (!this.animate || this.suspended || !line) return;+ this.open = true;+ this.render();+ this.ensureTicker();+ }++ render() {+ this.output.write(`\r${CLEAR_ACTIVITY_LINE}${this.C?.dim || ""} ${this.frameMark()} ${this.detail}${this.C?.reset || ""}`);+ }++ frameMark() {+ return FRAMES[this.frame % FRAMES.length];+ }++ ensureTicker() {+ if (this.timer || !this.animate) return;+ this.timer = this.setIntervalImpl(() => {+ if (!this.open || this.suspended || !this.detail) return;+ this.frame = (this.frame + 1) % FRAMES.length;+ this.render();+ }, this.intervalMs);+ this.timer?.unref?.();+ }++ stopTicker() {+ if (this.timer) {+ this.clearIntervalImpl(this.timer);+ this.timer = null;+ }+ }+}diff --git a/scripts/mso-agent-activity.test.ts b/scripts/mso-agent-activity.test.tsnew file mode 100644index 00000000..29a59268--- /dev/null+++ b/scripts/mso-agent-activity.test.ts@@ -0,0 +1,106 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ AgentActivity, activityText, formatDuration, formatElapsed,+ resumeActiveActivity, suspendActiveActivity,+} from "./mso-agent-activity.mjs";++const colors = { dim: "", reset: "", c: "", warn: "", err: "", bold: "" };++function collector() {+ const chunks: string[] = [];+ return {+ chunks,+ output: { isTTY: true, write: (value: string) => { chunks.push(String(value)); return true; } } as unknown as typeof process.stdout,+ text: () => chunks.join(""),+ };+}++function discrete(animate: boolean) {+ const lines: string[] = [];+ const sink = collector();+ const activity = new AgentActivity({+ output: sink.output, colors, animate, print: (line: string) => lines.push(String(line)),+ setIntervalImpl: (() => 0) as unknown as typeof setInterval,+ clearIntervalImpl: (() => undefined) as unknown as typeof clearInterval,+ });+ return { activity, lines, sink };+}++afterEach(() => { suspendActiveActivity(); resumeActiveActivity(); vi.restoreAllMocks(); });++describe("MSO Agent live activity row", () => {+ it("repaints one row in place instead of appending a line per tool", () => {+ const { activity, sink, lines } = discrete(true);+ activity.begin().setToolTotal(2);+ activity.toolStart({ name: "fs_search", scope: "read" });+ activity.toolStart({ name: "fs_read", scope: "read" });+ activity.toolEnd({ name: "fs_read", scope: "read" }, true);+ activity.finish("2 tools · all ok · 1s");++ const frame = sink.text();+ // Every paint addresses the same physical row (carriage return + erase-line).+ expect(frame.match(/\r\x1b\[2K/g)?.length).toBeGreaterThanOrEqual(4);+ expect(frame).toContain("fs_search");+ expect(frame).toContain("1/2 tools");+ expect(frame).toContain("✓ fs_read");+ expect(frame).toContain("1/2 ok");+ // The animated row never terminates itself; only the receipt is a real line.+ expect(frame).not.toContain("\n");+ expect(lines).toEqual(["2 tools · all ok · 1s"]);+ });++ it("keeps the historical discrete lines when stdout is not a tty", () => {+ const { activity, lines, sink } = discrete(false);+ activity.begin().setToolTotal(1);+ activity.label({ name: "workflow_start", scope: "write" });+ activity.toolStart({ name: "workflow_start", scope: "write" });+ activity.toolEnd({ name: "workflow_start", scope: "write" }, true);+ activity.finish("1 tool · all ok · 0s");++ expect(lines).toEqual([+ "[write] workflow_start",+ " ↳ workflow_start…",+ "\r ✓ workflow_start",+ "1 tool · all ok · 0s",+ ]);+ // Nothing animated: a pipe never receives cursor control.+ expect(sink.text()).toBe("");+ });++ it("clears the live row before streamed model text and before foreign writers", () => {+ const { activity, sink } = discrete(true);+ activity.begin();+ activity.waiting("thinking");+ activity.clear();+ expect(sink.text().endsWith("\r\x1b[2K")).toBe(true);++ activity.waiting("thinking");+ suspendActiveActivity();+ expect(sink.text().endsWith("\r\x1b[2K")).toBe(true);+ const frozen = sink.chunks.length;+ activity.toolStart({ name: "fs_list", scope: "read" });+ expect(sink.chunks.length).toBe(frozen);+ resumeActiveActivity();+ expect(sink.chunks.length).toBeGreaterThan(frozen);+ });++ it("reports progress with elapsed time and a tool tally", () => {+ let clock = 1_000;+ const { activity, sink } = discrete(true);+ Object.defineProperty(activity, "now", { value: () => clock });+ activity.begin().setToolTotal(3);+ clock += 12_000;+ activity.toolStart({ name: "exec_run", scope: "exec" });+ expect(sink.text()).toContain("exec_run");+ expect(sink.text()).toContain("1/3 tools");+ expect(sink.text()).toContain("12s");+ });++ it("formats durations and joins only non-empty segments", () => {+ expect(formatElapsed(0, 900)).toBe("0s");+ expect(formatElapsed(0, 12_400)).toBe("12s");+ expect(formatElapsed(0, 64_000)).toBe("1m04s");+ expect(formatDuration(0)).toBe("0s");+ expect(activityText(["fs_search", "", null, undefined, "2/5 tools"])).toBe("fs_search · 2/5 tools");+ });+});diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjsindex cd64acb1..8e293aed 100644--- a/scripts/mso-agent-composer.mjs+++ b/scripts/mso-agent-composer.mjs@@ -1,6 +1,7 @@import readline from "node:readline";import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";import process from "node:process";+import { resumeActiveActivity, suspendActiveActivity } from "./mso-agent-activity.mjs";import {chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, eraseComposerRows, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width,@@ -91,12 +92,16 @@ export class AgentComposer {};const notify = (text) => {if (settled) return false;+ // An in-flight turn may own a live activity row on this same row slot; clear+ // it so async traffic never lands inside the row, then repaint it after.+ suspendActiveActivity();erase();output.write(`${String(text ?? "").replace(/\r/g, "")}\r\n`);const separatorRow = separatorText();if (separatorRow) output.write(`${separatorRow}\r\n`);reservedRows = 0;render();+ resumeActiveActivity();return true;};this._cancelCurrent = cancel;diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjsindex 14842f0e..98f01c15 100644--- a/scripts/mso-agent-turn.mjs+++ b/scripts/mso-agent-turn.mjs@@ -3,6 +3,7 @@ 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 { AgentActivity, activityText, formatDuration } from "./mso-agent-activity.mjs";import { beginSkillInvocation, endSkillInvocation } from "./mso-agent-skills.mjs";import { isAbortError } from "./mso-agent-interrupt.mjs";import { approvesTool } from "./mso-agent-permissions.mjs";@@ -19,6 +20,7 @@ function lazyAssistantOutput(session, options = {}) {write(value) {if (!opened) {opened = true;+ options.activity?.clear();printSection("assistant", { detail: `@${session?.agentSession?.name || "agent"}`, colors: C });}return process.stdout.write(String(value ?? ""));@@ -26,6 +28,15 @@ function lazyAssistantOutput(session, options = {}) {};}+/** Rounds (stream → tools → stream) one turn may run. The historical cap was a+ * hard-coded 10; now `OS_AGENT_MAX_ROUNDS` (default 1000 = no practical cap). */+export function agentRoundLimit() {+ const configured = Number(process.env.OS_AGENT_MAX_ROUNDS);+ return Number.isFinite(configured) && configured > 0+ ? Math.trunc(configured)+ : 1000;+}+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";@@ -53,10 +64,14 @@ export async function executeTool(rl, tool, call, agentSession, permission = "asthrow error;}} else if (needsApprovalDigest && !options.quiet && !options.approvalScope) {- console.log(`${C.c}${C.bold}[${tool.scope}]${C.reset} ${tool.name}`);+ if (options.activity) options.activity.label(tool);+ else 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}`);+ if (!options.quiet) {+ if (options.activity) options.activity.toolStart(tool);+ else process.stdout.write(`${C.dim} ↳ ${tool.name}…${C.reset}`);+ }const request = options.apiRequest || api;try {const input = approval ? approval.payload.input : (call.input || {});@@ -70,12 +85,18 @@ export async function executeTool(rl, tool, call, agentSession, permission = "as}),signal,});- if (!options.quiet) process.stdout.write(`\r${C.c} ✓ ${tool.name}${C.reset}\n`);+ if (!options.quiet) {+ if (options.activity) options.activity.toolEnd(tool, true);+ else 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 (!options.quiet) {+ if (options.activity) options.activity.toolEnd(tool, false);+ else 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) };}@@ -86,15 +107,29 @@ export async function agentRound(rl, session, skillContext = null, signal = undeconst historyCheckpoint = Math.max(0, session.history.length - 1);const calls = [];let finalText = "", rounds = 0;+ const agentName = session?.agentSession?.name || "agent";+ const activity = options.quiet+ ? null+ : (options.activity || new AgentActivity({+ output: options.output || process.stdout,+ colors: C,+ now: options.now,+ animate: options.animate,+ })).begin();+ const roundLimit = agentRoundLimit();beginSkillInvocation(session, skillContext, C);const turnStream = options.streamTurn || streamTurn;const toolExecutor = options.executeTool || executeTool;+ const toolOptions = { ...options, activity };+ let workSectionPrinted = false;try {- for (let turn = 0; turn < 10; turn++) {+ for (let turn = 0; turn < roundLimit; turn++) {rounds = turn + 1;+ // Live row while the first token is in flight: a provider wait reads as work.+ activity?.waiting("thinking");const result = await turnStream(session.history, session.state.tools, session.agentSession, skillContext, signal,- session.state.modelMeta?.context, lazyAssistantOutput(session, options),+ session.state.modelMeta?.context, lazyAssistantOutput(session, toolOptions),);// The current model round has consumed all prior read-tool payloads that were// still inside its projected context. Persist only bounded replay envelopes@@ -106,19 +141,29 @@ export async function agentRound(rl, session, skillContext = null, signal = undesession.lastRouting = result.routing || null;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 });+ if (!result.toolUses.length) {+ activity?.finish(completedReceipt(calls, session.lastElapsedMs));+ return { text: finalText, calls, rounds, usage: session.usage, elapsedMs: session.lastElapsedMs };+ }+ activity?.clear();+ // One `Agent work` section per turn; the live row below carries tool progress.+ if (!options.quiet && !workSectionPrinted) {+ workSectionPrinted = true;+ printSection("work", { detail: `@${agentName}`, colors: C });+ }+ activity?.setToolTotal(result.toolUses.length);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,+ ...toolOptions, 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 });}+ activity?.finish(completedReceipt(calls, session.lastElapsedMs));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) {@@ -126,10 +171,24 @@ export async function agentRound(rl, session, skillContext = null, signal = undeelse if (error && typeof error === "object" && !error.turnJournal) error.turnJournal = { calls: [...calls] };throw error;} finally {+ activity?.stop();endSkillInvocation(session, skillContext);}}+/** Compact per-turn receipt replacing the rows each tool used to claim. */+function completedReceipt(calls, elapsedMs) {+ const rows = Array.isArray(calls) ? calls : [];+ if (!rows.length) return "";+ const ok = rows.filter((row) => row.ok).length;+ const failed = rows.length - ok;+ return activityText([+ `${rows.length} tool${rows.length === 1 ? "" : "s"}`,+ failed ? `${failed} failed` : "all ok",+ formatDuration(elapsedMs || 0),+ ]);+}+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 }));diff --git a/scripts/mso-agent-turn.test.ts b/scripts/mso-agent-turn.test.tsnew file mode 100644index 00000000..73358096--- /dev/null+++ b/scripts/mso-agent-turn.test.ts@@ -0,0 +1,104 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { AgentActivity } from "./mso-agent-activity.mjs";+import { agentRound, agentRoundLimit } from "./mso-agent-turn.mjs";++const colors = { blue: "", bold: "", reset: "", dim: "", c: "", cyan: "", warn: "", err: "" };++function session(overrides: Record<string, unknown> = {}) {+ return {+ history: [{ role: "user", text: "do the thing" }],+ permission: "yolo",+ state: { tools: [{ name: "fs_list", scope: "read" }, { name: "fs_write", scope: "write" }], modelMeta: null },+ agentSession: { id: "session-a", name: "ika" },+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },+ lastElapsedMs: 0,+ ...overrides,+ } as any;+}++function streamReturning(rounds: number) {+ let round = 0;+ return vi.fn(async () => {+ round += 1;+ return {+ text: `round ${round}`,+ usage: null,+ toolUses: round <= rounds+ ? [{ id: `call-${round}`, name: round % 2 ? "fs_list" : "fs_write", input: {} }]+ : [],+ };+ });+}++function ttyActivity() {+ const chunks: string[] = [];+ const lines: string[] = [];+ const activity = new AgentActivity({+ output: { isTTY: true, write: (v: string) => { chunks.push(String(v)); return true; } } as unknown as typeof process.stdout,+ colors,+ animate: true,+ print: (line: string) => lines.push(String(line)),+ setIntervalImpl: (() => 0) as unknown as typeof setInterval,+ clearIntervalImpl: (() => undefined) as unknown as typeof clearInterval,+ });+ return { activity, chunks, lines, text: () => chunks.join("") };+}++afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); });++describe("MSO Agent turn rendering and round budget", () => {+ it("opens exactly one Agent work section for a multi-round turn", async () => {+ const printed: string[] = [];+ vi.spyOn(console, "log").mockImplementation((line?: unknown) => { printed.push(String(line ?? "")); });+ const result = await agentRound(null, session(), null, undefined, null, {+ streamTurn: streamReturning(3), executeTool: vi.fn(async () => ({ ok: true, result: "ok" })),+ });+ const workSections = printed.filter((line) => line.includes("Agent work"));+ expect(result.rounds).toBe(4);+ expect(result.turnLimitReached).toBeUndefined();+ expect(workSections).toHaveLength(1);+ expect(printed.some((line) => line.includes("turn limit reached"))).toBe(false);+ });++ it("keeps tool progress on one repainted row and ends with one receipt", async () => {+ vi.spyOn(console, "log").mockImplementation(() => undefined);+ const { activity, lines, text } = ttyActivity();+ const result = await agentRound(null, session(), null, undefined, null, {+ quiet: false, activity, animate: true,+ streamTurn: streamReturning(2),+ apiRequest: vi.fn(async () => ({ ok: true, result: "ok" })),+ });+ expect(result.calls).toHaveLength(2);+ // Two rounds → one divider, and every paint rewrote the same physical row.+ expect((text().match(/\r\x1b\[2K/g) || []).length).toBeGreaterThanOrEqual(2);+ expect(text()).toContain("fs_list");+ expect(text()).toContain("fs_write");+ expect(text()).not.toContain("\n");+ expect(lines.join("\n")).toMatch(/2 tools/);+ expect(lines.join("\n")).toMatch(/all ok/);+ });++ it("stops only at the configured round budget", async () => {+ vi.stubEnv("OS_AGENT_MAX_ROUNDS", "2");+ const printed: string[] = [];+ vi.spyOn(console, "log").mockImplementation((line?: unknown) => { printed.push(String(line ?? "")); });+ const result = await agentRound(null, session(), null, undefined, null, {+ streamTurn: streamReturning(99), executeTool: vi.fn(async () => ({ ok: true, result: "ok" })),+ });+ expect(result.rounds).toBe(2);+ expect(result.turnLimitReached).toBe(true);+ expect(printed.filter((line) => line.includes("turn limit reached"))).toHaveLength(1);+ // The capped run still reported its work in a single section.+ expect(printed.filter((line) => line.includes("Agent work"))).toHaveLength(1);+ });++ it("defaults to a budget no real task reaches", () => {+ expect(agentRoundLimit()).toBe(1000);+ vi.stubEnv("OS_AGENT_MAX_ROUNDS", "0");+ expect(agentRoundLimit()).toBe(1000);+ vi.stubEnv("OS_AGENT_MAX_ROUNDS", "fifty");+ expect(agentRoundLimit()).toBe(1000);+ vi.stubEnv("OS_AGENT_MAX_ROUNDS", "37");+ expect(agentRoundLimit()).toBe(37);+ });+});