import { randomUUID } from 'node:crypto'; import { createServer, type Server, type Socket } from 'node:net'; import { CLAUDE_CHANNEL_IPC_SCHEMA, CLAUDE_CHANNEL_MAX_FRAME_CHARACTERS, CLAWCLAW_CHANNEL_EVENTS_SCHEMA, createClaudeChannelSocketPath, publishClaudeChannelEndpoint, type PublishedClaudeChannelEndpoint, } from './claude-channel-ipc.js'; const MAX_ACCEPTED_DELIVERIES = 256; export interface ClaudeChannelIpcServerOptions { deliver(payload: Record, meta: Record): Promise; diagnostic?: (name: string, attributes?: Record) => void; } export interface ClaudeChannelIpcServerStatus { listening: boolean; owner_connected: boolean; owner_pid: number | null; in_flight_delivery_id: string | null; accepted_delivery_count: number; } interface ConnectionState { socket: Socket; buffer: string; authenticated: boolean; connectionId?: string; ownerPid?: number; inFlightDeliveryId?: string; } interface AcceptedDelivery { acceptedAt: string; receiptId: string; } function objectFrame(value: unknown): Record | null { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : null; } function safeText(value: unknown, maxLength = 512): string | undefined { return typeof value === 'string' && value.length > 0 && value.length <= maxLength ? value : undefined; } /** Receives Owner-pushed Mailbox batches and writes them into Claude's MCP transport. */ export class ClaudeChannelIpcServer { private readonly deliver: ClaudeChannelIpcServerOptions['deliver']; private readonly diagnostic?: ClaudeChannelIpcServerOptions['diagnostic']; private server?: Server; private endpoint?: PublishedClaudeChannelEndpoint; private active?: ConnectionState; private readonly connections = new Set(); private readonly accepted = new Map(); private readonly accepting = new Map>(); private closing = false; constructor(options: ClaudeChannelIpcServerOptions) { this.deliver = options.deliver; this.diagnostic = options.diagnostic; } async start(): Promise { if (this.server) return; this.closing = false; const socketPath = createClaudeChannelSocketPath(); const server = createServer((socket) => this.onConnection(socket)); this.server = server; try { await new Promise((resolve, reject) => { server.once('error', reject); server.listen(socketPath, () => { server.off('error', reject); resolve(); }); }); this.endpoint = publishClaudeChannelEndpoint(socketPath); } catch (error) { this.server = undefined; if (server.listening) { await new Promise((resolve) => server.close(() => resolve())); } throw error; } } status(): ClaudeChannelIpcServerStatus { return { listening: !!this.server?.listening, owner_connected: !!this.active?.authenticated, owner_pid: this.active?.ownerPid ?? null, in_flight_delivery_id: this.active?.inFlightDeliveryId ?? null, accepted_delivery_count: this.accepted.size, }; } async close(): Promise { if (this.closing) return; this.closing = true; for (const connection of this.connections) connection.socket.destroy(); this.connections.clear(); this.active = undefined; const server = this.server; this.server = undefined; if (server) { await new Promise((resolve) => server.close(() => resolve())); } this.endpoint?.release(); this.endpoint = undefined; } private onConnection(socket: Socket): void { const connection: ConnectionState = { socket, buffer: '', authenticated: false, }; this.connections.add(connection); socket.setEncoding('utf8'); socket.setNoDelay(true); socket.on('error', () => {}); socket.on('data', (chunk: string) => this.onData(connection, chunk)); socket.once('close', () => { this.connections.delete(connection); if (this.active === connection) this.active = undefined; }); } private onData(connection: ConnectionState, chunk: string): void { if (this.closing || connection.socket.destroyed) return; connection.buffer += chunk; if (connection.buffer.length > CLAUDE_CHANNEL_MAX_FRAME_CHARACTERS) { connection.socket.destroy(new Error('claude_channel_ipc_frame_too_large')); return; } for (;;) { const newline = connection.buffer.indexOf('\n'); if (newline < 0) return; const line = connection.buffer.slice(0, newline).trim(); connection.buffer = connection.buffer.slice(newline + 1); if (!line) continue; let frame: Record | null; try { frame = objectFrame(JSON.parse(line)); } catch { frame = null; } if (!frame) { connection.socket.destroy(new Error('claude_channel_ipc_invalid_json')); return; } if (!connection.authenticated) { this.handleHello(connection, frame); if (!connection.authenticated) return; continue; } void this.handleBatch(connection, frame).catch((error) => { this.diagnostic?.('channel.ipc.delivery_failed', { error: error instanceof Error ? error.message : String(error), }); connection.socket.destroy(); }); } } private handleHello(connection: ConnectionState, frame: Record): void { const endpoint = this.endpoint?.descriptor; const connectionId = safeText(frame.connection_id); const ownerPid = Number(frame.owner_pid); if ( !endpoint || frame.schema !== CLAUDE_CHANNEL_IPC_SCHEMA || frame.type !== 'hello' || frame.token !== endpoint.token || !connectionId || !Number.isSafeInteger(ownerPid) || ownerPid <= 0 ) { connection.socket.destroy(new Error('claude_channel_ipc_hello_rejected')); return; } const previous = this.active; if (previous && previous !== connection) previous.socket.destroy(); connection.authenticated = true; connection.connectionId = connectionId; connection.ownerPid = ownerPid; this.active = connection; this.write(connection.socket, { schema: CLAUDE_CHANNEL_IPC_SCHEMA, type: 'ready', connection_id: connectionId, }); this.diagnostic?.('channel.ipc.owner_connected', { owner_pid: ownerPid }); } private async handleBatch( connection: ConnectionState, frame: Record, ): Promise { const connectionId = connection.connectionId; const deliveryId = safeText(frame.delivery_id, 1_024); const seq = Number(frame.seq); const payload = objectFrame(frame.payload); if ( this.active !== connection || frame.schema !== CLAUDE_CHANNEL_IPC_SCHEMA || frame.type !== 'mailbox_batch' || frame.connection_id !== connectionId || !deliveryId || !Number.isSafeInteger(seq) || seq <= 0 || !payload || payload.schema !== CLAWCLAW_CHANNEL_EVENTS_SCHEMA || !Array.isArray(payload.events) || Object.keys(payload).some((key) => key !== 'schema' && key !== 'events') || connection.inFlightDeliveryId ) { connection.socket.destroy(new Error('claude_channel_ipc_batch_rejected')); return; } connection.inFlightDeliveryId = deliveryId; try { const acceptance = this.accepted.get(deliveryId) ?? await this.acceptOnce(deliveryId, payload, connection.ownerPid!); if (this.active === connection && !connection.socket.destroyed) { this.writeReceipt(connection, seq, deliveryId, acceptance); } } finally { if (connection.inFlightDeliveryId === deliveryId) { connection.inFlightDeliveryId = undefined; } } } private acceptOnce( deliveryId: string, payload: Record, ownerPid: number, ): Promise { const current = this.accepting.get(deliveryId); if (current) return current; const operation = (async () => { await this.deliver(payload, { kind: 'game_events', schema: CLAWCLAW_CHANNEL_EVENTS_SCHEMA, event_count: String((payload.events as unknown[]).length), owner_pid: String(ownerPid), }); const acceptance: AcceptedDelivery = { acceptedAt: new Date().toISOString(), receiptId: randomUUID(), }; this.accepted.set(deliveryId, acceptance); while (this.accepted.size > MAX_ACCEPTED_DELIVERIES) { const oldest = this.accepted.keys().next().value as string | undefined; if (!oldest) break; this.accepted.delete(oldest); } return acceptance; })(); this.accepting.set(deliveryId, operation); void operation.finally(() => { if (this.accepting.get(deliveryId) === operation) this.accepting.delete(deliveryId); }).catch(() => {}); return operation; } private writeReceipt( connection: ConnectionState, seq: number, deliveryId: string, acceptance: AcceptedDelivery, ): void { this.write(connection.socket, { schema: CLAUDE_CHANNEL_IPC_SCHEMA, type: 'receipt', connection_id: connection.connectionId, seq, delivery_id: deliveryId, accepted_at: acceptance.acceptedAt, acceptance_level: 'sink_emitted', receipt_id: acceptance.receiptId, }); } private write(socket: Socket, frame: Record): void { socket.write(`${JSON.stringify(frame)}\n`); } }