Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
refactor(channel): delete the frame emitter and the trace diagnostics
Jack Rudenko7751901c1e1e
diff --git a/packages/cli/src/channel/diagnostics.ts b/packages/cli/src/channel/diagnostics.tsdeleted file mode 100644index 1da7209a..00000000--- a/packages/cli/src/channel/diagnostics.ts+++ /dev/null@@ -1,125 +0,0 @@-// ─── Channel Diagnostics ──────────────────────────────────────────────────────-//-// Optional instrumentation for the channel notification pipeline. Activated by-// setting CLAUDISH_CHANNEL_TRACE=1 in the environment before starting the MCP-// server.-//-// Three checkpoints are exposed so a debugger can pinpoint which layer fails:-// 1. wrapStateChange() — wraps SessionManager.onStateChange. Logs every-// callback invocation, captures rejections from server.notification(),-// and re-throws nothing — instrumentation must never break production.-// 2. installWireTap() — wraps process.stdout.write to mirror outbound-// notifications/claude/channel JSON-RPC frames to stderr. Confirms the-// wire-level write actually happens.-// 3. traceEnabled() — convenience predicate other modules can branch on.-//-// All output is single-line "[channel-trace] ..." records on stderr so they-// can be greppable from MCP server stderr logs.--import { appendFileSync } from "node:fs";-import type { ChannelEvent } from "./types.js";--const TRACE_ENV = "CLAUDISH_CHANNEL_TRACE";-const TRACE_FILE_ENV = "CLAUDISH_CHANNEL_TRACE_FILE";--export function traceEnabled(): boolean {- return process.env[TRACE_ENV] === "1";-}--function emit(line: string): void {- const formatted = `[channel-trace] ${line}\n`;- process.stderr.write(formatted);- // Optional file mirror — useful when the MCP server is spawned by a host- // (like Claude Code) that captures stderr internally and we need to observe- // trace output from outside the host process.- const filePath = process.env[TRACE_FILE_ENV];- if (filePath) {- try {- appendFileSync(filePath, formatted);- } catch {- // file write failure must never break the server- }- }-}--type StateChangeFn = (sessionId: string, event: ChannelEvent) => void;--/**- * Wrap a SessionManager onStateChange callback so each invocation is logged.- * Returns the original callback unchanged when tracing is off.- *- * Logs:- * - "fired sid=… type=… model=… elapsed=…s" on entry- * - "callback returned sid=… type=…" on success- * - "callback THREW sid=… type=… err=…" on synchronous error (re-thrown)- */-export function wrapStateChange(fn: StateChangeFn): StateChangeFn {- if (!traceEnabled()) return fn;- return (sessionId, event) => {- emit(- `fired sid=${sessionId} type=${event.type} model=${event.model} elapsed=${event.elapsedSeconds}s`- );- try {- fn(sessionId, event);- emit(`callback returned sid=${sessionId} type=${event.type}`);- } catch (err) {- emit(- `callback THREW sid=${sessionId} type=${event.type} err=${(err as Error)?.message ?? err}`- );- throw err;- }- };-}--/**- * Capture rejections from server.notification()'s returned Promise so they're- * visible on stderr. The MCP SDK's notification() returns a Promise that- * nothing in mcp-server.ts awaits; if it rejects, the error would otherwise- * be silently swallowed.- *- * Pass the value returned by server.notification() — if it's a Promise we- * attach a catch handler; otherwise we no-op.- */-export function watchNotificationResult(- result: unknown,- context: { sessionId: string; eventType: string }-): void {- if (!traceEnabled()) return;- if (result && typeof (result as Promise<unknown>).then === "function") {- (result as Promise<unknown>).catch((err) => {- emit(- `notification REJECTED sid=${context.sessionId} type=${context.eventType} err=${err?.message ?? err}`- );- });- }-}--/**- * Install a stdout.write wrapper that mirrors outbound JSON-RPC frames- * containing `notifications/claude/channel` to stderr. Idempotent — calling- * twice still installs only one wrapper.- *- * No-op when tracing is off.- */-let wireTapInstalled = false;-export function installWireTap(): void {- if (!traceEnabled()) return;- if (wireTapInstalled) return;- wireTapInstalled = true;-- const originalWrite = process.stdout.write.bind(process.stdout);- process.stdout.write = ((chunk: string | Uint8Array, ...rest: unknown[]): boolean => {- try {- const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf-8");- if (text.includes('"notifications/claude/channel"')) {- emit(`WIRE-OUT ${text.trim()}`);- }- } catch {- // never let logging break the real write- }- // @ts-expect-error pass-through to original signature- return originalWrite(chunk, ...rest);- }) as typeof process.stdout.write;-- emit("wire tap installed");-}diff --git a/packages/cli/src/channel/index.ts b/packages/cli/src/channel/index.tsindex 3b1568c4..2ec76692 100644--- a/packages/cli/src/channel/index.ts+++ b/packages/cli/src/channel/index.ts@@ -17,6 +17,5 @@ export type {SessionInfo,SessionCreateOptions,SessionManagerOptions,- ChannelEvent,ChannelEventType,} from "./types.js";diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.tsindex 5cab980d..0455f403 100644--- a/packages/cli/src/channel/session-manager.ts+++ b/packages/cli/src/channel/session-manager.ts@@ -76,7 +76,6 @@ import { sessionsDirFrom } from "./home-dir.js";import { hostPidFrom } from "./parent-session.js";import { ScrollbackBuffer } from "./scrollback-buffer.js";import type {- ChannelEvent,ChannelEventType,SessionCreateOptions,SessionInfo,@@ -220,19 +219,9 @@ interface SessionEntry {/** The terminal transition was handled (records written). */ended: boolean;evictHandle: ReturnType<typeof setTimeout> | null;- /** The last channel event emitted; STARTING is the initial state, never a frame. */- lastEvent: ChannelEventType;- lastFrameTool: string | null;- lastFrameToolCount: number;- lastToolFrameAt: number;lastLoggedTool: string | null;assistantIdsLogged: number;anomaliesLogged: Set<string>;- sendRejectedSeen: number;- /** Optional frame meta for the next frame (`prompt_not_read`, `send_rejected`). */- pendingMeta: Record<string, string>;- /** The question or permission text of the current block, for the frame content. */- blockText: string | null;}const DEFAULT_MAX_SESSIONS = 20;@@ -428,15 +417,6 @@ function writeJsonAtomic(path: string, value: unknown): void {renameSync(tmp, path);}-/** The count of one anomaly key in a snapshot's `anomalies` (`key` or `key ×n`). */-function anomalyCount(anomalies: readonly string[], key: string): number {- for (const a of anomalies) {- if (a === key) return 1;- if (a.startsWith(`${key} ×`)) return Number(a.slice(key.length + 2)) || 1;- }- return 0;-}-/** An anomaly entry without its `×n` count suffix. */function anomalyKey(a: string): string {const at = a.lastIndexOf(" ×");@@ -643,7 +623,6 @@ export class SessionManager {private scrollbackCapacity: number;private sessionsDir: string;private terminalRetentionMs: number;- private onStateChange?: (sessionId: string, event: ChannelEvent) => void;private readonly parentEnv: Record<string, string | undefined>;private readonly paneTimings: SessionManagerOptions["paneTimings"];/** createSession calls past their checks whose entry is not in the map yet. */@@ -672,7 +651,6 @@ export class SessionManager {// `$HOME` before `os.homedir()`, by the rule the plugin monitor shares —// see home-dir.ts. Diverging here makes every run invisible to it.this.sessionsDir = options?.sessionsDir ?? sessionsDirFrom(process.env);- this.onStateChange = options?.onStateChange;this.parentEnv = options?.parentEnv ?? process.env;this.paneTimings = options?.paneTimings;}@@ -957,16 +935,9 @@ export class SessionManager {waitSince: null,ended: false,evictHandle: null,- lastEvent: "starting",- lastFrameTool: null,- lastFrameToolCount: 0,- lastToolFrameAt: 0,lastLoggedTool: null,assistantIdsLogged: 0,anomaliesLogged: new Set(),- sendRejectedSeen: 0,- pendingMeta: {},- blockText: null,};}@@ -1026,7 +997,6 @@ export class SessionManager {info.elapsedSeconds = elapsedSecondsBetween(info.startedAt, Date.parse(at));this.appendEvent(entry, { type: "state", from: "STARTING", to: "FAILED", at });this.endRecords(entry, null);- this.emitFrame(entry, { state: "FAILED", activity: null, toolCalls: 0 });}// ─── Pane policy (D8) ──────────────────────────────────────────────────@@ -1053,10 +1023,9 @@ export class SessionManager {const v = classifyRunOutput({ answer: turn.answer, apiError: turn.apiError });return { state: "FAILED", reason: "api_error", detail: v?.detail ?? "API error" };}- // An interactive turn whose task file was not fully read continues; the caller is- // told on the next frame (r2, X-M4).+ // An interactive turn whose task file was not fully read continues; the anomaly is+ // in the session's event log (r2, X-M4).if (turn.delivery.complete === false) {- entry.pendingMeta.prompt_not_read = "true";this.appendEvent(entry, {type: "anomaly",key: "prompt_not_read",@@ -1069,15 +1038,14 @@ export class SessionManager {return "continue";}- /** A question or a permission dialog waits for `send_input` (the channel can answer). */- private onBlocked(entry: SessionEntry, b: PaneBlock): "wait" {- entry.blockText = b.text;+ /** A question or a permission dialog waits for `send_input` (the caller can answer). */+ private onBlocked(_entry: SessionEntry, _b: PaneBlock): "wait" {return "wait";}// ─── Pane callbacks ────────────────────────────────────────────────────- /** `onTransition`: every wire-state change, synchronously, before any frame. */+ /** `onTransition`: every wire-state change, synchronously. */private onPaneTransition(entry: SessionEntry,t: { from: SlotState; to: SlotState; at: string; snap: PaneSnapshot }@@ -1085,13 +1053,10 @@ export class SessionManager {if (entry.ended) return;const { snap } = t;this.applySnapshot(entry, snap);- // Before the frame, so the wait line is on disk by the time anyone hears of it.this.recordWaitTransition(entry, t.from, t.to, t.at, snap);this.appendEvent(entry, { type: "state", from: t.from, to: t.to, at: t.at });this.logPaneFacts(entry, snap);- if (!isWaiting(t.to)) entry.blockText = null;if (isTerminalState(t.to)) this.onTerminal(entry, snap);- this.emitFrame(entry, snap);}/** `onChange` (coalesced): activity and accounting changes within a state. */@@ -1099,7 +1064,6 @@ export class SessionManager {if (entry.ended) return;this.applySnapshot(entry, snap);this.logPaneFacts(entry, snap);- this.emitFrame(entry, snap);}/** The terminal transition: answer, records and eviction, before the reap starts. */@@ -1215,80 +1179,6 @@ export class SessionManager {entry.anomaliesLogged.add(key);this.appendEvent(entry, { type: "anomaly", key, at });}- const rejected = anomalyCount(snap.anomalies, "send_not_accepted");- if (rejected > entry.sendRejectedSeen) {- entry.sendRejectedSeen = rejected;- entry.pendingMeta.send_rejected = "true";- }- }-- /**- * One channel frame when the derived event changes, plus a coalesced `tool_executing`- * repeat (≤ 1 frame/s) when the tool or the tool count changes.- */- private emitFrame(- entry: SessionEntry,- snap: Pick<PaneSnapshot, "state" | "activity" | "toolCalls">- ): void {- const { event, tool } = channelEventFor(snap);- const now = Date.now();- const changed = event !== entry.lastEvent;- const toolRepeat =- !changed &&- event === "tool_executing" &&- (tool !== entry.lastFrameTool || snap.toolCalls !== entry.lastFrameToolCount) &&- now - entry.lastToolFrameAt >= 1000;- if (!changed && !toolRepeat) return;- entry.lastEvent = event;- if (event === "tool_executing") {- entry.lastFrameTool = tool;- entry.lastFrameToolCount = snap.toolCalls;- entry.lastToolFrameAt = now;- }- const extraMeta: Record<string, string> = {- ...(tool ? { tool, tool_count: String(snap.toolCalls) } : {}),- ...(snap.activity ? { activity: snap.activity } : {}),- ...entry.pendingMeta,- };- entry.pendingMeta = {};- try {- this.onStateChange?.(entry.info.sessionId, {- type: event,- model: entry.info.model,- content: this.frameContent(entry, event, tool),- elapsedSeconds: entry.info.elapsedSeconds,- createdAt: entry.info.startedAt,- extraMeta,- });- } catch {- // a notification consumer must never break the session- }- }-- private frameContent(entry: SessionEntry, event: ChannelEventType, tool: string | null): string {- const info = entry.info;- switch (event) {- case "running":- return "The turn is running.";- case "tool_executing":- return `Using ${tool}.`;- case "waiting_for_input":- return entry.blockText- ? `The model asked a question; send_input declines it and becomes the next prompt.\n${entry.blockText}`- : "The turn finished; waiting for send_input.";- case "awaiting_permission":- return `A permission dialog is open for ${info.activity ?? "a tool"}; send_input declines it and becomes the next prompt.${entry.blockText ? `\n${entry.blockText}` : ""}`;- case "completed":- return `Session completed (${info.turnsCompleted} turn(s)). Call get_output for the answer.`;- case "cancelled":- return "Session cancelled.";- case "timeout":- return `Timeout after ${info.timeoutSeconds}s; the pane was closed.`;- case "failed":- return `${info.state} ${info.reason ?? ""}${info.detail ? `: ${info.detail}` : ""}`.trim();- default:- return "";- }}// ─── Public verbs ──────────────────────────────────────────────────────diff --git a/packages/cli/src/channel/types.ts b/packages/cli/src/channel/types.tsindex 5444cc71..71dc4079 100644--- a/packages/cli/src/channel/types.ts+++ b/packages/cli/src/channel/types.ts@@ -163,24 +163,9 @@ export interface SessionCreateOptions {parentEnv?: Record<string, string | undefined>;}-export interface ChannelEvent {- type: ChannelEventType;- model: string;- content: string;- elapsedSeconds: number;- /**- * ISO-8601 timestamp of session creation. Populated by SessionManager from- * `entry.info.startedAt`. Used by the bridge to populate SEP-1686-shaped- * `meta.created_at` for forward-compat with notifications/tasks/status.- */- createdAt: string;- extraMeta?: Record<string, string>;-}-export interface SessionManagerOptions {maxSessions?: number;scrollbackCapacity?: number;- onStateChange?: (sessionId: string, event: ChannelEvent) => void;/** Artifact root override. Defaults to CLAUDISH_SESSIONS_DIR, then ~/.claudish/sessions. */sessionsDir?: string;/**