Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(cli): print the mso ai reply text instead of SSE frames

Abdurrahman Fakhrul87136a242503
diff --git a/app/api/assistant/normalize-content.test.ts b/app/api/assistant/normalize-content.test.ts
new file mode 100644
index 00000000..e455e394
--- /dev/null
+++ b/app/api/assistant/normalize-content.test.ts
@@ -0,0 +1,88 @@
+// Route-level regression for the `mso ai` failure mode that shipped as a bare 500:
+// the CLI posted OpenAI-shaped `{role:"user",content}` while OaMsg carries `text`,
+// so the prompt was dropped before recall() and before the streamer. PR #133 fixed
+// the route by normalizing at the trust boundary; this test locks that behavior at
+// the boundary rather than only inside recall().
+import { describe, expect, it, vi } from "vitest";
+
+const stableContext = {
+ session: { device_id: "normalize-content-device", issued_at: 1, expires_at: 2, cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" },
+ device: { label: "test owner", approvedAt: 1, role: "owner" as const },
+ role: "owner" as const,
+};
+
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: vi.fn(async () => stableContext),
+}));
+
+vi.mock("@/lib/config/store", () => ({
+ DEFAULT_PROVIDER: "anthropic",
+ readConfig: vi.fn(async () => ({})),
+ resolveModelRef: vi.fn(async () => "anthropic/claude-test"),
+ hostCredentialStore: vi.fn(() => ({ getKey: async () => "", setKey: async () => {}, deleteKey: async () => {} })),
+ selectedCustomConn: vi.fn(async () => null),
+ readOAuthBundle: vi.fn(async () => null),
+ writeOAuthBundle: vi.fn(async () => {}),
+}));
+
+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));
+
+// The provider round-trip is not under test; the normalized messages handed to it are.
+const streamed: unknown[][] = [];
+vi.mock("@/lib/ai/selected-model-stream", () => ({
+ SelectedModelConfigError: class SelectedModelConfigError extends Error {},
+ prepareSelectedModel: vi.fn(async () => ({ ref: "test/model" })),
+ streamPreparedSelectedModel: vi.fn(
+ async ({ messages, emit }: { messages: unknown[]; emit: (event: string, data: unknown) => void }) => {
+ streamed.push(messages);
+ emit("delta", "OK");
+ emit("done", { stopReason: "end_turn" });
+ },
+ ),
+}));
+
+vi.mock("@/lib/agent/legacy-owner-memory", () => ({
+ recall: vi.fn(async () => []),
+}));
+
+function makeReq(messages: unknown[]): Request {
+ return new Request("http://localhost/api/assistant", {
+ method: "POST",
+ body: JSON.stringify({ messages }),
+ headers: { "content-type": "application/json" },
+ });
+}
+
+describe("/api/assistant OpenAI-shaped message normalization", () => {
+ it("turns a user {content} into {text} so the prompt reaches recall and the streamer", async () => {
+ const memory = await import("@/lib/agent/legacy-owner-memory");
+ const { POST } = await import("./route");
+
+ const res = await POST(makeReq([{ role: "user", content: "halo dari CLI" }]));
+
+ expect(res.status).toBe(200);
+ expect(memory.recall).toHaveBeenLastCalledWith("halo dari CLI");
+ expect(streamed.at(-1)).toEqual([{ role: "user", content: "halo dari CLI", text: "halo dari CLI" }]);
+ await expect(res.text()).resolves.toContain("event: delta");
+ });
+
+ it("leaves an OaMsg {text} message untouched", async () => {
+ const memory = await import("@/lib/agent/legacy-owner-memory");
+ const { POST } = await import("./route");
+
+ const res = await POST(makeReq([{ role: "user", text: "halo mso" }]));
+
+ expect(res.status).toBe(200);
+ expect(memory.recall).toHaveBeenLastCalledWith("halo mso");
+ expect(streamed.at(-1)).toEqual([{ role: "user", text: "halo mso" }]);
+ });
+
+ it("streams instead of failing when neither shape carries a usable prompt", async () => {
+ const { POST } = await import("./route");
+
+ const res = await POST(makeReq([{ role: "user", content: [{ type: "text", text: "blok" }] }]));
+
+ expect(res.status).toBe(200);
+ await expect(res.text()).resolves.toContain("event: delta");
+ });
+});
diff --git a/bin/mso b/bin/mso
index b997cc0f..cd5ee54b 100755
--- a/bin/mso
+++ b/bin/mso
@@ -70,7 +70,7 @@
# term * Interactive PTY sessions (open | input | resize | stream | close)
#
# AI + state
-# ai <prompt…> One turn with the assistant
+# ai <prompt…> One turn with the assistant; prints the reply text
# cockpit [project] Alfa/MSO runtime context; search with `cockpit search <query>`
# threads * Conversation history: list | show | save | rename | rm
# agent-sessions * Durable MSO Agent sessions: list | show | create
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7de6a3b3..f1d87f24 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `cli` print the mso ai reply text instead of SSE frames
- `infra` add Linear provider and route Composio key kinds by header
**Fixed**
diff --git a/docs/CLI.md b/docs/CLI.md
index b3a21a67..b52a5065 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -110,7 +110,7 @@ Commands:
term * Interactive PTY sessions (open | input | resize | stream | close)
AI + state
- ai <prompt…> One turn with the assistant
+ ai <prompt…> One turn with the assistant; prints the reply text
cockpit [project] Alfa/MSO runtime context; search with `cockpit search <query>`
threads * Conversation history: list | show | save | rename | rm
agent-sessions * Durable MSO Agent sessions: list | show | create
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 47476ec7..8c0e9091 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,11 @@
+## 2026-10-21: `mso ai` shows the reply text, not the SSE frames
+
+`mso ai` sent the right OaMsg `text` after #133, but it still printed the raw response body, so an owner read `event: delta` / `data: "…"` frames instead of an answer. `scripts/mso-sse-text.mjs` now consumes that stream: `delta` frames become stdout text, an `error` frame fails the turn with a non-zero exit, unknown events stay silent, and a non-SSE or empty body can no longer pass as a successful empty answer. The verb pipes through the reader; the entrypoint header, generated `docs/CLI.md` and the runtime help all say so.
+
+Coverage pins both halves of the boundary instead of only the memory helper: `app/api/assistant/normalize-content.test.ts` asserts the route turns an OpenAI-shaped `{content}` into `{text}` before recall and the streamer, and keeps streaming when neither shape carries a prompt; `scripts/mso-ai-cli-contract.test.ts` asserts the verb posts `text` and renders through the reader; `scripts/mso-sse-text.test.ts` covers delta concatenation, JSON escapes, CRLF framing, unknown events, error frames and non-SSE or empty bodies.
+
+Evidence at the committed candidate: 13/13 targeted tests, `tsc --noEmit`, `eslint . --max-warnings=0`, architecture (entrypoint 203/220), cycles, docs and generated-CLI-docs checks all PASS; a live one-turn call through the worktree CLI printed a multi-line reply and exited 0. `bun run pr:local` and `bun run pr:security` are BLOCKED on this host (no `zip`, no Docker, no browser fixtures), so the PR stays Draft until hosted checks supply that evidence.
+
## 2026-10-18: MSO deep QA stopped at the user's request
Work and active QA were stopped on 18 October 2026 at the user's explicit request. This is a progress checkpoint directly on main, not a release of the development candidate. Resume implementation, validation or deployment only after a new user instruction.
diff --git a/scripts/cli/commands-state.sh b/scripts/cli/commands-state.sh
index 8578df4b..8a77a3ce 100755
--- a/scripts/cli/commands-state.sh
+++ b/scripts/cli/commands-state.sh
@@ -8,7 +8,10 @@ mso_cmd_state() {
local cmd="$1"; shift || true
case "$cmd" in
# ── assistant / state ────────────────────────────────────────────────────
- ai) jpost "/api/assistant" "$(jq -n --arg m "$*" '{messages:[{role:"user",text:$m}]}')" ;;
+ # OaMsg carries the prompt as `text`; the reply arrives as SSE, so the reader turns
+ # the delta frames into the answer (and a failed turn into a non-zero exit).
+ ai) jpost "/api/assistant" "$(jq -n --arg m "$*" '{messages:[{role:"user",text:$m}]}')" \
+ | node "$ROOT/scripts/mso-sse-text.mjs" ;;
cockpit)
case "${1:-show}" in
show)
diff --git a/scripts/mso-ai-cli-contract.test.ts b/scripts/mso-ai-cli-contract.test.ts
new file mode 100644
index 00000000..21121688
--- /dev/null
+++ b/scripts/mso-ai-cli-contract.test.ts
@@ -0,0 +1,36 @@
+// `mso ai` contract: the verb must post the OaMsg shape the route consumes and
+// must render the reply text instead of the raw SSE frames. Both halves failed
+// once already (a `content:` body returned a bare 500 and an unread stream showed
+// wire frames), so the wiring is pinned here rather than only in the route test.
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const root = process.cwd();
+const state = readFileSync(path.join(root, "scripts/cli/commands-state.sh"), "utf8");
+const entrypoint = readFileSync(path.join(root, "bin/mso"), "utf8");
+const docs = readFileSync(path.join(root, "docs/CLI.md"), "utf8");
+
+describe("mso ai CLI contract", () => {
+ it("posts the prompt as `text`, never as OpenAI wire `content`", () => {
+ expect(state).toContain('{messages:[{role:"user",text:$m}]}');
+ expect(state).not.toMatch(/api\/assistant[^\n]*content:\$m/);
+ });
+
+ it("renders the reply through the SSE text reader that ships with the CLI", () => {
+ const lines = state.split("\n");
+ const start = lines.findIndex((line) => line.trimStart().startsWith("ai) "));
+ const statement: string[] = [];
+ for (let i = start; i >= 0 && i < lines.length; i++) {
+ statement.push(lines[i]);
+ if (!lines[i].trimEnd().endsWith("\\")) break;
+ }
+ expect(statement.join("\n")).toContain('node "$ROOT/scripts/mso-sse-text.mjs"');
+ expect(existsSync(path.join(root, "scripts/mso-sse-text.mjs"))).toBe(true);
+ });
+
+ it("documents the reply-text output in help and generated CLI docs", () => {
+ expect(entrypoint).toMatch(/^#\s+ai <prompt…>.*reply/m);
+ expect(docs).toMatch(/^\s+ai <prompt…>.*reply/m);
+ });
+});
diff --git a/scripts/mso-sse-text.mjs b/scripts/mso-sse-text.mjs
new file mode 100644
index 00000000..d40caba9
--- /dev/null
+++ b/scripts/mso-sse-text.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+// Print the assistant's reply from the /api/assistant Server-Sent Events stream.
+//
+// `mso ai` is a one-turn assistant verb, so an owner wants the answer — not the
+// wire frames. Only `delta` text reaches stdout. An `error` frame is a failed turn
+// and exits non-zero, so a caller's `$?`/`set -o pipefail` sees the same failure the
+// HTTP layer reported instead of a silent half-answer. Unknown events (tool_use,
+// usage-only done, future additions) are ignored rather than printed as garbage.
+const MAX_BYTES = 8 * 1024 * 1024;
+
+function decode(payload) {
+ try {
+ const value = JSON.parse(payload);
+ return typeof value === "string" ? value : JSON.stringify(value);
+ } catch {
+ return payload;
+ }
+}
+
+let buffer = "";
+let written = "";
+let sawFrame = false;
+let sawInput = false;
+let failed = false;
+
+function handleBlock(block) {
+ let event = "message";
+ let data = "";
+ for (const line of block.split("\n")) {
+ if (line.startsWith("event:")) event = line.slice(6).trim();
+ else if (line.startsWith("data:")) data += line.slice(5).replace(/^ /, "");
+ }
+ if (!data) return;
+ sawFrame = true;
+ if (event === "delta") {
+ const chunk = decode(data);
+ written += chunk;
+ process.stdout.write(chunk);
+ } else if (event === "error") {
+ process.stderr.write(`mso: ${decode(data)}\n`);
+ failed = true;
+ }
+}
+
+function drain(final) {
+ const blocks = buffer.split(/\r?\n\r?\n/);
+ buffer = final ? "" : blocks.pop() || "";
+ for (const block of blocks) {
+ if (failed) return;
+ handleBlock(block.replace(/\r/g, ""));
+ }
+}
+
+async function main() {
+ let bytes = 0;
+ for await (const chunk of process.stdin) {
+ bytes += chunk.length;
+ if (bytes > MAX_BYTES) {
+ process.stderr.write("mso: assistant reply exceeded the size limit\n");
+ process.exitCode = 1;
+ return;
+ }
+ buffer += chunk.toString("utf8");
+ if (/\S/.test(buffer)) sawInput = true;
+ drain(false);
+ if (failed) break;
+ }
+ if (!failed) drain(true);
+
+ if (failed) {
+ process.exitCode = 1;
+ return;
+ }
+ if (written && !written.endsWith("\n")) process.stdout.write("\n");
+ if (!sawFrame) {
+ // A 2xx body that is not SSE must not look like a successful empty answer.
+ // Stay quiet on an empty stream: the HTTP layer already reported that failure.
+ process.exitCode = 1;
+ if (sawInput) process.stderr.write("mso: unexpected assistant response\n");
+ }
+}
+
+main().catch((error) => {
+ process.stderr.write(`mso: ${error instanceof Error ? error.message : String(error)}\n`);
+ process.exitCode = 1;
+});
diff --git a/scripts/mso-sse-text.test.ts b/scripts/mso-sse-text.test.ts
new file mode 100644
index 00000000..d524952e
--- /dev/null
+++ b/scripts/mso-sse-text.test.ts
@@ -0,0 +1,73 @@
+import { spawn } from "node:child_process";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+// `mso ai` shows the assistant's answer, so the SSE reader must emit exactly the
+// reply text and must fail the turn (non-zero) when the route reported an error
+// frame. A silent empty success would hide a failed turn behind a clean exit code.
+const script = path.join(process.cwd(), "scripts/mso-sse-text.mjs");
+
+function run(input: string): Promise<{ code: number | null; stdout: string; stderr: string }> {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [script], { stdio: ["pipe", "pipe", "pipe"] });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8").on("data", (d) => (stdout += d));
+ child.stderr.setEncoding("utf8").on("data", (d) => (stderr += d));
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
+ child.stdin.end(input);
+ });
+}
+
+const frame = (event: string, data: unknown) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
+
+describe("scripts/mso-sse-text.mjs", () => {
+ it("prints delta text and ends with one newline", async () => {
+ const result = await run(
+ frame("delta", "Halo ") + frame("delta", "dari MSO") + frame("done", { stopReason: "end_turn" }),
+ );
+ expect(result.code).toBe(0);
+ expect(result.stdout).toBe("Halo dari MSO\n");
+ expect(result.stderr).toBe("");
+ });
+
+ it("decodes JSON escapes instead of leaking quoted payloads", async () => {
+ const result = await run(frame("delta", 'baris satu\nbaris "dua"') + frame("done", {}));
+ expect(result.stdout).toBe('baris satu\nbaris "dua"\n');
+ });
+
+ it("tolerates CRLF framing and unknown events", async () => {
+ const result = await run(
+ 'event: delta\r\ndata: "OK"\r\n\r\n' + frame("tool_use", { id: "t1", name: "noop" }) + frame("delta", "!"),
+ );
+ expect(result.code).toBe(0);
+ expect(result.stdout).toBe("OK!\n");
+ });
+
+ it("fails the turn when the stream reports an error frame", async () => {
+ const result = await run(frame("delta", "partial") + frame("error", "provider_unavailable"));
+ expect(result.code).toBe(1);
+ expect(result.stdout).toBe("partial");
+ expect(result.stderr).toContain("provider_unavailable");
+ });
+
+ it("prints nothing for a reply with no text and still succeeds", async () => {
+ const result = await run(frame("done", { stopReason: "end_turn" }));
+ expect(result.code).toBe(0);
+ expect(result.stdout).toBe("");
+ });
+
+ it("refuses a non-SSE body instead of exiting clean with no reply", async () => {
+ const result = await run('{"error":"unexpected"}');
+ expect(result.code).toBe(1);
+ expect(result.stderr).toContain("unexpected assistant response");
+ });
+
+ it("never reports an empty stream as success", async () => {
+ // The HTTP layer already prints its own failure, so this stays quiet on stderr.
+ const result = await run("");
+ expect(result.code).toBe(1);
+ expect(result.stdout).toBe("");
+ expect(result.stderr).toBe("");
+ });
+});