Skip to content

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

feat(team): add reason_detail to SlotRow

Jack Rudenko059cb2535271
diff --git a/ai-docs/architecture/mcp-channel.md b/ai-docs/architecture/mcp-channel.md
index 753018ab..f2128b0c 100644
--- a/ai-docs/architecture/mcp-channel.md
+++ b/ai-docs/architecture/mcp-channel.md
@@ -325,7 +325,7 @@ what a caller cannot see from the model id.
**The polling verbs are the frozen mod contract v1** (`pane/contract.ts`, summarised in
`pane-session.md`): `list_sessions` answers `{contract_version, capabilities, sessions}` with one
-`SessionRow` per session (state, reason, tokens, `cost_usd`, tool calls, turns, `idle_seconds`,
+`SessionRow` per session (state, reason, `reason_detail`, tokens, `cost_usd`, tool calls, turns, `idle_seconds`,
`activity`, `pane`); `cancel_session` answers `{session_id, state, changed}`; `capture_session`
answers the session's current 160×50 screen `{seq, cols, rows, cursor, lines, final, spans?}`, or
`{unchanged:true, seq, final}` when `since_seq` is still current — a memory read, meant for polling
diff --git a/ai-docs/architecture/pane-session.md b/ai-docs/architecture/pane-session.md
index f85a100a..c1d5a744 100644
--- a/ai-docs/architecture/pane-session.md
+++ b/ai-docs/architecture/pane-session.md
@@ -508,6 +508,17 @@ type and new fields may only be added.
pricing, fictional spend for a subscription user; D12), tool calls, turns completed,
`last_activity_at`, `idle_seconds`, `activity` (`thinking`, `background`, `finishing`, a tool name,
`AskUserQuestion`; unknown values mean busy) and `pane`.
+- `reason_detail` (added within v1, 2026-10-16) is one line, at most 160 characters, saying why
+ `reason`: for `api_error` the provider's `error.message` from the LAST record of the upstream-error
+ capture (`errors/<slot>-upstream.jsonl` for team, `upstream-errors.jsonl` for a session), else the
+ child's API-error text with claudish's "The turn ended in an API error (status N): API Error: N"
+ boilerplate stripped; for every other reason, the first line of the verdict's detail (the dialog or
+ screen text of `boot_blocked` / `first_run_dialog`, the question of `blocked`, the exit line of
+ `child_exited`, the refusal of `agent_rejected`). Null on every non-terminal state, on COMPLETED,
+ and when nothing readable exists. Only `error.message` is ever lifted from an upstream body —
+ bodies carry `user_id`. One pure function, `reasonDetail()` in `pane/reason-detail.ts`, computes
+ it for both row builders (`toSlotRow` / `teamRunRowFromDisk` and `sessionRowOf`); the capture file
+ is read (16 KB tail) only for a terminal `api_error` row.
- Verbs: `team(mode="list")` → `{contract_version, capabilities, runs}`; `team(mode="status")` adds
`contract_version`, `capabilities` and a `run` row to its payload; `team(mode="cancel")` and
`cancel_session` return per-slot `{state, changed}`; `team(mode="capture")` and `capture_session`
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.md
index b9f1ebd2..eb84ea0a 100644
--- a/docs/usage/mcp-server.md
+++ b/docs/usage/mcp-server.md
@@ -187,7 +187,7 @@ interactive Claude Code session in its own headless magmux pane (see "Requiremen
| Mode | What it does |
|------|-------------|
| `run` | Start the models and return once every slot has taken its prompt (at most about two minutes, usually seconds) — it does not wait for answers. Outputs are written anonymized to the session directory. The result carries `run_id` and `monitor_record`, the run's record under `~/.claudish/sessions/` (see "Session records on disk") |
-| `status` | Progress of a run: per-slot rows under `run.slots` (state, reason, tokens, idle seconds, activity), plus `contract_version` and `capabilities` |
+| `status` | Progress of a run: per-slot rows under `run.slots` (state, reason, reason_detail, tokens, idle seconds, activity), plus `contract_version` and `capabilities` |
| `list` | Every run this server holds: `{contract_version, capabilities, runs}`. Finished runs stay listed for 30 minutes |
| `capture` | One slot's current terminal screen (same shape as `capture_session`) |
| `cancel` | Stop one slot (`slot`) or every slot of the run; answers each slot's `{state, changed}` |
@@ -384,9 +384,12 @@ List the sessions this server holds.
- `include_completed` (optional) - Include completed, failed, and cancelled sessions (default: false)
**Returns:** `{ contract_version: 1, capabilities: [...], sessions: [...] }`. Each row has `session_id`,
-`model`, `provider`, `state`, `reason`, `tokens_in`, `tokens_out`, `cost_usd` (null for native Claude
-models), `tool_calls`, `turns_completed`, `last_activity_at`, `idle_seconds`, `activity`, `started_at`,
-`completed_at` and `elapsed_seconds`. Nothing stops a session for being idle; `idle_seconds` is for
+`model`, `provider`, `state`, `reason`, `reason_detail`, `tokens_in`, `tokens_out`, `cost_usd` (null
+for native Claude models), `tool_calls`, `turns_completed`, `last_activity_at`, `idle_seconds`, `activity`, `started_at`,
+`completed_at` and `elapsed_seconds`. `reason_detail` is one line (at most 160 characters) saying
+why a failed session failed — for `api_error`, the provider's own error message (`no-such-model-zz9
+is not a valid model ID`) — and null while the session is live, on COMPLETED, and when nothing
+readable exists. Team status rows carry the same field. Nothing stops a session for being idle; `idle_seconds` is for
you to judge.
---
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.ts
index 0455f403..3d5f98a0 100644
--- a/packages/cli/src/channel/session-manager.ts
+++ b/packages/cli/src/channel/session-manager.ts
@@ -62,11 +62,13 @@ import {
isTerminalState,
mergeAccounting,
readTokenFileCached,
+ reasonDetail,
releasePaneReservations,
reservePanes,
resolveProvider,
sockRootFor,
startPaneSession,
+ upstreamRecordsFor,
} from "../pane/index.js";
import { redactSecrets } from "../redact.js";
import { projectsDir, transcriptPathFor } from "../session/session-discovery.js";
@@ -340,7 +342,11 @@ export function channelEventFor(snap: { state: SlotState; activity: string | nul
}
/** One `list_sessions` row (§8 B): exactly the SlotRow keys plus the four session keys. */
-export function sessionRowOf(info: SessionInfo): SessionRow {
+export function sessionRowOf(
+ info: SessionInfo,
+ /** the session's upstream-error records (`upstreamRecordsFor`); [] = none read */
+ upstreamRecords: readonly string[] = []
+): SessionRow {
const terminal = isTerminalState(info.state);
return {
slot: info.sessionId,
@@ -348,6 +354,7 @@ export function sessionRowOf(info: SessionInfo): SessionRow {
provider: info.provider,
state: info.state,
reason: info.state === "COMPLETED" || !terminal ? null : info.reason,
+ reason_detail: reasonDetail(info, upstreamRecords),
tokens_in: info.tokensIn,
tokens_out: info.tokensOut,
cost_usd: info.costUsd,
@@ -1362,7 +1369,14 @@ export class SessionManager {
/** `list_sessions` rows (§8 B). */
listSessionRows(includeCompleted = false): SessionRow[] {
- return this.listSessions(includeCompleted).map(sessionRowOf);
+ const rows: SessionRow[] = [];
+ for (const entry of this.sessions.values()) {
+ this.refresh(entry);
+ if (!includeCompleted && isTerminalState(entry.info.state)) continue;
+ const info = { ...entry.info };
+ rows.push(sessionRowOf(info, upstreamRecordsFor(info, entry.upstreamErrorLogPath)));
+ }
+ return rows;
}
/** A single session's info; falls back to `<sessionsDir>/<id>/meta.json`. */
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index ce91b4a1..22cbeeab 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -2159,7 +2159,9 @@ function defineTools(sessionManager: SessionManager): ToolDefinition[] {
"finished ones. Each row reports `state`, `activity` and `idle_seconds`: how long since " +
"the session's screen or transcript last changed. Nothing kills a session for being " +
"idle — a child inside a long Bash call is silent and working — so this is yours to " +
- "judge against the task you set, and `cancel_session` is yours to call if the answer is no.",
+ "judge against the task you set, and `cancel_session` is yours to call if the answer is no. " +
+ "A failed row's `reason_detail` is one line saying why (for api_error, the provider's " +
+ "own error message); it is null while the session is live and on COMPLETED.",
inputSchema: {
type: "object",
properties: {
diff --git a/packages/cli/src/pane/contract.ts b/packages/cli/src/pane/contract.ts
index 350c7535..0e074419 100644
--- a/packages/cli/src/pane/contract.ts
+++ b/packages/cli/src/pane/contract.ts
@@ -129,6 +129,11 @@ export interface SlotRow {
/** set on FAILED / EMPTY / CANCELLED / TIMEOUT; null otherwise (incl. COMPLETED). One exception: a
* pre-contract state read from disk is FAILED with null (§B) */
reason: FailureReason | null;
+ /** [additive] one line (≤ 160 chars) saying why `reason`: for api_error the provider's
+ * `error.message` from the last upstream-error record, else the child's API-error text;
+ * for any other reason the first line of its detail. null on non-terminal states, on
+ * COMPLETED, and when nothing readable exists. Never the upstream body. `reasonDetail()` */
+ reason_detail: string | null;
/** billed input incl. cache reads/writes, main conversation + subagents; null = no source yet */
tokens_in: number | null;
tokens_out: number | null;
diff --git a/packages/cli/src/pane/index.ts b/packages/cli/src/pane/index.ts
index bca4839f..a67c2a38 100644
--- a/packages/cli/src/pane/index.ts
+++ b/packages/cli/src/pane/index.ts
@@ -6,6 +6,7 @@
export * from "./contract.js";
export { toSlotRow } from "./slot-row.js";
+export { REASON_DETAIL_MAX_CHARS, reasonDetail, upstreamRecordsFor } from "./reason-detail.js";
export { deliveryRefusal } from "./prompt-delivery.js";
export {
type Accounting,
diff --git a/packages/cli/src/pane/reason-detail.ts b/packages/cli/src/pane/reason-detail.ts
new file mode 100644
index 00000000..451882a7
--- /dev/null
+++ b/packages/cli/src/pane/reason-detail.ts
@@ -0,0 +1,170 @@
+/**
+ * `SlotRow.reason_detail` (mod contract v1, additive): one readable line that says WHY a
+ * terminal slot or session did not complete, so a reader of `team(mode="status")` or
+ * `list_sessions` sees "no-such-model-zz9 is not a valid model ID" beside `api_error`
+ * instead of having to open `status.json` or `get_diagnostics`.
+ *
+ * `reasonDetail` is pure; both row builders (team's `toSlotRow` / `teamRunRowFromDisk`
+ * and the channel's `sessionRowOf`) call it. `upstreamRecordsFor` is the one bounded
+ * read of the upstream-error capture file, done only when the rule can use it.
+ *
+ * Only the provider's `error.message` is ever lifted out of an upstream body: the body
+ * itself carries account identifiers (`user_id`), so no other field and never the whole
+ * body reaches a row.
+ */
+
+import { closeSync, fstatSync, openSync, readSync } from "node:fs";
+import { type FailureReason, type SlotState, isTerminalState } from "./contract.js";
+
+/** Longest `reason_detail`, ellipsis included. */
+export const REASON_DETAIL_MAX_CHARS = 160;
+
+/** Tail of the upstream-error file read for the last record (one record is ≤ ~2.3 KB). */
+const UPSTREAM_TAIL_BYTES = 16 * 1024;
+
+export interface ReasonDetailInput {
+ state: SlotState;
+ reason: FailureReason | null;
+ /** the owner's verdict detail (`PaneSnapshot.detail`, `status.json` `error.detail`) */
+ detail: string | null | undefined;
+}
+
+/**
+ * The row's `reason_detail`: null on every non-terminal state, on COMPLETED, and when
+ * nothing readable exists. For `api_error`, the provider's `error.message` from the LAST
+ * upstream record when it has one, else the child's API-error text without claudish's
+ * "The turn ended in an API error (status N): API Error: N" boilerplate. For every other
+ * reason, the first line of its detail. One line, at most REASON_DETAIL_MAX_CHARS.
+ *
+ * `upstreamRecords` are raw JSONL lines of the capture file, oldest first.
+ */
+export function reasonDetail(
+ input: ReasonDetailInput,
+ upstreamRecords: readonly string[] = []
+): string | null {
+ if (!isTerminalState(input.state) || input.state === "COMPLETED") return null;
+ if (input.reason === "api_error") {
+ const last = upstreamRecords.length ? upstreamRecords[upstreamRecords.length - 1] : undefined;
+ const upstream = last === undefined ? null : upstreamMessage(last);
+ if (upstream) return oneLine(upstream);
+ const child = firstLine(input.detail);
+ return child ? oneLine(apiErrorText(child)) : null;
+ }
+ const first = firstLine(input.detail);
+ return first ? oneLine(first) : null;
+}
+
+/**
+ * The upstream records `reasonDetail` needs for this row: the capture file's tail when
+ * the row is a terminal `api_error`, else none (no read at all). Never throws.
+ */
+export function upstreamRecordsFor(
+ input: Pick<ReasonDetailInput, "state" | "reason">,
+ upstreamLogPath: string | null | undefined
+): string[] {
+ if (!upstreamLogPath || input.reason !== "api_error" || !isTerminalState(input.state)) return [];
+ return readTailLines(upstreamLogPath, UPSTREAM_TAIL_BYTES);
+}
+
+function firstLine(text: string | null | undefined): string | null {
+ if (!text) return null;
+ const line = text.split(/\r?\n/).find((l) => l.trim().length > 0);
+ return line ? line.trim() : null;
+}
+
+/** Whitespace collapsed, cut to the cap with an ellipsis; null when nothing is left. */
+function oneLine(text: string): string | null {
+ const flat = text.replace(/\s+/g, " ").trim();
+ if (!flat) return null;
+ return flat.length > REASON_DETAIL_MAX_CHARS
+ ? `${flat.slice(0, REASON_DETAIL_MAX_CHARS - 1).trimEnd()}…`
+ : flat;
+}
+
+/**
+ * The child's API-error line without its boilerplate. `classifyRunOutput` writes
+ * "The turn ended in an API error (status 400): API Error: 400 <text>"; Claude Code's
+ * own line is "API Error: 400 <text>", where <text> may be the provider's JSON body.
+ */
+function apiErrorText(detail: string): string {
+ const text = detail
+ // a team verdict's appended notes (" · background_shell_open …") are not the error
+ .split(" · ")[0]
+ .replace(/^The turn ended in an API error(?:\s*\(status \d+\))?:\s*/i, "")
+ .replace(/^API Error:?\s*(?:\d{3}\b)?\s*/i, "")
+ .trim();
+ if (/^[[{]/.test(text)) return messageOfJsonText(text) ?? "";
+ return text;
+}
+
+/** `error.message` of one upstream-capture JSONL record's `body`, or null. */
+function upstreamMessage(record: string): string | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(record);
+ } catch {
+ return null;
+ }
+ if (!isObject(parsed)) return null;
+ const body = parsed.body;
+ if (typeof body === "string") return messageOfJsonText(body);
+ return messageOf(body);
+}
+
+/**
+ * `error.message` from a JSON text. A body cut at the capture cap no longer parses; its
+ * message is then the first `"message":"…"` string, still never any other field.
+ */
+function messageOfJsonText(text: string): string | null {
+ try {
+ return messageOf(JSON.parse(text));
+ } catch {
+ const m = /"error"\s*:\s*\{[^{}]*?"message"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(text);
+ if (!m) return null;
+ try {
+ return nonEmpty(JSON.parse(`"${m[1]}"`));
+ } catch {
+ return null;
+ }
+ }
+}
+
+/** `{error:{message}}`, or the first element of an array of those (Gemini's shape). */
+function messageOf(value: unknown): string | null {
+ const v = Array.isArray(value) ? value[0] : value;
+ if (!isObject(v) || !isObject(v.error)) return null;
+ return nonEmpty(v.error.message);
+}
+
+function nonEmpty(v: unknown): string | null {
+ return typeof v === "string" && v.trim().length > 0 ? v : null;
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+/** The last `maxBytes` of a JSONL file as whole non-empty lines; [] on any failure. */
+function readTailLines(path: string, maxBytes: number): string[] {
+ let fd: number | null = null;
+ try {
+ fd = openSync(path, "r");
+ const size = fstatSync(fd).size;
+ const start = Math.max(0, size - maxBytes);
+ const buf = Buffer.alloc(size - start);
+ readSync(fd, buf, 0, buf.length, start);
+ const lines = buf.toString("utf-8").split("\n");
+ if (start > 0) lines.shift();
+ return lines.filter((l) => l.trim().length > 0);
+ } catch {
+ return [];
+ } finally {
+ if (fd !== null) {
+ try {
+ closeSync(fd);
+ } catch {
+ // nothing to recover
+ }
+ }
+ }
+}
diff --git a/packages/cli/src/pane/slot-row.ts b/packages/cli/src/pane/slot-row.ts
index e204afb3..77606a4b 100644
--- a/packages/cli/src/pane/slot-row.ts
+++ b/packages/cli/src/pane/slot-row.ts
@@ -5,13 +5,16 @@
import type { Accounting } from "./accounting.js";
import { type SlotRow, isTerminalState } from "./contract.js";
+import { reasonDetail } from "./reason-detail.js";
import type { PaneSnapshot } from "./types.js";
export function toSlotRow(
id: { slot: string; model: string; spawnModel: string | null },
snap: PaneSnapshot,
acct: Accounting,
- now: number = Date.now()
+ now: number = Date.now(),
+ /** the slot's upstream-error records (`upstreamRecordsFor`); [] = none read */
+ upstreamRecords: readonly string[] = []
): SlotRow {
const terminal = isTerminalState(snap.state);
let idle: number | null = null;
@@ -26,6 +29,10 @@ export function toSlotRow(
state: snap.state,
// set on FAILED / EMPTY / CANCELLED / TIMEOUT; null otherwise
reason: snap.state === "COMPLETED" || !terminal ? null : snap.reason,
+ reason_detail: reasonDetail(
+ { state: snap.state, reason: snap.reason, detail: snap.detail },
+ upstreamRecords
+ ),
tokens_in: acct.tokensIn,
tokens_out: acct.tokensOut,
cost_usd: acct.costUsd,
diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.ts
index e9954f50..a6d74151 100644
--- a/packages/cli/src/team-orchestrator.ts
+++ b/packages/cli/src/team-orchestrator.ts
@@ -33,12 +33,14 @@ import {
livePaneCount,
mergeAccounting,
readTokenFileCached,
+ reasonDetail,
releasePaneReservations,
reservePanes,
resolveProvider,
sockRootFor,
startPaneSession,
toSlotRow,
+ upstreamRecordsFor,
} from "./pane/index.js";
import { redactSecrets } from "./redact.js";
import { projectsDir, transcriptPathFor } from "./session/session-discovery.js";
@@ -429,6 +431,11 @@ function notableAnomalies(snap: PaneSnapshot): string[] {
);
}
+/** `errors/<slot>-upstream.jsonl`: the child proxy's upstream-error capture for one slot. */
+function upstreamLogPath(path: string, id: string): string {
+ return join(path, "errors", `${id}-upstream.jsonl`);
+}
+
function neverSpawnedRow(e: SlotEntry, m: ModelStatus | undefined): SlotRow {
return {
slot: e.id,
@@ -436,6 +443,11 @@ function neverSpawnedRow(e: SlotEntry, m: ModelStatus | undefined): SlotRow {
provider: e.acct.provider,
state: m?.state ?? "FAILED",
reason: m?.error?.reason ?? "pane_lost",
+ reason_detail: reasonDetail({
+ state: m?.state ?? "FAILED",
+ reason: m?.error?.reason ?? "pane_lost",
+ detail: m?.error?.detail,
+ }),
tokens_in: null,
tokens_out: null,
cost_usd: null,
@@ -454,7 +466,9 @@ function liveSlotRow(run: LiveTeamRun, e: SlotEntry): SlotRow {
return toSlotRow(
{ slot: e.id, model: e.model, spawnModel: e.spawnModel },
snap,
- refreshAccounting(e, snap)
+ refreshAccounting(e, snap),
+ Date.now(),
+ upstreamRecordsFor(snap, upstreamLogPath(run.path, e.id))
);
}
@@ -513,12 +527,16 @@ export function teamRunRowFromDisk(path: string, status: TeamStatus): TeamRunRow
.map(([id, m]) => {
const { state, known } = closedState(m?.state);
const terminal = isTerminalState(state);
+ const reason =
+ !known || !terminal || state === "COMPLETED" ? null : (m?.error?.reason ?? null);
+ const why = { state, reason, detail: m?.error?.detail };
return {
slot: id,
model: m?.model ?? manifest?.models[id]?.model ?? "unknown",
provider: m?.provider ?? null,
state,
- reason: !known || !terminal || state === "COMPLETED" ? null : (m?.error?.reason ?? null),
+ reason,
+ reason_detail: reasonDetail(why, upstreamRecordsFor(why, upstreamLogPath(path, id))),
tokens_in: m?.tokensIn ?? null,
tokens_out: m?.tokensOut ?? null,
cost_usd: m?.costUsd ?? null,
@@ -1242,7 +1260,7 @@ async function startModelsIn(
const entries = new Map<string, SlotEntry>();
let run: LiveTeamRun | null = null;
const errorLogPathOf = (id: string) => join(path, "errors", `${id}.log`);
- const upstreamLogOf = (id: string) => join(path, "errors", `${id}-upstream.jsonl`);
+ const upstreamLogOf = (id: string) => upstreamLogPath(path, id);
const commandOf = (e: SlotEntry) =>
["claudish", "-i", "--model", e.spawnModel ?? e.model, "-y", "--quiet", ...claudeFlags].join(
" "