Skip to content

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

fix(channel): report waiting_for_input only while stdin stays open

Jack Rudenkoc315ebc52296
diff --git a/ai-docs/architecture/mcp-channel.md b/ai-docs/architecture/mcp-channel.md
index 57972d73..4d888195 100644
--- a/ai-docs/architecture/mcp-channel.md
+++ b/ai-docs/architecture/mcp-channel.md
@@ -124,10 +124,46 @@ the divergence — is gone. **Mutation-proven**: remove the map key and a timed-
goes back to `status: "working"` on the wire.
**Session shape follows the prompt.** `create_session` WITH a prompt is one-shot: stdin is
-closed on the first `result` and the child exits 0 → `completed`. WITHOUT a prompt it is
-interactive: stdin stays open, the session sits in `waiting_for_input` between turns, and
-it ends on `send_input` → … → `cancel_session` or the timeout. A `send_input` call converts
-a one-shot session to interactive.
+closed on the first `result`, the session is `finishing` until the child exits 0, then
+`completed`. WITHOUT a prompt it is interactive: stdin stays open, the session is in
+`waiting_for_input` from creation and again between turns, and it ends on `send_input` → …
+→ `cancel_session` or the timeout. A `send_input` call converts a one-shot session to
+interactive.
+
+**`waiting_for_input` means a real wait, and nothing else.** It holds iff claudish holds the
+child's stdin open and the child has finished a turn no `send_input` has followed yet, or a
+promptless session has received no input yet. Before `finishing` existed, every `result` frame moved the
+reducer there, including a one-shot's last one, and `handleResult` closed stdin a moment
+later — so every one-shot session emitted an `input_required` nothing could answer. The turn
+end is now the OWNER's decision: `StreamJsonReducerOptions.onResult` is required and returns
+`TurnEnd` (`"stdin-open" | "stdin-closed"`), and `applyResultFrame` asks it BEFORE
+transitioning, to `waiting_for_input` or to `finishing`. `finishing` (non-terminal) admits
+only terminal successors; a late `assistant`/`user` frame there is refused and recorded as an
+anomaly (`get_diagnostics`). It projects to SEP-1686 `working`, and `checkStall` leaves it
+unwatched — the session timeout bounds it. `team` closes stdin at spawn, so its reducer
+always answers `"stdin-closed"`: a slot reads `finishing` between its `result` and its exit.
+A promptless session enters `waiting_for_input` through `awaitInput()` at creation; its
+`system:init` frame does not move it, and `beginTurn()` (every `writeFrame`) moves it to
+`running`.
+
+### `waits.jsonl` — the wait log
+
+`<sessionDir>/waits.jsonl` gets one line per transition INTO `waiting_for_input` and one per
+transition OUT of it (terminal states included), written in the reducer callback that changes
+the state:
+
+```jsonc
+{"wait":"open","since":"2026-10-02T10:03:12.000Z","turns":1}
+{"wait":"closed","since":"2026-10-02T10:03:12.000Z","at":"2026-10-02T10:03:13.400Z","to":"running"}
+```
+
+`since` keys the wait (the `closed` line repeats it); `turns` is `turnsCompleted` at the
+open. It is append-only because an observer polling the directory (the magus `claudish`
+plugin monitor) must see a wait that opened and closed between two of its reads — a marker
+file that exists only during the wait cannot give it that. `finalize` settles before
+`writeArtifacts`, so a live writer never leaves an open wait beside a `meta.json`. One
+`appendFileSync` of < 200 bytes per line; a write failure goes to stderr and loses only that
+line; the file stops at 1 MB. A one-shot session never writes one.
### Diagnostics are captured unconditionally, and reachable from the API
@@ -225,7 +261,7 @@ The wire format is contractually pinned by `channel-wire-format.test.ts`:
"content": "<string>",
"meta": {
"session_id": "<8-char hex>",
- "event": "starting|running|tool_executing|waiting_for_input|completed|failed|cancelled|timeout",
+ "event": "starting|running|tool_executing|waiting_for_input|finishing|completed|failed|cancelled|timeout",
"model": "<model-id>",
"elapsed_seconds": "<numeric string>",
"task_id": "<same as session_id>",
diff --git a/ai-docs/architecture/team-lifecycle.md b/ai-docs/architecture/team-lifecycle.md
index a1224df9..76ae92c0 100644
--- a/ai-docs/architecture/team-lifecycle.md
+++ b/ai-docs/architecture/team-lifecycle.md
@@ -69,7 +69,8 @@ activity frozen at `waiting_for_input`, idle counting up from its exit. Measured
a real status payload: `completedAt + idle_seconds` landed on the poll time for
both finished slots (idle 57 s and 571 s), while the third slot was still working.
A caller read `waiting_for_input` as a slot that needed an answer, which `team`
-has no way to send.
+has no way to send. A slot now never reports `waiting_for_input` at all:
+between its `result` and its exit it reads `finishing` (see below).
**The caller decides, and `cancel` is how it acts.** `cancelTeamRun` is the only
thing that kills a slot. It kills the process GROUP: `claudish` is a launcher
@@ -197,11 +198,13 @@ and the slot was classified EMPTY.
### Team must settle the reducer itself
-A `result` frame moves the reducer to `waiting_for_input`, on the premise that
-stdin is still open and the supervisor decides what happens next. The channel's
-`SessionManager` is that supervisor and calls `settle()`. `team` closes stdin at
-spawn, so the premise never holds, and until 2026-09-12 nothing settled the
-reducer: it stayed in `waiting_for_input` after the child had exited.
+A `result` frame ends a turn, and the reducer asks its owner whether stdin stays
+open (`onResult` returns `TurnEnd`). `team` closes stdin at spawn, so it always
+answers `"stdin-closed"` and the slot moves to `finishing`, which only a terminal
+state may follow. Before `finishing` existed, every `result` moved the reducer to
+`waiting_for_input`, on the premise that stdin was still open — a premise that
+never held for a slot — and until 2026-09-12 nothing settled the reducer after
+that: it stayed in `waiting_for_input` after the child had exited.
`finish()` now settles it to the outcome it just recorded (COMPLETED → `completed`,
EMPTY or FAILED → `failed`, a cancelled slot → `cancelled`, TIMEOUT → `timeout`)
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.md
index ff1d9d24..cda51ae9 100644
--- a/docs/usage/mcp-server.md
+++ b/docs/usage/mcp-server.md
@@ -199,13 +199,16 @@ When a session runs, Claude Code receives `<channel source="claudish">` notifica
|-------|---------|
| `session_started` | Session began. Note the `session_id` for future calls. |
| `tool_executing` | Model is using a tool (Read, Write, Bash, etc.). |
-| `input_required` | Model is waiting for input. Call `send_input` with your answer. |
+| `input_required` | The session finished a turn and waits for `send_input`. Only interactive sessions do this: created without a `prompt`, or after a `send_input`. |
+| `finishing` | The session's last turn ended and claudish closed its input; it is exiting. Nothing to do — `completed` follows. |
| `completed` | Session finished. Call `get_output` for the full response. |
| `failed` | Session exited with an error. Check the notification content for details. |
| `cancelled` | Session was cancelled via `cancel_session`. |
### Workflow example
+One-shot — a `prompt` is given, so the session ends on its own after its answer:
+
```
1. create_session(model: "[email protected]", prompt: "Refactor this module")
→ { session_id: "sess_abc123", status: "starting" }
@@ -213,17 +216,31 @@ When a session runs, Claude Code receives `<channel source="claudish">` notifica
2. <channel event="session_started" session_id="sess_abc123" ...>
<channel event="tool_executing" tool_count="3" ...>
-3. <channel event="input_required" session_id="sess_abc123">
- "Should I keep the old interface for backwards compatibility?"
-
-4. send_input(session_id: "sess_abc123", text: "Yes, keep the old interface")
+3. <channel event="finishing" session_id="sess_abc123">
-5. <channel event="completed" session_id="sess_abc123">
+4. <channel event="completed" session_id="sess_abc123">
-6. get_output(session_id: "sess_abc123")
+5. get_output(session_id: "sess_abc123")
→ { lines: [...], status: "completed" }
```
+Interactive — no `prompt`, so the session waits for input from the start and after every
+turn, until you cancel it or it times out:
+
+```
+1. create_session(model: "[email protected]")
+ → { session_id: "sess_def456", status: "starting" }
+
+2. <channel event="input_required" session_id="sess_def456">
+
+3. send_input(session_id: "sess_def456", text: "Refactor this module")
+
+4. <channel event="tool_executing" ...>
+ <channel event="input_required" session_id="sess_def456">
+
+5. get_output(session_id: "sess_def456"), then send_input again or cancel_session
+```
+
### `create_session`
Spawn an async external model session.
@@ -241,7 +258,7 @@ Spawn an async external model session.
### `send_input`
-Send text to a session's stdin. Use when the session is in `waiting_for_input` state (after an `input_required` channel event).
+Send text to a session's stdin. Use when the session is in `waiting_for_input` state (after an `input_required` channel event). A session in `finishing` has already closed its input and refuses it.
**Parameters:**
- `session_id` (required) - Session ID from `create_session`
@@ -283,6 +300,20 @@ List all active channel sessions.
---
+### Session records on disk
+
+Every `create_session` session keeps its record under `~/.claudish/sessions/<session_id>/`
+(`CLAUDISH_SESSIONS_DIR` overrides the root). Tools that watch sessions from outside the MCP
+server — such as the magus `claudish` plugin's monitor — read these files; they are a stable
+contract.
+
+| File | Written | Contents |
+|------|---------|----------|
+| `waits.jsonl` | one line each time the session starts and stops waiting for `send_input` | `{"wait":"open","since":…,"turns":…}` then `{"wait":"closed","since":…,"at":…,"to":…}`. Interactive sessions only; append-only, so a wait that opened and closed between two reads still shows. Stops at 1 MB |
+| `meta.json` | once, when the session ends | the final `SessionInfo`: status, exit code, turns, tokens, cost |
+
+---
+
## Error Reporting
When a tool call fails (provider errors, model not found, timeouts), the error response includes a hint to use the `report_error` tool. This applies to:
diff --git a/packages/cli/src/channel/channel-wire-format.test.ts b/packages/cli/src/channel/channel-wire-format.test.ts
index 97e551e8..2787f203 100644
--- a/packages/cli/src/channel/channel-wire-format.test.ts
+++ b/packages/cli/src/channel/channel-wire-format.test.ts
@@ -237,7 +237,7 @@ describe("Channel notification wire format", () => {
}
}, 20_000);
- test("SEP-1686 status mapping: 7-value event collapses to 5-value status correctly", async () => {
+ test("SEP-1686 status mapping: 9-value event collapses to 5-value status correctly", async () => {
const captured = await captureSessionFrames({ shimArgs: ["--lines", "3"] });
expect(captured.notifications.length).toBeGreaterThan(0);
@@ -248,9 +248,11 @@ describe("Channel notification wire format", () => {
running: "working",
tool_executing: "working",
waiting_for_input: "input_required",
+ finishing: "working",
completed: "completed",
failed: "failed",
cancelled: "cancelled",
+ timeout: "failed",
};
for (const n of captured.notifications) {
diff --git a/packages/cli/src/channel/session-manager.test.ts b/packages/cli/src/channel/session-manager.test.ts
index 1538644a..c63e0ba8 100644
--- a/packages/cli/src/channel/session-manager.test.ts
+++ b/packages/cli/src/channel/session-manager.test.ts
@@ -142,7 +142,8 @@ describe("SessionManager", () => {
const info = manager.getSession(id);
expect(info.sessionId).toBe(id);
expect(info.model).toBe("test-model");
- expect(["starting", "running"]).toContain(info.status);
+ // Promptless: it waits for its first send_input from the moment it exists.
+ expect(info.status).toBe("waiting_for_input");
expect(info.pid).not.toBeNull();
expect(typeof info.startedAt).toBe("string");
expect(info.completedAt).toBeNull();
@@ -291,11 +292,9 @@ describe("SessionManager", () => {
await waitForCompleted(callbackManager, id);
- expect(events.map(({ event }) => event.type)).toEqual([
- "running",
- "waiting_for_input",
- "completed",
- ]);
+ // A one-shot session's turn end is `finishing`: claudish closed stdin, so
+ // nothing waits for input. It never passes through `waiting_for_input`.
+ expect(events.map(({ event }) => event.type)).toEqual(["running", "finishing", "completed"]);
for (const observed of events) {
expect(observed.sessionId).toBe(id);
expect(observed.event.model).toBe("test-model");
@@ -358,7 +357,8 @@ describe("SessionManager", () => {
claudishFlags: ["--result-then-hang", "--trap-term-exit-zero"],
});
- await waitForStatus(timeoutManager, id, ["running"]);
+ // Promptless, so it waits for its first input from creation.
+ await waitForStatus(timeoutManager, id, ["waiting_for_input"]);
expect(timeoutManager.sendInput(id, "interactive turn")).toBe(true);
await waitForStatus(timeoutManager, id, ["waiting_for_input"]);
@@ -391,7 +391,8 @@ describe("SessionManager", () => {
test("G7: a promptless session reaches a usable state and accepts later input", async () => {
const id = manager.createSession({ model: "test-model", timeoutSeconds: 5 });
- await waitForStatus(manager, id, ["running"], 2000);
+ // Waiting for input from creation: nothing happens until send_input.
+ await waitForStatus(manager, id, ["waiting_for_input"], 2000);
expect(manager.sendInput(id, "first interactive turn")).toBe(true);
await waitUntil(
() =>
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.ts
index cfe143bd..fff85543 100644
--- a/packages/cli/src/channel/session-manager.ts
+++ b/packages/cli/src/channel/session-manager.ts
@@ -49,7 +49,12 @@ import { decodeChunk } from "../stdio-decode.js";
import { STDOUT_TAIL_LIMIT, classifyRunOutput, meaningfulStderr } from "../team-orchestrator.js";
import { readTokenStatsAt } from "../team-stats.js";
import { ScrollbackBuffer } from "./scrollback-buffer.js";
-import { type ResultSummary, StreamJsonReducer, labelForLine } from "./stream-json-reducer.js";
+import {
+ type ResultSummary,
+ StreamJsonReducer,
+ type TurnEnd,
+ labelForLine,
+} from "./stream-json-reducer.js";
import type {
ChannelEvent,
SessionCreateOptions,
@@ -203,6 +208,15 @@ interface SessionEntry {
*/
autoCloseOnResult: boolean;
stdinClosed: boolean;
+ /** `<sessionDir>/waits.jsonl`. See `appendWait`. */
+ waitLogPath: string;
+ /** Bytes already appended to `waits.jsonl`; the log stops at WAIT_LOG_LIMIT. */
+ waitLogBytes: number;
+ /**
+ * The `since` of the wait that is open now, or null. Kept so the `closed`
+ * line repeats its `open` line's key exactly.
+ */
+ waitSince: string | null;
}
const DEFAULT_MAX_SESSIONS = 20;
@@ -255,6 +269,13 @@ const STDERR_SIDE_LIMIT = 32 * 1024;
*/
const EVENT_LOG_LIMIT = 4 * 1024 * 1024;
+/**
+ * Cap on `waits.jsonl`. One line is under 200 bytes, so this is about 6 000
+ * waits — far beyond any real interactive session. Past it, later waits are
+ * not recorded.
+ */
+const WAIT_LOG_LIMIT = 1024 * 1024;
+
/**
* How many semantic frames `get_diagnostics` can hand back, and how much of each.
*
@@ -290,6 +311,7 @@ const KNOWN_STATUSES: readonly SessionStatus[] = [
"running",
"tool_executing",
"waiting_for_input",
+ "finishing",
"completed",
"failed",
"cancelled",
@@ -877,6 +899,9 @@ export class SessionManager {
finalized: false,
autoCloseOnResult: Boolean(opts.prompt),
stdinClosed: false,
+ waitLogPath: join(sessionDir, "waits.jsonl"),
+ waitLogBytes: 0,
+ waitSince: null,
};
entry.reducer = new StreamJsonReducer({
@@ -895,6 +920,10 @@ export class SessionManager {
current.info.status = data.newState;
current.info.elapsedSeconds = this.getElapsed(current.info.startedAt);
+ // Before the notification, so the wait line is on disk by the time
+ // anyone hears of the transition.
+ this.recordWaitTransition(current, data);
+
this.onStateChange?.(sid, {
type: data.newState,
model: current.info.model,
@@ -954,9 +983,7 @@ export class SessionManager {
// The prompt is the opening frame, not a positional argument. stdin stays
// OPEN: that is what makes `send_input` real, and closing it here is what
// used to make a promptless session hang until the timeout.
- if (opts.prompt) {
- this.writeFrame(entry, opts.prompt);
- }
+ this.openFirstTurn(entry, opts.prompt);
proc.on("exit", (code, signal) => this.handleExit(sessionId, code, signal));
@@ -1707,24 +1734,120 @@ export class SessionManager {
}
/**
- * A turn ended. For a one-shot session that is also the end of the session:
- * close stdin, and the child exits 0 on its own (measured — see §3.2 of the
- * design). For an interactive one, stay in `waiting_for_input`.
+ * A turn ended; answer the reducer's question "does stdin stay open?".
+ *
+ * Called BEFORE the reducer changes state, so the answer decides it:
+ *
+ * - one-shot (`autoCloseOnResult`): close stdin now and answer
+ * `"stdin-closed"`. The session moves to `finishing` and the child exits 0
+ * on its own (measured — see §3.2 of the channel design).
+ * - stdin already closed (the child broke the pipe, or exit raced us):
+ * `"stdin-closed"` too — nothing can send it input any more.
+ * - otherwise `"stdin-open"`: an interactive session now waits for
+ * `send_input` in `waiting_for_input`.
+ *
+ * The bookkeeping runs first in every case, so a wait opened by this turn end
+ * logs the turn count that includes it.
*/
- private handleResult(sessionId: string, summary: ResultSummary): void {
+ private handleResult(sessionId: string, summary: ResultSummary): TurnEnd {
const entry = this.sessions.get(sessionId);
- if (!entry) return;
+ // No entry means no stdin held open for anyone, so nothing can wait.
+ if (!entry) return "stdin-closed";
entry.info.turnsCompleted = summary.numTurns || entry.info.turnsCompleted;
entry.info.terminalReason = summary.terminalReason;
- if (!entry.autoCloseOnResult || entry.stdinClosed) return;
+ if (entry.stdinClosed) return "stdin-closed";
+ if (!entry.autoCloseOnResult) return "stdin-open";
entry.stdinClosed = true;
try {
entry.process.stdin?.end();
} catch {
/* the child may already be gone */
}
+ return "stdin-closed";
+ }
+
+ /**
+ * Hand the child its opening turn, or record that the session waits for one.
+ *
+ * A promptless session waits for its first `send_input` from the moment it
+ * exists, and says so (`starting → waiting_for_input`). Called after
+ * `sessions.set`, so the reducer callback finds the entry and the wait is
+ * logged.
+ */
+ private openFirstTurn(entry: SessionEntry, prompt: string | undefined): void {
+ if (prompt) {
+ this.writeFrame(entry, prompt);
+ return;
+ }
+ entry.reducer.awaitInput();
+ }
+
+ /**
+ * The wait log's two hooks: one `open` line on every transition INTO
+ * `waiting_for_input`, one `closed` line on every transition OUT of it,
+ * including into a terminal state.
+ *
+ * Runs in the same callback that changes the state, so a wait cannot happen
+ * unrecorded while this process lives. `settle()` goes through `transition()`,
+ * so cancel and timeout close an open wait, and `finalize` settles before
+ * `writeArtifacts` — no `meta.json` ever sits beside an unclosed wait written
+ * by a live process. Self-transitions never reach the callback unless
+ * `repeat`, and no `repeat` caller targets `waiting_for_input`.
+ */
+ private recordWaitTransition(
+ entry: SessionEntry,
+ data: { previousState: SessionStatus; newState: SessionStatus; timestamp: string }
+ ): void {
+ const wasWaiting = data.previousState === "waiting_for_input";
+ const isWaiting = data.newState === "waiting_for_input";
+ if (!wasWaiting && isWaiting) {
+ entry.waitSince = data.timestamp;
+ this.appendWait(entry, {
+ wait: "open",
+ since: data.timestamp,
+ turns: entry.info.turnsCompleted,
+ });
+ return;
+ }
+ if (wasWaiting && !isWaiting) {
+ this.appendWait(entry, {
+ wait: "closed",
+ since: entry.waitSince ?? data.timestamp,
+ at: data.timestamp,
+ to: data.newState,
+ });
+ entry.waitSince = null;
+ }
+ }
+
+ /**
+ * Append one line to `waits.jsonl`.
+ *
+ * Durable on purpose: a wait can open and close between two reads of any
+ * observer, and an append-only line survives that where a marker file that
+ * exists only during the wait would not. One `appendFileSync` of under 200
+ * bytes per line. A write failure is reported on stderr and changes nothing
+ * else — only that line is lost. The log stops at WAIT_LOG_LIMIT.
+ */
+ private appendWait(
+ entry: SessionEntry,
+ line:
+ | { wait: "open"; since: string; turns: number }
+ | { wait: "closed"; since: string; at: string; to: SessionStatus }
+ ): void {
+ if (entry.waitLogBytes >= WAIT_LOG_LIMIT) return;
+ const payload = `${JSON.stringify(line)}\n`;
+ entry.waitLogBytes += Buffer.byteLength(payload, "utf-8");
+ try {
+ appendFileSync(entry.waitLogPath, payload);
+ } catch (err) {
+ process.stderr.write(
+ `[claudish] session ${entry.info.sessionId}: could not append to waits.jsonl: ` +
+ `${err instanceof Error ? err.message : String(err)}\n`
+ );
+ }
}
/**
diff --git a/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts b/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts
index 9d05550e..de8eb63a 100644
--- a/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts
+++ b/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts
@@ -18,6 +18,7 @@ function feedLine(line: string, keepUnrecognizedJson?: true): string {
sessionId: "unrecognized-json-test",
stallSeconds: 0,
callback: () => {},
+ onResult: () => "stdin-closed",
...(keepUnrecognizedJson === true ? { keepUnrecognizedJson } : {}),
});
diff --git a/packages/cli/src/channel/stream-json-reducer.test.ts b/packages/cli/src/channel/stream-json-reducer.test.ts
index 93e31c87..8169e1f8 100644
--- a/packages/cli/src/channel/stream-json-reducer.test.ts
+++ b/packages/cli/src/channel/stream-json-reducer.test.ts
@@ -30,8 +30,11 @@ describe("StreamJsonReducer", () => {
stallSeconds: 0,
callback: (_sessionId, event) => events.push(event),
onSemanticLine: (semanticLine) => semanticLines.push(semanticLine),
+ // The captured stream is a one-shot run: its owner closes stdin at the
+ // result, so the turn end moves to `finishing`, never `waiting_for_input`.
onResult: (result) => {
summary = result;
+ return "stdin-closed";
},
};
const reducer = new StreamJsonReducer(options);
@@ -43,9 +46,9 @@ describe("StreamJsonReducer", () => {
prose += reducer.feed(line(capturedSuccessResult(CAPTURED_ASSISTANT_PROSE)));
prose += reducer.end();
- expect(events.map((event) => event.newState)).toEqual(["running", "waiting_for_input"]);
+ expect(events.map((event) => event.newState)).toEqual(["running", "finishing"]);
expect(prose).toBe(`${CAPTURED_ASSISTANT_PROSE}\n`);
- expect(reducer.state).toBe("waiting_for_input");
+ expect(reducer.state).toBe("finishing");
expect(reducer.sawResult).toBe(true);
expect(reducer.turns).toBe(1);
expect(reducer.tokens).toBeGreaterThan(0);
@@ -61,6 +64,7 @@ describe("StreamJsonReducer", () => {
sessionId: "delta-regression",
stallSeconds: 0,
callback: () => {},
+ onResult: () => "stdin-closed",
});
const appendRecovered = (chunk: string): void => {
const recovered = reducer.feed(chunk);
diff --git a/packages/cli/src/channel/stream-json-reducer.ts b/packages/cli/src/channel/stream-json-reducer.ts
index 59b7bb30..ca837231 100644
--- a/packages/cli/src/channel/stream-json-reducer.ts
+++ b/packages/cli/src/channel/stream-json-reducer.ts
@@ -98,10 +98,14 @@ const TERMINAL_STATES: readonly ChannelEventType[] = [
* ended, nothing may revise it.
*/
const LEGAL_TRANSITIONS: Record<ChannelEventType, readonly ChannelEventType[]> = {
- starting: ["running", "tool_executing", "waiting_for_input", ...TERMINAL_STATES],
- running: ["tool_executing", "waiting_for_input", ...TERMINAL_STATES],
- tool_executing: ["running", "waiting_for_input", ...TERMINAL_STATES],
+ starting: ["running", "tool_executing", "waiting_for_input", "finishing", ...TERMINAL_STATES],
+ running: ["tool_executing", "waiting_for_input", "finishing", ...TERMINAL_STATES],
+ tool_executing: ["running", "waiting_for_input", "finishing", ...TERMINAL_STATES],
waiting_for_input: ["running", "tool_executing", ...TERMINAL_STATES],
+ // The final turn ended and stdin is closed: only the exit verdict may follow.
+ // A frame arriving here is outside the stream-json contract, so it is refused
+ // and recorded as an anomaly rather than moving the session backwards.
+ finishing: [...TERMINAL_STATES],
completed: [],
failed: [],
cancelled: [],
@@ -120,7 +124,8 @@ const TOOL_BATCH_MS = 500;
* Only `starting` and `running` are watched. `tool_executing` is deliberately
* exempt: a 10-minute `Bash` produces no frames at all and is not stalled, it is
* working. `waiting_for_input` is exempt for the same reason — silence there is
- * the contract.
+ * the contract. `finishing` is exempt too: the child is exiting, and the session
+ * timeout bounds it.
*/
const DEFAULT_STALL_SECONDS = 120;
@@ -146,6 +151,18 @@ export interface ResultSummary {
permissionDenials: number;
}
+/**
+ * The owner's answer, at a turn end, to "does stdin stay open?".
+ *
+ * - `"stdin-open"` → the session waits for `send_input`: `waiting_for_input`.
+ * - `"stdin-closed"` → that was the final turn and the child is exiting:
+ * `finishing`, then a terminal state.
+ *
+ * The reducer cannot see stdin, so it asks. Deciding it here instead is what
+ * used to put every one-shot session through a false `waiting_for_input`.
+ */
+export type TurnEnd = "stdin-open" | "stdin-closed";
+
export interface StreamJsonReducerOptions {
sessionId: string;
callback: ReducerCallback;
@@ -169,11 +186,17 @@ export interface StreamJsonReducerOptions {
*/
keepUnrecognizedJson?: boolean;
/**
- * Fired once per terminal `result` frame. SessionManager uses the FIRST one to
- * close stdin on a one-shot session, which is what lets it reach `completed`
- * instead of idling until the timeout.
+ * Fired once per terminal `result` frame, BEFORE the state changes, and its
+ * answer decides the state the turn end moves to (see `TurnEnd`).
+ * SessionManager closes stdin on a one-shot session's first `result` and
+ * answers `"stdin-closed"`, which is what lets the session reach `completed`
+ * instead of idling until the timeout; `team` closes stdin at spawn and always
+ * answers `"stdin-closed"`.
+ *
+ * Required, so the compiler names every construction site: a default would
+ * silently pick one of the two states for a caller that never decided.
*/
- onResult?: (summary: ResultSummary) => void;
+ onResult: (summary: ResultSummary) => TurnEnd;
/**
* Every line except the delta firehose, verbatim. Persisted to `events.jsonl`
* so a post-mortem has the structured record the prose cannot carry.
@@ -390,6 +413,10 @@ export class StreamJsonReducer {
* `_turns`, the token counters and `_terminalReason` are deliberately NOT
* reset — they are cumulative session accounting and the last observed
* reason, not completion evidence.
+ *
+ * A session that was `waiting_for_input` is no longer waiting once a turn is
+ * handed over, so this moves it to `running` — the only transition it makes.
+ * From any other state it only resets the flags above.
*/
beginTurn(): void {
if (this.disposed) return;
@@ -399,6 +426,21 @@ export class StreamJsonReducer {
// A turn was just sent, so the stream is legitimately busy again.
this.lastFrameAt = Date.now();
this.stallAnnounced = false;
+ if (this._state === "waiting_for_input") {
+ this.transition("running", { content: "input received" });
+ }
+ }
+
+ /**
+ * A promptless session waits for its first `send_input` from the moment it
+ * exists: `starting → waiting_for_input`. A no-op from any other state.
+ *
+ * Without it such a session read `starting`, then `running` on the child's
+ * `system:init`, while nothing would happen until the caller sent input.
+ */
+ awaitInput(): void {
+ if (this.disposed || this._state !== "starting") return;
+ this.transition("waiting_for_input", { content: "waiting for the first input" });
}
/**
@@ -485,7 +527,10 @@ export class StreamJsonReducer {
// metric ("93 tool calls") the silent-success incident was measured by.
this._toolUseCount += tools.length;
this.batchToolUse(tools[0], tools.length);
- } else if (this._state === "starting") {
+ } else if (this._state === "starting" || this._state === "finishing") {
+ // From `finishing` the transition table refuses this and records the
+ // anomaly: a frame after the final `result`, with stdin closed, is
+ // outside the stream-json contract and must not revive the session.
this.transition("running", { content: "assistant turn started" });
}
return;
@@ -494,8 +539,13 @@ export class StreamJsonReducer {
case "user":
// A `tool_result` closes a tool round trip; a replayed user message
// (`--replay-user-messages`) is the child acking our input. Either way
- // the model is the thing that runs next.
- if (this._state === "tool_executing" || this._state === "waiting_for_input") {
+ // the model is the thing that runs next. From `finishing` the table
+ // refuses it and records the anomaly, as for `assistant` above.
+ if (
+ this._state === "tool_executing" ||
+ this._state === "waiting_for_input" ||
+ this._state === "finishing"
+ ) {
this.transition("running");
} else if (this._state === "starting") {
this.transition("running");
@@ -520,6 +570,9 @@ export class StreamJsonReducer {
if (subtype === "init") {
this._claudeSessionId = asString(frame.session_id);
this._cwd = asString(frame.cwd);
+ // A promptless session announces itself with `init` while it still waits
+ // for its first input; that is not a turn starting, so the wait stands.
+ if (this._state === "waiting_for_input") return;
this.transition("running", { content: "session initialised" });
return;
}
@@ -566,17 +619,16 @@ export class StreamJsonReducer {
: 0,
};
- // A turn boundary with stdin still open IS `waiting_for_input` — a fact, not
- // the 2-second quiet-period guess it replaces. Whether the session stays
- // there is SessionManager's call: for a one-shot it closes stdin here and
- // the child walks to `completed` on its own.
- this.transition("waiting_for_input", {
- content: summary.isError
- ? `turn ended with an error (${summary.terminalReason ?? summary.subtype ?? "unknown"})`
- : `turn ${summary.numTurns} complete`,
- });
-
- this.opts.onResult?.(summary);
+ // The owner decides FIRST whether stdin stays open, and the state follows
+ // its answer. A turn boundary with stdin still open IS `waiting_for_input`;
+ // one where the owner just closed stdin is `finishing`, and the child walks
+ // to a terminal state on its own. Transitioning before asking is what put
+ // every one-shot session through a `waiting_for_input` nothing waited in.
+ const turnEnd = this.opts.onResult(summary);
+ const content = summary.isError
+ ? `turn ended with an error (${summary.terminalReason ?? summary.subtype ?? "unknown"})`
+ : `turn ${summary.numTurns} complete`;
+ this.transition(turnEnd === "stdin-closed" ? "finishing" : "waiting_for_input", { content });
}
/** Every `tool_use` block in an assistant message, in order. */
diff --git a/packages/cli/src/channel/types.ts b/packages/cli/src/channel/types.ts
index a8e7ec54..07e8d7ad 100644
--- a/packages/cli/src/channel/types.ts
+++ b/packages/cli/src/channel/types.ts
@@ -5,6 +5,13 @@ export type SessionStatus =
| "running"
| "tool_executing"
| "waiting_for_input"
+ /**
+ * The session's FINAL turn ended and claudish closed the child's stdin; the
+ * child has not exited yet. Non-terminal, and nothing waits for input: only
+ * a terminal state follows. Distinct from `waiting_for_input`, which holds
+ * only while stdin stays open and the session waits for `send_input`.
+ */
+ | "finishing"
| "completed"
| "failed"
| "cancelled"
@@ -114,10 +121,12 @@ export interface SessionCreateOptions {
* The first turn. Its presence also selects the session's SHAPE:
*
* - given → one-shot. Sent as the opening `user` frame; stdin is closed as
- * soon as the child reports a terminal `result`, so the session ends at
- * `completed` instead of idling to the timeout.
- * - absent → interactive. Stdin stays open indefinitely and the session sits
- * in `waiting_for_input` between turns, waiting for `send_input`.
+ * soon as the child reports a terminal `result`, so the session passes
+ * through `finishing` and ends at `completed` instead of idling to the
+ * timeout. It never enters `waiting_for_input`.
+ * - absent → interactive. Stdin stays open indefinitely. The session is in
+ * `waiting_for_input` from creation until the first `send_input`, and again
+ * after every turn the child finishes.
*
* A `send_input` call converts a one-shot session to interactive — the caller
* has taken over driving it, so we stop deciding when it is finished.
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index 7a2abadf..60f6023e 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -104,7 +104,8 @@ When channel mode is active, you receive <channel source="claudish" ...> notific
- session_started: A session began producing output. Note the session_id for future calls.
- tool_executing: The model is using a tool (Read, Write, Bash, etc.). May include tool_count for batched events.
-- input_required: The model is asking a question and waiting for input. Call send_input with the session_id and your answer.
+- input_required: The session finished a turn and waits for send_input. Only interactive sessions do this (no prompt, or after a send_input). Call send_input with the session_id and your answer.
+- finishing: The session's last turn ended and claudish closed its input; it is exiting. Nothing to do; completed follows.
- completed: The session finished successfully. Call get_output to retrieve the full output.
- failed: The session exited with an error. Call get_diagnostics for the cause.
- timeout: The session hit its timeout_seconds and was killed. Call get_diagnostics to see how far it got.
@@ -114,7 +115,7 @@ When channel mode is active, you receive <channel source="claudish" ...> notific
1. Call create_session with a model and prompt to start an async session.
2. Watch for <channel> notifications — they arrive automatically.
-3. On input_required: call send_input with the answer.
+3. On input_required (interactive sessions only: no prompt, or after a send_input): call send_input with the answer.
4. On completed: call get_output to get the full response.
5. On failed or timeout — or on a completed session whose output is empty or
surprising — call get_diagnostics. It returns the child's stderr, the upstream
@@ -1959,7 +1960,7 @@ function resolveToolGroups(mode: string): Set<ToolGroup> {
}
// ─── SEP-1686 status mapping ─────────────────────────────────────────────────
-// Maps Claudish's 7-value `event` enum to SEP-1686's 5-value `TaskStatus`.
+// Maps Claudish's 9-value `event` enum to SEP-1686's 5-value `TaskStatus`.
// See: https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1732
// Migration plan: ai-docs/sessions/.../sep-1686-migration-schema.md
type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled";
@@ -1969,6 +1970,10 @@ const EVENT_TO_TASK_STATUS = new Map<string, TaskStatus>([
["running", "working"],
["tool_executing", "working"],
["waiting_for_input", "input_required"],
+ // Explicit although the fall-through below gives the same value: a missing
+ // key is how the timeout projection hid (see the `timeout` entry). The final
+ // turn ended and the child is exiting; nothing is asked of the caller.
+ ["finishing", "working"],
["completed", "completed"],
["failed", "failed"],
["cancelled", "cancelled"],
diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.ts
index d6fc6ed7..e59adee4 100644
--- a/packages/cli/src/team-orchestrator.ts
+++ b/packages/cli/src/team-orchestrator.ts
@@ -288,7 +288,9 @@ export function teamSlotIdleSeconds(teamSessionId: string): Record<string, numbe
/**
* What each still-running slot is doing, from the stream-json reducer:
- * `running`, `tool_executing` or `waiting_for_input`. Null for a run that is not
+ * `starting`, `running`, `tool_executing` or `finishing` (its `result` arrived
+ * and it is exiting). A slot never reports `waiting_for_input`: its stdin is
+ * closed at spawn, so nothing can wait for input. Null for a run that is not
* live; a slot is absent once it has exited (its outcome is `state` in
* `status.json`), and under `"print"` capture, which emits no frames to read.
*
@@ -999,7 +1001,7 @@ export async function startModels(
getIdleMs: () => number;
/**
* What this slot is doing right now, from the shared stream-json reducer:
- * `running`, `tool_executing`, `waiting_for_input`, a terminal state, or
+ * `starting`, `running`, `tool_executing`, `finishing`, a terminal state, or
* null under `"print"` capture, which produces no frames to read.
*
* This is the other half of the idle number. 90 seconds of silence means
@@ -1227,6 +1229,10 @@ export async function startModels(
// already has its own status file and progress ticker; routing reducer
// transitions into a second notification path would duplicate it.
callback: () => {},
+ // stdin is written and ended right after spawn (below), so a `result`
+ // is always the end of the slot's work: `finishing` until it exits,
+ // never `waiting_for_input`.
+ onResult: () => "stdin-closed",
});
reducer = slotReducer;
@@ -1309,8 +1315,8 @@ export async function startModels(
* Settle the reducer to the outcome just recorded, then release it.
*
* Without the settle the reducer stays wherever the stream left it — a
- * `result` frame parks it in `waiting_for_input` — so an exited slot read
- * as idle rather than done. Runs only once `state` is final, which is why
+ * `result` frame parks it in `finishing` — so an exited slot read as
+ * still exiting rather than done. Runs only once `state` is final, which is why
* the dispose lives here and not in `finalizeCapture`. No-op under
* `"print"`, which has no reducer.
*/