tandem-editor 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/channel/index.ts","../../src/shared/constants.ts","../../src/server/events/types.ts","../../src/channel/event-bridge.ts"],"sourcesContent":["#!/usr/bin/env node\r\n/**\r\n * Tandem Channel Shim — Claude Code spawns this as a subprocess.\r\n *\r\n * Bridges Tandem's SSE event stream → Claude Code channel notifications,\r\n * and exposes a `tandem_reply` tool for Claude to respond to chat messages.\r\n *\r\n * Uses the low-level MCP `Server` class (not `McpServer`) as required by\r\n * the Channels API spec.\r\n */\r\n\r\nimport { createConnection } from \"node:net\";\r\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\r\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\r\nimport { CallToolRequestSchema, ListToolsRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\r\nimport { z } from \"zod\";\r\nimport { DEFAULT_MCP_PORT } from \"../shared/constants.js\";\r\nimport { startEventBridge } from \"./event-bridge.js\";\r\n\r\n// stdout is the MCP wire — redirect console.log to stderr\r\nconsole.log = console.error;\r\nconsole.warn = console.error;\r\nconsole.info = console.error;\r\n\r\nconst TANDEM_URL = process.env.TANDEM_URL || \"http://localhost:3479\";\r\n\r\n// --- Pre-flight: verify Tandem server is reachable before MCP handshake ---\r\n\r\nasync function checkServerReachable(url: string, timeoutMs = 2000): Promise<boolean> {\r\n let parsed: URL;\r\n try {\r\n parsed = new URL(url);\r\n } catch {\r\n console.error(\r\n `[Channel] Invalid TANDEM_URL: \"${url}\" — expected format: http://localhost:3479`,\r\n );\r\n return false;\r\n }\r\n const port = parseInt(parsed.port || String(DEFAULT_MCP_PORT), 10);\r\n return new Promise((resolve) => {\r\n const socket = createConnection({ port, host: parsed.hostname }, () => {\r\n socket.destroy();\r\n resolve(true);\r\n });\r\n socket.setTimeout(timeoutMs);\r\n socket.on(\"timeout\", () => {\r\n socket.destroy();\r\n resolve(false);\r\n });\r\n socket.on(\"error\", (err) => {\r\n console.error(`[Channel] Server probe failed: ${err.message}`);\r\n socket.destroy();\r\n resolve(false);\r\n });\r\n });\r\n}\r\n\r\n// --- MCP Server setup ---\r\n\r\nconst mcp = new Server(\r\n { name: \"tandem-channel\", version: \"0.1.0\" },\r\n {\r\n capabilities: {\r\n experimental: {\r\n \"claude/channel\": {},\r\n \"claude/channel/permission\": {},\r\n },\r\n tools: {},\r\n },\r\n instructions: [\r\n 'Events from Tandem arrive as <channel source=\"tandem-channel\" event_type=\"...\" document_id=\"...\">.',\r\n \"These are real-time push notifications of user actions in the collaborative document editor.\",\r\n \"Event types: annotation:created, annotation:accepted, annotation:dismissed,\",\r\n \"chat:message, selection:changed, document:opened, document:closed, document:switched.\",\r\n \"Use your tandem MCP tools (tandem_getTextContent, tandem_comment, tandem_highlight, etc.) to act on them.\",\r\n \"Reply to chat messages using tandem_reply. Pass document_id from the tag attributes.\",\r\n \"Do not reply to non-chat events — just act on them using tools.\",\r\n \"If you haven't received channel notifications recently, call tandem_checkInbox as a fallback.\",\r\n ].join(\" \"),\r\n },\r\n);\r\n\r\n// --- Tool: tandem_reply (forwarded to Tandem HTTP server) ---\r\n\r\nmcp.setRequestHandler(ListToolsRequestSchema, async () => ({\r\n tools: [\r\n {\r\n name: \"tandem_reply\",\r\n description: \"Reply to a chat message in Tandem\",\r\n inputSchema: {\r\n type: \"object\" as const,\r\n properties: {\r\n text: { type: \"string\", description: \"The reply message\" },\r\n documentId: {\r\n type: \"string\",\r\n description: \"Document ID from the channel event (optional)\",\r\n },\r\n replyTo: {\r\n type: \"string\",\r\n description: \"Message ID being replied to (optional)\",\r\n },\r\n },\r\n required: [\"text\"],\r\n },\r\n },\r\n ],\r\n}));\r\n\r\nmcp.setRequestHandler(CallToolRequestSchema, async (req) => {\r\n if (req.params.name === \"tandem_reply\") {\r\n const args = req.params.arguments as Record<string, unknown>;\r\n try {\r\n const res = await fetch(`${TANDEM_URL}/api/channel-reply`, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(args),\r\n });\r\n let data: unknown;\r\n try {\r\n data = await res.json();\r\n } catch {\r\n data = { message: \"Non-JSON response\" };\r\n }\r\n if (!res.ok) {\r\n return {\r\n content: [\r\n {\r\n type: \"text\" as const,\r\n text: `Reply failed (${res.status}): ${JSON.stringify(data)}`,\r\n },\r\n ],\r\n isError: true,\r\n };\r\n }\r\n return { content: [{ type: \"text\" as const, text: JSON.stringify(data) }] };\r\n } catch (err) {\r\n return {\r\n content: [\r\n {\r\n type: \"text\" as const,\r\n text: `Failed to send reply: ${err instanceof Error ? err.message : String(err)}`,\r\n },\r\n ],\r\n isError: true,\r\n };\r\n }\r\n }\r\n throw new Error(`Unknown tool: ${req.params.name}`);\r\n});\r\n\r\n// --- Permission relay: forward Claude Code's tool approval prompts to Tandem browser ---\r\n\r\nconst PermissionRequestSchema = z.object({\r\n method: z.literal(\"notifications/claude/channel/permission_request\"),\r\n params: z.object({\r\n request_id: z.string(),\r\n tool_name: z.string(),\r\n description: z.string(),\r\n input_preview: z.string(),\r\n }),\r\n});\r\n\r\nmcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {\r\n try {\r\n const res = await fetch(`${TANDEM_URL}/api/channel-permission`, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify({\r\n requestId: params.request_id,\r\n toolName: params.tool_name,\r\n description: params.description,\r\n inputPreview: params.input_preview,\r\n }),\r\n });\r\n if (!res.ok) {\r\n console.error(\r\n `[Channel] Permission relay got HTTP ${res.status} — browser may not see prompt`,\r\n );\r\n }\r\n } catch (err) {\r\n console.error(\"[Channel] Failed to forward permission request:\", err);\r\n }\r\n});\r\n\r\n// --- Connect and start ---\r\n\r\nasync function main() {\r\n console.error(`[Channel] Tandem channel shim starting (server: ${TANDEM_URL})`);\r\n\r\n const reachable = await checkServerReachable(TANDEM_URL);\r\n if (!reachable) {\r\n console.error(`[Channel] Cannot reach Tandem server at ${TANDEM_URL}`);\r\n console.error(\"[Channel] Start it with: npm run dev:standalone\");\r\n // Continue anyway — the event bridge will retry, and the server may start later\r\n }\r\n\r\n // Connect to Claude Code over stdio\r\n const transport = new StdioServerTransport();\r\n await mcp.connect(transport);\r\n console.error(\"[Channel] Connected to Claude Code via stdio\");\r\n\r\n // Start the SSE event bridge (runs until disconnected or max retries)\r\n startEventBridge(mcp, TANDEM_URL).catch((err) => {\r\n console.error(\"[Channel] Event bridge failed unexpectedly:\", err);\r\n process.exit(1);\r\n });\r\n}\r\n\r\nmain().catch((err) => {\r\n console.error(\"[Channel] Fatal error:\", err);\r\n process.exit(1);\r\n});\r\n","export const DEFAULT_WS_PORT = 3478;\r\nexport const DEFAULT_MCP_PORT = 3479;\r\n\r\n/** File extensions the server accepts for opening. */\r\nexport const SUPPORTED_EXTENSIONS = new Set([\".md\", \".txt\", \".html\", \".htm\", \".docx\"]);\r\nexport const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB\r\nexport const MAX_WS_PAYLOAD = 10 * 1024 * 1024; // 10MB\r\nexport const MAX_WS_CONNECTIONS = 4;\r\nexport const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes\r\nexport const SESSION_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days\r\nexport const TYPING_DEBOUNCE = 3000; // 3 seconds\r\nexport const DISCONNECT_DEBOUNCE_MS = 3000; // 3 seconds before showing \"server not reachable\"\r\nexport const PROLONGED_DISCONNECT_MS = 30_000; // 30 seconds before showing App-level disconnect banner\r\nexport const OVERLAY_STALE_DEBOUNCE = 200; // 200ms\r\nexport const REVIEW_BANNER_THRESHOLD = 5;\r\n\r\nexport const HIGHLIGHT_COLORS: Record<string, string> = {\r\n yellow: \"rgba(255, 235, 59, 0.3)\",\r\n red: \"rgba(244, 67, 54, 0.3)\",\r\n green: \"rgba(76, 175, 80, 0.3)\",\r\n blue: \"rgba(33, 150, 243, 0.3)\",\r\n purple: \"rgba(156, 39, 176, 0.3)\",\r\n};\r\n\r\nexport const INTERRUPTION_MODE_DEFAULT = \"all\" as const;\r\nexport const INTERRUPTION_MODE_KEY = \"tandem:interruptionMode\";\r\n\r\n// Large file thresholds\r\nexport const CHARS_PER_PAGE = 3_000;\r\nexport const LARGE_FILE_PAGE_THRESHOLD = 50;\r\nexport const VERY_LARGE_FILE_PAGE_THRESHOLD = 100;\r\n\r\nexport const CLAUDE_PRESENCE_COLOR = \"#6366f1\";\r\nexport const CLAUDE_FOCUS_OPACITY = 0.1;\r\n\r\nexport const CTRL_ROOM = \"__tandem_ctrl__\";\r\n\r\n/** Y.Map key constants — centralized to prevent silent bugs from string typos. */\r\nexport const Y_MAP_ANNOTATIONS = \"annotations\";\r\nexport const Y_MAP_AWARENESS = \"awareness\";\r\nexport const Y_MAP_USER_AWARENESS = \"userAwareness\";\r\nexport const Y_MAP_CHAT = \"chat\";\r\nexport const Y_MAP_DOCUMENT_META = \"documentMeta\";\r\nexport const Y_MAP_SAVED_AT_VERSION = \"savedAtVersion\";\r\n\r\nexport const SERVER_INFO_DIR = \".tandem\";\r\nexport const SERVER_INFO_FILE = \".tandem/.server-info\";\r\n\r\nexport const RECENT_FILES_KEY = \"tandem:recentFiles\";\r\nexport const RECENT_FILES_CAP = 20;\r\n\r\nexport const USER_NAME_KEY = \"tandem:userName\";\r\nexport const USER_NAME_DEFAULT = \"You\";\r\n\r\n// Toast notifications\r\nexport const TOAST_DISMISS_MS = { error: 8000, warning: 6000, info: 4000 } as const;\r\nexport const MAX_VISIBLE_TOASTS = 5;\r\nexport const NOTIFICATION_BUFFER_SIZE = 50;\r\n\r\n// Onboarding tutorial\r\nexport const TUTORIAL_COMPLETED_KEY = \"tandem:tutorialCompleted\";\r\nexport const TUTORIAL_ANNOTATION_PREFIX = \"tutorial-\";\r\n\r\n// Channel / event queue\r\nexport const CHANNEL_EVENT_BUFFER_SIZE = 200;\r\nexport const CHANNEL_EVENT_BUFFER_AGE_MS = 60_000; // 60 seconds\r\nexport const CHANNEL_SSE_KEEPALIVE_MS = 15_000; // 15 seconds\r\nexport const CHANNEL_MAX_RETRIES = 5;\r\nexport const CHANNEL_RETRY_DELAY_MS = 2_000;\r\n","/**\r\n * Event types for the Tandem → Claude Code channel.\r\n *\r\n * These events flow from browser-originated Y.Map changes through an SSE\r\n * endpoint to the channel shim, which pushes them into Claude Code as\r\n * `notifications/claude/channel` messages.\r\n */\r\n\r\n// --- Per-event payload interfaces ---\r\n\r\nexport interface AnnotationCreatedPayload {\r\n annotationId: string;\r\n annotationType: string;\r\n content: string;\r\n textSnippet: string;\r\n}\r\n\r\nexport interface AnnotationAcceptedPayload {\r\n annotationId: string;\r\n textSnippet: string;\r\n}\r\n\r\nexport interface AnnotationDismissedPayload {\r\n annotationId: string;\r\n textSnippet: string;\r\n}\r\n\r\nexport interface ChatMessagePayload {\r\n messageId: string;\r\n text: string;\r\n replyTo: string | null;\r\n anchor: { from: number; to: number; textSnapshot: string } | null;\r\n}\r\n\r\nexport interface SelectionChangedPayload {\r\n from: number;\r\n to: number;\r\n selectedText: string;\r\n}\r\n\r\nexport interface DocumentOpenedPayload {\r\n fileName: string;\r\n format: string;\r\n}\r\n\r\nexport interface DocumentClosedPayload {\r\n fileName: string;\r\n}\r\n\r\nexport interface DocumentSwitchedPayload {\r\n fileName: string;\r\n}\r\n\r\n// --- Discriminated union ---\r\n\r\ninterface TandemEventBase {\r\n /** Timestamp-based unique ID for SSE `Last-Event-ID` reconnection. Format: `evt_<timestamp>_<rand>`. Roughly ordered but not strictly monotonic. */\r\n id: string;\r\n timestamp: number;\r\n /** Which document this event relates to (absent for global events). */\r\n documentId?: string;\r\n}\r\n\r\nexport type TandemEvent =\r\n | (TandemEventBase & { type: \"annotation:created\"; payload: AnnotationCreatedPayload })\r\n | (TandemEventBase & { type: \"annotation:accepted\"; payload: AnnotationAcceptedPayload })\r\n | (TandemEventBase & { type: \"annotation:dismissed\"; payload: AnnotationDismissedPayload })\r\n | (TandemEventBase & { type: \"chat:message\"; payload: ChatMessagePayload })\r\n | (TandemEventBase & { type: \"selection:changed\"; payload: SelectionChangedPayload })\r\n | (TandemEventBase & { type: \"document:opened\"; payload: DocumentOpenedPayload })\r\n | (TandemEventBase & { type: \"document:closed\"; payload: DocumentClosedPayload })\r\n | (TandemEventBase & { type: \"document:switched\"; payload: DocumentSwitchedPayload });\r\n\r\n/** Union of all event type discriminants. */\r\nexport type TandemEventType = TandemEvent[\"type\"];\r\n\r\n// Re-export from shared utils (single ID generation pattern)\r\nexport { generateEventId } from \"../../shared/utils.js\";\r\n\r\n// --- Parse guard for SSE consumers ---\r\n\r\nconst VALID_EVENT_TYPES = new Set<TandemEventType>([\r\n \"annotation:created\",\r\n \"annotation:accepted\",\r\n \"annotation:dismissed\",\r\n \"chat:message\",\r\n \"selection:changed\",\r\n \"document:opened\",\r\n \"document:closed\",\r\n \"document:switched\",\r\n]);\r\n\r\n/**\r\n * Validate a JSON-parsed value as a TandemEvent.\r\n * Used by the event-bridge to safely consume SSE data.\r\n */\r\nexport function parseTandemEvent(raw: unknown): TandemEvent | null {\r\n if (\r\n typeof raw !== \"object\" ||\r\n raw === null ||\r\n !(\"id\" in raw) ||\r\n typeof (raw as Record<string, unknown>).id !== \"string\" ||\r\n !(\"type\" in raw) ||\r\n !VALID_EVENT_TYPES.has((raw as Record<string, unknown>).type as TandemEventType) ||\r\n !(\"timestamp\" in raw) ||\r\n typeof (raw as Record<string, unknown>).timestamp !== \"number\" ||\r\n !(\"payload\" in raw) ||\r\n typeof (raw as Record<string, unknown>).payload !== \"object\"\r\n ) {\r\n return null;\r\n }\r\n return raw as TandemEvent;\r\n}\r\n\r\n/**\r\n * Convert a TandemEvent into a human-readable string for the channel `content` field.\r\n * Claude sees this text inside `<channel source=\"tandem-channel\">` tags.\r\n */\r\nexport function formatEventContent(event: TandemEvent): string {\r\n const doc = event.documentId ? ` [doc: ${event.documentId}]` : \"\";\r\n\r\n switch (event.type) {\r\n case \"annotation:created\": {\r\n const { annotationType, content, textSnippet } = event.payload;\r\n const snippet = textSnippet ? ` on \"${textSnippet}\"` : \"\";\r\n return `User created ${annotationType}${snippet}: ${content || \"(no content)\"}${doc}`;\r\n }\r\n case \"annotation:accepted\": {\r\n const { annotationId, textSnippet } = event.payload;\r\n return `User accepted annotation ${annotationId}${textSnippet ? ` (\"${textSnippet}\")` : \"\"}${doc}`;\r\n }\r\n case \"annotation:dismissed\": {\r\n const { annotationId, textSnippet } = event.payload;\r\n return `User dismissed annotation ${annotationId}${textSnippet ? ` (\"${textSnippet}\")` : \"\"}${doc}`;\r\n }\r\n case \"chat:message\": {\r\n const { text, replyTo } = event.payload;\r\n const reply = replyTo ? ` (replying to ${replyTo})` : \"\";\r\n return `User says${reply}: ${text}${doc}`;\r\n }\r\n case \"selection:changed\": {\r\n const { from, to, selectedText } = event.payload;\r\n if (!selectedText) return `User cleared selection${doc}`;\r\n return `User selected text (${from}-${to}): \"${selectedText}\"${doc}`;\r\n }\r\n case \"document:opened\": {\r\n const { fileName, format } = event.payload;\r\n return `User opened document: ${fileName} (${format})${doc}`;\r\n }\r\n case \"document:closed\": {\r\n const { fileName } = event.payload;\r\n return `User closed document: ${fileName}${doc}`;\r\n }\r\n case \"document:switched\": {\r\n const { fileName } = event.payload;\r\n return `User switched to document: ${fileName}${doc}`;\r\n }\r\n default: {\r\n const _exhaustive: never = event;\r\n return `Unknown event${doc}`;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Build the `meta` record for a channel notification.\r\n * Keys use underscores only (Channels API silently drops hyphenated keys).\r\n */\r\nexport function formatEventMeta(event: TandemEvent): Record<string, string> {\r\n const meta: Record<string, string> = {\r\n event_type: event.type,\r\n };\r\n if (event.documentId) meta.document_id = event.documentId;\r\n\r\n switch (event.type) {\r\n case \"annotation:created\":\r\n case \"annotation:accepted\":\r\n case \"annotation:dismissed\":\r\n meta.annotation_id = event.payload.annotationId;\r\n break;\r\n case \"chat:message\":\r\n meta.message_id = event.payload.messageId;\r\n break;\r\n }\r\n\r\n return meta;\r\n}\r\n","/**\r\n * SSE event bridge: connects to Tandem server's /api/events endpoint\r\n * and pushes received events to Claude Code as channel notifications.\r\n */\r\n\r\nimport type { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\r\nimport type { TandemEvent } from \"../server/events/types.js\";\r\nimport { formatEventContent, formatEventMeta, parseTandemEvent } from \"../server/events/types.js\";\r\nimport { CHANNEL_MAX_RETRIES, CHANNEL_RETRY_DELAY_MS } from \"../shared/constants.js\";\r\n\r\nconst AWARENESS_DEBOUNCE_MS = 500;\r\n\r\nexport async function startEventBridge(mcp: Server, tandemUrl: string): Promise<void> {\r\n let retries = 0;\r\n let lastEventId: string | undefined;\r\n\r\n while (retries < CHANNEL_MAX_RETRIES) {\r\n try {\r\n await connectAndStream(mcp, tandemUrl, lastEventId, (id) => {\r\n lastEventId = id;\r\n retries = 0;\r\n });\r\n } catch (err) {\r\n retries++;\r\n console.error(\r\n `[Channel] SSE connection failed (${retries}/${CHANNEL_MAX_RETRIES}):`,\r\n err instanceof Error ? err.message : err,\r\n );\r\n\r\n if (retries >= CHANNEL_MAX_RETRIES) {\r\n console.error(\"[Channel] SSE connection exhausted, reporting error and exiting\");\r\n try {\r\n await fetch(`${tandemUrl}/api/channel-error`, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify({\r\n error: \"CHANNEL_CONNECT_FAILED\",\r\n message: `Channel shim lost connection after ${CHANNEL_MAX_RETRIES} retries.`,\r\n }),\r\n });\r\n } catch (reportErr) {\r\n console.error(\r\n \"[Channel] Could not report failure to server:\",\r\n reportErr instanceof Error ? reportErr.message : reportErr,\r\n );\r\n }\r\n process.exit(1);\r\n }\r\n\r\n await new Promise((r) => setTimeout(r, CHANNEL_RETRY_DELAY_MS));\r\n }\r\n }\r\n}\r\n\r\nasync function connectAndStream(\r\n mcp: Server,\r\n tandemUrl: string,\r\n lastEventId: string | undefined,\r\n onEventId: (id: string) => void,\r\n): Promise<void> {\r\n const headers: Record<string, string> = { Accept: \"text/event-stream\" };\r\n if (lastEventId) headers[\"Last-Event-ID\"] = lastEventId;\r\n\r\n const res = await fetch(`${tandemUrl}/api/events`, { headers });\r\n if (!res.ok) throw new Error(`SSE endpoint returned ${res.status}`);\r\n if (!res.body) throw new Error(\"SSE endpoint returned no body\");\r\n\r\n const reader = res.body.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = \"\";\r\n\r\n // Debounced awareness: only send the latest status after a quiet period\r\n let awarenessTimer: ReturnType<typeof setTimeout> | null = null;\r\n let pendingAwareness: TandemEvent | null = null;\r\n\r\n function flushAwareness() {\r\n if (!pendingAwareness) return;\r\n const event = pendingAwareness;\r\n pendingAwareness = null;\r\n fetch(`${tandemUrl}/api/channel-awareness`, {\r\n method: \"POST\",\r\n headers: { \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify({\r\n documentId: event.documentId,\r\n status: `processing: ${event.type}`,\r\n active: true,\r\n }),\r\n }).catch((err) => {\r\n console.error(\"[Channel] Awareness update failed:\", err instanceof Error ? err.message : err);\r\n });\r\n }\r\n\r\n function scheduleAwareness(event: TandemEvent) {\r\n pendingAwareness = event;\r\n if (awarenessTimer) clearTimeout(awarenessTimer);\r\n awarenessTimer = setTimeout(flushAwareness, AWARENESS_DEBOUNCE_MS);\r\n }\r\n\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) throw new Error(\"SSE stream ended\");\r\n\r\n buffer += decoder.decode(value, { stream: true });\r\n\r\n let boundary: number;\r\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\r\n const frame = buffer.slice(0, boundary);\r\n buffer = buffer.slice(boundary + 2);\r\n\r\n if (frame.startsWith(\":\")) continue;\r\n\r\n let eventId: string | undefined;\r\n let data: string | undefined;\r\n\r\n for (const line of frame.split(\"\\n\")) {\r\n if (line.startsWith(\"id: \")) eventId = line.slice(4);\r\n else if (line.startsWith(\"data: \")) data = line.slice(6);\r\n }\r\n\r\n if (!data) continue;\r\n\r\n let event: TandemEvent | null;\r\n try {\r\n event = parseTandemEvent(JSON.parse(data));\r\n } catch {\r\n console.error(\"[Channel] Malformed SSE event data (skipping):\", data.slice(0, 200));\r\n continue;\r\n }\r\n if (!event) {\r\n console.error(\"[Channel] Received invalid SSE event, skipping\");\r\n continue;\r\n }\r\n\r\n if (eventId) onEventId(eventId);\r\n\r\n try {\r\n await mcp.notification({\r\n method: \"notifications/claude/channel\",\r\n params: {\r\n content: formatEventContent(event),\r\n meta: formatEventMeta(event),\r\n },\r\n });\r\n } catch (err) {\r\n console.error(\"[Channel] MCP notification failed (transport broken?):\", err);\r\n throw err;\r\n }\r\n\r\n scheduleAwareness(event);\r\n }\r\n }\r\n}\r\n"],"mappings":";;;AAWA,SAAS,wBAAwB;AACjC,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,8BAA8B;AAC9D,SAAS,SAAS;;;ACdX,IAAM,mBAAmB;AAIzB,IAAM,gBAAgB,KAAK,OAAO;AAClC,IAAM,iBAAiB,KAAK,OAAO;AAEnC,IAAM,eAAe,KAAK,KAAK;AAC/B,IAAM,kBAAkB,KAAK,KAAK,KAAK,KAAK;AA0D5C,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;;;ACatC,IAAM,oBAAoB,oBAAI,IAAqB;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMM,SAAS,iBAAiB,KAAkC;AACjE,MACE,OAAO,QAAQ,YACf,QAAQ,QACR,EAAE,QAAQ,QACV,OAAQ,IAAgC,OAAO,YAC/C,EAAE,UAAU,QACZ,CAAC,kBAAkB,IAAK,IAAgC,IAAuB,KAC/E,EAAE,eAAe,QACjB,OAAQ,IAAgC,cAAc,YACtD,EAAE,aAAa,QACf,OAAQ,IAAgC,YAAY,UACpD;AACA,WAAO;AAAA,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AAM,0BAA0B,GAAG;AAC3C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["mcp"]}
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/shared/constants.ts
13
+ var DEFAULT_MCP_PORT, MAX_FILE_SIZE, MAX_WS_PAYLOAD, IDLE_TIMEOUT, SESSION_MAX_AGE;
14
+ var init_constants = __esm({
15
+ "src/shared/constants.ts"() {
16
+ "use strict";
17
+ DEFAULT_MCP_PORT = 3479;
18
+ MAX_FILE_SIZE = 50 * 1024 * 1024;
19
+ MAX_WS_PAYLOAD = 10 * 1024 * 1024;
20
+ IDLE_TIMEOUT = 30 * 60 * 1e3;
21
+ SESSION_MAX_AGE = 30 * 24 * 60 * 60 * 1e3;
22
+ }
23
+ });
24
+
25
+ // src/cli/setup.ts
26
+ var setup_exports = {};
27
+ __export(setup_exports, {
28
+ applyConfig: () => applyConfig,
29
+ buildMcpEntries: () => buildMcpEntries,
30
+ detectTargets: () => detectTargets,
31
+ runSetup: () => runSetup
32
+ });
33
+ import { readFileSync, existsSync } from "fs";
34
+ import { writeFile, rename, copyFile, unlink, mkdir } from "fs/promises";
35
+ import { homedir } from "os";
36
+ import { join, dirname, resolve } from "path";
37
+ import { fileURLToPath } from "url";
38
+ import { randomUUID } from "crypto";
39
+ function buildMcpEntries(channelPath) {
40
+ return {
41
+ tandem: {
42
+ type: "http",
43
+ url: `${MCP_URL}/mcp`
44
+ },
45
+ "tandem-channel": {
46
+ command: "node",
47
+ args: [channelPath],
48
+ env: { TANDEM_URL: MCP_URL }
49
+ }
50
+ };
51
+ }
52
+ function detectTargets(opts = {}) {
53
+ const home = opts.homeOverride ?? homedir();
54
+ const targets = [];
55
+ const claudeCodeConfig = join(home, ".claude", "mcp_settings.json");
56
+ const claudeCodeDir = dirname(claudeCodeConfig);
57
+ if (opts.force || existsSync(claudeCodeConfig) || existsSync(claudeCodeDir)) {
58
+ targets.push({ label: "Claude Code", configPath: claudeCodeConfig });
59
+ }
60
+ let desktopConfig = null;
61
+ if (process.platform === "win32") {
62
+ const appdata = process.env.APPDATA ?? join(home, "AppData", "Roaming");
63
+ desktopConfig = join(appdata, "Claude", "claude_desktop_config.json");
64
+ } else if (process.platform === "darwin") {
65
+ desktopConfig = join(
66
+ home,
67
+ "Library",
68
+ "Application Support",
69
+ "Claude",
70
+ "claude_desktop_config.json"
71
+ );
72
+ } else {
73
+ desktopConfig = join(home, ".config", "claude", "claude_desktop_config.json");
74
+ }
75
+ if (desktopConfig && (opts.force || existsSync(desktopConfig))) {
76
+ targets.push({ label: "Claude Desktop", configPath: desktopConfig });
77
+ }
78
+ return targets;
79
+ }
80
+ async function atomicWrite(content, dest) {
81
+ const tmp = join(dirname(dest), `.tandem-setup-${randomUUID()}.json.tmp`);
82
+ await writeFile(tmp, content, "utf-8");
83
+ try {
84
+ await rename(tmp, dest);
85
+ } catch (err) {
86
+ if (err.code === "EXDEV") {
87
+ await copyFile(tmp, dest);
88
+ await unlink(tmp);
89
+ } else {
90
+ await unlink(tmp).catch((cleanupErr) => {
91
+ console.error(` Warning: could not remove temp file ${tmp}: ${cleanupErr.message}`);
92
+ });
93
+ throw err;
94
+ }
95
+ }
96
+ }
97
+ async function applyConfig(configPath, entries) {
98
+ let existing = {};
99
+ try {
100
+ existing = JSON.parse(readFileSync(configPath, "utf-8"));
101
+ } catch (err) {
102
+ const code = err.code;
103
+ if (code === "ENOENT") {
104
+ } else if (err instanceof SyntaxError) {
105
+ console.error(
106
+ ` Warning: ${configPath} contains malformed JSON \u2014 replacing with fresh config`
107
+ );
108
+ } else {
109
+ throw err;
110
+ }
111
+ }
112
+ const updated = {
113
+ ...existing,
114
+ mcpServers: {
115
+ ...existing.mcpServers ?? {},
116
+ ...entries
117
+ }
118
+ };
119
+ await mkdir(dirname(configPath), { recursive: true });
120
+ await atomicWrite(JSON.stringify(updated, null, 2) + "\n", configPath);
121
+ }
122
+ async function runSetup(opts = {}) {
123
+ console.error("\nTandem Setup\n");
124
+ console.error("Detecting Claude installations...");
125
+ const targets = detectTargets({ force: opts.force });
126
+ if (targets.length === 0) {
127
+ console.error(
128
+ " No Claude installations detected.\n If Claude Code is installed, ensure ~/.claude exists.\n You can force configuration to default paths with: tandem setup --force"
129
+ );
130
+ return;
131
+ }
132
+ for (const t of targets) {
133
+ console.error(` Found: ${t.label} (${t.configPath})`);
134
+ }
135
+ console.error("\nWriting MCP configuration...");
136
+ const entries = buildMcpEntries(CHANNEL_DIST);
137
+ let failures = 0;
138
+ for (const t of targets) {
139
+ try {
140
+ await applyConfig(t.configPath, entries);
141
+ console.error(` \x1B[32m\u2713\x1B[0m ${t.label}`);
142
+ } catch (err) {
143
+ failures++;
144
+ console.error(
145
+ ` \x1B[31m\u2717\x1B[0m ${t.label}: ${err instanceof Error ? err.message : String(err)}`
146
+ );
147
+ }
148
+ }
149
+ if (failures === targets.length) {
150
+ console.error("\nSetup failed \u2014 could not write any configuration. Check file permissions.");
151
+ process.exit(1);
152
+ } else if (failures > 0) {
153
+ console.error(
154
+ `
155
+ Setup partially complete (${failures} target(s) failed). Start Tandem with: tandem`
156
+ );
157
+ } else {
158
+ console.error("\nSetup complete! Start Tandem with: tandem");
159
+ console.error("Then in Claude, your tandem_* tools will be available.\n");
160
+ }
161
+ }
162
+ var __dirname, CHANNEL_DIST, MCP_URL;
163
+ var init_setup = __esm({
164
+ "src/cli/setup.ts"() {
165
+ "use strict";
166
+ init_constants();
167
+ __dirname = dirname(fileURLToPath(import.meta.url));
168
+ CHANNEL_DIST = resolve(__dirname, "../channel/index.js");
169
+ MCP_URL = `http://localhost:${DEFAULT_MCP_PORT}`;
170
+ }
171
+ });
172
+
173
+ // src/cli/start.ts
174
+ var start_exports = {};
175
+ __export(start_exports, {
176
+ runStart: () => runStart
177
+ });
178
+ import { spawn } from "child_process";
179
+ import { existsSync as existsSync2 } from "fs";
180
+ import { dirname as dirname2, resolve as resolve2 } from "path";
181
+ import { fileURLToPath as fileURLToPath2 } from "url";
182
+ function runStart() {
183
+ if (!existsSync2(SERVER_DIST)) {
184
+ console.error(`[Tandem] Server not found at ${SERVER_DIST}`);
185
+ console.error("[Tandem] The installation may be corrupted. Try: npm install -g tandem-editor");
186
+ process.exit(1);
187
+ }
188
+ console.error("[Tandem] Starting server...");
189
+ const proc = spawn("node", [SERVER_DIST], {
190
+ stdio: "inherit",
191
+ env: { ...process.env, TANDEM_OPEN_BROWSER: "1" }
192
+ });
193
+ proc.on("error", (err) => {
194
+ console.error(`[Tandem] Failed to start server: ${err.message}`);
195
+ process.exit(1);
196
+ });
197
+ proc.on("exit", (code) => {
198
+ process.exit(code ?? 0);
199
+ });
200
+ for (const sig of ["SIGINT", "SIGTERM"]) {
201
+ process.once(sig, () => proc.kill());
202
+ }
203
+ }
204
+ var __dirname2, SERVER_DIST;
205
+ var init_start = __esm({
206
+ "src/cli/start.ts"() {
207
+ "use strict";
208
+ __dirname2 = dirname2(fileURLToPath2(import.meta.url));
209
+ SERVER_DIST = resolve2(__dirname2, "../server/index.js");
210
+ }
211
+ });
212
+
213
+ // src/cli/index.ts
214
+ var version = true ? "0.1.0" : "0.0.0-dev";
215
+ var args = process.argv.slice(2);
216
+ if (args.includes("--help") || args.includes("-h")) {
217
+ console.log(`tandem v${version}
218
+
219
+ Usage:
220
+ tandem Start Tandem server and open the browser
221
+ tandem setup Register MCP tools with Claude Code / Claude Desktop
222
+ tandem setup --force Register to default paths regardless of detection
223
+ tandem --version
224
+ tandem --help
225
+ `);
226
+ process.exit(0);
227
+ }
228
+ if (args.includes("--version") || args.includes("-v")) {
229
+ console.log(version);
230
+ process.exit(0);
231
+ }
232
+ try {
233
+ if (args[0] === "setup") {
234
+ const { runSetup: runSetup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
235
+ await runSetup2({ force: args.includes("--force") });
236
+ } else if (!args[0] || args[0] === "start") {
237
+ const { runStart: runStart2 } = await Promise.resolve().then(() => (init_start(), start_exports));
238
+ runStart2();
239
+ } else {
240
+ console.error(`Unknown command: ${args[0]}`);
241
+ console.error("Run 'tandem --help' for usage.");
242
+ process.exit(1);
243
+ }
244
+ } catch (err) {
245
+ console.error(`
246
+ [Tandem] Fatal error: ${err instanceof Error ? err.message : String(err)}`);
247
+ console.error("If this persists, try reinstalling: npm install -g tandem-editor\n");
248
+ process.exit(1);
249
+ }
250
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shared/constants.ts","../../src/cli/setup.ts","../../src/cli/start.ts","../../src/cli/index.ts"],"sourcesContent":["export const DEFAULT_WS_PORT = 3478;\r\nexport const DEFAULT_MCP_PORT = 3479;\r\n\r\n/** File extensions the server accepts for opening. */\r\nexport const SUPPORTED_EXTENSIONS = new Set([\".md\", \".txt\", \".html\", \".htm\", \".docx\"]);\r\nexport const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB\r\nexport const MAX_WS_PAYLOAD = 10 * 1024 * 1024; // 10MB\r\nexport const MAX_WS_CONNECTIONS = 4;\r\nexport const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes\r\nexport const SESSION_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days\r\nexport const TYPING_DEBOUNCE = 3000; // 3 seconds\r\nexport const DISCONNECT_DEBOUNCE_MS = 3000; // 3 seconds before showing \"server not reachable\"\r\nexport const PROLONGED_DISCONNECT_MS = 30_000; // 30 seconds before showing App-level disconnect banner\r\nexport const OVERLAY_STALE_DEBOUNCE = 200; // 200ms\r\nexport const REVIEW_BANNER_THRESHOLD = 5;\r\n\r\nexport const HIGHLIGHT_COLORS: Record<string, string> = {\r\n yellow: \"rgba(255, 235, 59, 0.3)\",\r\n red: \"rgba(244, 67, 54, 0.3)\",\r\n green: \"rgba(76, 175, 80, 0.3)\",\r\n blue: \"rgba(33, 150, 243, 0.3)\",\r\n purple: \"rgba(156, 39, 176, 0.3)\",\r\n};\r\n\r\nexport const INTERRUPTION_MODE_DEFAULT = \"all\" as const;\r\nexport const INTERRUPTION_MODE_KEY = \"tandem:interruptionMode\";\r\n\r\n// Large file thresholds\r\nexport const CHARS_PER_PAGE = 3_000;\r\nexport const LARGE_FILE_PAGE_THRESHOLD = 50;\r\nexport const VERY_LARGE_FILE_PAGE_THRESHOLD = 100;\r\n\r\nexport const CLAUDE_PRESENCE_COLOR = \"#6366f1\";\r\nexport const CLAUDE_FOCUS_OPACITY = 0.1;\r\n\r\nexport const CTRL_ROOM = \"__tandem_ctrl__\";\r\n\r\n/** Y.Map key constants — centralized to prevent silent bugs from string typos. */\r\nexport const Y_MAP_ANNOTATIONS = \"annotations\";\r\nexport const Y_MAP_AWARENESS = \"awareness\";\r\nexport const Y_MAP_USER_AWARENESS = \"userAwareness\";\r\nexport const Y_MAP_CHAT = \"chat\";\r\nexport const Y_MAP_DOCUMENT_META = \"documentMeta\";\r\nexport const Y_MAP_SAVED_AT_VERSION = \"savedAtVersion\";\r\n\r\nexport const SERVER_INFO_DIR = \".tandem\";\r\nexport const SERVER_INFO_FILE = \".tandem/.server-info\";\r\n\r\nexport const RECENT_FILES_KEY = \"tandem:recentFiles\";\r\nexport const RECENT_FILES_CAP = 20;\r\n\r\nexport const USER_NAME_KEY = \"tandem:userName\";\r\nexport const USER_NAME_DEFAULT = \"You\";\r\n\r\n// Toast notifications\r\nexport const TOAST_DISMISS_MS = { error: 8000, warning: 6000, info: 4000 } as const;\r\nexport const MAX_VISIBLE_TOASTS = 5;\r\nexport const NOTIFICATION_BUFFER_SIZE = 50;\r\n\r\n// Onboarding tutorial\r\nexport const TUTORIAL_COMPLETED_KEY = \"tandem:tutorialCompleted\";\r\nexport const TUTORIAL_ANNOTATION_PREFIX = \"tutorial-\";\r\n\r\n// Channel / event queue\r\nexport const CHANNEL_EVENT_BUFFER_SIZE = 200;\r\nexport const CHANNEL_EVENT_BUFFER_AGE_MS = 60_000; // 60 seconds\r\nexport const CHANNEL_SSE_KEEPALIVE_MS = 15_000; // 15 seconds\r\nexport const CHANNEL_MAX_RETRIES = 5;\r\nexport const CHANNEL_RETRY_DELAY_MS = 2_000;\r\n","import { readFileSync, existsSync } from \"node:fs\";\r\nimport { writeFile, rename, copyFile, unlink, mkdir } from \"node:fs/promises\";\r\nimport { homedir } from \"node:os\";\r\nimport { join, dirname, resolve } from \"node:path\";\r\nimport { fileURLToPath } from \"node:url\";\r\nimport { randomUUID } from \"node:crypto\";\r\nimport { DEFAULT_MCP_PORT } from \"../shared/constants.js\";\r\n\r\nconst __dirname = dirname(fileURLToPath(import.meta.url));\r\n\r\n// Absolute path to dist/channel/index.js (sibling of dist/cli/)\r\nconst CHANNEL_DIST = resolve(__dirname, \"../channel/index.js\");\r\n\r\nconst MCP_URL = `http://localhost:${DEFAULT_MCP_PORT}`;\r\n\r\nexport interface McpEntry {\r\n type?: \"http\";\r\n url?: string;\r\n command?: string;\r\n args?: string[];\r\n env?: Record<string, string>;\r\n}\r\n\r\nexport interface McpEntries {\r\n tandem: McpEntry;\r\n \"tandem-channel\": McpEntry;\r\n}\r\n\r\nexport function buildMcpEntries(channelPath: string): McpEntries {\r\n return {\r\n tandem: {\r\n type: \"http\",\r\n url: `${MCP_URL}/mcp`,\r\n },\r\n \"tandem-channel\": {\r\n command: \"node\",\r\n args: [channelPath],\r\n env: { TANDEM_URL: MCP_URL },\r\n },\r\n };\r\n}\r\n\r\nexport interface DetectedTarget {\r\n label: string;\r\n configPath: string;\r\n}\r\n\r\ninterface DetectOptions {\r\n homeOverride?: string;\r\n force?: boolean;\r\n}\r\n\r\nexport function detectTargets(opts: DetectOptions = {}): DetectedTarget[] {\r\n const home = opts.homeOverride ?? homedir();\r\n const targets: DetectedTarget[] = [];\r\n\r\n // Claude Code — cross-platform.\r\n // Detect if the config file exists OR if ~/.claude directory exists\r\n // (Claude Code creates ~/.claude at install; mcp_settings.json may not exist yet).\r\n // With --force, always include regardless.\r\n const claudeCodeConfig = join(home, \".claude\", \"mcp_settings.json\");\r\n const claudeCodeDir = dirname(claudeCodeConfig);\r\n if (opts.force || existsSync(claudeCodeConfig) || existsSync(claudeCodeDir)) {\r\n targets.push({ label: \"Claude Code\", configPath: claudeCodeConfig });\r\n }\r\n\r\n // Claude Desktop — platform-specific.\r\n // Only detect if the config file already exists (user has launched Desktop at least once).\r\n // With --force, always include.\r\n let desktopConfig: string | null = null;\r\n if (process.platform === \"win32\") {\r\n const appdata = process.env.APPDATA ?? join(home, \"AppData\", \"Roaming\");\r\n desktopConfig = join(appdata, \"Claude\", \"claude_desktop_config.json\");\r\n } else if (process.platform === \"darwin\") {\r\n desktopConfig = join(\r\n home,\r\n \"Library\",\r\n \"Application Support\",\r\n \"Claude\",\r\n \"claude_desktop_config.json\",\r\n );\r\n } else {\r\n desktopConfig = join(home, \".config\", \"claude\", \"claude_desktop_config.json\");\r\n }\r\n\r\n if (desktopConfig && (opts.force || existsSync(desktopConfig))) {\r\n targets.push({ label: \"Claude Desktop\", configPath: desktopConfig });\r\n }\r\n\r\n return targets;\r\n}\r\n\r\n/**\r\n * Atomic write: write to a temp file in the SAME directory as the destination,\r\n * then rename. Using the same directory avoids EXDEV errors on Windows when\r\n * %TEMP% and %APPDATA% are on different drives.\r\n */\r\nasync function atomicWrite(content: string, dest: string): Promise<void> {\r\n const tmp = join(dirname(dest), `.tandem-setup-${randomUUID()}.json.tmp`);\r\n await writeFile(tmp, content, \"utf-8\");\r\n try {\r\n await rename(tmp, dest);\r\n } catch (err) {\r\n // EXDEV: cross-device link — fall back to copy + delete\r\n if ((err as NodeJS.ErrnoException).code === \"EXDEV\") {\r\n await copyFile(tmp, dest);\r\n await unlink(tmp);\r\n } else {\r\n await unlink(tmp).catch((cleanupErr: Error) => {\r\n console.error(` Warning: could not remove temp file ${tmp}: ${cleanupErr.message}`);\r\n });\r\n throw err;\r\n }\r\n }\r\n}\r\n\r\nexport async function applyConfig(configPath: string, entries: McpEntries): Promise<void> {\r\n // Read existing config or start fresh — no existsSync guard needed.\r\n // ENOENT and malformed JSON start fresh; other errors (permissions, disk) propagate.\r\n let existing: { mcpServers?: Record<string, McpEntry> } = {};\r\n try {\r\n existing = JSON.parse(readFileSync(configPath, \"utf-8\"));\r\n } catch (err) {\r\n const code = (err as NodeJS.ErrnoException).code;\r\n if (code === \"ENOENT\") {\r\n // File doesn't exist yet — start fresh\r\n } else if (err instanceof SyntaxError) {\r\n console.error(\r\n ` Warning: ${configPath} contains malformed JSON — replacing with fresh config`,\r\n );\r\n } else {\r\n throw err; // Permission errors, disk errors, etc. should not be silently swallowed\r\n }\r\n }\r\n\r\n const updated = {\r\n ...existing,\r\n mcpServers: {\r\n ...(existing.mcpServers ?? {}),\r\n ...entries,\r\n },\r\n };\r\n\r\n await mkdir(dirname(configPath), { recursive: true });\r\n await atomicWrite(JSON.stringify(updated, null, 2) + \"\\n\", configPath);\r\n}\r\n\r\n/** Run the setup command. Writes MCP config to all detected Claude installs. */\r\nexport async function runSetup(opts: { force?: boolean } = {}): Promise<void> {\r\n console.error(\"\\nTandem Setup\\n\");\r\n console.error(\"Detecting Claude installations...\");\r\n\r\n const targets = detectTargets({ force: opts.force });\r\n\r\n if (targets.length === 0) {\r\n console.error(\r\n \" No Claude installations detected.\\n\" +\r\n \" If Claude Code is installed, ensure ~/.claude exists.\\n\" +\r\n \" You can force configuration to default paths with: tandem setup --force\",\r\n );\r\n return;\r\n }\r\n\r\n for (const t of targets) {\r\n console.error(` Found: ${t.label} (${t.configPath})`);\r\n }\r\n\r\n console.error(\"\\nWriting MCP configuration...\");\r\n const entries = buildMcpEntries(CHANNEL_DIST);\r\n\r\n let failures = 0;\r\n for (const t of targets) {\r\n try {\r\n await applyConfig(t.configPath, entries);\r\n console.error(` \\x1b[32m✓\\x1b[0m ${t.label}`);\r\n } catch (err) {\r\n failures++;\r\n console.error(\r\n ` \\x1b[31m✗\\x1b[0m ${t.label}: ${err instanceof Error ? err.message : String(err)}`,\r\n );\r\n }\r\n }\r\n\r\n if (failures === targets.length) {\r\n console.error(\"\\nSetup failed — could not write any configuration. Check file permissions.\");\r\n process.exit(1);\r\n } else if (failures > 0) {\r\n console.error(\r\n `\\nSetup partially complete (${failures} target(s) failed). Start Tandem with: tandem`,\r\n );\r\n } else {\r\n console.error(\"\\nSetup complete! Start Tandem with: tandem\");\r\n console.error(\"Then in Claude, your tandem_* tools will be available.\\n\");\r\n }\r\n}\r\n","import { spawn } from \"node:child_process\";\r\nimport { existsSync } from \"node:fs\";\r\nimport { dirname, resolve } from \"node:path\";\r\nimport { fileURLToPath } from \"node:url\";\r\n\r\nconst __dirname = dirname(fileURLToPath(import.meta.url));\r\nconst SERVER_DIST = resolve(__dirname, \"../server/index.js\");\r\n\r\nexport function runStart(): void {\r\n if (!existsSync(SERVER_DIST)) {\r\n console.error(`[Tandem] Server not found at ${SERVER_DIST}`);\r\n console.error(\"[Tandem] The installation may be corrupted. Try: npm install -g tandem-editor\");\r\n process.exit(1);\r\n }\r\n\r\n console.error(\"[Tandem] Starting server...\");\r\n\r\n const proc = spawn(\"node\", [SERVER_DIST], {\r\n stdio: \"inherit\",\r\n env: { ...process.env, TANDEM_OPEN_BROWSER: \"1\" },\r\n });\r\n\r\n proc.on(\"error\", (err) => {\r\n console.error(`[Tandem] Failed to start server: ${err.message}`);\r\n process.exit(1);\r\n });\r\n\r\n proc.on(\"exit\", (code) => {\r\n process.exit(code ?? 0);\r\n });\r\n\r\n // Forward signals — proc.kill() with no argument uses SIGTERM on Unix\r\n // and TerminateProcess on Windows (correct cross-platform behavior).\r\n // On Windows SIGTERM is not emitted by the OS, but SIGINT (Ctrl+C) works.\r\n // Both are listed for Unix compatibility.\r\n for (const sig of [\"SIGINT\", \"SIGTERM\"] as const) {\r\n process.once(sig, () => proc.kill());\r\n }\r\n}\r\n","/**\r\n * Tandem CLI — entry point for the `tandem` global command.\r\n * Shebang is added by tsup banner at build time.\r\n *\r\n * Usage:\r\n * tandem Start the Tandem server and open the browser\r\n * tandem setup Register Tandem MCP tools with Claude Code / Claude Desktop\r\n * tandem setup --force Register even if no Claude install is auto-detected\r\n * tandem --help Show this help\r\n * tandem --version Show version\r\n */\r\n\r\n// Injected at build time by tsup define; declared here for TypeScript\r\ndeclare const __TANDEM_VERSION__: string;\r\nconst version = typeof __TANDEM_VERSION__ !== \"undefined\" ? __TANDEM_VERSION__ : \"0.0.0-dev\";\r\n\r\n// TypeScript needs a top-level export to treat this as a module (enabling top-level await)\r\nexport {};\r\n\r\nconst args = process.argv.slice(2);\r\n\r\nif (args.includes(\"--help\") || args.includes(\"-h\")) {\r\n console.log(`tandem v${version}\r\n\r\nUsage:\r\n tandem Start Tandem server and open the browser\r\n tandem setup Register MCP tools with Claude Code / Claude Desktop\r\n tandem setup --force Register to default paths regardless of detection\r\n tandem --version\r\n tandem --help\r\n`);\r\n process.exit(0);\r\n}\r\n\r\nif (args.includes(\"--version\") || args.includes(\"-v\")) {\r\n console.log(version);\r\n process.exit(0);\r\n}\r\n\r\ntry {\r\n if (args[0] === \"setup\") {\r\n const { runSetup } = await import(\"./setup.js\");\r\n await runSetup({ force: args.includes(\"--force\") });\r\n } else if (!args[0] || args[0] === \"start\") {\r\n const { runStart } = await import(\"./start.js\");\r\n runStart();\r\n } else {\r\n console.error(`Unknown command: ${args[0]}`);\r\n console.error(\"Run 'tandem --help' for usage.\");\r\n process.exit(1);\r\n }\r\n} catch (err) {\r\n console.error(`\\n[Tandem] Fatal error: ${err instanceof Error ? err.message : String(err)}`);\r\n console.error(\"If this persists, try reinstalling: npm install -g tandem-editor\\n\");\r\n process.exit(1);\r\n}\r\n"],"mappings":";;;;;;;;;;;;AAAA,IACa,kBAIA,eACA,gBAEA,cACA;AATb;AAAA;AAAA;AACO,IAAM,mBAAmB;AAIzB,IAAM,gBAAgB,KAAK,OAAO;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