import { createHash, randomBytes, randomUUID } from 'node:crypto'; import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { getWorkspaceDir } from '../lib/init-command.js'; import { ensureUserDataLayout, getRuntimeDir } from '../lib/user-data.js'; export const CLAUDE_CHANNEL_IPC_SCHEMA = 'ccl.claude-channel-ipc.v1'; export const CLAUDE_CHANNEL_ENDPOINT_SCHEMA = 'ccl.claude-channel-endpoint.v1'; export const CLAWCLAW_CHANNEL_EVENTS_SCHEMA = 'clawclaw.channel-events.v2'; export const CLAUDE_CHANNEL_ENDPOINT_FILE = 'claude-channel-endpoint.json'; export const CLAUDE_CHANNEL_MAX_FRAME_CHARACTERS = 16 * 1024 * 1024; export interface ClaudeChannelEndpointDescriptor { schema: typeof CLAUDE_CHANNEL_ENDPOINT_SCHEMA; instance_id: string; pid: number; socket_path: string; token: string; started_at: string; } export interface PublishedClaudeChannelEndpoint { descriptor: ClaudeChannelEndpointDescriptor; path: string; release(): void; } export function processAlive(pid: number): boolean { if (!Number.isSafeInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (error: any) { return error?.code === 'EPERM'; } } export function claudeChannelEndpointPath(workspaceDir = getWorkspaceDir()): string { return join(getRuntimeDir(workspaceDir), CLAUDE_CHANNEL_ENDPOINT_FILE); } export function createClaudeChannelSocketPath( workspaceDir = getWorkspaceDir(), pid = process.pid, ): string { const hash = createHash('sha1').update(workspaceDir).digest('hex').slice(0, 12); const nonce = randomBytes(6).toString('hex'); if (process.platform === 'win32') { return `\\\\.\\pipe\\clawclaw-channel-${hash}-${pid}-${nonce}`; } const userId = typeof process.getuid === 'function' ? String(process.getuid()) : hash; const dir = join(tmpdir(), `clawclaw-channel-${userId}`); mkdirSync(dir, { recursive: true, mode: 0o700 }); try { chmodSync(dir, 0o700); } catch {} return join(dir, `${hash}-${pid}-${nonce}.sock`); } function validDescriptor(value: unknown): value is ClaudeChannelEndpointDescriptor { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const descriptor = value as Record; return descriptor.schema === CLAUDE_CHANNEL_ENDPOINT_SCHEMA && typeof descriptor.instance_id === 'string' && descriptor.instance_id.length > 0 && Number.isSafeInteger(descriptor.pid) && Number(descriptor.pid) > 0 && typeof descriptor.socket_path === 'string' && descriptor.socket_path.length > 0 && typeof descriptor.token === 'string' && descriptor.token.length >= 32 && typeof descriptor.started_at === 'string'; } export function readClaudeChannelEndpoint( workspaceDir = getWorkspaceDir(), ): ClaudeChannelEndpointDescriptor | null { const path = claudeChannelEndpointPath(workspaceDir); if (!existsSync(path)) return null; try { const value = JSON.parse(readFileSync(path, 'utf8')); if (!validDescriptor(value) || !processAlive(value.pid)) return null; return value; } catch { return null; } } export function publishClaudeChannelEndpoint( socketPath: string, workspaceDir = getWorkspaceDir(), ): PublishedClaudeChannelEndpoint { ensureUserDataLayout(workspaceDir); const path = claudeChannelEndpointPath(workspaceDir); const existing = readClaudeChannelEndpoint(workspaceDir); if (existing && existing.pid !== process.pid) { throw new Error( `Another ClawClaw Channel bridge is already active (pid ${existing.pid}).`, ); } const descriptor: ClaudeChannelEndpointDescriptor = { schema: CLAUDE_CHANNEL_ENDPOINT_SCHEMA, instance_id: randomUUID(), pid: process.pid, socket_path: socketPath, token: randomBytes(32).toString('hex'), started_at: new Date().toISOString(), }; const tempPath = `${path}.${process.pid}.tmp`; mkdirSync(dirname(path), { recursive: true }); writeFileSync(tempPath, JSON.stringify(descriptor), { encoding: 'utf8', mode: 0o600 }); try { chmodSync(tempPath, 0o600); } catch {} try { renameSync(tempPath, path); } catch (error) { try { unlinkSync(path); renameSync(tempPath, path); } catch { try { unlinkSync(tempPath); } catch {} throw error; } } let released = false; return { descriptor, path, release: () => { if (released) return; released = true; try { const current = JSON.parse(readFileSync(path, 'utf8')) as Record; if ( current.instance_id === descriptor.instance_id && current.pid === descriptor.pid ) { unlinkSync(path); } } catch {} if (process.platform !== 'win32') { try { unlinkSync(socketPath); } catch {} } }, }; }