Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(mcp): settle a local slash-command turn on its local-command-stdout

Jack Rudenkod0f59a1f9f85
diff --git a/packages/cli/src/pane/pane-session.integration.test.ts b/packages/cli/src/pane/pane-session.integration.test.ts
index 9aa26abd..a2f1c184 100644
--- a/packages/cli/src/pane/pane-session.integration.test.ts
+++ b/packages/cli/src/pane/pane-session.integration.test.ts
@@ -396,6 +396,36 @@ describe.skipIf(!MAGMUX)(
);
});
+ describe.concurrent("slash commands", () => {
+ test(
+ "local commands settle on their stdout (path L) and the prompt queued behind them is answered",
+ async () => {
+ const r = await start("answer", {
+ shape: "interactive",
+ initialPrompt: undefined,
+ decide: () => "continue",
+ });
+ await r.s.ready;
+ expect(r.s.send("/compact").ok).toBe(true);
+ expect(r.s.send("/model haiku").ok).toBe(true);
+ expect(r.s.send("Reply with exactly KIWI.").ok).toBe(true);
+ await until(r, (s) => s.turnsCompleted === 3 && s.state === "AWAITING_INPUT");
+ expect(r.turns.map((t) => t.settledBy)).toEqual([
+ "local_command",
+ "local_command",
+ "turn_duration",
+ ]);
+ expect(r.turns[0]?.answer).toBe("Compacted (ctrl+o to see full summary)");
+ expect(r.turns[0]?.delivery.mode).toBe("command");
+ expect(r.turns[1]?.answer).toBe("Set model to `haiku`");
+ expect(r.turns[2]?.answer).toBe(`ANSWER fake-answer ${sha8("Reply with exactly KIWI.")}`);
+ r.s.cancel();
+ await finish(r);
+ },
+ T
+ );
+ });
+
describe.concurrent("blocked, interrupts and permission", () => {
test(
"ask_user (team): FAILED blocked with the question text, in one net transition",
@@ -538,7 +568,7 @@ describe.skipIf(!MAGMUX)(
const r = await start("answer", { shape: "interactive", decide: () => "continue" });
await until(r, (s) => s.state === "AWAITING_INPUT" && s.turnsCompleted === 1);
r.s.send("/exit");
- const snap = await finish(r);
+ const snap = await finish(r, 8000);
expect(snap.state).toBe("COMPLETED");
expect(snap.reason).toBeNull();
expect(snap.turnsCompleted).toBe(1);
diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.ts
index fb66c294..95e5f37b 100644
--- a/packages/cli/src/pane/pane-session.ts
+++ b/packages/cli/src/pane/pane-session.ts
@@ -1081,7 +1081,11 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
const d = this.currentDelivery;
return {
index: t.index,
- answer: t.assistantText.join("\n\n"),
+ // a local command's answer is its own stdout: it has no assistant message (path L)
+ answer:
+ decision.by === "local_command"
+ ? (t.localCommandOutput ?? "")
+ : t.assistantText.join("\n\n"),
apiError: t.apiError,
stopReason: decision.stopReason,
captureSource: "transcript",
diff --git a/packages/cli/src/pane/settle-rule.test.ts b/packages/cli/src/pane/settle-rule.test.ts
index 926972aa..3f7bca14 100644
--- a/packages/cli/src/pane/settle-rule.test.ts
+++ b/packages/cli/src/pane/settle-rule.test.ts
@@ -350,3 +350,34 @@ describe("refusal (redacted corpus)", () => {
});
});
});
+
+describe("path L — a local command's stdout", () => {
+ function compactView(): TranscriptView {
+ const n = "local-commands";
+ const recs = transcriptRecords(n);
+ const at = recs.findIndex((r) => r.type === "user" && textOf(r) === "/compact");
+ const upTo = recs.findIndex((r) => textOf(r).startsWith("Reply with exactly KIWI"));
+ const r = replay(n, [{ at, witness: { kind: "command", name: "compact" } }], { upTo });
+ cleanups.push(r.cleanup);
+ return r.views[0]!;
+ }
+
+ test("settles /compact (no assistant record, no turn_duration) once corroborated", () => {
+ const v = compactView();
+ expect(v.current?.turnDurationAfterLast).toBeNull();
+ expect(decideSettle(input(v))).toEqual({
+ settled: true,
+ by: "local_command",
+ stopReason: null,
+ anomalies: [],
+ });
+ expect(decideSettle(input(v, { chatQuietMs: 0 })).settled).toBe(false);
+ expect(decideSettle(input(v, { screen: { ...IDLE_SCREEN, working: true } })).settled).toBe(
+ false
+ );
+ expect(decideSettle(input(v, { screen: null, paneExited: true }))).toMatchObject({
+ settled: true,
+ by: "local_command",
+ });
+ });
+});
diff --git a/packages/cli/src/pane/settle-rule.ts b/packages/cli/src/pane/settle-rule.ts
index aed97f55..7349f968 100644
--- a/packages/cli/src/pane/settle-rule.ts
+++ b/packages/cli/src/pane/settle-rule.ts
@@ -15,6 +15,9 @@
* satisfy S: until its summary is written there is none, and the screen's working
* row is rewritten every second while it runs.
* X only when the pane has exited: an ending `stop_reason` and nothing waking after it.
+ * L a LOCAL slash command (`/compact`, `/model x`): its `<local-command-stdout>` after
+ * the witness and no assistant message. Claude Code writes neither an assistant record
+ * nor `turn_duration` for one (captured, 2.1.290 and 2.1.291).
*
* Nothing here is a timer that ends work (D10): S's window only confirms an ending that
* has already happened, and an unsettled turn just reports its `activity`.
@@ -60,7 +63,7 @@ export interface SettleInput {
corroborationMs?: number;
}
-export type SettledBy = "turn_duration" | "interrupt" | "quiet" | "exit";
+export type SettledBy = "turn_duration" | "interrupt" | "quiet" | "exit" | "local_command";
export type SettleDecision =
| { settled: true; by: SettledBy; stopReason: string | null; anomalies: string[] }
@@ -127,6 +130,13 @@ function pathInterrupt(input: SettleInput): Path {
return c.ok ? settledAs("interrupt", "interrupted", c) : null;
}
+/** L — a local command's stdout (corroborated like P; no screen once the pane exited). */
+function pathLocalCommand(input: SettleInput): Path {
+ if (input.paneExited) return settledAs("local_command", null, {});
+ const c = corroborated(input);
+ return c.ok ? settledAs("local_command", null, c) : null;
+}
+
/** P — turn_duration with no background agent pending. */
function pathPrimary(t: TurnView, input: SettleInput): Path {
const td = t.turnDurationAfterLast;
@@ -152,6 +162,8 @@ function pathSecondary(t: TurnView, input: SettleInput): Path {
export function decideSettle(input: SettleInput): SettleDecision {
const t = input.turn;
const notYet: SettleDecision = { settled: false, activity: activityOf(t) };
+ if (t && t.acceptedAt !== null && !t.lastAssistant && t.localCommandOutput !== null)
+ return pathLocalCommand(input) ?? notYet;
// 1. accepted, with an assistant message after the witness; 2. nothing waking after it
if (!t || t.acceptedAt === null || !t.lastAssistant || t.wakingAfterLast) return notYet;
if (t.interruptAfterLast) return pathInterrupt(input) ?? notYet;
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
index 40c9ae80..a3293733 100755
--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -713,6 +713,28 @@ async function screenOnlyTurn(line: string): Promise<void> {
else showHistory(`⏺ ${answerFor(line)}`, finishedRow());
}
+/** Local commands the fake runs the way 2.1.291 does: their own records, no model turn. */
+const LOCAL_COMMANDS = new Set(["compact", "model"]);
+
+async function localCommandTurn(name: string, args: string): Promise<void> {
+ S.history.push(`❯ /${name}${args ? ` ${args}` : ""}`);
+ let stdout = `Set model to \`${args}\``;
+ if (name === "compact") {
+ // file order as captured: the typed line, the boundary and summary, then the
+ // command's caveat / <command-name> / <local-command-stdout>
+ rec.slice([L.compactTyped]);
+ S.working = "✶ Compacting conversation…";
+ render();
+ await sleep(gap("COMPACT", 300));
+ rec.slice([L.compactBoundary, L.compactSummary]);
+ stdout = "\u001b[2mCompacted (ctrl+o to see full summary)\u001b[22m";
+ }
+ S.working = null;
+ rec.localCommand(name, args, stdout);
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the ANSI the stdout carries
+ showHistory(` ⎿ ${stdout.replace(/\x1b\[[0-9;]*m/g, "")}`);
+}
+
async function submit(line: string): Promise<void> {
turn++;
busy = true;
@@ -737,6 +759,8 @@ async function submit(line: string): Promise<void> {
} else {
if (scenario !== "immediate_write") await sleep(gap("WITNESS", 50));
const slash = line.match(/^\/([A-Za-z0-9][A-Za-z0-9:_-]*)\s*(.*)$/);
+ if (slash && LOCAL_COMMANDS.has(slash[1] as string))
+ return await localCommandTurn(slash[1] as string, slash[2] ?? "");
if (slash) rec.command(slash[1] as string, slash[2] ?? "");
else rec.user(line);
S.history.push(`❯ ${line.split("\n")[0]}`);
diff --git a/packages/cli/src/pane/transcript-follower.test.ts b/packages/cli/src/pane/transcript-follower.test.ts
index 67f2c896..742cf1e6 100644
--- a/packages/cli/src/pane/transcript-follower.test.ts
+++ b/packages/cli/src/pane/transcript-follower.test.ts
@@ -634,6 +634,40 @@ describe("tailing", () => {
});
describe("local commands", () => {
+ test("a local command turn carries its stdout (2.1.291 /model, /compact), ANSI removed", () => {
+ const n = "local-commands";
+ const recs = transcriptRecords(n);
+ const model = recs.findIndex((r) => textOf(r).includes("<command-name>/model</command-name>"));
+ const compactTyped = recs.findIndex((r) => r.type === "user" && textOf(r) === "/compact");
+ const { views } = run(n, [
+ { at: model - 2, witness: { kind: "command", name: "model" } },
+ { at: compactTyped, witness: { kind: "command", name: "compact" } },
+ ]);
+ const m = cur(views[0]);
+ expect(m.acceptedAt).not.toBeNull();
+ expect(m.lastAssistant).toBeNull();
+ expect(m.localCommandOutput?.startsWith("Set model to `Haiku 4.5`")).toBe(true);
+ expect(m.localCommandOutput).not.toContain("\u001b");
+ // the second turn ran on to the KIWI turn, so view the compact turn before it
+ const { views: v2 } = run(
+ n,
+ [{ at: compactTyped, witness: { kind: "command", name: "compact" } }],
+ { upTo: recs.findIndex((r) => textOf(r).startsWith("Reply with exactly KIWI")) }
+ );
+ expect(cur(v2[0]).localCommandOutput).toBe("Compacted (ctrl+o to see full summary)");
+ });
+
+ test("a prompt command (/pear) carries no local output: it settles on its assistant turn", () => {
+ const n = "slash-and-reads";
+ const at = transcriptRecords(n).findIndex((r) => textOf(r).includes("<command-name>/pear"));
+ const td = indexOf(n, (r) => r.subtype === "turn_duration", at);
+ const { views } = run(n, [{ at, witness: { kind: "command", name: "pear" } }], {
+ upTo: td + 1,
+ });
+ expect(cur(views[0]).localCommandOutput).toBeNull();
+ expect(cur(views[0]).assistantText).toEqual(["PEAR"]);
+ });
+
test("/exit's own records after a settled turn (real 2.1.285) never wake it", async () => {
const { appendFileSync } = await import("node:fs");
const PEAR = "Reply with exactly PEAR and nothing else.";
diff --git a/packages/cli/src/pane/transcript-follower.ts b/packages/cli/src/pane/transcript-follower.ts
index 5a16fa89..059b37cd 100644
--- a/packages/cli/src/pane/transcript-follower.ts
+++ b/packages/cli/src/pane/transcript-follower.ts
@@ -83,6 +83,8 @@ export interface TurnView {
preambleBytes: number;
/** offset of the last main-chain chat record (user or assistant) of this turn */
lastChatOffset: number | null;
+ /** a local command's `<local-command-stdout>` after its witness (ANSI removed); null otherwise */
+ localCommandOutput: string | null;
}
export interface SessionFacts {
@@ -140,6 +142,7 @@ interface TurnState {
compactions: number;
read: ReadState | null;
lastChatOffset: number | null;
+ localOutput: { text: string; offset: number } | null;
}
export interface FollowerState {
@@ -403,6 +406,24 @@ function applyToolResults(t: TurnState, r: Rec, blocks: Rec[], offset: number):
}
}
+const STDOUT_RE = /^\s*<local-command-(stdout|stderr)>([\s\S]*?)<\/local-command-\1>/;
+// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences in local-command output
+const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
+
+/**
+ * A command turn's settle evidence (§2.7): the `<local-command-stdout>` record a LOCAL
+ * command writes after its `<command-name>` witness, with no assistant message (captured:
+ * `/compact`, `/model x` in 2.1.291). A command that prompts the model (`/pear`) writes
+ * none and settles like any other turn.
+ */
+function applyLocalCommandRecord(t: TurnState, text: string, offset: number): void {
+ if (t.witness.kind !== "command" || t.lastAssistant || t.localOutput) return;
+ const m = text.match(STDOUT_RE);
+ if (!m) return;
+ t.localOutput = { text: (m[2] ?? "").replace(ANSI_RE, "").trim(), offset };
+ t.lastChatOffset = offset;
+}
+
function applyNotification(t: TurnState, text: string): void {
const id = taskIdOf(text);
if (!id) return;
@@ -421,7 +442,10 @@ function applyUser(t: TurnState, r: Rec, offset: number): void {
return;
}
const text = userText(r);
- if (isLocalCommandText(text)) return;
+ if (isLocalCommandText(text)) {
+ applyLocalCommandRecord(t, text, offset);
+ return;
+ }
if (text.startsWith("[Request interrupted by user")) {
t.interrupt = { forToolUse: text.includes("for tool use") };
t.pending.clear();
@@ -537,6 +561,7 @@ export function openTurnState(
compactions: 0,
read: t.delivery ? newReadState(t.delivery) : null,
lastChatOffset: null,
+ localOutput: null,
});
return state;
}
@@ -589,6 +614,7 @@ export function turnView(t: TurnState): TurnView {
: { linesReturned: 0, complete: true, reads: 0, completedAtOffset: null },
preambleBytes,
lastChatOffset: t.lastChatOffset,
+ localCommandOutput: t.localOutput?.text ?? null,
};
}