tandem-editor 0.6.2 → 0.6.3
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.
- package/CHANGELOG.md +22 -0
- package/dist/channel/index.js.map +1 -1
- package/dist/cli/index.js +167 -46
- package/dist/cli/index.js.map +1 -1
- package/dist/client/assets/index-B1Cd5UGT.js +349 -0
- package/dist/client/index.html +48 -1
- package/dist/monitor/index.js +1 -0
- package/dist/monitor/index.js.map +1 -1
- package/dist/server/index.js +60501 -59641
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/client/assets/index-mo5ZOPfU.js +0 -349
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shared/constants.ts","../../src/cli/skill-content.ts","../../src/cli/setup.ts","../../src/shared/cli-runtime.ts","../../src/cli/preflight.ts","../../src/cli/mcp-stdio.ts","../../src/shared/utils.ts","../../src/server/events/types.ts","../../src/channel/event-bridge.ts","../../src/channel/run.ts","../../src/cli/channel.ts","../../src/cli/start.ts","../../src/cli/index.ts"],"sourcesContent":["export const DEFAULT_WS_PORT = 3478;\nexport const DEFAULT_MCP_PORT = 3479;\n\n/** File extensions the server accepts for opening. */\nexport const SUPPORTED_EXTENSIONS = new Set([\".md\", \".txt\", \".html\", \".htm\", \".docx\"]);\nexport const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB\nexport const MAX_WS_PAYLOAD = 10 * 1024 * 1024; // 10MB\nexport const MAX_WS_CONNECTIONS = 4;\nexport const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes\nexport const SESSION_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days\nexport const TYPING_DEBOUNCE = 3000; // 3 seconds\nexport const DISCONNECT_DEBOUNCE_MS = 3000; // 3 seconds before showing \"server not reachable\"\nexport const PROLONGED_DISCONNECT_MS = 30_000; // 30 seconds before showing App-level disconnect banner\nexport const OVERLAY_STALE_DEBOUNCE = 200; // 200ms\n\nexport const HIGHLIGHT_COLORS: Record<string, string> = {\n yellow: \"rgba(255, 235, 59, 0.3)\",\n red: \"rgba(244, 67, 54, 0.3)\",\n green: \"rgba(76, 175, 80, 0.3)\",\n blue: \"rgba(33, 150, 243, 0.3)\",\n purple: \"rgba(156, 39, 176, 0.3)\",\n};\n\nexport const TANDEM_MODE_DEFAULT = \"tandem\" as const;\nexport const TANDEM_MODE_KEY = \"tandem:mode\";\nexport const TANDEM_SETTINGS_KEY = \"tandem:settings\";\n// Panel-width localStorage keys.\n//\n// NOTE: these use legacy hyphen naming (vs the neighboring colon convention\n// `tandem:mode`/`tandem:settings`) because they predate the colon scheme and\n// changing the strings would invalidate every existing user's saved widths.\n// Do not \"fix\" the style — the key string is the persistence contract.\n//\n// Right-side panel width is shared between the tabbed layout and the\n// three-panel right panel. The left key only applies in three-panel mode.\nexport const PANEL_WIDTH_KEY = \"tandem-panel-width\";\nexport const LEFT_PANEL_WIDTH_KEY = \"tandem-left-panel-width\";\n\nexport type PanelSide = \"left\" | \"right\";\n\n/**\n * Maps a panel side to its localStorage key. Using a Record instead of two\n * bare constants makes the \"both handles write to the same key\" regression\n * (#228) structurally impossible — you can't accidentally map both sides to\n * the same value at a callsite.\n *\n * Uses `as const satisfies Record<PanelSide, string>` so the value type stays\n * as the literal strings rather than widening to `string` — this preserves\n * the persistence-key identity at every callsite while still enforcing\n * exhaustive coverage of `PanelSide`.\n */\nexport const PANEL_WIDTH_KEYS = {\n left: LEFT_PANEL_WIDTH_KEY,\n right: PANEL_WIDTH_KEY,\n} as const satisfies Record<PanelSide, string>;\nexport const SELECTION_DWELL_DEFAULT_MS = 1000;\nexport const SELECTION_DWELL_MIN_MS = 500;\nexport const SELECTION_DWELL_MAX_MS = 3000;\n\n// Large file thresholds\nexport const CHARS_PER_PAGE = 3_000;\nexport const LARGE_FILE_PAGE_THRESHOLD = 50;\nexport const VERY_LARGE_FILE_PAGE_THRESHOLD = 100;\n\nexport const CLAUDE_PRESENCE_COLOR = \"#6366f1\";\nexport const CLAUDE_FOCUS_OPACITY = 0.1;\n\nexport const CTRL_ROOM = \"__tandem_ctrl__\";\n\n/** Y.Map key constants — centralized to prevent silent bugs from string typos. */\nexport const Y_MAP_ANNOTATIONS = \"annotations\";\nexport const Y_MAP_AWARENESS = \"awareness\";\nexport const Y_MAP_USER_AWARENESS = \"userAwareness\";\nexport const Y_MAP_MODE = \"mode\";\nexport const Y_MAP_DWELL_MS = \"selectionDwellMs\";\nexport const Y_MAP_CHAT = \"chat\";\nexport const Y_MAP_DOCUMENT_META = \"documentMeta\";\nexport const Y_MAP_ANNOTATION_REPLIES = \"annotationReplies\";\nexport const Y_MAP_SAVED_AT_VERSION = \"savedAtVersion\";\nexport const Y_MAP_AUTHORSHIP = \"authorship\";\n\nexport const AUTHORSHIP_TOGGLE_KEY = \"tandem:showAuthorship\";\n\nexport const SERVER_INFO_DIR = \".tandem\";\nexport const SERVER_INFO_FILE = \".tandem/.server-info\";\n\nexport const RECENT_FILES_KEY = \"tandem:recentFiles\";\nexport const RECENT_FILES_CAP = 20;\n\nexport const USER_NAME_KEY = \"tandem:userName\";\nexport const USER_NAME_DEFAULT = \"You\";\nexport const USER_NAME_EVENT = \"tandem:user-name-changed\";\nexport const USER_NAME_MAX_LEN = 40;\n\n// Toast notifications\nexport const TOAST_DISMISS_MS = { error: 8000, warning: 6000, info: 4000 } as const;\nexport const MAX_VISIBLE_TOASTS = 5;\nexport const NOTIFICATION_BUFFER_SIZE = 50;\n\n// Onboarding tutorial\nexport const TUTORIAL_COMPLETED_KEY = \"tandem:tutorialCompleted\";\nexport const TUTORIAL_ANNOTATION_PREFIX = \"tutorial-\";\n\n// Editor layout\nexport const EDITOR_WIDTH_MODE_KEY = \"tandem:editorWidthMode\";\n\n// Channel / event queue\nexport const CHANNEL_EVENT_BUFFER_SIZE = 200;\nexport const CHANNEL_EVENT_BUFFER_AGE_MS = 60_000; // 60 seconds\nexport const CHANNEL_SSE_KEEPALIVE_MS = 15_000; // 15 seconds\nexport const CHANNEL_MAX_RETRIES = 5;\nexport const CHANNEL_RETRY_DELAY_MS = 2_000;\n\n/** Tauri WebView origin hostname — must be accepted alongside localhost. */\nexport const TAURI_HOSTNAME = \"tauri.localhost\";\n\n// Zoom persistence (Tauri desktop)\nexport const ZOOM_STORAGE_KEY = \"tandem:zoomLevel\";\nexport const ZOOM_MIN = 0.5;\nexport const ZOOM_MAX = 2.0;\nexport const ZOOM_DEFAULT = 1.0;\n","/**\n * SKILL.md content installed to ~/.claude/skills/tandem/ by `tandem setup`.\n * Single source of truth lives at `skills/tandem/SKILL.md`. This module\n * reads that file at module load so the plugin install path and the\n * `tandem setup` install path always deliver byte-identical content.\n *\n * The file is shipped via package.json `files: [\"skills/\", ...]`, and the\n * CLI entry (dist/cli/index.js) is not self-contained — so at runtime the\n * relative path `../../skills/tandem/SKILL.md` resolves from either\n * dist/cli/ (tsx dev) or dist/cli/ (npm install) to the package-root\n * `skills/tandem/SKILL.md`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst SKILL_PATH = resolve(__dirname, \"../../skills/tandem/SKILL.md\");\n\nexport const SKILL_CONTENT = readFileSync(SKILL_PATH, \"utf-8\");\n","import { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { copyFile, mkdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DEFAULT_MCP_PORT } from \"../shared/constants.js\";\nimport { SKILL_CONTENT } from \"./skill-content.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// Paths are anchored to the package root (dist/cli/ resolves up two levels).\nconst PACKAGE_ROOT = resolve(__dirname, \"../..\");\nconst CHANNEL_DIST = resolve(PACKAGE_ROOT, \"dist/channel/index.js\");\n\nconst MCP_URL = `http://localhost:${DEFAULT_MCP_PORT}`;\n\nexport interface McpEntry {\n type?: \"http\";\n url?: string;\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n}\n\nexport interface McpEntries {\n tandem: McpEntry;\n \"tandem-channel\"?: McpEntry;\n}\n\nexport interface BuildMcpEntriesOptions {\n /** Include the legacy stdio channel shim. Defaults to false — the plugin\n * monitor handles event push for modern installs. Users on older setups\n * can run `tandem setup --with-channel-shim` to preserve the shim. */\n withChannelShim?: boolean;\n nodeBinary?: string;\n}\n\nexport function buildMcpEntries(\n channelPath: string,\n opts: BuildMcpEntriesOptions = {},\n): McpEntries {\n const entries: McpEntries = {\n tandem: { type: \"http\", url: `${MCP_URL}/mcp` },\n };\n if (opts.withChannelShim) {\n entries[\"tandem-channel\"] = {\n command: opts.nodeBinary ?? \"node\",\n args: [channelPath],\n env: { TANDEM_URL: MCP_URL },\n };\n }\n return entries;\n}\n\nexport interface DetectedTarget {\n label: string;\n configPath: string;\n}\n\ninterface DetectOptions {\n homeOverride?: string;\n force?: boolean;\n}\n\nexport function detectTargets(opts: DetectOptions = {}): DetectedTarget[] {\n const home = opts.homeOverride ?? homedir();\n const targets: DetectedTarget[] = [];\n\n // Claude Code — cross-platform.\n // MCP servers are configured in ~/.claude.json under the \"mcpServers\" key.\n // Detect if the file exists OR if ~/.claude directory exists (Claude Code is installed).\n // With --force, always include regardless.\n const claudeCodeConfig = join(home, \".claude.json\");\n const claudeCodeDir = join(home, \".claude\");\n if (opts.force || existsSync(claudeCodeConfig) || existsSync(claudeCodeDir)) {\n targets.push({ label: \"Claude Code\", configPath: claudeCodeConfig });\n }\n\n // Claude Desktop — platform-specific.\n // Only detect if the config file already exists (user has launched Desktop at least once).\n // With --force, always include.\n let desktopConfig: string | null = null;\n if (process.platform === \"win32\") {\n const appdata = process.env.APPDATA ?? join(home, \"AppData\", \"Roaming\");\n desktopConfig = join(appdata, \"Claude\", \"claude_desktop_config.json\");\n } else if (process.platform === \"darwin\") {\n desktopConfig = join(\n home,\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\",\n );\n } else {\n desktopConfig = join(home, \".config\", \"claude\", \"claude_desktop_config.json\");\n }\n\n if (desktopConfig && (opts.force || existsSync(desktopConfig))) {\n targets.push({ label: \"Claude Desktop\", configPath: desktopConfig });\n }\n\n return targets;\n}\n\n/**\n * Atomic write: write to a temp file in the SAME directory as the destination,\n * then rename. Using the same directory avoids EXDEV errors on Windows when\n * %TEMP% and %APPDATA% are on different drives.\n */\nasync function atomicWrite(content: string, dest: string): Promise<void> {\n const tmp = join(dirname(dest), `.tandem-setup-${randomUUID()}.tmp`);\n await writeFile(tmp, content, \"utf-8\");\n try {\n await rename(tmp, dest);\n } catch (err) {\n // EXDEV: cross-device link — fall back to copy + delete\n if ((err as NodeJS.ErrnoException).code === \"EXDEV\") {\n await copyFile(tmp, dest);\n await unlink(tmp).catch((cleanupErr: Error) => {\n console.error(` Warning: could not remove temp file ${tmp}: ${cleanupErr.message}`);\n });\n } else {\n await unlink(tmp).catch((cleanupErr: Error) => {\n console.error(` Warning: could not remove temp file ${tmp}: ${cleanupErr.message}`);\n });\n throw err;\n }\n }\n}\n\nexport async function applyConfig(configPath: string, entries: McpEntries): Promise<void> {\n // Read existing config or start fresh — no existsSync guard needed.\n // ENOENT and malformed JSON start fresh; other errors (permissions, disk) propagate.\n let existing: { mcpServers?: Record<string, McpEntry> } = {};\n try {\n existing = JSON.parse(readFileSync(configPath, \"utf-8\"));\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n // File doesn't exist yet — start fresh\n } else if (err instanceof SyntaxError) {\n // Don't silently wipe the user's other mcpServers. Copy the malformed\n // file to a .broken-<ts> sibling first so they can recover it. If the\n // backup itself fails, refuse to overwrite — runSetup's per-target\n // try/catch reports the partial failure.\n const backupPath = `${configPath}.broken-${Date.now()}`;\n try {\n await copyFile(configPath, backupPath);\n console.error(\n ` Warning: ${configPath} contains malformed JSON — backed up to ${basename(backupPath)}, replacing with fresh config`,\n );\n } catch (copyErr) {\n console.error(\n ` Warning: ${configPath} contains malformed JSON and backup failed (${\n copyErr instanceof Error ? copyErr.message : copyErr\n }) — refusing to overwrite. Fix the JSON manually and rerun 'tandem setup'.`,\n );\n throw copyErr;\n }\n } else {\n throw err; // Permission errors, disk errors, etc. should not be silently swallowed\n }\n }\n\n const updated = {\n ...existing,\n mcpServers: {\n ...(existing.mcpServers ?? {}),\n ...entries,\n },\n };\n\n await mkdir(dirname(configPath), { recursive: true });\n await atomicWrite(JSON.stringify(updated, null, 2) + \"\\n\", configPath);\n}\n\n/**\n * Install the Tandem skill to ~/.claude/skills/tandem/SKILL.md.\n * Claude Code auto-discovers skills in this directory and uses the description\n * field to trigger them when tandem_* tools are present.\n */\nexport async function installSkill(opts: { homeOverride?: string } = {}): Promise<void> {\n const home = opts.homeOverride ?? homedir();\n const skillPath = join(home, \".claude\", \"skills\", \"tandem\", \"SKILL.md\");\n await mkdir(dirname(skillPath), { recursive: true });\n await atomicWrite(SKILL_CONTENT, skillPath);\n}\n\n/**\n * Returns true if the channel-shim build artifact exists at the given path.\n * Exported so the prereq check can be tested without spawning runSetup.\n */\nexport function validateChannelShimPrereq(channelPath: string): boolean {\n return existsSync(channelPath);\n}\n\n/** Run the setup command. Writes MCP config to all detected Claude installs. */\nexport async function runSetup(\n opts: { force?: boolean; withChannelShim?: boolean } = {},\n): Promise<void> {\n console.error(\"\\nTandem Setup\\n\");\n\n if (opts.withChannelShim && !validateChannelShimPrereq(CHANNEL_DIST)) {\n console.error(\n `Error: --with-channel-shim requires dist/channel/index.js at ${CHANNEL_DIST}\\n` +\n `Run 'npm run build' first, or drop --with-channel-shim to use the plugin monitor.`,\n );\n process.exit(1);\n }\n\n console.error(\"Detecting Claude installations...\");\n\n const targets = detectTargets({ force: opts.force });\n\n if (targets.length === 0) {\n console.error(\n \" No Claude installations detected.\\n\" +\n \" If Claude Code is installed, ensure ~/.claude exists.\\n\" +\n \" You can force configuration to default paths with: tandem setup --force\",\n );\n return;\n }\n\n for (const t of targets) {\n console.error(` Found: ${t.label} (${t.configPath})`);\n }\n\n console.error(\"\\nWriting MCP configuration...\");\n const entries = buildMcpEntries(CHANNEL_DIST, { withChannelShim: opts.withChannelShim });\n\n let failures = 0;\n for (const t of targets) {\n try {\n await applyConfig(t.configPath, entries);\n console.error(` \\x1b[32m✓\\x1b[0m ${t.label}`);\n } catch (err) {\n failures++;\n console.error(\n ` \\x1b[31m✗\\x1b[0m ${t.label}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n if (failures === targets.length) {\n console.error(\"\\nSetup failed — could not write any configuration. Check file permissions.\");\n process.exit(1);\n } else if (failures > 0) {\n console.error(\n `\\nSetup partially complete (${failures} target(s) failed). Start Tandem with: tandem`,\n );\n } else {\n console.error(\"\\nSetup complete! Start Tandem with: tandem\");\n console.error(\"Then in Claude, your tandem_* tools will be available.\");\n }\n\n // Install Claude Code skill (best-effort — doesn't block MCP setup)\n console.error(\"\\nInstalling Claude Code skill...\");\n try {\n await installSkill();\n console.error(\" \\x1b[32m✓\\x1b[0m ~/.claude/skills/tandem/SKILL.md\");\n } catch (err) {\n console.error(\n ` \\x1b[33m⚠\\x1b[0m Could not install skill: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Plugin install instructions (shown on all successful setups)\n if (failures < targets.length) {\n const pluginManifest = join(PACKAGE_ROOT, \".claude-plugin\", \"plugin.json\");\n const devInstructions = existsSync(pluginManifest)\n ? ` Or for development, load directly from this package:\\n\\n` +\n ` claude --plugin-dir ${PACKAGE_ROOT}\\n\\n`\n : ` (Development plugin dir not found at ${pluginManifest}; skipping local-plugin instructions.)\\n\\n`;\n\n console.error(\n \"\\n\\x1b[1mReal-time push notifications (recommended):\\x1b[0m\\n\" +\n \" Install the Tandem plugin for instant events (one-time):\\n\\n\" +\n \" claude plugin marketplace add bloknayrb/tandem\\n\" +\n \" claude plugin install tandem@tandem-editor\\n\\n\" +\n devInstructions +\n \" Without the plugin, Claude still works but relies on tandem_checkInbox polling.\\n\",\n );\n }\n}\n","/**\n * Helpers shared by CLI stdio entry points (`mcp-stdio`, `channel`) and the\n * standalone server / monitor binaries that all speak MCP over stdout.\n */\n\nimport { DEFAULT_MCP_PORT } from \"./constants.js\";\n\n/**\n * In stdio MCP mode, stdout is the JSON-RPC wire — any stray library write\n * corrupts the protocol. Redirect `console.log/warn/info` to stderr so\n * incidental logging is safe. Callers that also run in-process tests (e.g.\n * `src/monitor/index.ts`) can gate this behind `!process.env.VITEST`.\n */\nexport function redirectConsoleToStderr(): void {\n console.log = console.error;\n console.warn = console.error;\n console.info = console.error;\n}\n\n/**\n * Resolve the Tandem HTTP base URL used by stdio subcommands. Precedence is\n * (1) explicit override, (2) `TANDEM_URL` env var, (3) the default port on\n * localhost. The returned string has no trailing slash so callers can\n * concatenate `/health`, `/mcp`, etc. without double-slash.\n */\nexport function resolveTandemUrl(override?: string): string {\n const raw = override ?? process.env.TANDEM_URL ?? `http://localhost:${DEFAULT_MCP_PORT}`;\n return raw.replace(/\\/$/, \"\");\n}\n","/**\n * Shared preflight check for stdio MCP subcommands.\n *\n * Both `tandem mcp-stdio` and `tandem channel` need a live Tandem server on\n * localhost before they can do anything useful. If the server isn't running,\n * fail fast with a single clear error on stderr and exit 1 — otherwise\n * repeated handshake failures surface as reconnect-loop noise.\n */\n\nimport { resolveTandemUrl } from \"../shared/cli-runtime.js\";\n\nconst DEFAULT_TIMEOUT_MS = 2000;\n\nexport interface PreflightOptions {\n url?: string;\n timeoutMs?: number;\n}\n\nexport async function ensureTandemServer(opts: PreflightOptions = {}): Promise<void> {\n const url = resolveTandemUrl(opts.url);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const res = await fetch(`${url}/health`, { signal: controller.signal });\n if (!res.ok) {\n fail(url, `health endpoint returned HTTP ${res.status}`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n fail(url, msg);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction fail(url: string, detail: string): never {\n process.stderr.write(\n `[tandem] Tandem server not reachable at ${url} (${detail}).\\n` +\n `[tandem] Start the Tauri app or run \\`tandem start\\` on the host, then retry.\\n`,\n );\n process.exit(1);\n}\n","/**\n * Tandem mcp-stdio subcommand — stdio ↔ Streamable HTTP JSON-RPC proxy.\n *\n * Claude Desktop's plugin loader bridges stdio MCP servers into sandboxed\n * sessions but not HTTP MCP servers, so plugin-cached stdio entries that\n * forward to the local HTTP MCP endpoint are the only supported way to\n * surface tandem_* tools into those sessions.\n *\n * Raw message forwarding: no handler registrations, no per-method logic.\n * Any message the upstream emits (tool results, notifications, future\n * methods we haven't heard of) reaches the stdio client unchanged.\n *\n * Intentional: no reconnection logic. If the upstream HTTP server dies\n * mid-session, `http.onclose` fires and we exit(0). The plugin loader will\n * respawn us on the next tool call and the preflight will re-run with a\n * fresh, accurate error if the server is still down. A reconnect loop here\n * would hide server death from the user.\n */\n\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { redirectConsoleToStderr, resolveTandemUrl } from \"../shared/cli-runtime.js\";\nimport { ensureTandemServer } from \"./preflight.js\";\n\nredirectConsoleToStderr();\n\nexport async function runMcpStdio(): Promise<void> {\n const baseUrl = resolveTandemUrl();\n await ensureTandemServer({ url: baseUrl });\n\n const http = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));\n const stdio = new StdioServerTransport();\n\n let shuttingDown = false;\n const shutdown = async (code = 0): Promise<never> => {\n if (!shuttingDown) {\n shuttingDown = true;\n await http.close().catch(() => {});\n await stdio.close().catch(() => {});\n }\n process.exit(code);\n };\n\n stdio.onmessage = (msg: JSONRPCMessage) => {\n http.send(msg).catch((err: unknown) => {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] upstream send failed: ${detail}\\n`);\n const requestId = getRequestId(msg);\n if (requestId !== undefined) {\n const errorResponse: JSONRPCMessage = {\n jsonrpc: \"2.0\",\n id: requestId,\n error: {\n // -32000 is the implementation-defined server error range per\n // JSON-RPC 2.0 §5.1 — the upstream being unreachable is an\n // application-level condition, not a generic Internal Error.\n code: -32000,\n message: \"Tandem HTTP upstream unreachable\",\n data: { detail },\n },\n };\n stdio.send(errorResponse).catch(() => {});\n }\n });\n };\n\n http.onmessage = (msg: JSONRPCMessage) => {\n stdio.send(msg).catch((err: unknown) => {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] stdio write failed: ${detail}\\n`);\n });\n };\n\n stdio.onerror = (err) => {\n process.stderr.write(`[tandem mcp-stdio] stdio error: ${err.message}\\n`);\n };\n http.onerror = (err) => {\n process.stderr.write(`[tandem mcp-stdio] http error: ${err.message}\\n`);\n };\n\n stdio.onclose = () => {\n void shutdown(0);\n };\n http.onclose = () => {\n void shutdown(0);\n };\n\n // stdio first: if http.start() throws in the window between preflight and\n // here, the stderr log still reaches the upstream instead of dying silent.\n await stdio.start();\n try {\n await http.start();\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] upstream http start failed: ${detail}\\n`);\n await shutdown(1);\n }\n}\n\nexport function getRequestId(msg: JSONRPCMessage): string | number | undefined {\n const m = msg as { id?: unknown; method?: unknown };\n if (typeof m.method !== \"string\") return undefined;\n if (typeof m.id === \"string\" || typeof m.id === \"number\") return m.id;\n return undefined;\n}\n","function generateId(prefix: string): string {\n return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function generateAnnotationId(): string {\n return generateId(\"ann\");\n}\n\nexport function generateMessageId(): string {\n return generateId(\"msg\");\n}\n\nexport function generateEventId(): string {\n return generateId(\"evt\");\n}\n\nexport function generateReplyId(): string {\n return generateId(\"rpl\");\n}\n\nexport function generateNotificationId(): string {\n return generateId(\"ntf\");\n}\n\nexport function generateAuthorshipId(author: \"user\" | \"claude\"): string {\n return generateId(author);\n}\n","/**\n * Event types for the Tandem → Claude Code channel.\n *\n * These events flow from browser-originated Y.Map changes through an SSE\n * endpoint to the channel shim, which pushes them into Claude Code as\n * `notifications/claude/channel` messages.\n */\n\n// --- Per-event payload interfaces ---\n\nexport interface AnnotationCreatedPayload {\n annotationId: string;\n annotationType: string;\n content: string;\n textSnippet: string;\n hasSuggestedText?: boolean;\n directedAt?: \"claude\";\n}\n\nexport interface AnnotationAcceptedPayload {\n annotationId: string;\n textSnippet: string;\n}\n\nexport interface AnnotationDismissedPayload {\n annotationId: string;\n textSnippet: string;\n}\n\nexport interface ChatMessagePayload {\n messageId: string;\n text: string;\n replyTo: string | null;\n anchor: { from: number; to: number; textSnapshot: string } | null;\n /** Buffered selection context at the time the chat message was sent. */\n selection?: { from: number; to: number; selectedText: string } | { selectedText: string };\n}\n\nexport interface DocumentOpenedPayload {\n fileName: string;\n format: string;\n}\n\nexport interface DocumentClosedPayload {\n fileName: string;\n}\n\nexport interface AnnotationReplyPayload {\n annotationId: string;\n replyId: string;\n replyText: string;\n replyAuthor: \"user\" | \"claude\";\n textSnippet: string;\n}\n\nexport interface DocumentSwitchedPayload {\n fileName: string;\n}\n\n// --- Discriminated union ---\n\ninterface TandemEventBase {\n /** Timestamp-based unique ID for SSE `Last-Event-ID` reconnection. Format: `evt_<timestamp>_<rand>`. Roughly ordered but not strictly monotonic. */\n id: string;\n timestamp: number;\n /** Which document this event relates to (absent for global events). */\n documentId?: string;\n}\n\nexport type TandemEvent =\n | (TandemEventBase & { type: \"annotation:created\"; payload: AnnotationCreatedPayload })\n | (TandemEventBase & { type: \"annotation:accepted\"; payload: AnnotationAcceptedPayload })\n | (TandemEventBase & { type: \"annotation:dismissed\"; payload: AnnotationDismissedPayload })\n | (TandemEventBase & { type: \"annotation:reply\"; payload: AnnotationReplyPayload })\n | (TandemEventBase & { type: \"chat:message\"; payload: ChatMessagePayload })\n | (TandemEventBase & { type: \"document:opened\"; payload: DocumentOpenedPayload })\n | (TandemEventBase & { type: \"document:closed\"; payload: DocumentClosedPayload })\n | (TandemEventBase & { type: \"document:switched\"; payload: DocumentSwitchedPayload });\n\n/** Union of all event type discriminants. */\nexport type TandemEventType = TandemEvent[\"type\"];\n\n// Re-export from shared utils (single ID generation pattern)\nexport { generateEventId } from \"../../shared/utils.js\";\n\n// --- Parse guard for SSE consumers ---\n\nconst VALID_EVENT_TYPES = new Set<TandemEventType>([\n \"annotation:created\",\n \"annotation:accepted\",\n \"annotation:dismissed\",\n \"annotation:reply\",\n \"chat:message\",\n \"document:opened\",\n \"document:closed\",\n \"document:switched\",\n]);\n\n/**\n * Validate a JSON-parsed value as a TandemEvent.\n * Used by the event-bridge to safely consume SSE data.\n */\nexport function parseTandemEvent(raw: unknown): TandemEvent | null {\n if (\n typeof raw !== \"object\" ||\n raw === null ||\n !(\"id\" in raw) ||\n typeof (raw as Record<string, unknown>).id !== \"string\" ||\n !(\"type\" in raw) ||\n !VALID_EVENT_TYPES.has((raw as Record<string, unknown>).type as TandemEventType) ||\n !(\"timestamp\" in raw) ||\n typeof (raw as Record<string, unknown>).timestamp !== \"number\" ||\n !(\"payload\" in raw) ||\n typeof (raw as Record<string, unknown>).payload !== \"object\"\n ) {\n return null;\n }\n return raw as TandemEvent;\n}\n\n/**\n * Convert a TandemEvent into a human-readable string for the channel `content` field.\n * Claude sees this text inside `<channel source=\"tandem-channel\">` tags.\n */\nexport function formatEventContent(event: TandemEvent): string {\n const doc = event.documentId ? ` [doc: ${event.documentId}]` : \"\";\n\n switch (event.type) {\n case \"annotation:created\": {\n const { annotationType, content, textSnippet, hasSuggestedText, directedAt } = event.payload;\n const snippet = textSnippet ? ` on \"${textSnippet}\"` : \"\";\n const label = hasSuggestedText\n ? \"replacement\"\n : directedAt === \"claude\"\n ? \"question for Claude\"\n : annotationType;\n return `User created ${label}${snippet}: ${content || \"(no content)\"}${doc}`;\n }\n case \"annotation:accepted\": {\n const { annotationId, textSnippet } = event.payload;\n return `User accepted annotation ${annotationId}${textSnippet ? ` (\"${textSnippet}\")` : \"\"}${doc}`;\n }\n case \"annotation:dismissed\": {\n const { annotationId, textSnippet } = event.payload;\n return `User dismissed annotation ${annotationId}${textSnippet ? ` (\"${textSnippet}\")` : \"\"}${doc}`;\n }\n case \"annotation:reply\": {\n const { annotationId, replyAuthor, replyText, textSnippet } = event.payload;\n const who = replyAuthor === \"claude\" ? \"Claude\" : \"User\";\n const snippet = textSnippet ? ` (on \"${textSnippet}\")` : \"\";\n return `${who} replied to annotation ${annotationId}${snippet}: ${replyText}${doc}`;\n }\n case \"chat:message\": {\n const { text, replyTo, selection } = event.payload;\n const reply = replyTo ? ` (replying to ${replyTo})` : \"\";\n const sel =\n selection && selection.selectedText\n ? ` [selection: \"${selection.selectedText}\"${\"from\" in selection ? ` (${selection.from}-${selection.to})` : \"\"}]`\n : \"\";\n return `User says${reply}: ${text}${sel}${doc}`;\n }\n case \"document:opened\": {\n const { fileName, format } = event.payload;\n return `User opened document: ${fileName} (${format})${doc}`;\n }\n case \"document:closed\": {\n const { fileName } = event.payload;\n return `User closed document: ${fileName}${doc}`;\n }\n case \"document:switched\": {\n const { fileName } = event.payload;\n return `User switched to document: ${fileName}${doc}`;\n }\n default: {\n const _exhaustive: never = event;\n return `Unknown event${doc}`;\n }\n }\n}\n\n/**\n * Build the `meta` record for a channel notification.\n * Keys use underscores only (Channels API silently drops hyphenated keys).\n */\nexport function formatEventMeta(event: TandemEvent): Record<string, string> {\n const meta: Record<string, string> = {\n event_type: event.type,\n };\n if (event.documentId) meta.document_id = event.documentId;\n\n switch (event.type) {\n case \"annotation:created\":\n case \"annotation:accepted\":\n case \"annotation:dismissed\":\n meta.annotation_id = event.payload.annotationId;\n break;\n case \"annotation:reply\":\n meta.annotation_id = event.payload.annotationId;\n meta.reply_id = event.payload.replyId;\n break;\n case \"chat:message\":\n meta.message_id = event.payload.messageId;\n if (event.payload.selection?.selectedText) meta.has_selection = \"true\";\n break;\n case \"document:opened\":\n case \"document:closed\":\n case \"document:switched\":\n break;\n default: {\n const _exhaustive: never = event;\n break;\n }\n }\n\n return meta;\n}\n","/**\n * SSE event bridge: connects to Tandem server's /api/events endpoint\n * and pushes received events to Claude Code as channel notifications.\n */\n\nimport type { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport type { TandemEvent } from \"../server/events/types.js\";\nimport { formatEventContent, formatEventMeta, parseTandemEvent } from \"../server/events/types.js\";\nimport { CHANNEL_MAX_RETRIES, CHANNEL_RETRY_DELAY_MS } from \"../shared/constants.js\";\n\nconst AWARENESS_DEBOUNCE_MS = 500;\nconst MODE_CACHE_TTL_MS = 2000;\n\nexport async function startEventBridge(mcp: Server, tandemUrl: string): Promise<void> {\n let retries = 0;\n let lastEventId: string | undefined;\n\n while (retries < CHANNEL_MAX_RETRIES) {\n try {\n await connectAndStream(mcp, tandemUrl, lastEventId, (id) => {\n lastEventId = id;\n retries = 0;\n });\n } catch (err) {\n retries++;\n console.error(\n `[Channel] SSE connection failed (${retries}/${CHANNEL_MAX_RETRIES}):`,\n err instanceof Error ? err.message : err,\n );\n\n if (retries >= CHANNEL_MAX_RETRIES) {\n console.error(\"[Channel] SSE connection exhausted, reporting error and exiting\");\n try {\n await fetch(`${tandemUrl}/api/channel-error`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n error: \"CHANNEL_CONNECT_FAILED\",\n message: `Channel shim lost connection after ${CHANNEL_MAX_RETRIES} retries.`,\n }),\n });\n } catch (reportErr) {\n console.error(\n \"[Channel] Could not report failure to server:\",\n reportErr instanceof Error ? reportErr.message : reportErr,\n );\n }\n process.exit(1);\n }\n\n await new Promise((r) => setTimeout(r, CHANNEL_RETRY_DELAY_MS));\n }\n }\n}\n\nasync function connectAndStream(\n mcp: Server,\n tandemUrl: string,\n lastEventId: string | undefined,\n onEventId: (id: string) => void,\n): Promise<void> {\n const headers: Record<string, string> = { Accept: \"text/event-stream\" };\n if (lastEventId) headers[\"Last-Event-ID\"] = lastEventId;\n\n const res = await fetch(`${tandemUrl}/api/events`, { headers });\n if (!res.ok) throw new Error(`SSE endpoint returned ${res.status}`);\n if (!res.body) throw new Error(\"SSE endpoint returned no body\");\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n // Debounced awareness: only send the latest status after a quiet period\n let awarenessTimer: ReturnType<typeof setTimeout> | null = null;\n let clearAwarenessTimer: ReturnType<typeof setTimeout> | null = null;\n let pendingAwareness: TandemEvent | null = null;\n const AWARENESS_CLEAR_MS = 3000; // Reset active state after 3s of no new events\n\n function clearAwareness(documentId?: string) {\n fetch(`${tandemUrl}/api/channel-awareness`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n documentId: documentId ?? null,\n status: \"idle\",\n active: false,\n }),\n }).catch(() => {});\n }\n\n function flushAwareness() {\n if (!pendingAwareness) return;\n const event = pendingAwareness;\n pendingAwareness = null;\n fetch(`${tandemUrl}/api/channel-awareness`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n documentId: event.documentId,\n status: `processing: ${event.type}`,\n active: true,\n }),\n }).catch((err) => {\n console.error(\"[Channel] Awareness update failed:\", err instanceof Error ? err.message : err);\n });\n\n // Auto-clear after timeout so the indicator doesn't stick\n if (clearAwarenessTimer) clearTimeout(clearAwarenessTimer);\n clearAwarenessTimer = setTimeout(() => clearAwareness(event.documentId), AWARENESS_CLEAR_MS);\n }\n\n function scheduleAwareness(event: TandemEvent) {\n pendingAwareness = event;\n if (awarenessTimer) clearTimeout(awarenessTimer);\n awarenessTimer = setTimeout(flushAwareness, AWARENESS_DEBOUNCE_MS);\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) throw new Error(\"SSE stream ended\");\n\n buffer += decoder.decode(value, { stream: true });\n\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n\n if (frame.startsWith(\":\")) continue;\n\n let eventId: string | undefined;\n let data: string | undefined;\n\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\"id: \")) eventId = line.slice(4);\n else if (line.startsWith(\"data: \")) data = line.slice(6);\n }\n\n if (!data) continue;\n\n let event: TandemEvent | null;\n try {\n event = parseTandemEvent(JSON.parse(data));\n } catch {\n console.error(\"[Channel] Malformed SSE event data (skipping):\", data.slice(0, 200));\n continue;\n }\n if (!event) {\n console.error(\"[Channel] Received invalid SSE event, skipping\");\n continue;\n }\n\n // Solo mode suppression: drop non-chat events when mode is \"solo\"\n if (event.type !== \"chat:message\") {\n const mode = await getCachedMode(tandemUrl);\n if (mode === \"solo\") {\n console.error(`[Channel] Solo mode: suppressed ${event.type} event`);\n if (eventId) onEventId(eventId);\n continue;\n }\n }\n\n if (eventId) onEventId(eventId);\n\n try {\n await mcp.notification({\n method: \"notifications/claude/channel\",\n params: {\n content: formatEventContent(event),\n meta: formatEventMeta(event),\n },\n });\n } catch (err) {\n console.error(\"[Channel] MCP notification failed (transport broken?):\", err);\n throw err;\n }\n\n scheduleAwareness(event);\n }\n }\n}\n\n// Cached mode lookup — avoids an HTTP fetch per event\nlet cachedMode: string = \"tandem\";\nlet cachedModeAt = 0;\n\nasync function getCachedMode(tandemUrl: string): Promise<string> {\n const now = Date.now();\n if (now - cachedModeAt < MODE_CACHE_TTL_MS) return cachedMode;\n try {\n const res = await fetch(`${tandemUrl}/api/mode`);\n if (res.ok) {\n const { mode } = (await res.json()) as { mode: string };\n cachedMode = mode;\n } else {\n console.error(`[Channel] Mode check returned ${res.status}, using cached: \"${cachedMode}\"`);\n }\n cachedModeAt = now;\n } catch (err) {\n console.error(\n \"[Channel] Mode check failed, delivering event (fail-open):\",\n err instanceof Error ? err.message : err,\n );\n cachedModeAt = now;\n }\n return cachedMode;\n}\n","/**\n * Tandem Channel Shim — core runtime, shared by:\n * - src/channel/index.ts (standalone binary, used by the Desktop sidecar)\n * - src/cli/channel.ts (npm-delivered entry for the plugin `tandem-channel`)\n *\n * Bridges Tandem's SSE event stream → Claude Code channel notifications,\n * and exposes a `tandem_reply` tool for Claude to respond to chat messages.\n *\n * Uses the low-level MCP `Server` class (not `McpServer`) as required by\n * the Channels API spec.\n */\n\nimport { createConnection } from \"node:net\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { CallToolRequestSchema, ListToolsRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { redirectConsoleToStderr, resolveTandemUrl } from \"../shared/cli-runtime.js\";\nimport { DEFAULT_MCP_PORT } from \"../shared/constants.js\";\nimport { startEventBridge } from \"./event-bridge.js\";\n\nexport interface RunChannelOptions {\n /** Skip the non-fatal reachability probe. The CLI wrapper runs a strict\n * preflight upstream and we don't want to double-log \"server not reachable\"\n * noise. Defaults to false. */\n skipReachabilityLog?: boolean;\n}\n\nexport async function runChannel(opts: RunChannelOptions = {}): Promise<void> {\n redirectConsoleToStderr();\n\n const tandemUrl = resolveTandemUrl();\n\n const mcp = new Server(\n { name: \"tandem-channel\", version: \"0.1.0\" },\n {\n capabilities: {\n experimental: {\n \"claude/channel\": {},\n \"claude/channel/permission\": {},\n },\n tools: {},\n },\n instructions: [\n 'Events from Tandem arrive as <channel source=\"tandem-channel\" event_type=\"...\" document_id=\"...\">.',\n \"These are real-time push notifications of user actions in the collaborative document editor.\",\n \"Event types: annotation:created, annotation:accepted, annotation:dismissed, annotation:reply,\",\n \"chat:message, document:opened, document:closed, document:switched.\",\n \"Chat messages may include a 'selection' field with buffered selection context.\",\n \"Use your tandem MCP tools (tandem_getTextContent, tandem_comment, tandem_highlight, etc.) to act on them.\",\n \"Reply to chat messages using tandem_reply. Pass document_id from the tag attributes.\",\n \"Do not reply to non-chat events — just act on them using tools.\",\n \"If you haven't received channel notifications recently, call tandem_checkInbox as a fallback.\",\n ].join(\" \"),\n },\n );\n\n mcp.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"tandem_reply\",\n description: \"Reply to a chat message in Tandem\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n text: { type: \"string\", description: \"The reply message\" },\n documentId: {\n type: \"string\",\n description: \"Document ID from the channel event (optional)\",\n },\n replyTo: {\n type: \"string\",\n description: \"Message ID being replied to (optional)\",\n },\n },\n required: [\"text\"],\n },\n },\n ],\n }));\n\n mcp.setRequestHandler(CallToolRequestSchema, async (req) => {\n if (req.params.name === \"tandem_reply\") {\n const args = req.params.arguments as Record<string, unknown>;\n try {\n const res = await fetch(`${tandemUrl}/api/channel-reply`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(args),\n });\n let data: unknown;\n try {\n data = await res.json();\n } catch {\n data = { message: \"Non-JSON response\" };\n }\n if (!res.ok) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Reply failed (${res.status}): ${JSON.stringify(data)}`,\n },\n ],\n isError: true,\n };\n }\n return { content: [{ type: \"text\" as const, text: JSON.stringify(data) }] };\n } catch (err) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Failed to send reply: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n }\n throw new Error(`Unknown tool: ${req.params.name}`);\n });\n\n const PermissionRequestSchema = z.object({\n method: z.literal(\"notifications/claude/channel/permission_request\"),\n params: z.object({\n request_id: z.string(),\n tool_name: z.string(),\n description: z.string(),\n input_preview: z.string(),\n }),\n });\n\n mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {\n try {\n const res = await fetch(`${tandemUrl}/api/channel-permission`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n requestId: params.request_id,\n toolName: params.tool_name,\n description: params.description,\n inputPreview: params.input_preview,\n }),\n });\n if (!res.ok) {\n console.error(\n `[Channel] Permission relay got HTTP ${res.status} — browser may not see prompt`,\n );\n }\n } catch (err) {\n console.error(\"[Channel] Failed to forward permission request:\", err);\n }\n });\n\n console.error(`[Channel] Tandem channel shim starting (server: ${tandemUrl})`);\n\n if (!opts.skipReachabilityLog) {\n const reachable = await checkServerReachable(tandemUrl);\n if (!reachable) {\n console.error(`[Channel] Cannot reach Tandem server at ${tandemUrl}`);\n console.error(\"[Channel] Start it with: tandem start\");\n // Continue anyway — the event bridge will retry, and the server may start later\n }\n }\n\n const transport = new StdioServerTransport();\n await mcp.connect(transport);\n console.error(\"[Channel] Connected to Claude Code via stdio\");\n\n startEventBridge(mcp, tandemUrl).catch((err) => {\n console.error(\"[Channel] Event bridge failed unexpectedly:\", err);\n process.exit(1);\n });\n}\n\nasync function checkServerReachable(url: string, timeoutMs = 2000): Promise<boolean> {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n console.error(\n `[Channel] Invalid TANDEM_URL: \"${url}\" — expected format: http://localhost:3479`,\n );\n return false;\n }\n const port = parseInt(parsed.port || String(DEFAULT_MCP_PORT), 10);\n return new Promise((resolve) => {\n const socket = createConnection({ port, host: parsed.hostname }, () => {\n socket.destroy();\n resolve(true);\n });\n socket.setTimeout(timeoutMs);\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(false);\n });\n socket.on(\"error\", (err) => {\n console.error(`[Channel] Server probe failed: ${err.message}`);\n socket.destroy();\n resolve(false);\n });\n });\n}\n","/**\n * Tandem channel subcommand — npm-delivered entry for the plugin\n * `tandem-channel` MCP server. Runs the unified preflight, then hands off to\n * the shared channel shim runtime in src/channel/run.ts.\n */\n\nimport { runChannel } from \"../channel/run.js\";\nimport { ensureTandemServer } from \"./preflight.js\";\n\nexport async function runChannelCli(): Promise<void> {\n await ensureTandemServer();\n await runChannel({ skipReachabilityLog: true });\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst SERVER_DIST = resolve(__dirname, \"../server/index.js\");\n\nexport function runStart(): void {\n if (!existsSync(SERVER_DIST)) {\n console.error(`[Tandem] Server not found at ${SERVER_DIST}`);\n console.error(\"[Tandem] The installation may be corrupted. Try: npm install -g tandem-editor\");\n process.exit(1);\n }\n\n console.error(\"[Tandem] Starting server...\");\n\n const proc = spawn(\"node\", [SERVER_DIST], {\n stdio: \"inherit\",\n env: { ...process.env, TANDEM_OPEN_BROWSER: \"1\" },\n });\n\n proc.on(\"error\", (err) => {\n console.error(`[Tandem] Failed to start server: ${err.message}`);\n process.exit(1);\n });\n\n proc.on(\"exit\", (code) => {\n process.exit(code ?? 0);\n });\n\n // Forward signals — proc.kill() with no argument uses SIGTERM on Unix\n // and TerminateProcess on Windows (correct cross-platform behavior).\n // On Windows SIGTERM is not emitted by the OS, but SIGINT (Ctrl+C) works.\n // Both are listed for Unix compatibility.\n for (const sig of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.once(sig, () => proc.kill());\n }\n}\n","/**\n * Tandem CLI — entry point for the `tandem` global command.\n * Shebang is added by tsup banner at build time.\n *\n * Usage:\n * tandem Start the Tandem server and open the browser\n * tandem setup Register Tandem MCP tools with Claude Code / Claude Desktop\n * tandem setup --force Register even if no Claude install is auto-detected\n * tandem --help Show this help\n * tandem --version Show version\n */\n\nimport updateNotifier from \"update-notifier\";\n\n// Injected at build time by tsup define; declared here for TypeScript\ndeclare const __TANDEM_VERSION__: string;\nconst version = typeof __TANDEM_VERSION__ !== \"undefined\" ? __TANDEM_VERSION__ : \"0.0.0-dev\";\n\nconst args = process.argv.slice(2);\n\n// Skip the update notifier for stdio subcommands — the output is machine-consumed\n// by Claude Desktop's plugin loader, and any incidental write risks corrupting\n// the MCP wire or producing log noise no human will ever read.\nconst isStdioMode = args[0] === \"mcp-stdio\" || args[0] === \"channel\";\nif (!isStdioMode) {\n updateNotifier({ pkg: { name: \"tandem-editor\", version } }).notify();\n}\n\nif (args.includes(\"--help\") || args.includes(\"-h\")) {\n console.log(`tandem v${version}\n\nUsage:\n tandem Start Tandem server and open the browser\n tandem setup Register MCP tools with Claude Code / Claude Desktop\n tandem setup --force Register to default paths regardless of detection\n tandem setup --with-channel-shim Also register the stdio channel shim (legacy opt-in)\n tandem mcp-stdio Run as a stdio MCP server proxying to local HTTP\n (used by the plugin's Cowork bridge; requires\n tandem server running on the host)\n tandem channel Run the Tandem channel shim (stdio MCP)\n (used by the plugin's tandem-channel entry)\n tandem --version\n tandem --help\n`);\n process.exit(0);\n}\n\nif (args.includes(\"--version\") || args.includes(\"-v\")) {\n console.log(version);\n process.exit(0);\n}\n\ntry {\n if (args[0] === \"setup\") {\n const { runSetup } = await import(\"./setup.js\");\n await runSetup({\n force: args.includes(\"--force\"),\n withChannelShim: args.includes(\"--with-channel-shim\"),\n });\n } else if (args[0] === \"mcp-stdio\") {\n const { runMcpStdio } = await import(\"./mcp-stdio.js\");\n await runMcpStdio();\n } else if (args[0] === \"channel\") {\n const { runChannelCli } = await import(\"./channel.js\");\n await runChannelCli();\n } else if (!args[0] || args[0] === \"start\") {\n const { runStart } = await import(\"./start.js\");\n runStart();\n } else {\n console.error(`Unknown command: ${args[0]}`);\n console.error(\"Run 'tandem --help' for usage.\");\n process.exit(1);\n }\n} catch (err) {\n console.error(`\\n[Tandem] Fatal error: ${err instanceof Error ? err.message : String(err)}`);\n console.error(\"If this persists, try reinstalling: npm install -g tandem-editor\\n\");\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IACa,kBAIA,eACA,gBAEA,cACA,iBAqGA,qBACA;AA/Gb;AAAA;AAAA;AACO,IAAM,mBAAmB;AAIzB,IAAM,gBAAgB,KAAK,OAAO;AAClC,IAAM,iBAAiB,KAAK,OAAO;AAEnC,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AAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAc/B;AACC,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,IAAI,GAAG;AACrD,UAAQ,IAAI,OAAO;AACnB,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAI;AACF,MAAI,KAAK,CAAC,MAAM,SAAS;AACvB,UAAM,EAAE,UAAAC,UAAS,IAAI,MAAM;AAC3B,UAAMA,UAAS;AAAA,MACb,OAAO,KAAK,SAAS,SAAS;AAAA,MAC9B,iBAAiB,KAAK,SAAS,qBAAqB;AAAA,IACtD,CAAC;AAAA,EACH,WAAW,KAAK,CAAC,MAAM,aAAa;AAClC,UAAM,EAAE,aAAAC,aAAY,IAAI,MAAM;AAC9B,UAAMA,aAAY;AAAA,EACpB,WAAW,KAAK,CAAC,MAAM,WAAW;AAChC,UAAM,EAAE,eAAAC,eAAc,IAAI,MAAM;AAChC,UAAMA,eAAc;AAAA,EACtB,WAAW,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC,MAAM,SAAS;AAC1C,UAAM,EAAE,UAAAC,UAAS,IAAI,MAAM;AAC3B,IAAAA,UAAS;AAAA,EACX,OAAO;AACL,YAAQ,MAAM,oBAAoB,KAAK,CAAC,CAAC,EAAE;AAC3C,YAAQ,MAAM,gCAAgC;AAC9C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,SAAS,KAAK;AACZ,UAAQ,MAAM;AAAA,wBAA2B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAC3F,UAAQ,MAAM,oEAAoE;AAClF,UAAQ,KAAK,CAAC;AAChB;","names":["readFileSync","dirname","resolve","fileURLToPath","__dirname","StdioServerTransport","args","resolve","existsSync","dirname","resolve","fileURLToPath","__dirname","runSetup","runMcpStdio","runChannelCli","runStart"]}
|
|
1
|
+
{"version":3,"sources":["../../src/shared/constants.ts","../../src/cli/skill-content.ts","../../src/cli/setup.ts","../../src/shared/cli-runtime.ts","../../src/cli/preflight.ts","../../src/cli/mcp-stdio.ts","../../src/shared/utils.ts","../../src/server/events/types.ts","../../src/channel/event-bridge.ts","../../src/channel/run.ts","../../src/cli/channel.ts","../../src/cli/start.ts","../../src/cli/index.ts"],"sourcesContent":["export const DEFAULT_WS_PORT = 3478;\nexport const DEFAULT_MCP_PORT = 3479;\n\n/** File extensions the server accepts for opening. */\nexport const SUPPORTED_EXTENSIONS = new Set([\".md\", \".txt\", \".html\", \".htm\", \".docx\"]);\nexport const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB\nexport const MAX_WS_PAYLOAD = 10 * 1024 * 1024; // 10MB\nexport const MAX_WS_CONNECTIONS = 4;\nexport const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes\nexport const SESSION_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days\nexport const TYPING_DEBOUNCE = 3000; // 3 seconds\nexport const DISCONNECT_DEBOUNCE_MS = 3000; // 3 seconds before showing \"server not reachable\"\nexport const PROLONGED_DISCONNECT_MS = 30_000; // 30 seconds before showing App-level disconnect banner\nexport const OVERLAY_STALE_DEBOUNCE = 200; // 200ms\n\nexport const HIGHLIGHT_COLORS: Record<string, string> = {\n yellow: \"rgba(255, 235, 59, 0.3)\",\n red: \"rgba(244, 67, 54, 0.3)\",\n green: \"rgba(76, 175, 80, 0.3)\",\n blue: \"rgba(33, 150, 243, 0.3)\",\n purple: \"rgba(156, 39, 176, 0.3)\",\n};\n\nexport const TANDEM_MODE_DEFAULT = \"tandem\" as const;\nexport const TANDEM_MODE_KEY = \"tandem:mode\";\nexport const TANDEM_SETTINGS_KEY = \"tandem:settings\";\n// Panel-width localStorage keys.\n//\n// NOTE: these use legacy hyphen naming (vs the neighboring colon convention\n// `tandem:mode`/`tandem:settings`) because they predate the colon scheme and\n// changing the strings would invalidate every existing user's saved widths.\n// Do not \"fix\" the style — the key string is the persistence contract.\n//\n// Right-side panel width is shared between the tabbed layout and the\n// three-panel right panel. The left key only applies in three-panel mode.\nexport const PANEL_WIDTH_KEY = \"tandem-panel-width\";\nexport const LEFT_PANEL_WIDTH_KEY = \"tandem-left-panel-width\";\n\nexport type PanelSide = \"left\" | \"right\";\n\n/**\n * Maps a panel side to its localStorage key. Using a Record instead of two\n * bare constants makes the \"both handles write to the same key\" regression\n * (#228) structurally impossible — you can't accidentally map both sides to\n * the same value at a callsite.\n *\n * Uses `as const satisfies Record<PanelSide, string>` so the value type stays\n * as the literal strings rather than widening to `string` — this preserves\n * the persistence-key identity at every callsite while still enforcing\n * exhaustive coverage of `PanelSide`.\n */\nexport const PANEL_WIDTH_KEYS = {\n left: LEFT_PANEL_WIDTH_KEY,\n right: PANEL_WIDTH_KEY,\n} as const satisfies Record<PanelSide, string>;\nexport const SELECTION_DWELL_DEFAULT_MS = 1000;\nexport const SELECTION_DWELL_MIN_MS = 500;\nexport const SELECTION_DWELL_MAX_MS = 3000;\n\n// Large file thresholds\nexport const CHARS_PER_PAGE = 3_000;\nexport const LARGE_FILE_PAGE_THRESHOLD = 50;\nexport const VERY_LARGE_FILE_PAGE_THRESHOLD = 100;\n\nexport const CLAUDE_PRESENCE_COLOR = \"#6366f1\";\nexport const CLAUDE_FOCUS_OPACITY = 0.1;\n\nexport const CTRL_ROOM = \"__tandem_ctrl__\";\n\n/** Y.Map key constants — centralized to prevent silent bugs from string typos. */\nexport const Y_MAP_ANNOTATIONS = \"annotations\";\nexport const Y_MAP_AWARENESS = \"awareness\";\nexport const Y_MAP_USER_AWARENESS = \"userAwareness\";\nexport const Y_MAP_MODE = \"mode\";\nexport const Y_MAP_DWELL_MS = \"selectionDwellMs\";\nexport const Y_MAP_CHAT = \"chat\";\nexport const Y_MAP_DOCUMENT_META = \"documentMeta\";\nexport const Y_MAP_ANNOTATION_REPLIES = \"annotationReplies\";\nexport const Y_MAP_SAVED_AT_VERSION = \"savedAtVersion\";\nexport const Y_MAP_AUTHORSHIP = \"authorship\";\n\nexport const AUTHORSHIP_TOGGLE_KEY = \"tandem:showAuthorship\";\n\nexport const SERVER_INFO_DIR = \".tandem\";\nexport const SERVER_INFO_FILE = \".tandem/.server-info\";\n\nexport const RECENT_FILES_KEY = \"tandem:recentFiles\";\nexport const RECENT_FILES_CAP = 20;\n\nexport const USER_NAME_KEY = \"tandem:userName\";\nexport const USER_NAME_DEFAULT = \"You\";\nexport const USER_NAME_EVENT = \"tandem:user-name-changed\";\nexport const USER_NAME_MAX_LEN = 40;\n\n// Toast notifications\nexport const TOAST_DISMISS_MS = { error: 8000, warning: 6000, info: 4000 } as const;\nexport const MAX_VISIBLE_TOASTS = 5;\nexport const NOTIFICATION_BUFFER_SIZE = 50;\n\n// Onboarding tutorial\nexport const TUTORIAL_COMPLETED_KEY = \"tandem:tutorialCompleted\";\nexport const TUTORIAL_ANNOTATION_PREFIX = \"tutorial-\";\n\n// Editor layout\nexport const EDITOR_WIDTH_MODE_KEY = \"tandem:editorWidthMode\";\n\n// Channel / event queue\nexport const CHANNEL_EVENT_BUFFER_SIZE = 200;\nexport const CHANNEL_EVENT_BUFFER_AGE_MS = 60_000; // 60 seconds\nexport const CHANNEL_SSE_KEEPALIVE_MS = 15_000; // 15 seconds\nexport const CHANNEL_MAX_RETRIES = 5;\nexport const CHANNEL_RETRY_DELAY_MS = 2_000;\n\n/** Tauri WebView origin hostname — must be accepted alongside localhost. */\nexport const TAURI_HOSTNAME = \"tauri.localhost\";\n\n// Zoom persistence (Tauri desktop)\nexport const ZOOM_STORAGE_KEY = \"tandem:zoomLevel\";\nexport const ZOOM_MIN = 0.5;\nexport const ZOOM_MAX = 2.0;\nexport const ZOOM_DEFAULT = 1.0;\n","/**\n * SKILL.md content installed to ~/.claude/skills/tandem/ by `tandem setup`.\n * Single source of truth lives at `skills/tandem/SKILL.md`. This module\n * reads that file at module load so the plugin install path and the\n * `tandem setup` install path always deliver byte-identical content.\n *\n * The file is shipped via package.json `files: [\"skills/\", ...]`, and the\n * CLI entry (dist/cli/index.js) is not self-contained — so at runtime the\n * relative path `../../skills/tandem/SKILL.md` resolves from either\n * dist/cli/ (tsx dev) or dist/cli/ (npm install) to the package-root\n * `skills/tandem/SKILL.md`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst SKILL_PATH = resolve(__dirname, \"../../skills/tandem/SKILL.md\");\n\nexport const SKILL_CONTENT = readFileSync(SKILL_PATH, \"utf-8\");\n","import { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { copyFile, mkdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DEFAULT_MCP_PORT } from \"../shared/constants.js\";\nimport { SKILL_CONTENT } from \"./skill-content.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// Paths are anchored to the package root (dist/cli/ resolves up two levels).\nconst PACKAGE_ROOT = resolve(__dirname, \"../..\");\nconst CHANNEL_DIST = resolve(PACKAGE_ROOT, \"dist/channel/index.js\");\n\nconst MCP_URL = `http://localhost:${DEFAULT_MCP_PORT}`;\n\nexport interface McpEntry {\n type?: \"http\";\n url?: string;\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n}\n\nexport interface McpEntries {\n tandem: McpEntry;\n \"tandem-channel\"?: McpEntry;\n}\n\nexport interface BuildMcpEntriesOptions {\n /** Include the legacy stdio channel shim. Defaults to false — the plugin\n * monitor handles event push for modern installs. Users on older setups\n * can run `tandem setup --with-channel-shim` to preserve the shim. */\n withChannelShim?: boolean;\n nodeBinary?: string;\n}\n\nexport function buildMcpEntries(\n channelPath: string,\n opts: BuildMcpEntriesOptions = {},\n): McpEntries {\n const entries: McpEntries = {\n tandem: { type: \"http\", url: `${MCP_URL}/mcp` },\n };\n if (opts.withChannelShim) {\n entries[\"tandem-channel\"] = {\n command: opts.nodeBinary ?? \"node\",\n args: [channelPath],\n env: { TANDEM_URL: MCP_URL },\n };\n }\n return entries;\n}\n\nexport interface DetectedTarget {\n label: string;\n configPath: string;\n}\n\ninterface DetectOptions {\n homeOverride?: string;\n force?: boolean;\n}\n\nexport function detectTargets(opts: DetectOptions = {}): DetectedTarget[] {\n const home = opts.homeOverride ?? homedir();\n const targets: DetectedTarget[] = [];\n\n // Claude Code — cross-platform.\n // MCP servers are configured in ~/.claude.json under the \"mcpServers\" key.\n // Detect if the file exists OR if ~/.claude directory exists (Claude Code is installed).\n // With --force, always include regardless.\n const claudeCodeConfig = join(home, \".claude.json\");\n const claudeCodeDir = join(home, \".claude\");\n if (opts.force || existsSync(claudeCodeConfig) || existsSync(claudeCodeDir)) {\n targets.push({ label: \"Claude Code\", configPath: claudeCodeConfig });\n }\n\n // Claude Desktop — platform-specific.\n // Only detect if the config file already exists (user has launched Desktop at least once).\n // With --force, always include.\n let desktopConfig: string | null = null;\n if (process.platform === \"win32\") {\n const appdata = process.env.APPDATA ?? join(home, \"AppData\", \"Roaming\");\n desktopConfig = join(appdata, \"Claude\", \"claude_desktop_config.json\");\n } else if (process.platform === \"darwin\") {\n desktopConfig = join(\n home,\n \"Library\",\n \"Application Support\",\n \"Claude\",\n \"claude_desktop_config.json\",\n );\n } else {\n desktopConfig = join(home, \".config\", \"claude\", \"claude_desktop_config.json\");\n }\n\n if (desktopConfig && (opts.force || existsSync(desktopConfig))) {\n targets.push({ label: \"Claude Desktop\", configPath: desktopConfig });\n }\n\n return targets;\n}\n\n/**\n * Atomic write: write to a temp file in the SAME directory as the destination,\n * then rename. Using the same directory avoids EXDEV errors on Windows when\n * %TEMP% and %APPDATA% are on different drives.\n */\nasync function atomicWrite(content: string, dest: string): Promise<void> {\n const tmp = join(dirname(dest), `.tandem-setup-${randomUUID()}.tmp`);\n await writeFile(tmp, content, \"utf-8\");\n try {\n await rename(tmp, dest);\n } catch (err) {\n // EXDEV: cross-device link — fall back to copy + delete\n if ((err as NodeJS.ErrnoException).code === \"EXDEV\") {\n await copyFile(tmp, dest);\n await unlink(tmp).catch((cleanupErr: Error) => {\n console.error(` Warning: could not remove temp file ${tmp}: ${cleanupErr.message}`);\n });\n } else {\n await unlink(tmp).catch((cleanupErr: Error) => {\n console.error(` Warning: could not remove temp file ${tmp}: ${cleanupErr.message}`);\n });\n throw err;\n }\n }\n}\n\nexport async function applyConfig(configPath: string, entries: McpEntries): Promise<void> {\n // Read existing config or start fresh — no existsSync guard needed.\n // ENOENT and malformed JSON start fresh; other errors (permissions, disk) propagate.\n let existing: { mcpServers?: Record<string, McpEntry> } = {};\n try {\n existing = JSON.parse(readFileSync(configPath, \"utf-8\"));\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n // File doesn't exist yet — start fresh\n } else if (err instanceof SyntaxError) {\n // Don't silently wipe the user's other mcpServers. Copy the malformed\n // file to a .broken-<ts> sibling first so they can recover it. If the\n // backup itself fails, refuse to overwrite — runSetup's per-target\n // try/catch reports the partial failure.\n const backupPath = `${configPath}.broken-${Date.now()}`;\n try {\n await copyFile(configPath, backupPath);\n console.error(\n ` Warning: ${configPath} contains malformed JSON — backed up to ${basename(backupPath)}, replacing with fresh config`,\n );\n } catch (copyErr) {\n console.error(\n ` Warning: ${configPath} contains malformed JSON and backup failed (${\n copyErr instanceof Error ? copyErr.message : copyErr\n }) — refusing to overwrite. Fix the JSON manually and rerun 'tandem setup'.`,\n );\n throw copyErr;\n }\n } else {\n throw err; // Permission errors, disk errors, etc. should not be silently swallowed\n }\n }\n\n const updated = {\n ...existing,\n mcpServers: {\n ...(existing.mcpServers ?? {}),\n ...entries,\n },\n };\n\n await mkdir(dirname(configPath), { recursive: true });\n await atomicWrite(JSON.stringify(updated, null, 2) + \"\\n\", configPath);\n}\n\n/**\n * Install the Tandem skill to ~/.claude/skills/tandem/SKILL.md.\n * Claude Code auto-discovers skills in this directory and uses the description\n * field to trigger them when tandem_* tools are present.\n */\nexport async function installSkill(opts: { homeOverride?: string } = {}): Promise<void> {\n const home = opts.homeOverride ?? homedir();\n const skillPath = join(home, \".claude\", \"skills\", \"tandem\", \"SKILL.md\");\n await mkdir(dirname(skillPath), { recursive: true });\n await atomicWrite(SKILL_CONTENT, skillPath);\n}\n\n/**\n * Returns true if the channel-shim build artifact exists at the given path.\n * Exported so the prereq check can be tested without spawning runSetup.\n */\nexport function validateChannelShimPrereq(channelPath: string): boolean {\n return existsSync(channelPath);\n}\n\n/** Run the setup command. Writes MCP config to all detected Claude installs. */\nexport async function runSetup(\n opts: { force?: boolean; withChannelShim?: boolean } = {},\n): Promise<void> {\n console.error(\"\\nTandem Setup\\n\");\n\n if (opts.withChannelShim && !validateChannelShimPrereq(CHANNEL_DIST)) {\n console.error(\n `Error: --with-channel-shim requires dist/channel/index.js at ${CHANNEL_DIST}\\n` +\n `Run 'npm run build' first, or drop --with-channel-shim to use the plugin monitor.`,\n );\n process.exit(1);\n }\n\n console.error(\"Detecting Claude installations...\");\n\n const targets = detectTargets({ force: opts.force });\n\n if (targets.length === 0) {\n console.error(\n \" No Claude installations detected.\\n\" +\n \" If Claude Code is installed, ensure ~/.claude exists.\\n\" +\n \" You can force configuration to default paths with: tandem setup --force\",\n );\n return;\n }\n\n for (const t of targets) {\n console.error(` Found: ${t.label} (${t.configPath})`);\n }\n\n console.error(\"\\nWriting MCP configuration...\");\n const entries = buildMcpEntries(CHANNEL_DIST, { withChannelShim: opts.withChannelShim });\n\n let failures = 0;\n for (const t of targets) {\n try {\n await applyConfig(t.configPath, entries);\n console.error(` \\x1b[32m✓\\x1b[0m ${t.label}`);\n } catch (err) {\n failures++;\n console.error(\n ` \\x1b[31m✗\\x1b[0m ${t.label}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n if (failures === targets.length) {\n console.error(\"\\nSetup failed — could not write any configuration. Check file permissions.\");\n process.exit(1);\n } else if (failures > 0) {\n console.error(\n `\\nSetup partially complete (${failures} target(s) failed). Start Tandem with: tandem`,\n );\n } else {\n console.error(\"\\nSetup complete! Start Tandem with: tandem\");\n console.error(\"Then in Claude, your tandem_* tools will be available.\");\n }\n\n // Install Claude Code skill (best-effort — doesn't block MCP setup)\n console.error(\"\\nInstalling Claude Code skill...\");\n try {\n await installSkill();\n console.error(\" \\x1b[32m✓\\x1b[0m ~/.claude/skills/tandem/SKILL.md\");\n } catch (err) {\n console.error(\n ` \\x1b[33m⚠\\x1b[0m Could not install skill: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // Plugin install instructions (shown on all successful setups)\n if (failures < targets.length) {\n const pluginManifest = join(PACKAGE_ROOT, \".claude-plugin\", \"plugin.json\");\n const devInstructions = existsSync(pluginManifest)\n ? ` Or for development, load directly from this package:\\n\\n` +\n ` claude --plugin-dir ${PACKAGE_ROOT}\\n\\n`\n : ` (Development plugin dir not found at ${pluginManifest}; skipping local-plugin instructions.)\\n\\n`;\n\n console.error(\n \"\\n\\x1b[1mReal-time push notifications (recommended):\\x1b[0m\\n\" +\n \" Install the Tandem plugin for instant events (one-time):\\n\\n\" +\n \" claude plugin marketplace add bloknayrb/tandem\\n\" +\n \" claude plugin install tandem@tandem-editor\\n\\n\" +\n devInstructions +\n \" Without the plugin, Claude still works but relies on tandem_checkInbox polling.\\n\",\n );\n }\n}\n","/**\n * Helpers shared by CLI stdio entry points (`mcp-stdio`, `channel`) and the\n * standalone server / monitor binaries that all speak MCP over stdout.\n */\n\nimport { DEFAULT_MCP_PORT } from \"./constants.js\";\n\n/**\n * In stdio MCP mode, stdout is the JSON-RPC wire — any stray library write\n * corrupts the protocol. Redirect `console.log/warn/info` to stderr so\n * incidental logging is safe. Callers that also run in-process tests (e.g.\n * `src/monitor/index.ts`) can gate this behind `!process.env.VITEST`.\n */\nexport function redirectConsoleToStderr(): void {\n console.log = console.error;\n console.warn = console.error;\n console.info = console.error;\n}\n\n/**\n * Resolve the Tandem HTTP base URL used by stdio subcommands. Precedence is\n * (1) explicit override, (2) `TANDEM_URL` env var, (3) the default port on\n * localhost. The returned string has no trailing slash so callers can\n * concatenate `/health`, `/mcp`, etc. without double-slash.\n */\nexport function resolveTandemUrl(override?: string): string {\n const raw = override ?? process.env.TANDEM_URL ?? `http://localhost:${DEFAULT_MCP_PORT}`;\n return raw.replace(/\\/$/, \"\");\n}\n","/**\n * Shared preflight check for stdio MCP subcommands.\n *\n * Both `tandem mcp-stdio` and `tandem channel` need a live Tandem server on\n * localhost before they can do anything useful. Two flavors:\n *\n * - `ensureTandemServer` — fail fast via stderr + exit(1) when the server\n * isn't reachable. Used by `tandem channel`, whose stdio transport can't\n * meaningfully respond on its own.\n * - `probeTandemServer` — returns a result without side effects. Used by\n * `tandem mcp-stdio`, which starts its stdio transport before preflight\n * so it can synthesize -32000 JSON-RPC errors for any in-flight request\n * before exiting (issue #336).\n */\n\nimport { resolveTandemUrl } from \"../shared/cli-runtime.js\";\n\nconst DEFAULT_TIMEOUT_MS = 2000;\n\nexport interface PreflightOptions {\n url?: string;\n timeoutMs?: number;\n}\n\n// Note: \"unreachable\" is a catch-all for any non-HTTP-status failure —\n// DNS, TLS, timeout, ECONNREFUSED, RST all land here. \"unhealthy\" is\n// strictly non-2xx responses from /health.\nexport type PreflightProbe =\n | { ok: true }\n | { ok: false; url: string; reason: string; kind: \"unreachable\" | \"unhealthy\" };\n\nexport async function probeTandemServer(opts: PreflightOptions = {}): Promise<PreflightProbe> {\n const url = resolveTandemUrl(opts.url);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const res = await fetch(`${url}/health`, { signal: controller.signal });\n if (!res.ok) {\n return {\n ok: false,\n url,\n reason: `health endpoint returned HTTP ${res.status}`,\n kind: \"unhealthy\",\n };\n }\n return { ok: true };\n } catch (err) {\n return {\n ok: false,\n url,\n reason: err instanceof Error ? err.message : String(err),\n kind: \"unreachable\",\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport async function ensureTandemServer(opts: PreflightOptions = {}): Promise<void> {\n const probe = await probeTandemServer(opts);\n if (!probe.ok) {\n const guidance =\n probe.kind === \"unreachable\"\n ? \"Start the Tauri app or run `tandem start` on the host, then retry.\"\n : \"The Tandem server is running but unhealthy — check the host logs.\";\n process.stderr.write(\n `[tandem] Tandem server preflight failed at ${probe.url} (${probe.reason}).\\n` +\n `[tandem] ${guidance}\\n`,\n );\n process.exit(1);\n }\n}\n","/**\n * Tandem mcp-stdio subcommand — stdio ↔ Streamable HTTP JSON-RPC proxy.\n *\n * Claude Desktop's plugin loader bridges stdio MCP servers into sandboxed\n * sessions but not HTTP MCP servers, so plugin-cached stdio entries that\n * forward to the local HTTP MCP endpoint are the only supported way to\n * surface tandem_* tools into those sessions.\n *\n * Raw message forwarding: no handler registrations, no per-method logic.\n * Any message the upstream emits (tool results, notifications, future\n * methods we haven't heard of) reaches the stdio client unchanged.\n *\n * Error surfacing (issue #336): the stdio transport is started before\n * preflight and http.start(), and early messages are buffered until the\n * upstream is ready. If the upstream never becomes ready — or dies mid-\n * session — every in-flight request ID is answered with a synthesized\n * `-32000` JSON-RPC error instead of a silent stdio close. Plugin hosts\n * surface `-32000` as actionable; a silent close is what produces \"tools\n * never appear in Cowork\" with nothing diagnosable in the logs.\n *\n * Intentional: no reconnection logic. If the upstream HTTP server dies\n * mid-session, we synthesize errors for pending requests and exit 1.\n * The plugin loader will respawn us on the next tool call and preflight\n * will re-run with a fresh, accurate error if the server is still down.\n */\n\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { redirectConsoleToStderr, resolveTandemUrl } from \"../shared/cli-runtime.js\";\nimport { probeTandemServer } from \"./preflight.js\";\n\nredirectConsoleToStderr();\n\n// After preflight or http.start() fails we wait ~1.5s for any already-in-\n// flight `initialize` from the plugin loader to land on stdin and receive\n// a -32000 reply before tear-down. Sizing covers stdin-read lag between\n// preflight resolution and first message arrival — independent of\n// preflight's own fetch timeout.\nconst PREFLIGHT_GRACE_MS = 1500;\n\n// Last-gasp handlers for truly unexpected crashes: write one diagnostic to\n// stderr before exit. Installed at module load; process.once bounds each\n// handler to a single fire. No -32000 synthesis here because pendingIds\n// lives inside runMcpStdio()'s closure.\nprocess.once(\"uncaughtException\", (err: Error) => {\n process.stderr.write(\n `[tandem mcp-stdio] uncaughtException: ${err.message}\\n${err.stack ?? \"\"}\\n`,\n );\n process.exit(1);\n});\nprocess.once(\"unhandledRejection\", (reason: unknown) => {\n const detail = reason instanceof Error ? reason.message : String(reason);\n process.stderr.write(`[tandem mcp-stdio] unhandledRejection: ${detail}\\n`);\n process.exit(1);\n});\n\nexport async function runMcpStdio(): Promise<void> {\n const baseUrl = resolveTandemUrl();\n\n const http = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));\n const stdio = new StdioServerTransport();\n\n // On upstream failure we synthesize -32000 for every entry before exit.\n const pendingIds = new Set<string | number>();\n // Messages arriving before httpReady flips; either drained and forwarded\n // on success, or each request answered with -32000 on preflight/http-start\n // failure.\n const preReadyBuffer: JSONRPCMessage[] = [];\n let shuttingDown = false;\n let httpReady = false;\n\n async function sendErrorResponse(\n id: string | number,\n message: string,\n detail?: string,\n ): Promise<void> {\n const errorResponse: JSONRPCMessage = {\n jsonrpc: \"2.0\",\n id,\n error: {\n // -32000 is the implementation-defined server error range per\n // JSON-RPC 2.0 §5.1 — upstream unavailability is an application-\n // level condition, not a generic Internal Error.\n code: -32000,\n message,\n ...(detail !== undefined ? { data: { detail } } : {}),\n },\n };\n try {\n await stdio.send(errorResponse);\n } catch (err) {\n // stdio already torn down; log so synth failures during shutdown\n // (e.g., http.onclose racing stdio.onclose) aren't silently dropped —\n // a silent drop here would recreate exactly the failure mode this\n // module exists to prevent.\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(\n `[tandem mcp-stdio] failed to send synthesized error for id ${id}: ${detail}\\n`,\n );\n }\n }\n\n function forwardToUpstream(msg: JSONRPCMessage): void {\n const requestId = getRequestId(msg);\n if (requestId !== undefined) pendingIds.add(requestId);\n http.send(msg).catch((err: unknown) => {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] upstream send failed: ${detail}\\n`);\n // `delete` returns true iff the id was still pending — prevents double-\n // synth if a future change ever allows synthesizePending to fire while\n // http.send is still in flight. (Not a current bug; belt-and-suspenders.)\n if (requestId !== undefined && pendingIds.delete(requestId)) {\n void sendErrorResponse(requestId, \"Tandem HTTP upstream unreachable\", detail);\n }\n });\n }\n\n async function synthesizeBuffered(message: string, detail?: string): Promise<void> {\n const buffered = preReadyBuffer.splice(0);\n const ids = buffered\n .map((msg) => getRequestId(msg))\n .filter((id): id is string | number => id !== undefined);\n for (const id of ids) {\n await sendErrorResponse(id, message, detail);\n }\n }\n\n async function synthesizePending(message: string, detail?: string): Promise<void> {\n if (pendingIds.size === 0) return;\n const ids = [...pendingIds];\n pendingIds.clear();\n await Promise.all(ids.map((id) => sendErrorResponse(id, message, detail)));\n }\n\n const shutdown = async (\n code = 0,\n synth?: { message: string; detail?: string },\n ): Promise<never> => {\n if (!shuttingDown) {\n shuttingDown = true;\n if (synth) {\n await synthesizeBuffered(synth.message, synth.detail);\n await synthesizePending(synth.message, synth.detail);\n }\n await http.close().catch((err: unknown) => {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] http.close failed: ${detail}\\n`);\n });\n await stdio.close().catch((err: unknown) => {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] stdio.close failed: ${detail}\\n`);\n });\n }\n process.exit(code);\n };\n\n // Plugin hosts typically send `initialize` immediately after spawn (MCP\n // lifecycle §initialization). Deferring shutdown by PREFLIGHT_GRACE_MS\n // lets that request land during the preflight/start window and receive\n // a -32000 reply rather than a silent stdio close. stdio.onclose\n // short-circuits this if the loader closes stdin first.\n function deferredShutdown(synth: { message: string; detail?: string }): void {\n setTimeout(() => void shutdown(1, synth), PREFLIGHT_GRACE_MS);\n }\n\n stdio.onmessage = (msg: JSONRPCMessage) => {\n if (!httpReady) {\n preReadyBuffer.push(msg);\n return;\n }\n forwardToUpstream(msg);\n };\n\n http.onmessage = (msg: JSONRPCMessage) => {\n const responseId = getResponseId(msg);\n stdio.send(msg).then(\n () => {\n if (responseId !== undefined) pendingIds.delete(responseId);\n },\n (err: unknown) => {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(\n `[tandem mcp-stdio] stdio write failed for id ${responseId ?? \"<notification>\"}: ${detail}\\n`,\n );\n // Leave responseId in pendingIds — shutdown's synthesizePending will\n // retry via sendErrorResponse. If stdio is truly gone, that send also\n // fails and we log twice. Safe delete-after-send narrows the pending\n // window; it never widens for well-ordered responses.\n void shutdown(1, {\n message: \"Tandem stdio write failed\",\n detail,\n });\n },\n );\n };\n\n stdio.onerror = (err) => {\n process.stderr.write(`[tandem mcp-stdio] stdio error: ${err.message}\\n${err.stack ?? \"\"}\\n`);\n };\n http.onerror = (err) => {\n const cause = (err as { cause?: unknown }).cause;\n process.stderr.write(\n `[tandem mcp-stdio] http error: ${err.message}\\n${err.stack ?? \"\"}${cause !== undefined ? `\\ncause: ${cause}` : \"\"}\\n`,\n );\n };\n\n stdio.onclose = () => {\n void shutdown(0);\n };\n http.onclose = () => {\n // We've observed the current @modelcontextprotocol/sdk (0.20.x) only\n // firing onclose from inside its own close() method — i.e., as a\n // consequence of *our* shutdown. The synth branch below is defensive\n // for future SDK versions that may propagate socket-death as onclose.\n // The `shuttingDown` guard prevents double-synth when shutdown() calls\n // http.close() itself.\n if (shuttingDown) return;\n void shutdown(1, {\n message: \"Tandem HTTP upstream closed unexpectedly\",\n detail: \"upstream connection dropped mid-session\",\n });\n };\n\n // Start stdio BEFORE preflight so any `initialize` that arrives during\n // the preflight window is captured and either forwarded once upstream is\n // ready, or answered with -32000 if upstream never comes up.\n await stdio.start();\n\n const probe = await probeTandemServer({ url: baseUrl });\n if (!probe.ok) {\n const guidance =\n probe.kind === \"unreachable\"\n ? \"Start the Tauri app or run `tandem start` on the host, then retry.\"\n : \"The Tandem server is running but unhealthy — check the host logs.\";\n process.stderr.write(\n `[tandem mcp-stdio] Tandem server preflight failed at ${probe.url} (${probe.reason}).\\n` +\n `[tandem mcp-stdio] ${guidance}\\n`,\n );\n const synthMessage =\n probe.kind === \"unreachable\"\n ? \"Tandem server not running. Start the Tauri app or run `tandem start`.\"\n : \"Tandem server unhealthy (check host logs).\";\n deferredShutdown({ message: synthMessage, detail: probe.reason });\n return;\n }\n\n // The current @modelcontextprotocol/sdk's StreamableHTTPClientTransport.start()\n // only creates an AbortController and returns synchronously — this catch is\n // defensive for future SDK versions that may perform real I/O during start().\n try {\n await http.start();\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[tandem mcp-stdio] upstream http start failed: ${detail}\\n`);\n deferredShutdown({ message: \"Tandem HTTP upstream failed to start\", detail });\n return;\n }\n httpReady = true;\n\n // Held to preserve forwarding semantics — push through the normal path\n // now that upstream is ready. Note: forwardToUpstream does not await the\n // http.send, so buffered requests POST in parallel. Plugin hosts wait\n // for `initialize` to resolve before sending follow-ups per MCP spec, so\n // the buffer is usually ≤1 entry; we don't enforce serial ordering here.\n const buffered = preReadyBuffer.splice(0);\n for (const msg of buffered) forwardToUpstream(msg);\n}\n\nexport function getRequestId(msg: JSONRPCMessage): string | number | undefined {\n const m = msg as { id?: unknown; method?: unknown };\n if (typeof m.method !== \"string\") return undefined;\n if (typeof m.id === \"string\" || typeof m.id === \"number\") return m.id;\n return undefined;\n}\n\nexport function getResponseId(msg: JSONRPCMessage): string | number | undefined {\n const m = msg as { id?: unknown; method?: unknown };\n if (typeof m.method === \"string\") return undefined;\n if (typeof m.id === \"string\" || typeof m.id === \"number\") return m.id;\n return undefined;\n}\n","function generateId(prefix: string): string {\n return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function generateAnnotationId(): string {\n return generateId(\"ann\");\n}\n\nexport function generateMessageId(): string {\n return generateId(\"msg\");\n}\n\nexport function generateEventId(): string {\n return generateId(\"evt\");\n}\n\nexport function generateReplyId(): string {\n return generateId(\"rpl\");\n}\n\nexport function generateNotificationId(): string {\n return generateId(\"ntf\");\n}\n\nexport function generateAuthorshipId(author: \"user\" | \"claude\"): string {\n return generateId(author);\n}\n","/**\n * Event types for the Tandem → Claude Code channel.\n *\n * These events flow from browser-originated Y.Map changes through an SSE\n * endpoint to the channel shim, which pushes them into Claude Code as\n * `notifications/claude/channel` messages.\n */\n\nimport type { ReplyAuthor } from \"../../shared/types.js\";\n\n// --- Per-event payload interfaces ---\n\nexport interface AnnotationCreatedPayload {\n annotationId: string;\n annotationType: string;\n content: string;\n textSnippet: string;\n hasSuggestedText?: boolean;\n directedAt?: \"claude\";\n}\n\nexport interface AnnotationAcceptedPayload {\n annotationId: string;\n textSnippet: string;\n}\n\nexport interface AnnotationDismissedPayload {\n annotationId: string;\n textSnippet: string;\n}\n\nexport interface ChatMessagePayload {\n messageId: string;\n text: string;\n replyTo: string | null;\n anchor: { from: number; to: number; textSnapshot: string } | null;\n /** Buffered selection context at the time the chat message was sent. */\n selection?: { from: number; to: number; selectedText: string } | { selectedText: string };\n}\n\nexport interface DocumentOpenedPayload {\n fileName: string;\n format: string;\n}\n\nexport interface DocumentClosedPayload {\n fileName: string;\n}\n\nexport interface AnnotationReplyPayload {\n annotationId: string;\n replyId: string;\n replyText: string;\n replyAuthor: ReplyAuthor;\n textSnippet: string;\n}\n\nexport interface DocumentSwitchedPayload {\n fileName: string;\n}\n\n// --- Discriminated union ---\n\ninterface TandemEventBase {\n /** Timestamp-based unique ID for SSE `Last-Event-ID` reconnection. Format: `evt_<timestamp>_<rand>`. Roughly ordered but not strictly monotonic. */\n id: string;\n timestamp: number;\n /** Which document this event relates to (absent for global events). */\n documentId?: string;\n}\n\nexport type TandemEvent =\n | (TandemEventBase & { type: \"annotation:created\"; payload: AnnotationCreatedPayload })\n | (TandemEventBase & { type: \"annotation:accepted\"; payload: AnnotationAcceptedPayload })\n | (TandemEventBase & { type: \"annotation:dismissed\"; payload: AnnotationDismissedPayload })\n | (TandemEventBase & { type: \"annotation:reply\"; payload: AnnotationReplyPayload })\n | (TandemEventBase & { type: \"chat:message\"; payload: ChatMessagePayload })\n | (TandemEventBase & { type: \"document:opened\"; payload: DocumentOpenedPayload })\n | (TandemEventBase & { type: \"document:closed\"; payload: DocumentClosedPayload })\n | (TandemEventBase & { type: \"document:switched\"; payload: DocumentSwitchedPayload });\n\n/** Union of all event type discriminants. */\nexport type TandemEventType = TandemEvent[\"type\"];\n\n// Re-export from shared utils (single ID generation pattern)\nexport { generateEventId } from \"../../shared/utils.js\";\n\n// --- Parse guard for SSE consumers ---\n\nconst VALID_EVENT_TYPES = new Set<TandemEventType>([\n \"annotation:created\",\n \"annotation:accepted\",\n \"annotation:dismissed\",\n \"annotation:reply\",\n \"chat:message\",\n \"document:opened\",\n \"document:closed\",\n \"document:switched\",\n]);\n\n/**\n * Validate a JSON-parsed value as a TandemEvent.\n * Used by the event-bridge to safely consume SSE data.\n */\nexport function parseTandemEvent(raw: unknown): TandemEvent | null {\n if (\n typeof raw !== \"object\" ||\n raw === null ||\n !(\"id\" in raw) ||\n typeof (raw as Record<string, unknown>).id !== \"string\" ||\n !(\"type\" in raw) ||\n !VALID_EVENT_TYPES.has((raw as Record<string, unknown>).type as TandemEventType) ||\n !(\"timestamp\" in raw) ||\n typeof (raw as Record<string, unknown>).timestamp !== \"number\" ||\n !(\"payload\" in raw) ||\n typeof (raw as Record<string, unknown>).payload !== \"object\"\n ) {\n return null;\n }\n return raw as TandemEvent;\n}\n\n/**\n * Convert a TandemEvent into a human-readable string for the channel `content` field.\n * Claude sees this text inside `<channel source=\"tandem-channel\">` tags.\n */\nexport function formatEventContent(event: TandemEvent): string {\n const doc = event.documentId ? ` [doc: ${event.documentId}]` : \"\";\n\n switch (event.type) {\n case \"annotation:created\": {\n const { annotationType, content, textSnippet, hasSuggestedText, directedAt } = event.payload;\n const snippet = textSnippet ? ` on \"${textSnippet}\"` : \"\";\n const label = hasSuggestedText\n ? \"replacement\"\n : directedAt === \"claude\"\n ? \"question for Claude\"\n : annotationType;\n return `User created ${label}${snippet}: ${content || \"(no content)\"}${doc}`;\n }\n case \"annotation:accepted\": {\n const { annotationId, textSnippet } = event.payload;\n return `User accepted annotation ${annotationId}${textSnippet ? ` (\"${textSnippet}\")` : \"\"}${doc}`;\n }\n case \"annotation:dismissed\": {\n const { annotationId, textSnippet } = event.payload;\n return `User dismissed annotation ${annotationId}${textSnippet ? ` (\"${textSnippet}\")` : \"\"}${doc}`;\n }\n case \"annotation:reply\": {\n const { annotationId, replyAuthor, replyText, textSnippet } = event.payload;\n const who = replyAuthor === \"claude\" ? \"Claude\" : \"User\";\n const snippet = textSnippet ? ` (on \"${textSnippet}\")` : \"\";\n return `${who} replied to annotation ${annotationId}${snippet}: ${replyText}${doc}`;\n }\n case \"chat:message\": {\n const { text, replyTo, selection } = event.payload;\n const reply = replyTo ? ` (replying to ${replyTo})` : \"\";\n const sel =\n selection && selection.selectedText\n ? ` [selection: \"${selection.selectedText}\"${\"from\" in selection ? ` (${selection.from}-${selection.to})` : \"\"}]`\n : \"\";\n return `User says${reply}: ${text}${sel}${doc}`;\n }\n case \"document:opened\": {\n const { fileName, format } = event.payload;\n return `User opened document: ${fileName} (${format})${doc}`;\n }\n case \"document:closed\": {\n const { fileName } = event.payload;\n return `User closed document: ${fileName}${doc}`;\n }\n case \"document:switched\": {\n const { fileName } = event.payload;\n return `User switched to document: ${fileName}${doc}`;\n }\n default: {\n const _exhaustive: never = event;\n return `Unknown event${doc}`;\n }\n }\n}\n\n/**\n * Build the `meta` record for a channel notification.\n * Keys use underscores only (Channels API silently drops hyphenated keys).\n */\nexport function formatEventMeta(event: TandemEvent): Record<string, string> {\n const meta: Record<string, string> = {\n event_type: event.type,\n };\n if (event.documentId) meta.document_id = event.documentId;\n\n switch (event.type) {\n case \"annotation:created\":\n case \"annotation:accepted\":\n case \"annotation:dismissed\":\n meta.annotation_id = event.payload.annotationId;\n break;\n case \"annotation:reply\":\n meta.annotation_id = event.payload.annotationId;\n meta.reply_id = event.payload.replyId;\n break;\n case \"chat:message\":\n meta.message_id = event.payload.messageId;\n if (event.payload.selection?.selectedText) meta.has_selection = \"true\";\n break;\n case \"document:opened\":\n case \"document:closed\":\n case \"document:switched\":\n break;\n default: {\n const _exhaustive: never = event;\n break;\n }\n }\n\n return meta;\n}\n","/**\n * SSE event bridge: connects to Tandem server's /api/events endpoint\n * and pushes received events to Claude Code as channel notifications.\n */\n\nimport type { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport type { TandemEvent } from \"../server/events/types.js\";\nimport { formatEventContent, formatEventMeta, parseTandemEvent } from \"../server/events/types.js\";\nimport { CHANNEL_MAX_RETRIES, CHANNEL_RETRY_DELAY_MS } from \"../shared/constants.js\";\n\nconst AWARENESS_DEBOUNCE_MS = 500;\nconst MODE_CACHE_TTL_MS = 2000;\n\nexport async function startEventBridge(mcp: Server, tandemUrl: string): Promise<void> {\n let retries = 0;\n let lastEventId: string | undefined;\n\n while (retries < CHANNEL_MAX_RETRIES) {\n try {\n await connectAndStream(mcp, tandemUrl, lastEventId, (id) => {\n lastEventId = id;\n retries = 0;\n });\n } catch (err) {\n retries++;\n console.error(\n `[Channel] SSE connection failed (${retries}/${CHANNEL_MAX_RETRIES}):`,\n err instanceof Error ? err.message : err,\n );\n\n if (retries >= CHANNEL_MAX_RETRIES) {\n console.error(\"[Channel] SSE connection exhausted, reporting error and exiting\");\n try {\n await fetch(`${tandemUrl}/api/channel-error`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n error: \"CHANNEL_CONNECT_FAILED\",\n message: `Channel shim lost connection after ${CHANNEL_MAX_RETRIES} retries.`,\n }),\n });\n } catch (reportErr) {\n console.error(\n \"[Channel] Could not report failure to server:\",\n reportErr instanceof Error ? reportErr.message : reportErr,\n );\n }\n process.exit(1);\n }\n\n await new Promise((r) => setTimeout(r, CHANNEL_RETRY_DELAY_MS));\n }\n }\n}\n\nasync function connectAndStream(\n mcp: Server,\n tandemUrl: string,\n lastEventId: string | undefined,\n onEventId: (id: string) => void,\n): Promise<void> {\n const headers: Record<string, string> = { Accept: \"text/event-stream\" };\n if (lastEventId) headers[\"Last-Event-ID\"] = lastEventId;\n\n const res = await fetch(`${tandemUrl}/api/events`, { headers });\n if (!res.ok) throw new Error(`SSE endpoint returned ${res.status}`);\n if (!res.body) throw new Error(\"SSE endpoint returned no body\");\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n // Debounced awareness: only send the latest status after a quiet period\n let awarenessTimer: ReturnType<typeof setTimeout> | null = null;\n let clearAwarenessTimer: ReturnType<typeof setTimeout> | null = null;\n let pendingAwareness: TandemEvent | null = null;\n const AWARENESS_CLEAR_MS = 3000; // Reset active state after 3s of no new events\n\n function clearAwareness(documentId?: string) {\n fetch(`${tandemUrl}/api/channel-awareness`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n documentId: documentId ?? null,\n status: \"idle\",\n active: false,\n }),\n }).catch(() => {});\n }\n\n function flushAwareness() {\n if (!pendingAwareness) return;\n const event = pendingAwareness;\n pendingAwareness = null;\n fetch(`${tandemUrl}/api/channel-awareness`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n documentId: event.documentId,\n status: `processing: ${event.type}`,\n active: true,\n }),\n }).catch((err) => {\n console.error(\"[Channel] Awareness update failed:\", err instanceof Error ? err.message : err);\n });\n\n // Auto-clear after timeout so the indicator doesn't stick\n if (clearAwarenessTimer) clearTimeout(clearAwarenessTimer);\n clearAwarenessTimer = setTimeout(() => clearAwareness(event.documentId), AWARENESS_CLEAR_MS);\n }\n\n function scheduleAwareness(event: TandemEvent) {\n pendingAwareness = event;\n if (awarenessTimer) clearTimeout(awarenessTimer);\n awarenessTimer = setTimeout(flushAwareness, AWARENESS_DEBOUNCE_MS);\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) throw new Error(\"SSE stream ended\");\n\n buffer += decoder.decode(value, { stream: true });\n\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n\n if (frame.startsWith(\":\")) continue;\n\n let eventId: string | undefined;\n let data: string | undefined;\n\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\"id: \")) eventId = line.slice(4);\n else if (line.startsWith(\"data: \")) data = line.slice(6);\n }\n\n if (!data) continue;\n\n let event: TandemEvent | null;\n try {\n event = parseTandemEvent(JSON.parse(data));\n } catch {\n console.error(\"[Channel] Malformed SSE event data (skipping):\", data.slice(0, 200));\n continue;\n }\n if (!event) {\n console.error(\"[Channel] Received invalid SSE event, skipping\");\n continue;\n }\n\n // Solo mode suppression: drop non-chat events when mode is \"solo\"\n if (event.type !== \"chat:message\") {\n const mode = await getCachedMode(tandemUrl);\n if (mode === \"solo\") {\n console.error(`[Channel] Solo mode: suppressed ${event.type} event`);\n if (eventId) onEventId(eventId);\n continue;\n }\n }\n\n if (eventId) onEventId(eventId);\n\n try {\n await mcp.notification({\n method: \"notifications/claude/channel\",\n params: {\n content: formatEventContent(event),\n meta: formatEventMeta(event),\n },\n });\n } catch (err) {\n console.error(\"[Channel] MCP notification failed (transport broken?):\", err);\n throw err;\n }\n\n scheduleAwareness(event);\n }\n }\n}\n\n// Cached mode lookup — avoids an HTTP fetch per event\nlet cachedMode: string = \"tandem\";\nlet cachedModeAt = 0;\n\nasync function getCachedMode(tandemUrl: string): Promise<string> {\n const now = Date.now();\n if (now - cachedModeAt < MODE_CACHE_TTL_MS) return cachedMode;\n try {\n const res = await fetch(`${tandemUrl}/api/mode`);\n if (res.ok) {\n const { mode } = (await res.json()) as { mode: string };\n cachedMode = mode;\n } else {\n console.error(`[Channel] Mode check returned ${res.status}, using cached: \"${cachedMode}\"`);\n }\n cachedModeAt = now;\n } catch (err) {\n console.error(\n \"[Channel] Mode check failed, delivering event (fail-open):\",\n err instanceof Error ? err.message : err,\n );\n cachedModeAt = now;\n }\n return cachedMode;\n}\n","/**\n * Tandem Channel Shim — core runtime, shared by:\n * - src/channel/index.ts (standalone binary, used by the Desktop sidecar)\n * - src/cli/channel.ts (npm-delivered entry for the plugin `tandem-channel`)\n *\n * Bridges Tandem's SSE event stream → Claude Code channel notifications,\n * and exposes a `tandem_reply` tool for Claude to respond to chat messages.\n *\n * Uses the low-level MCP `Server` class (not `McpServer`) as required by\n * the Channels API spec.\n */\n\nimport { createConnection } from \"node:net\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { CallToolRequestSchema, ListToolsRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport { redirectConsoleToStderr, resolveTandemUrl } from \"../shared/cli-runtime.js\";\nimport { DEFAULT_MCP_PORT } from \"../shared/constants.js\";\nimport { startEventBridge } from \"./event-bridge.js\";\n\nexport interface RunChannelOptions {\n /** Skip the non-fatal reachability probe. The CLI wrapper runs a strict\n * preflight upstream and we don't want to double-log \"server not reachable\"\n * noise. Defaults to false. */\n skipReachabilityLog?: boolean;\n}\n\nexport async function runChannel(opts: RunChannelOptions = {}): Promise<void> {\n redirectConsoleToStderr();\n\n const tandemUrl = resolveTandemUrl();\n\n const mcp = new Server(\n { name: \"tandem-channel\", version: \"0.1.0\" },\n {\n capabilities: {\n experimental: {\n \"claude/channel\": {},\n \"claude/channel/permission\": {},\n },\n tools: {},\n },\n instructions: [\n 'Events from Tandem arrive as <channel source=\"tandem-channel\" event_type=\"...\" document_id=\"...\">.',\n \"These are real-time push notifications of user actions in the collaborative document editor.\",\n \"Event types: annotation:created, annotation:accepted, annotation:dismissed, annotation:reply,\",\n \"chat:message, document:opened, document:closed, document:switched.\",\n \"Chat messages may include a 'selection' field with buffered selection context.\",\n \"Use your tandem MCP tools (tandem_getTextContent, tandem_comment, tandem_highlight, etc.) to act on them.\",\n \"Reply to chat messages using tandem_reply. Pass document_id from the tag attributes.\",\n \"Do not reply to non-chat events — just act on them using tools.\",\n \"If you haven't received channel notifications recently, call tandem_checkInbox as a fallback.\",\n ].join(\" \"),\n },\n );\n\n mcp.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: \"tandem_reply\",\n description: \"Reply to a chat message in Tandem\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n text: { type: \"string\", description: \"The reply message\" },\n documentId: {\n type: \"string\",\n description: \"Document ID from the channel event (optional)\",\n },\n replyTo: {\n type: \"string\",\n description: \"Message ID being replied to (optional)\",\n },\n },\n required: [\"text\"],\n },\n },\n ],\n }));\n\n mcp.setRequestHandler(CallToolRequestSchema, async (req) => {\n if (req.params.name === \"tandem_reply\") {\n const args = req.params.arguments as Record<string, unknown>;\n try {\n const res = await fetch(`${tandemUrl}/api/channel-reply`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(args),\n });\n let data: unknown;\n try {\n data = await res.json();\n } catch {\n data = { message: \"Non-JSON response\" };\n }\n if (!res.ok) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Reply failed (${res.status}): ${JSON.stringify(data)}`,\n },\n ],\n isError: true,\n };\n }\n return { content: [{ type: \"text\" as const, text: JSON.stringify(data) }] };\n } catch (err) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Failed to send reply: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n }\n throw new Error(`Unknown tool: ${req.params.name}`);\n });\n\n const PermissionRequestSchema = z.object({\n method: z.literal(\"notifications/claude/channel/permission_request\"),\n params: z.object({\n request_id: z.string(),\n tool_name: z.string(),\n description: z.string(),\n input_preview: z.string(),\n }),\n });\n\n mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {\n try {\n const res = await fetch(`${tandemUrl}/api/channel-permission`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n requestId: params.request_id,\n toolName: params.tool_name,\n description: params.description,\n inputPreview: params.input_preview,\n }),\n });\n if (!res.ok) {\n console.error(\n `[Channel] Permission relay got HTTP ${res.status} — browser may not see prompt`,\n );\n }\n } catch (err) {\n console.error(\"[Channel] Failed to forward permission request:\", err);\n }\n });\n\n console.error(`[Channel] Tandem channel shim starting (server: ${tandemUrl})`);\n\n if (!opts.skipReachabilityLog) {\n const reachable = await checkServerReachable(tandemUrl);\n if (!reachable) {\n console.error(`[Channel] Cannot reach Tandem server at ${tandemUrl}`);\n console.error(\"[Channel] Start it with: tandem start\");\n // Continue anyway — the event bridge will retry, and the server may start later\n }\n }\n\n const transport = new StdioServerTransport();\n await mcp.connect(transport);\n console.error(\"[Channel] Connected to Claude Code via stdio\");\n\n startEventBridge(mcp, tandemUrl).catch((err) => {\n console.error(\"[Channel] Event bridge failed unexpectedly:\", err);\n process.exit(1);\n });\n}\n\nasync function checkServerReachable(url: string, timeoutMs = 2000): Promise<boolean> {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n console.error(\n `[Channel] Invalid TANDEM_URL: \"${url}\" — expected format: http://localhost:3479`,\n );\n return false;\n }\n const port = parseInt(parsed.port || String(DEFAULT_MCP_PORT), 10);\n return new Promise((resolve) => {\n const socket = createConnection({ port, host: parsed.hostname }, () => {\n socket.destroy();\n resolve(true);\n });\n socket.setTimeout(timeoutMs);\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(false);\n });\n socket.on(\"error\", (err) => {\n console.error(`[Channel] Server probe failed: ${err.message}`);\n socket.destroy();\n resolve(false);\n });\n });\n}\n","/**\n * Tandem channel subcommand — npm-delivered entry for the plugin\n * `tandem-channel` MCP server. Runs the unified preflight, then hands off to\n * the shared channel shim runtime in src/channel/run.ts.\n */\n\nimport { runChannel } from \"../channel/run.js\";\nimport { ensureTandemServer } from \"./preflight.js\";\n\nexport async function runChannelCli(): Promise<void> {\n await ensureTandemServer();\n await runChannel({ skipReachabilityLog: true });\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst SERVER_DIST = resolve(__dirname, \"../server/index.js\");\n\nexport function runStart(): void {\n if (!existsSync(SERVER_DIST)) {\n console.error(`[Tandem] Server not found at ${SERVER_DIST}`);\n console.error(\"[Tandem] The installation may be corrupted. Try: npm install -g tandem-editor\");\n process.exit(1);\n }\n\n console.error(\"[Tandem] Starting server...\");\n\n const proc = spawn(\"node\", [SERVER_DIST], {\n stdio: \"inherit\",\n env: { ...process.env, TANDEM_OPEN_BROWSER: \"1\" },\n });\n\n proc.on(\"error\", (err) => {\n console.error(`[Tandem] Failed to start server: ${err.message}`);\n process.exit(1);\n });\n\n proc.on(\"exit\", (code) => {\n process.exit(code ?? 0);\n });\n\n // Forward signals — proc.kill() with no argument uses SIGTERM on Unix\n // and TerminateProcess on Windows (correct cross-platform behavior).\n // On Windows SIGTERM is not emitted by the OS, but SIGINT (Ctrl+C) works.\n // Both are listed for Unix compatibility.\n for (const sig of [\"SIGINT\", \"SIGTERM\"] as const) {\n process.once(sig, () => proc.kill());\n }\n}\n","/**\n * Tandem CLI — entry point for the `tandem` global command.\n * Shebang is added by tsup banner at build time.\n *\n * Usage:\n * tandem Start the Tandem server and open the browser\n * tandem setup Register Tandem MCP tools with Claude Code / Claude Desktop\n * tandem setup --force Register even if no Claude install is auto-detected\n * tandem --help Show this help\n * tandem --version Show version\n */\n\nimport updateNotifier from \"update-notifier\";\n\n// Injected at build time by tsup define; declared here for TypeScript\ndeclare const __TANDEM_VERSION__: string;\nconst version = typeof __TANDEM_VERSION__ !== \"undefined\" ? __TANDEM_VERSION__ : \"0.0.0-dev\";\n\nconst args = process.argv.slice(2);\n\n// Skip the update notifier for stdio subcommands — the output is machine-consumed\n// by Claude Desktop's plugin loader, and any incidental write risks corrupting\n// the MCP wire or producing log noise no human will ever read.\nconst isStdioMode = args[0] === \"mcp-stdio\" || args[0] === \"channel\";\nif (!isStdioMode) {\n updateNotifier({ pkg: { name: \"tandem-editor\", version } }).notify();\n}\n\nif (args.includes(\"--help\") || args.includes(\"-h\")) {\n console.log(`tandem v${version}\n\nUsage:\n tandem Start Tandem server and open the browser\n tandem setup Register MCP tools with Claude Code / Claude Desktop\n tandem setup --force Register to default paths regardless of detection\n tandem setup --with-channel-shim Also register the stdio channel shim (legacy opt-in)\n tandem mcp-stdio Run as a stdio MCP server proxying to local HTTP\n (used by the plugin's Cowork bridge; requires\n tandem server running on the host)\n tandem channel Run the Tandem channel shim (stdio MCP)\n (used by the plugin's tandem-channel entry)\n tandem --version\n tandem --help\n`);\n process.exit(0);\n}\n\nif (args.includes(\"--version\") || args.includes(\"-v\")) {\n console.log(version);\n process.exit(0);\n}\n\ntry {\n if (args[0] === \"setup\") {\n const { runSetup } = await import(\"./setup.js\");\n await runSetup({\n force: args.includes(\"--force\"),\n withChannelShim: args.includes(\"--with-channel-shim\"),\n });\n } else if (args[0] === \"mcp-stdio\") {\n const { runMcpStdio } = await import(\"./mcp-stdio.js\");\n await runMcpStdio();\n } else if (args[0] === \"channel\") {\n const { runChannelCli } = await import(\"./channel.js\");\n await runChannelCli();\n } else if (!args[0] || args[0] === \"start\") {\n const { runStart } = await import(\"./start.js\");\n runStart();\n } else {\n console.error(`Unknown command: ${args[0]}`);\n console.error(\"Run 'tandem --help' for usage.\");\n process.exit(1);\n }\n} catch (err) {\n console.error(`\\n[Tandem] Fatal error: ${err instanceof Error ? err.message : String(err)}`);\n console.error(\"If this persists, try reinstalling: npm install -g tandem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K,CAAC,MAAM,SAAS;AACvB,UAAM,EAAE,UAAAC,UAAS,IAAI,MAAM;AAC3B,UAAMA,UAAS;AAAA,MACb,OAAO,KAAK,SAAS,SAAS;AAAA,MAC9B,iBAAiB,KAAK,SAAS,qBAAqB;AAAA,IACtD,CAAC;AAAA,EACH,WAAW,KAAK,CAAC,MAAM,aAAa;AAClC,UAAM,EAAE,aAAAC,aAAY,IAAI,MAAM;AAC9B,UAAMA,aAAY;AAAA,EACpB,WAAW,KAAK,CAAC,MAAM,WAAW;AAChC,UAAM,EAAE,eAAAC,eAAc,IAAI,MAAM;AAChC,UAAMA,eAAc;AAAA,EACtB,WAAW,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC,MAAM,SAAS;AAC1C,UAAM,EAAE,UAAAC,UAAS,IAAI,MAAM;AAC3B,IAAAA,UAAS;AAAA,EACX,OAAO;AACL,YAAQ,MAAM,oBAAoB,KAAK,CAAC,CAAC,EAAE;AAC3C,YAAQ,MAAM,gCAAgC;AAC9C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,SAAS,KAAK;AACZ,UAAQ,MAAM;AAAA,wBAA2B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAC3F,UAAQ,MAAM,oEAAoE;AAClF,UAAQ,KAAK,CAAC;AAChB;","names":["readFileSync","dirname","resolve","fileURLToPath","__dirname","detail","buffered","StdioServerTransport","args","resolve","existsSync","dirname","resolve","fileURLToPath","__dirname","runSetup","runMcpStdio","runChannelCli","runStart"]}
|