imsg-mcp 1.3.0 → 1.3.2
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 +17 -0
- package/dist/cli.js +7 -7
- package/dist/cli.js.map +1 -1
- package/dist/{exportFormats-CWWiy5uz.js → exportFormats-wytSyBTp.js} +6 -3
- package/dist/exportFormats-wytSyBTp.js.map +1 -0
- package/dist/{exportStream-B86sO7Mg.js → exportStream-BCoZYUUZ.js} +2 -2
- package/dist/{exportStream-B86sO7Mg.js.map → exportStream-BCoZYUUZ.js.map} +1 -1
- package/dist/{imessage-db-C7w6mu1Q.js → imessage-db-Cz8MIIpG.js} +7 -2
- package/dist/imessage-db-Cz8MIIpG.js.map +1 -0
- package/dist/index.js +27 -11
- package/dist/index.js.map +1 -1
- package/dist/{meta-D3NoTAjA.js → meta-DzE7CSrZ.js} +2 -2
- package/dist/meta-DzE7CSrZ.js.map +1 -0
- package/dist/{setup-B2HejfMT.js → setup-BuXuKAHA.js} +2 -2
- package/dist/{setup-B2HejfMT.js.map → setup-BuXuKAHA.js.map} +1 -1
- package/dist/{shutdown-CikCSZru.js → shutdown-pPAPSnk3.js} +40 -45
- package/dist/shutdown-pPAPSnk3.js.map +1 -0
- package/dist/tui.js +16 -12
- package/dist/tui.js.map +1 -1
- package/dist/{watchdog-CnbBZnfg.js → watchdog-Cbgm050b.js} +2 -2
- package/dist/{watchdog-CnbBZnfg.js.map → watchdog-Cbgm050b.js.map} +1 -1
- package/package.json +3 -2
- package/dist/exportFormats-CWWiy5uz.js.map +0 -1
- package/dist/imessage-db-C7w6mu1Q.js.map +0 -1
- package/dist/meta-D3NoTAjA.js.map +0 -1
- package/dist/shutdown-CikCSZru.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"shutdown-CikCSZru.js","sources":["../src/config.ts","../src/logger.ts","../src/db-schema.ts","../src/mock-send-db.ts","../src/applescript.ts","../src/access-check.ts","../src/thread-slug.ts","../src/shutdown.ts"],"sourcesContent":["import { existsSync, readdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve, sep } from \"node:path\";\n\nfunction resolveEnvPath(value: string | undefined, fallback: string): string {\n if (!value) return fallback;\n if (value.startsWith(\"~/\") || value === \"~\") {\n return join(homedir(), value.slice(2));\n }\n return resolve(process.cwd(), value);\n}\n\nexport function getEnv(): string {\n return process.env.VITE_ENV ?? \"development\";\n}\n\n/** Bundled DB / mock-sending mode (cloud, CI tests via `.env.test`). */\nexport function isAiEnv(): boolean {\n return getEnv() === \"ai\";\n}\n\n/** Any non-`ai` mode (e.g. `development` on your Mac). */\nexport function isLocalEnv(): boolean {\n return !isAiEnv();\n}\n\nexport function getImsgDbPath(): string {\n return resolveEnvPath(\n process.env.VITE_IMSG_DB_PATH,\n join(homedir(), \"Library\", \"Messages\", \"chat.db\"),\n );\n}\n\nexport function getContactsDbPaths(): string[] | undefined {\n const main =\n process.env.VITE_CONTACTS_DB_PATH ??\n join(homedir(), \"Library\", \"Application Support\", \"AddressBook\", \"AddressBook-v22.abcddb\");\n\n const mainResolved = resolveEnvPath(main, \"\");\n const paths = new Set<string>([mainResolved]);\n\n const sourcesSegment = `${sep}Sources${sep}`;\n const sourcesIndex = mainResolved.indexOf(sourcesSegment);\n const addressBookDir =\n sourcesIndex >= 0 ? mainResolved.slice(0, sourcesIndex) : dirname(mainResolved);\n\n const addSourceDb = (path: string) => {\n if (existsSync(path)) {\n paths.add(path);\n }\n };\n\n const uuid = process.env.VITE_ADDRESS_BOOK_UUID;\n if (uuid) {\n addSourceDb(join(addressBookDir, \"Sources\", uuid, \"AddressBook-v22.abcddb\"));\n }\n\n const sourcesDir = join(addressBookDir, \"Sources\");\n if (existsSync(sourcesDir)) {\n try {\n const entries = readdirSync(sourcesDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n addSourceDb(join(sourcesDir, entry.name, \"AddressBook-v22.abcddb\"));\n }\n } catch {\n // Ignore unreadable Address Book source directories.\n }\n }\n\n return [...paths];\n}\n\nexport function getSlugsDbPath(): string {\n return resolveEnvPath(process.env.VITE_SLUGS_DB_PATH, join(homedir(), \".imsg-mcp\", \"slugs.db\"));\n}\n\nexport function getVcfPath(): string {\n return resolveEnvPath(process.env.VITE_VCF_PATH, join(process.cwd(), \"fixtures\", \"contacts.vcf\"));\n}\n","/**\n * Structured logger with performance monitoring.\n *\n * - In-memory buffer for MCP `get_logs` tool (backwards compatible)\n * - NDJSON file output to $TMPDIR/imsg-mcp/ for post-mortem analysis\n * - Performance spans: `const span = perf(\"op\"); ... span.end({ rows: 100 })`\n * - Heap memory tracking on every log entry\n *\n * Files in $TMPDIR are cleaned up by the OS automatically.\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from \"node:fs\";\nimport { freemem, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\n// ── Types ──────────────────────────────────────────────────────────────\n\nexport type LogLevel = \"info\" | \"warn\" | \"error\" | \"perf\";\n\nexport interface LogEntry {\n ts: string;\n level: LogLevel;\n msg: string;\n dur_ms?: number;\n mem_mb: number;\n mem_delta_mb?: number;\n data?: Record<string, unknown>;\n}\n\nexport interface PerfSpan {\n /** End the span. Logs duration, memory delta, and optional metadata. */\n end(data?: Record<string, unknown>): number;\n}\n\nexport interface LastSendErrorDetails {\n message: string;\n stderr?: string;\n stdout?: string;\n code?: string | number;\n timestamp: string;\n}\n\n// ── State ──────────────────────────────────────────────────────────────\n\nconst MAX_LOG_LINES = 500;\nconst MAX_FILE_BYTES = 10 * 1024 * 1024; // 10 MB rotation\n\n/**\n * File logging is opt-in via IMSG_DEV=1 OR a programmatic `enableFileLogging()`\n * call. End users running the published `imsg mcp` bin don't get NDJSON files\n * in $TMPDIR by default. The TUI flips this on unconditionally so a future\n * crash leaves a postmortem trail — without it, the user's \"tool exited on its\n * own\" report has nothing to investigate. The in-memory ring buffer (500\n * lines) still works either way.\n *\n * Checked at call time, not module-load time, so tests can flip the flag\n * without needing to re-import the module.\n */\nlet fileLoggingForced = false;\n\n/**\n * Force file logging on regardless of `IMSG_DEV`. Called by long-running\n * interactive entry points (TUI) where a postmortem trail justifies the\n * disk usage (file is 10 MB capped). Idempotent. No way to disable once on.\n */\nexport function enableFileLogging(): void {\n fileLoggingForced = true;\n}\n\nfunction isFileLoggingEnabled(): boolean {\n return fileLoggingForced || process.env.IMSG_DEV === \"1\";\n}\n\nfunction isVerboseLogging(): boolean {\n return process.env.IMSG_LOG_VERBOSE === \"1\";\n}\n\nconst memoryLines: string[] = [];\nlet logFilePath: string | null = null;\nlet logFileBytes = 0;\nlet lastSendError: LastSendErrorDetails | null = null;\n\n// ── File output ────────────────────────────────────────────────────────\n\nfunction getLogDir(): string {\n return join(tmpdir(), \"imsg-mcp\");\n}\n\nfunction ensureLogFile(): string | null {\n if (logFilePath && logFileBytes < MAX_FILE_BYTES) return logFilePath;\n\n try {\n const dir = getLogDir();\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\n const date = new Date().toISOString().replace(/[:.]/g, \"-\").slice(0, 19);\n logFilePath = join(dir, `imsg-mcp-${process.pid}-${date}.ndjson`);\n logFileBytes = 0;\n return logFilePath;\n } catch {\n return null;\n }\n}\n\nfunction writeToFile(json: string): void {\n if (!isFileLoggingEnabled()) return;\n const path = ensureLogFile();\n if (!path) return;\n try {\n const line = `${json}\\n`;\n appendFileSync(path, line);\n logFileBytes += line.length;\n } catch {\n // Don't let file I/O failures break the app.\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\nfunction heapMB(): number {\n return Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 10) / 10;\n}\n\nfunction formatMemoryLine(entry: LogEntry): string {\n let line = `${entry.ts} [${entry.level}] ${entry.msg}`;\n if (entry.dur_ms != null) line += ` (${entry.dur_ms.toFixed(1)}ms)`;\n if (entry.data != null) line += ` ${JSON.stringify(entry.data)}`;\n return line;\n}\n\nfunction emit(entry: LogEntry): void {\n // In-memory buffer for MCP get_logs tool\n const line = formatMemoryLine(entry);\n memoryLines.push(line);\n if (memoryLines.length > MAX_LOG_LINES) {\n memoryLines.splice(0, memoryLines.length - MAX_LOG_LINES);\n }\n\n // NDJSON file output\n writeToFile(JSON.stringify(entry));\n}\n\n// ── Public API ─────────────────────────────────────────────────────────\n\nexport function info(msg: string, data?: Record<string, unknown>): void {\n emit({ ts: new Date().toISOString(), level: \"info\", msg, mem_mb: heapMB(), data });\n}\n\nexport function warn(msg: string, data?: Record<string, unknown>): void {\n emit({ ts: new Date().toISOString(), level: \"warn\", msg, mem_mb: heapMB(), data });\n}\n\nexport function error(msg: string, data?: Record<string, unknown>): void {\n emit({ ts: new Date().toISOString(), level: \"error\", msg, mem_mb: heapMB(), data });\n}\n\n/**\n * Start a performance span. Call `.end()` on the returned object to log\n * the duration, heap delta, and optional metadata.\n *\n * ```ts\n * const span = perf(\"listConversations\");\n * // ... work ...\n * span.end({ chats: 200, deduped: 180 });\n * ```\n */\nexport function perf(msg: string): PerfSpan {\n const startTime = performance.now();\n const startHeap = heapMB();\n\n return {\n end(data?: Record<string, unknown>): number {\n const dur_ms = performance.now() - startTime;\n const endHeap = heapMB();\n emit({\n ts: new Date().toISOString(),\n level: \"perf\",\n msg,\n dur_ms,\n mem_mb: endHeap,\n mem_delta_mb: Math.round((endHeap - startHeap) * 10) / 10,\n data,\n });\n return dur_ms;\n },\n };\n}\n\n// ── Backwards-compatible API (used by MCP tools in index.ts) ───────────\n\n/** @deprecated Use info/warn/error instead. Kept for MCP tool compat. */\nexport function appendLog(level: string, message: string, data?: unknown): void {\n const entry: LogEntry = {\n ts: new Date().toISOString(),\n level: level as LogLevel,\n msg: message,\n mem_mb: heapMB(),\n data:\n data != null\n ? typeof data === \"object\"\n ? (data as Record<string, unknown>)\n : { value: data }\n : undefined,\n };\n emit(entry);\n}\n\nexport function getLogs(tail?: number): string[] {\n if (tail != null && tail > 0) return memoryLines.slice(-tail);\n return [...memoryLines];\n}\n\nexport function clearLogs(): void {\n memoryLines.length = 0;\n}\n\nexport function setLastSendError(details: Omit<LastSendErrorDetails, \"timestamp\">): void {\n lastSendError = { ...details, timestamp: new Date().toISOString() };\n error(\"send_message failed\", details as Record<string, unknown>);\n}\n\nexport function getLastSendError(): LastSendErrorDetails | null {\n return lastSendError ? { ...lastSendError } : null;\n}\n\n/** Return the path to the current log file (if any). */\nexport function getLogFilePath(): string | null {\n return logFilePath;\n}\n\n/** Return the log directory path. */\nexport function getLogDirectory(): string {\n return getLogDir();\n}\n\n/** Log a startup marker — call at process start. */\nexport function logStartup(entrypoint: string): void {\n info(\"startup\", { pid: process.pid, ppid: process.ppid, entrypoint, node: process.version });\n}\n\n/** Log a shutdown marker — call before process exits. */\nexport function logShutdown(reason: string): void {\n info(\"shutdown\", { pid: process.pid, reason, uptime_s: Math.round(process.uptime()) });\n}\n\n/**\n * Read the latest NDJSON log file from disk (for external access).\n * Returns the last N lines from the most recent log file.\n */\nexport function getFileLogLines(tail = 50): string[] {\n try {\n // Previously this used inline `require(\"node:fs\")`, which throws\n // ReferenceError under ESM and gets silently swallowed — returning []\n // even when a 135-line NDJSON sat right next to it. The imports now\n // live at the top of the file (ESM-correct).\n //\n // Strategy: read every PID-tagged file in the log dir so the caller\n // gets logs from THIS server process even when stale files from prior\n // crashes / older PIDs sort later. We fall back to the most-recent\n // file if the current PID isn't present (e.g. file rotated).\n const dir = getLogDir();\n if (!existsSync(dir)) return [];\n const files = readdirSync(dir)\n .filter((f: string) => f.endsWith(\".ndjson\"))\n .sort();\n if (files.length === 0) return [];\n\n const currentPid = String(process.pid);\n const mine = files.filter((f: string) => f.includes(`imsg-mcp-${currentPid}-`));\n const targetFile = mine[mine.length - 1] ?? files[files.length - 1];\n\n const content = readFileSync(join(dir, targetFile), \"utf8\");\n const lines = content.trim().split(\"\\n\").filter(Boolean);\n return tail > 0 ? lines.slice(-tail) : lines;\n } catch {\n return [];\n }\n}\n\n// ── Heap monitor ───────────────────────────────────────────────────────\n\n/**\n * Heap warning threshold for the heartbeat monitor. Tunable via\n * `IMSG_HEAP_WARN_MB` env var. The default of 256 MB is set above the\n * legitimate working-set for big chat_analytics / large search_messages\n * sweeps on real Mac DBs (~240 MB at peak). Pre-fix this was 150,\n * which tripped on every analytic call — agents reading get_logs\n * saw a wall of false-positive \"heap exceeds threshold\" warnings on\n * every healthy invocation.\n */\nconst HEAP_WARN_MB = Math.max(\n 64,\n Number.parseInt(process.env.IMSG_HEAP_WARN_MB ?? \"256\", 10) || 256,\n);\nlet heapMonitorTimer: ReturnType<typeof setInterval> | null = null;\n\n/**\n * Start periodic heap monitoring. Logs a warning if heap exceeds the\n * threshold. Call once at server startup.\n *\n * No-op when IMSG_DEV is unset — end users running the published bin don't\n * accumulate heartbeats. The watchdog itself (src/watchdog.ts) still runs\n * unconditionally for self-healing; this monitor is purely observability.\n *\n * Heartbeats fire every 60s by default, or every 10s when IMSG_LOG_VERBOSE=1.\n */\nexport function startHeapMonitor(): void {\n if (!isFileLoggingEnabled()) return;\n if (heapMonitorTimer) return;\n const intervalMs = isVerboseLogging() ? 10_000 : 60_000;\n heapMonitorTimer = setInterval(() => {\n const heap = heapMB();\n const { rss } = process.memoryUsage();\n const rssMb = Math.round((rss / 1024 / 1024) * 10) / 10;\n if (heap > HEAP_WARN_MB) {\n warn(\"heap exceeds threshold\", { heap_mb: heap, rss_mb: rssMb, threshold_mb: HEAP_WARN_MB });\n }\n // System-level memory pressure — captures cases where the host or OS may\n // be about to reclaim us. Helps diagnose \"process vanished\" reports where\n // the kill came from outside (SIGKILL, OOM, parent host).\n const freeMb = Math.round(freemem() / 1024 / 1024);\n // Always log a periodic heartbeat at info level for post-mortem analysis\n emit({\n ts: new Date().toISOString(),\n level: \"info\",\n msg: \"heartbeat\",\n mem_mb: heap,\n data: {\n rss_mb: rssMb,\n uptime_s: Math.round(process.uptime()),\n system_free_mb: freeMb || undefined,\n },\n });\n }, intervalMs);\n // Don't prevent process exit\n heapMonitorTimer.unref();\n}\n\nexport function stopHeapMonitor(): void {\n if (heapMonitorTimer) {\n clearInterval(heapMonitorTimer);\n heapMonitorTimer = null;\n }\n}\n","/**\n * iMessage SQLite database schema constants and helpers.\n * Single source of truth for chat.db structure (synced with Messages.app / SMS).\n * See docs/IMESSAGE_DB_SCHEMA.md for full reference.\n */\n\n/** Seconds between Unix epoch (1970-01-01) and Mac epoch (2001-01-01). */\nexport const MAC_EPOCH_OFFSET = 978307200;\n\n/** Timestamps in DB are nanoseconds since 2001-01-01. */\nexport const NANOS_PER_SECOND = 1_000_000_000;\n\nexport const Tables = {\n MESSAGE: \"message\",\n HANDLE: \"handle\",\n CHAT: \"chat\",\n CHAT_MESSAGE_JOIN: \"chat_message_join\",\n CHAT_HANDLE_JOIN: \"chat_handle_join\",\n ATTACHMENT: \"attachment\",\n MESSAGE_ATTACHMENT_JOIN: \"message_attachment_join\",\n RECOVERABLE_MESSAGE_PART: \"recoverable_message_part\",\n} as const;\n\n/** associated_message_type: 0 = normal message; 2,3 = business; 1000 = sticker; 2000–3006 = tapbacks. */\nexport const AssociatedMessageType = {\n NORMAL: 0,\n STICKER: 1000,\n LOVE_ADD: 2000,\n LIKE_ADD: 2001,\n DISLIKE_ADD: 2002,\n LAUGH_ADD: 2003,\n EMPHASIZE_ADD: 2004,\n QUESTION_ADD: 2005,\n EMOJI_ADD: 2006,\n LOVE_REMOVE: 3000,\n LIKE_REMOVE: 3001,\n DISLIKE_REMOVE: 3002,\n LAUGH_REMOVE: 3003,\n EMPHASIZE_REMOVE: 3004,\n QUESTION_REMOVE: 3005,\n EMOJI_REMOVE: 3006,\n} as const;\n\n/** Minimum type value for tapback/reaction messages (add). */\nexport const TAPBACK_ADD_MIN = 2000;\n\n/** Minimum type value for reaction messages we query (adds). */\nexport const TAPBACK_QUERY_MIN = 2000;\n\n/** Format: p:PART_INDEX/MESSAGE_GUID. */\nexport const ASSOCIATED_MESSAGE_GUID_REGEX = /^p:(\\d+)\\/(.+)$/;\n\n/** Object replacement character used as placeholder for inline attachments / rich content. */\nexport const OBJECT_REPLACEMENT_CHAR = \"\\uFFFC\";\n\n/**\n * Convert macOS timestamp (nanoseconds since 2001-01-01) to JS Date.\n */\nexport function macTimestampToDate(timestamp: number | null): Date | null {\n if (timestamp == null || timestamp === 0) return null;\n const unixSeconds = timestamp / NANOS_PER_SECOND + MAC_EPOCH_OFFSET;\n return new Date(unixSeconds * 1000);\n}\n\n/**\n * Convert a macOS timestamp where the storage unit isn't guaranteed.\n *\n * `message.date` is nanoseconds on modern macOS, but other columns\n * (notably `attachment.created_date`) store **seconds** since the\n * Mac epoch. Same baseline, different magnitude — and the two ranges\n * don't overlap for any reasonable date:\n * - \"now\" in seconds: ~8 × 10⁸\n * - \"now\" in nanoseconds: ~8 × 10¹⁷\n *\n * Anything below `SECONDS_NS_BOUNDARY` (10¹⁵) is treated as seconds;\n * anything at or above is treated as nanoseconds. Values of 0 or null\n * return null (no recorded timestamp).\n */\nexport const SECONDS_NS_BOUNDARY = 1e15;\n\nexport function macAutoTimestampToDate(timestamp: number | null): Date | null {\n if (timestamp == null || timestamp === 0) return null;\n const unitDivisor = timestamp < SECONDS_NS_BOUNDARY ? 1 : NANOS_PER_SECOND;\n const unixSeconds = timestamp / unitDivisor + MAC_EPOCH_OFFSET;\n return new Date(unixSeconds * 1000);\n}\n\n/**\n * Parse associated_message_guid to extract target message GUID and part index.\n * Format: \"p:PART_INDEX/MESSAGE_GUID\"\n */\nexport function parseAssociatedMessageGuid(\n guid: string | null,\n): { targetGuid: string; partIndex: number } | null {\n if (!guid) return null;\n const match = guid.match(ASSOCIATED_MESSAGE_GUID_REGEX);\n if (match) {\n return { partIndex: parseInt(match[1], 10), targetGuid: match[2] };\n }\n return null;\n}\n\n/** Whether associated_message_type represents a reaction/tapback (excludes normal and business). */\nexport function isReactionType(associatedMessageType: number): boolean {\n return associatedMessageType >= 1000 && associatedMessageType !== 0;\n}\n","import { randomUUID } from \"node:crypto\";\nimport Database from \"better-sqlite3\";\nimport { MAC_EPOCH_OFFSET, NANOS_PER_SECOND } from \"./db-schema.js\";\n\nfunction dateToMacTimestamp(date: Date): number {\n return Math.floor((date.getTime() / 1000 - MAC_EPOCH_OFFSET) * NANOS_PER_SECOND);\n}\n\nfunction resolveChat(\n db: Database.Database,\n opts: { chatIdentifier?: string; chatGuid?: string },\n): { chatRowId: number; handleId: number } | null {\n let chatRow: any;\n if (opts.chatGuid) {\n chatRow = db\n .prepare(\"SELECT ROWID, chat_identifier FROM chat WHERE guid = ?\")\n .get(opts.chatGuid);\n }\n if (!chatRow && opts.chatIdentifier) {\n chatRow = db\n .prepare(\"SELECT ROWID, chat_identifier FROM chat WHERE chat_identifier = ?\")\n .get(opts.chatIdentifier);\n }\n if (!chatRow) return null;\n\n const handle: any = db\n .prepare(\"SELECT ROWID FROM handle WHERE id = ?\")\n .get(chatRow.chat_identifier);\n\n const handleId = handle?.ROWID ?? 0;\n return { chatRowId: chatRow.ROWID, handleId };\n}\n\nexport function insertSentMessage(\n dbPath: string,\n target: { chatIdentifier?: string; chatGuid?: string },\n text: string,\n): number | null {\n const db = new Database(dbPath);\n db.pragma(\"journal_mode = WAL\");\n\n try {\n const resolved = resolveChat(db, target);\n if (!resolved) {\n console.warn(\"[mock-send] Could not resolve chat for\", target);\n return null;\n }\n\n const now = new Date();\n const macDate = dateToMacTimestamp(now);\n const guid = `mock:${randomUUID()}`;\n\n const insert = db.prepare(`\n INSERT INTO message (guid, text, handle_id, date, is_from_me, associated_message_type, is_read, is_delivered, service)\n VALUES (?, ?, ?, ?, 1, 0, 1, 1, 'iMessage')\n `);\n const result = insert.run(guid, text, resolved.handleId, macDate);\n const messageRowId = Number(result.lastInsertRowid);\n\n db.prepare(\n \"INSERT INTO chat_message_join (chat_id, message_id, message_date) VALUES (?, ?, ?)\",\n ).run(resolved.chatRowId, messageRowId, macDate);\n\n return messageRowId;\n } finally {\n db.close();\n }\n}\n","import { execFile } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { unlinkSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { getImsgDbPath, isAiEnv } from \"./config.js\";\nimport { setLastSendError } from \"./logger.js\";\nimport { insertSentMessage } from \"./mock-send-db.js\";\nimport type { SendMessageResult } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Detect whether a handle looks like a phone number suitable for SMS\n * fallback. We don't bother validating the country/area code — Messages.app\n * will reject malformed ones with a clear error.\n */\nfunction isPhoneLike(handle: string): boolean {\n return /^\\+?[\\d\\s\\-()]+$/.test(handle.trim());\n}\n\n/** Result shape for the preflight reachability check. */\nexport interface ImessageAvailability {\n /** Best-guess service that will reach this handle. */\n service: \"iMessage\" | \"SMS\" | \"unknown\";\n /** True iff at least one service appears to be reachable for the handle. */\n reachable: boolean;\n /** Human-readable hint when not reachable, for LLM remediation. */\n hint?: string;\n}\n/** `VITE_ENV=ai`, or any test run (never hit Messages.app / osascript under Vitest). */\nconst MOCK = isAiEnv() || process.env.VITEST === \"true\";\n\n// ---------------------------------------------------------------------------\n// Mock helpers (MOCK: return success + optional insert into chat.db)\n// ---------------------------------------------------------------------------\n\nfunction mockSend(\n text: string,\n target: { chatIdentifier?: string; chatGuid?: string },\n): SendMessageResult {\n // Under Vitest, return success only — no SQLite (avoids LFS/pointer noise; tests cover API shape).\n if (process.env.VITEST !== \"true\") {\n try {\n insertSentMessage(getImsgDbPath(), target, text);\n } catch (err) {\n console.warn(\"[mock-send] DB insert failed (non-fatal):\", err);\n }\n }\n return { success: true, timestamp: new Date() };\n}\n\n// ---------------------------------------------------------------------------\n// Real AppleScript helpers\n// ---------------------------------------------------------------------------\n\nasync function runAppleScript(\n script: string,\n captureErrorForSend: boolean = false,\n): Promise<string> {\n try {\n const { stdout, stderr } = await execFileAsync(\"osascript\", [\"-e\", script], {\n timeout: 30000,\n });\n if (stderr?.trim()) {\n console.error(\"[osascript] stderr:\", stderr);\n }\n return stdout.trim();\n } catch (error: any) {\n if (captureErrorForSend) {\n setLastSendError({\n message: error.message || String(error),\n stderr: error.stderr ?? undefined,\n stdout: error.stdout ?? undefined,\n code: error.code ?? undefined,\n });\n }\n if (error.code === \"ENOENT\") {\n throw new Error(\"osascript not found. This tool requires macOS.\");\n }\n if (error.stderr) {\n throw new Error(`AppleScript error: ${error.stderr}`);\n }\n throw error;\n }\n}\n\nexport function appleScriptEscape(str: string): string {\n return str\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\");\n}\n\n// ---------------------------------------------------------------------------\n// Public API -- each function branches on MOCK\n// ---------------------------------------------------------------------------\n\nexport async function sendMessage(recipient: string, message: string): Promise<SendMessageResult> {\n if (MOCK) return mockSend(message, { chatIdentifier: recipient });\n\n const escapedRecipient = appleScriptEscape(recipient);\n const escapedMessage = appleScriptEscape(message);\n const script = `\n tell application \"Messages\"\n set targetService to 1st account whose service type = iMessage\n set targetBuddy to participant \"${escapedRecipient}\" of targetService\n send \"${escapedMessage}\" to targetBuddy\n end tell\n `;\n try {\n await runAppleScript(script, true);\n return { success: true, timestamp: new Date() };\n } catch (error: any) {\n return { success: false, error: error.message || String(error) };\n }\n}\n\nexport async function sendMessageAlt(\n recipient: string,\n message: string,\n): Promise<SendMessageResult> {\n if (MOCK) return mockSend(message, { chatIdentifier: recipient });\n\n const escapedRecipient = appleScriptEscape(recipient);\n const escapedMessage = appleScriptEscape(message);\n const script = `\n tell application \"Messages\"\n send \"${escapedMessage}\" to buddy \"${escapedRecipient}\" of (service 1 whose service type is iMessage)\n end tell\n `;\n try {\n await runAppleScript(script, true);\n return { success: true, timestamp: new Date() };\n } catch (_error: any) {\n return sendSMS(recipient, message);\n }\n}\n\nexport async function sendSMS(phoneNumber: string, message: string): Promise<SendMessageResult> {\n if (MOCK) return mockSend(message, { chatIdentifier: phoneNumber });\n\n const escapedPhone = appleScriptEscape(phoneNumber);\n const escapedMessage = appleScriptEscape(message);\n const script = `\n tell application \"Messages\"\n send \"${escapedMessage}\" to buddy \"${escapedPhone}\" of (service 1 whose service type is SMS)\n end tell\n `;\n try {\n await runAppleScript(script, true);\n return { success: true, timestamp: new Date() };\n } catch (error: any) {\n return { success: false, error: error.message || String(error) };\n }\n}\n\nexport async function sendToChat(chatName: string, message: string): Promise<SendMessageResult> {\n if (MOCK) return mockSend(message, { chatIdentifier: chatName });\n\n const escapedName = appleScriptEscape(chatName);\n const escapedMessage = appleScriptEscape(message);\n const script = `\n tell application \"Messages\"\n send \"${escapedMessage}\" to chat \"${escapedName}\"\n end tell\n `;\n try {\n await runAppleScript(script, true);\n return { success: true, timestamp: new Date() };\n } catch (error: any) {\n return { success: false, error: error.message || String(error) };\n }\n}\n\nexport async function sendToChatId(chatId: string, message: string): Promise<SendMessageResult> {\n if (MOCK) return mockSend(message, { chatGuid: chatId });\n\n const escapedId = appleScriptEscape(chatId);\n const escapedMessage = appleScriptEscape(message);\n const script = `\n tell application \"Messages\"\n send \"${escapedMessage}\" to text chat id \"${escapedId}\"\n end tell\n `;\n try {\n await runAppleScript(script, true);\n return { success: true, timestamp: new Date() };\n } catch (error: any) {\n return { success: false, error: error.message || String(error) };\n }\n}\n\nexport async function checkMessagesAvailable(): Promise<boolean> {\n if (MOCK) return true;\n\n const script = `\n tell application \"System Events\"\n return exists application process \"Messages\"\n end tell\n `;\n try {\n const result = await runAppleScript(script);\n return result === \"true\";\n } catch {\n return false;\n }\n}\n\nexport async function getAvailableServices(): Promise<string[]> {\n if (MOCK) return [\"iMessage\", \"SMS\"];\n\n const script = `\n tell application \"Messages\"\n set serviceList to {}\n repeat with s in services\n set end of serviceList to (service type of s as string)\n end repeat\n return serviceList\n end tell\n `;\n try {\n const result = await runAppleScript(script);\n return result\n .split(\", \")\n .map((s) => s.trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\nexport async function activateMessages(): Promise<void> {\n if (MOCK) return;\n await runAppleScript('tell application \"Messages\" to activate');\n}\n\nexport async function buddyExists(address: string): Promise<boolean> {\n if (MOCK) return true;\n\n const escaped = appleScriptEscape(address);\n const script = `\n tell application \"Messages\"\n try\n set targetBuddy to buddy \"${escaped}\" of (service 1 whose service type is iMessage)\n return true\n on error\n return false\n end try\n end tell\n `;\n try {\n const result = await runAppleScript(script);\n return result === \"true\";\n } catch {\n return false;\n }\n}\n\n/**\n * Reliable send: writes the message body to a UTF-8 temp file and uses\n * `read (POSIX file \"...\") as «class utf8»` inside AppleScript. This avoids\n * two recurring failure modes of inline-string sends:\n * 1. AppleScript string-length limits on very long messages.\n * 2. Quote/backslash/escape bugs when the message contains arbitrary user\n * content (emoji ZWJ sequences, smart quotes, backticks, etc).\n *\n * Auto-fallback: if iMessage send fails AND the recipient looks like a phone\n * number, retries via the SMS service in the same AppleScript invocation.\n */\nexport async function sendMessageReliable(\n recipient: string,\n message: string,\n): Promise<SendMessageResult> {\n if (MOCK) return mockSend(message, { chatIdentifier: recipient });\n\n const tmpFile = join(tmpdir(), `imsg-send-${randomBytes(8).toString(\"hex\")}.txt`);\n try {\n writeFileSync(tmpFile, message, { encoding: \"utf8\" });\n } catch (error: any) {\n return { success: false, error: `Failed to stage send payload: ${error.message ?? error}` };\n }\n\n const escapedRecipient = appleScriptEscape(recipient);\n const escapedPath = appleScriptEscape(tmpFile);\n const phoneFallback = isPhoneLike(recipient);\n\n // Outer try sends via iMessage; if it errors AND the recipient is a phone\n // number, the on-error branch falls back to SMS. Both branches read the\n // body from the temp file to avoid AppleScript string handling.\n const script = phoneFallback\n ? `\n tell application \"Messages\"\n set msgBody to read (POSIX file \"${escapedPath}\") as «class utf8»\n try\n set iSvc to 1st account whose service type = iMessage\n send msgBody to participant \"${escapedRecipient}\" of iSvc\n return \"iMessage\"\n on error\n set sSvc to 1st account whose service type = SMS\n send msgBody to participant \"${escapedRecipient}\" of sSvc\n return \"SMS\"\n end try\n end tell\n `\n : `\n tell application \"Messages\"\n set msgBody to read (POSIX file \"${escapedPath}\") as «class utf8»\n set iSvc to 1st account whose service type = iMessage\n send msgBody to participant \"${escapedRecipient}\" of iSvc\n return \"iMessage\"\n end tell\n `;\n\n try {\n const service = await runAppleScript(script, true);\n return {\n success: true,\n timestamp: new Date(),\n service: service === \"SMS\" || service === \"iMessage\" ? service : undefined,\n };\n } catch (error: any) {\n return { success: false, error: error.message || String(error) };\n } finally {\n // Best-effort cleanup — failure here is non-fatal (OS will reap $TMPDIR).\n try {\n unlinkSync(tmpFile);\n } catch {\n // ignore\n }\n }\n}\n\n/**\n * Send a file attachment to a participant. Returns success/error.\n *\n * Uses `send (POSIX file \"...\") to participant ...` — the Messages SDEF\n * accepts a file specifier as the first argument to `send`. The file must\n * exist on disk; Messages.app will rate-limit or reject very large files\n * (typical cap ~100MB).\n *\n * For phone-like recipients, falls back to SMS service on iMessage failure.\n */\nexport async function sendAttachment(\n recipient: string,\n filepath: string,\n): Promise<SendMessageResult> {\n if (MOCK) return mockSend(`[attachment:${filepath}]`, { chatIdentifier: recipient });\n\n const escapedRecipient = appleScriptEscape(recipient);\n const escapedPath = appleScriptEscape(filepath);\n const phoneFallback = isPhoneLike(recipient);\n\n const script = phoneFallback\n ? `\n tell application \"Messages\"\n try\n set iSvc to 1st account whose service type = iMessage\n send (POSIX file \"${escapedPath}\") to participant \"${escapedRecipient}\" of iSvc\n return \"iMessage\"\n on error\n set sSvc to 1st account whose service type = SMS\n send (POSIX file \"${escapedPath}\") to participant \"${escapedRecipient}\" of sSvc\n return \"SMS\"\n end try\n end tell\n `\n : `\n tell application \"Messages\"\n set iSvc to 1st account whose service type = iMessage\n send (POSIX file \"${escapedPath}\") to participant \"${escapedRecipient}\" of iSvc\n return \"iMessage\"\n end tell\n `;\n\n try {\n const service = await runAppleScript(script, true);\n return {\n success: true,\n timestamp: new Date(),\n service: service === \"SMS\" || service === \"iMessage\" ? service : undefined,\n };\n } catch (error: any) {\n return { success: false, error: error.message || String(error) };\n }\n}\n\n/**\n * Preflight reachability check. Cheap call that an agent should make BEFORE\n * `send_message` to avoid wasted attempts when the handle can't be reached.\n *\n * Detection rules:\n * - Try iMessage `buddy` lookup → if success, return `iMessage`.\n * - If handle looks like a phone number, try SMS `buddy` → if success,\n * return `SMS`.\n * - Otherwise return `unknown` with a remediation hint.\n */\n/**\n * Cheap format check used by checkImessageAvailability before invoking\n * AppleScript. Messages.app's `buddy \"...\" of account` resolution is\n * lazy: any string returns a buddy reference, even literal nonsense\n * (\"not-a-handle\"). Without this guard the preflight reports\n * reachable:true for garbage and the caller's send_message later fails.\n *\n * Accepts E.164 phones (and digit/separator variants — the broader\n * recipient normalizer in `recipient.ts` will pick those up downstream)\n * and properly-shaped emails. Returns null when the handle passes; the\n * caller should then run the AppleScript probe.\n */\nexport function validateAvailabilityHandle(handle: string): ImessageAvailability | null {\n const trimmed = handle.trim();\n const isEmail = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(trimmed);\n const isPhone = /^\\+\\d{6,15}$/.test(trimmed.replace(/[\\s()\\-.]/g, \"\"));\n if (isEmail || isPhone) return null;\n return {\n service: \"unknown\",\n reachable: false,\n hint: \"Handle is neither a valid email nor a recognizable phone (expect E.164 like +61401990797).\",\n };\n}\n\nexport async function checkImessageAvailability(handle: string): Promise<ImessageAvailability> {\n // Reject obviously-invalid input first so we don't get false-positive\n // \"reachable: true\" from AppleScript's lazy buddy resolution.\n const formatFail = validateAvailabilityHandle(handle);\n if (formatFail) return formatFail;\n\n if (MOCK) {\n return { service: \"iMessage\", reachable: true };\n }\n\n const escaped = appleScriptEscape(handle);\n const script = `\n tell application \"Messages\"\n try\n set b to buddy \"${escaped}\" of (1st account whose service type is iMessage)\n return \"iMessage\"\n on error\n try\n set b to buddy \"${escaped}\" of (1st account whose service type is SMS)\n return \"SMS\"\n on error\n return \"unknown\"\n end try\n end try\n end tell\n `;\n try {\n const result = await runAppleScript(script);\n if (result === \"iMessage\" || result === \"SMS\") {\n return { service: result, reachable: true };\n }\n return {\n service: \"unknown\",\n reachable: false,\n hint: isPhoneLike(handle)\n ? \"Handle not found in iMessage or SMS buddies. Verify the number format (try '+1...' for US) and that the recipient has at least one of iMessage or SMS reachable.\"\n : \"Handle not found in iMessage buddies. For email addresses, the recipient must have iMessage active on that address.\",\n };\n } catch (error: any) {\n return {\n service: \"unknown\",\n reachable: false,\n hint: `Availability check failed: ${error.message ?? error}. Most common cause: Messages.app Automation permission is not granted to this terminal/IDE.`,\n };\n }\n}\n","import { existsSync } from \"node:fs\";\nimport os from \"node:os\";\nimport Database from \"better-sqlite3\";\nimport { checkMessagesAvailable } from \"./applescript.js\";\nimport { getContactsDbPaths, getImsgDbPath } from \"./config.js\";\n\nexport type AccessStatus = \"ok\" | \"warn\" | \"error\";\n\nexport interface AccessCheckItem {\n key: string;\n label: string;\n status: AccessStatus;\n detail: string;\n}\n\nexport interface AccessReport {\n ok: boolean;\n items: AccessCheckItem[];\n}\n\nfunction inspectSqlite(path: string): string | null {\n const db = new Database(path, { readonly: true, fileMustExist: true });\n try {\n db.pragma(\"schema_version\");\n return null;\n } finally {\n db.close();\n }\n}\n\nfunction classifyDbError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (/operation not permitted/i.test(message) || /authorization denied/i.test(message)) {\n return [\n \"Full Disk Access is missing for the app running this command.\",\n \"Grant Full Disk Access to Terminal, iTerm2, Warp, VS Code, Cursor, or whichever app is launching imsg-mcp, then fully restart that app.\",\n \"Open System Settings -> Privacy & Security -> Full Disk Access.\",\n ].join(\" \");\n }\n if (/unable to open database file/i.test(message) || /no such file/i.test(message)) {\n return \"Database file was not found at the configured path.\";\n }\n return message;\n}\n\nfunction iconFor(status: AccessStatus): string {\n if (status === \"ok\") return \"OK\";\n if (status === \"warn\") return \"WARN\";\n return \"ERR\";\n}\n\nexport async function checkLocalAccess(): Promise<AccessReport> {\n const items: AccessCheckItem[] = [];\n\n items.push({\n key: \"platform\",\n label: \"Platform\",\n status: process.platform === \"darwin\" ? \"ok\" : \"error\",\n detail:\n process.platform === \"darwin\"\n ? `Running on macOS ${os.release()}`\n : `Running on ${process.platform}; live iMessage access only works on macOS.`,\n });\n\n const imsgDbPath = getImsgDbPath();\n if (!existsSync(imsgDbPath)) {\n items.push({\n key: \"messages-db\",\n label: \"Messages DB\",\n status: \"error\",\n detail: `Missing ${imsgDbPath}`,\n });\n } else {\n try {\n const error = inspectSqlite(imsgDbPath);\n items.push({\n key: \"messages-db\",\n label: \"Messages DB\",\n status: error ? \"error\" : \"ok\",\n detail: error ? classifyDbError(error) : `Readable at ${imsgDbPath}`,\n });\n } catch (error) {\n items.push({\n key: \"messages-db\",\n label: \"Messages DB\",\n status: \"error\",\n detail: classifyDbError(error),\n });\n }\n }\n\n const contactPaths = getContactsDbPaths() ?? [];\n const existingContactPaths = contactPaths.filter((path) => existsSync(path));\n if (existingContactPaths.length === 0) {\n items.push({\n key: \"contacts-db\",\n label: \"Contacts DB\",\n status: \"warn\",\n detail:\n \"No readable Address Book database was found. Message reads still work, but names may stay as raw phone numbers or emails.\",\n });\n } else {\n const failures: string[] = [];\n for (const path of existingContactPaths) {\n try {\n inspectSqlite(path);\n } catch (error) {\n failures.push(`${path}: ${classifyDbError(error)}`);\n }\n }\n items.push({\n key: \"contacts-db\",\n label: \"Contacts DB\",\n status: failures.length === 0 ? \"ok\" : \"warn\",\n detail:\n failures.length === 0\n ? `Readable at ${existingContactPaths.join(\", \")}`\n : `Some contact databases are unreadable. ${failures.join(\" \")}`,\n });\n }\n\n const messagesRunning = await checkMessagesAvailable().catch(() => false);\n items.push({\n key: \"messages-app\",\n label: \"Messages.app\",\n status: messagesRunning ? \"ok\" : \"warn\",\n detail: messagesRunning\n ? \"Messages.app is running.\"\n : \"Messages.app is not running. Reading still works, but sending requires Messages.app to be open.\",\n });\n\n return {\n ok: items.every((item) => item.status !== \"error\"),\n items,\n };\n}\n\nexport function formatAccessReport(report: AccessReport): string {\n const lines = [\"imsg-mcp doctor\", \"\"];\n for (const item of report.items) {\n lines.push(`${iconFor(item.status)} ${item.label}`);\n lines.push(` ${item.detail}`);\n }\n lines.push(\"\");\n lines.push(\n report.ok\n ? \"Environment looks ready for local message reads.\"\n : \"Fix the ERR items above, then rerun `imsg doctor`.\",\n );\n return lines.join(\"\\n\");\n}\n","/**\n * Pure slug generation logic for conversation threads.\n * No side effects; takes data in, returns slug string.\n */\n\nimport { createHash } from \"node:crypto\";\n\n/** Sanitize a name into a slug-safe part: lowercase, spaces to hyphens, strip non-alphanumeric. */\nexport function sanitizeSlugPart(name: string): string {\n return name\n .toLowerCase()\n .replace(/['']/g, \"\")\n .replace(/[\\s_]+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\")\n .replace(/-{2,}/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/** 4-char hex hash derived from a string (deterministic). */\nexport function shortHash(input: string): string {\n return createHash(\"md5\").update(input).digest(\"hex\").slice(0, 4);\n}\n\n/** Abbreviate service name: \"iMessage\" -> \"imsg\", \"SMS\" -> \"sms\". */\nexport function serviceAbbrev(service: string): string {\n const lower = service.toLowerCase();\n if (lower === \"imessage\") return \"imsg\";\n if (lower === \"sms\") return \"sms\";\n return sanitizeSlugPart(lower) || \"msg\";\n}\n\n/** True if a chat_identifier looks like a group chat (starts with \"chat\"). */\nexport function isGroupChatIdentifier(chatIdentifier: string): boolean {\n return chatIdentifier.startsWith(\"chat\");\n}\n\n/** True if a chat guid indicates a group chat (contains \";+;\"). */\nexport function isGroupGuid(guid: string): boolean {\n return guid.includes(\";+;\");\n}\n\n/**\n * True if `value` matches the `name~service~hash` slug shape generated\n * above. Used by the CLI to decide whether `imsg send <target>` should\n * treat the target as a slug or as a recipient handle.\n *\n * Specifically distinguishes slugs from:\n * - emails — `~` is legal in the local-part (`user~beta@example.com`),\n * but slugs never have `@`\n * - phone numbers — never have `~`\n * - contact names — typed names don't use `~`\n */\nexport function looksLikeThreadSlug(value: string | undefined): boolean {\n if (!value) return false;\n if (value.includes(\"@\")) return false;\n const parts = value.split(\"~\");\n return parts.length === 3 && parts.every((p) => p.length > 0);\n}\n\nexport interface SlugInput {\n chatIdentifier: string;\n guid: string;\n displayName: string | null;\n serviceName: string | null;\n /** Resolved contact name for 1-on-1 chats (from ContactsDB). */\n resolvedContactName: string | null;\n /**\n * Stable identity key the hash is derived from, so every chat leg of one\n * identity yields the SAME slug. For a 1-on-1 with a resolved contact this is\n * `contact:<contactId>` (covers all the contact's numbers + emails across SMS\n * and iMessage); otherwise the normalized handle; for groups, the chat guid.\n * Falls back to `guid` when not provided.\n */\n identityKey?: string;\n}\n\n/**\n * Generate a thread slug from chat metadata.\n *\n * Format: {sanitized-name}~{service}~{short-hash}\n *\n * The hash is derived from `identityKey` (not the per-chat guid) so a contact\n * whose conversation is split across a phone chat and an email chat — and across\n * SMS + iMessage — collapses to ONE stable slug.\n *\n * Examples:\n * 1-on-1 with contact: alice~imsg~a3f2\n * 1-on-1 no contact: 61451082095~sms~b7c1\n * Named group: weekend-crew~imsg~d4e5\n * Unnamed group: group~imsg~f6a7\n */\nexport function generateThreadSlug(input: SlugInput): string {\n const svc = serviceAbbrev(input.serviceName || \"iMessage\");\n const hash = shortHash(input.identityKey ?? input.guid);\n const isGroup = isGroupGuid(input.guid) || isGroupChatIdentifier(input.chatIdentifier);\n\n let namePart: string;\n if (isGroup) {\n if (input.displayName && !input.displayName.startsWith(\"chat\")) {\n namePart = sanitizeSlugPart(input.displayName);\n } else {\n namePart = \"group\";\n }\n } else {\n if (input.resolvedContactName) {\n namePart = sanitizeSlugPart(input.resolvedContactName);\n } else if (input.displayName && input.displayName !== input.chatIdentifier) {\n namePart = sanitizeSlugPart(input.displayName);\n } else {\n namePart = sanitizeSlugPart(input.chatIdentifier.replace(/^\\+/, \"\"));\n }\n }\n\n if (!namePart) namePart = \"unknown\";\n\n return `${namePart}~${svc}~${hash}`;\n}\n","/**\n * Central shutdown / cleanup registry.\n *\n * Any module can register a cleanup function. On process exit (via signal,\n * stdin EOF, or orphan detection), all registered functions run exactly once\n * before the process exits.\n *\n * Prevents orphaned processes by:\n * 1. Trapping SIGINT, SIGTERM, SIGHUP, SIGQUIT\n * 2. Detecting stdin EOF (parent MCP host died)\n * 3. Watching for parent PID change (reparented to launchd = orphaned)\n */\n\nimport { appendLog } from \"./logger.js\";\n\ntype CleanupFn = () => void | Promise<void>;\n\nconst registry = new Set<CleanupFn>();\nlet shuttingDown = false;\nlet watchdogTimer: ReturnType<typeof setInterval> | null = null;\n\n/**\n * Register a cleanup function to run on shutdown.\n * Functions are called in registration order.\n */\nexport function registerCleanup(fn: CleanupFn): void {\n registry.add(fn);\n}\n\n/**\n * Unregister a previously registered cleanup function.\n */\nexport function unregisterCleanup(fn: CleanupFn): void {\n registry.delete(fn);\n}\n\n/**\n * Trigger graceful shutdown. Runs all cleanup functions, then exits.\n * Safe to call multiple times — only runs once.\n */\nexport async function shutdown(exitCode = 0): Promise<never> {\n if (shuttingDown) {\n // Already shutting down — force exit after 3s safety net\n setTimeout(() => process.exit(exitCode), 3000).unref();\n // Block forever (the timeout or a prior shutdown will exit)\n return new Promise<never>(() => {});\n }\n shuttingDown = true;\n\n // Stop watchdog\n if (watchdogTimer) {\n clearInterval(watchdogTimer);\n watchdogTimer = null;\n }\n\n // Run all cleanup functions (best-effort, don't let one failure block others)\n for (const fn of registry) {\n try {\n await fn();\n } catch {\n // Ignore cleanup errors during shutdown\n }\n }\n registry.clear();\n\n process.exit(exitCode);\n}\n\n/** Synchronous cleanup — last resort on process.on('exit') */\nfunction syncCleanup(): void {\n for (const fn of registry) {\n try {\n // Only call sync-safe functions here; async ones will be no-ops\n const result = fn();\n // If it returns a promise, we can't await it here — just ignore\n if (result && typeof (result as Promise<void>).catch === \"function\") {\n (result as Promise<void>).catch(() => {});\n }\n } catch {\n // Ignore\n }\n }\n}\n\nexport interface ShutdownOpts {\n /**\n * Whether to call `shutdown(70)` on `uncaughtException`. Defaults to\n * `true` — correct for MCP / one-shot CLI where an uncaught error means\n * undefined state and a clean restart is the right answer.\n *\n * **Set to `false` for the TUI**, where killing a long-running interactive\n * session over a transient render or async error wastes the user's work\n * and feels like a phantom crash. The TUI keeps running; the error is\n * still recorded via `appendLog(\"error\", \"uncaught_exception\", …)` so the\n * postmortem trail is intact.\n */\n exitOnUncaughtException?: boolean;\n}\n\n/**\n * Install signal handlers and orphan detection.\n * Call once at process startup.\n */\nexport function installShutdownHandlers(opts: ShutdownOpts = {}): void {\n const exitOnUncaught = opts.exitOnUncaughtException ?? true;\n // Signal handlers — log the signal name before cleanup so the post-mortem\n // NDJSON tells us *why* the process ended (e.g. host sent SIGTERM at $time).\n const onSignal = (signal: string) => {\n try {\n appendLog(\"info\", \"signal_received\", { signal });\n } catch {\n // logger may already be torn down; never fail shutdown over logging.\n }\n shutdown(signal === \"SIGINT\" ? 130 : 0);\n };\n\n for (const sig of [\"SIGINT\", \"SIGTERM\", \"SIGHUP\", \"SIGQUIT\"] as const) {\n process.on(sig, () => onSignal(sig));\n }\n\n // Catch-all for stray async errors. Pre-fix, a single unhandled\n // rejection in a background task (heartbeat / cache sweeper /\n // contact-sync) would crash the MCP without any trace in the NDJSON\n // log — the host saw an EPIPE and reconnected with a fresh PID.\n // We log + record but DO NOT exit; the SDK's per-request error\n // handler already isolates request failures.\n process.on(\"unhandledRejection\", (reason) => {\n try {\n appendLog(\"error\", \"unhandled_rejection\", {\n reason: reason instanceof Error ? reason.message : String(reason),\n stack: reason instanceof Error ? reason.stack : undefined,\n });\n } catch {\n // Logger may be torn down mid-shutdown; never re-throw from here.\n }\n });\n process.on(\"uncaughtException\", (err) => {\n try {\n appendLog(\"error\", \"uncaught_exception\", {\n message: err.message,\n stack: err.stack,\n });\n } catch {\n // Same as above.\n }\n // MCP / CLI policy: shutdown on uncaughtException — state is undefined,\n // a restart is the right answer. TUI policy (opt-in): log + keep\n // running so a transient React/Ink error doesn't kill the user's\n // session mid-compose.\n if (exitOnUncaught) shutdown(70);\n });\n\n // Synchronous last-resort cleanup\n process.on(\"exit\", syncCleanup);\n}\n\n/**\n * Enable stdin EOF detection — when the parent process dies, stdin closes.\n * Essential for MCP stdio servers to detect host death.\n */\nexport function enableStdinEofDetection(): void {\n process.stdin.on(\"end\", () => {\n if (!shuttingDown) shutdown(0);\n });\n process.stdin.resume();\n}\n\n/**\n * Enable parent PID watchdog — detects orphaned processes.\n * If the parent PID changes (reparented to launchd/init), trigger shutdown.\n * Timer is unref'd so it doesn't prevent natural exit.\n */\nexport function enableOrphanWatchdog(intervalMs = 5000): void {\n if (watchdogTimer) return;\n const parentPid = process.ppid;\n\n watchdogTimer = setInterval(() => {\n // ppid changes to 1 (launchd/init) when parent dies\n if (process.ppid === 1 || process.ppid !== parentPid) {\n shutdown(0);\n }\n }, intervalMs);\n watchdogTimer.unref();\n}\n\n/**\n * Check if shutdown is in progress.\n */\nexport function isShuttingDown(): boolean {\n return shuttingDown;\n}\n"],"names":["error"],"mappings":";;;;;;;AAIA,SAAS,eAAe,OAA2B,UAA0B;AAC3E,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,MAAM,WAAW,IAAI,KAAK,UAAU,KAAK;AAC3C,WAAO,KAAK,QAAA,GAAW,MAAM,MAAM,CAAC,CAAC;AAAA,EACvC;AACA,SAAO,QAAQ,QAAQ,IAAA,GAAO,KAAK;AACrC;AAEO,SAAS,SAAiB;AAC/B,SAAO,QAAQ,IAAI,YAAY;AACjC;AAGO,SAAS,UAAmB;AACjC,SAAO,aAAa;AACtB;AAOO,SAAS,gBAAwB;AACtC,SAAO;AAAA,IACL,QAAQ,IAAI;AAAA,IACZ,KAAK,QAAA,GAAW,WAAW,YAAY,SAAS;AAAA,EAAA;AAEpD;AAEO,SAAS,qBAA2C;AACzD,QAAM,OACJ,QAAQ,IAAI,yBACZ,KAAK,WAAW,WAAW,uBAAuB,eAAe,wBAAwB;AAE3F,QAAM,eAAe,eAAe,MAAM,EAAE;AAC5C,QAAM,QAAQ,oBAAI,IAAY,CAAC,YAAY,CAAC;AAE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