@posthog/wizard 2.84.1 → 2.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/{PickerMenu-BtheKi1o.js → PickerMenu-DB8MO29j.js} +14 -5
  2. package/dist/PickerMenu-DB8MO29j.js.map +1 -0
  3. package/dist/{agent-interface-D8mrarFD.js → agent-interface-DuRXDmuv.js} +18 -11
  4. package/dist/agent-interface-DuRXDmuv.js.map +1 -0
  5. package/dist/{agent-prompt-loader-Bt6mrV7q.js → agent-prompt-loader-DibvEzkO.js} +6 -6
  6. package/dist/{agent-prompt-loader-Bt6mrV7q.js.map → agent-prompt-loader-DibvEzkO.js.map} +1 -1
  7. package/dist/{analytics-CX2kvq0R.js → analytics-CZNcNpiq.js} +2 -2
  8. package/dist/{analytics-CX2kvq0R.js.map → analytics-CZNcNpiq.js.map} +1 -1
  9. package/dist/analytics-jaYrwNS5.js +2 -0
  10. package/dist/{api-BOP8gF35.js → api-C3wnIy9r.js} +2 -2
  11. package/dist/{api-BOP8gF35.js.map → api-C3wnIy9r.js.map} +1 -1
  12. package/dist/api-Cjhon9jT.js +2 -0
  13. package/dist/{api-key-login-DbrZknHp.js → api-key-login-BEoyy3Pq.js} +5 -5
  14. package/dist/{api-key-login-DbrZknHp.js.map → api-key-login-BEoyy3Pq.js.map} +1 -1
  15. package/dist/api-key-login-zfRkp4JK.js +2 -0
  16. package/dist/bin.js +1 -1
  17. package/dist/{bounded-fs-BENh-Jzc.js → bounded-fs-CQGn0HxE.js} +5 -4
  18. package/dist/bounded-fs-CQGn0HxE.js.map +1 -0
  19. package/dist/{ci-install-DnjuAl1l.js → ci-install-BG77SHEw.js} +4 -4
  20. package/dist/{ci-install-DnjuAl1l.js.map → ci-install-BG77SHEw.js.map} +1 -1
  21. package/dist/{debug-C_9xDg9j.js → debug-Bw13gmS3.js} +3 -3
  22. package/dist/debug-Bw13gmS3.js.map +1 -0
  23. package/dist/{defaults-BWLIffh5.js → defaults-CLRka8GN.js} +4 -5
  24. package/dist/{defaults-BWLIffh5.js.map → defaults-CLRka8GN.js.map} +1 -1
  25. package/dist/{family-picker-CAW_VtYf.js → family-picker-CntEtZJE.js} +2 -2
  26. package/dist/{family-picker-CAW_VtYf.js.map → family-picker-CntEtZJE.js.map} +1 -1
  27. package/dist/{gateway-C6_zPLyx.js → gateway-Cl7h4Eot.js} +9 -6
  28. package/dist/{gateway-C6_zPLyx.js.map → gateway-Cl7h4Eot.js.map} +1 -1
  29. package/dist/{headless-BIQpNAHc.js → headless-DRA4mv9n.js} +2 -2
  30. package/dist/{headless-BIQpNAHc.js.map → headless-DRA4mv9n.js.map} +1 -1
  31. package/dist/{headless-sWzDbxAu.js → headless-DZAVKFMW.js} +1 -1
  32. package/dist/{host-resolution-C3ctTKNg.js → host-resolution-B0cQUK2A.js} +4 -4
  33. package/dist/{host-resolution-C3ctTKNg.js.map → host-resolution-B0cQUK2A.js.map} +1 -1
  34. package/dist/{install-CDhljVka.js → install-C0CKn7AV.js} +1 -1
  35. package/dist/{install-Dayhuaun.js → install-IvnTzMlR.js} +137 -39
  36. package/dist/install-IvnTzMlR.js.map +1 -0
  37. package/dist/{interactive-CjbttghI.js → interactive-wm9OcauB.js} +3 -3
  38. package/dist/{interactive-CjbttghI.js.map → interactive-wm9OcauB.js.map} +1 -1
  39. package/dist/{links-BOOGSL_G.js → links-Cj6OQ9Kv.js} +3 -3
  40. package/dist/{links-BOOGSL_G.js.map → links-Cj6OQ9Kv.js.map} +1 -1
  41. package/dist/{main-MzQaWN8w.js → main-SU6W6oek.js} +20 -20
  42. package/dist/{main-MzQaWN8w.js.map → main-SU6W6oek.js.map} +1 -1
  43. package/dist/{mcp-BwlD260T.js → mcp-m46rxecB.js} +3 -3
  44. package/dist/{mcp-BwlD260T.js.map → mcp-m46rxecB.js.map} +1 -1
  45. package/dist/{mcp-prompt-streaming-CoplNPI8.js → mcp-prompt-streaming-DuDUi7nq.js} +5 -5
  46. package/dist/{mcp-prompt-streaming-CoplNPI8.js.map → mcp-prompt-streaming-DuDUi7nq.js.map} +1 -1
  47. package/dist/{models-HwzgIr2E.js → models-D6XiGoty.js} +2 -2
  48. package/dist/{models-HwzgIr2E.js.map → models-D6XiGoty.js.map} +1 -1
  49. package/dist/{oauth-session-C4JV-yA9.js → oauth-session-DvAgen9l.js} +2 -2
  50. package/dist/{oauth-session-C4JV-yA9.js.map → oauth-session-DvAgen9l.js.map} +1 -1
  51. package/dist/{orchestrator-tools-Dr4w80Tn.js → orchestrator-tools-DSKw-1S6.js} +3 -3
  52. package/dist/{orchestrator-tools-Dr4w80Tn.js.map → orchestrator-tools-DSKw-1S6.js.map} +1 -1
  53. package/dist/{package-manager-Zw0JN1Kh.js → package-manager-CPzIaeu0.js} +4 -4
  54. package/dist/{package-manager-Zw0JN1Kh.js.map → package-manager-CPzIaeu0.js.map} +1 -1
  55. package/dist/{pi-qzRJcTgu.js → pi-T8emzbHL.js} +12 -12
  56. package/dist/{pi-qzRJcTgu.js.map → pi-T8emzbHL.js.map} +1 -1
  57. package/dist/{playground-B0SpcGYQ.js → playground-DE_9g_nd.js} +4 -4
  58. package/dist/{playground-B0SpcGYQ.js.map → playground-DE_9g_nd.js.map} +1 -1
  59. package/dist/{posthog-integration-4vQjbU-f.js → posthog-integration-CuEK-hPp.js} +21 -21
  60. package/dist/{posthog-integration-4vQjbU-f.js.map → posthog-integration-CuEK-hPp.js.map} +1 -1
  61. package/dist/programs-CWXzMPOe.js +3 -0
  62. package/dist/{programs-7aIrstFy.js → programs-T4EhU20m.js} +19 -15
  63. package/dist/programs-T4EhU20m.js.map +1 -0
  64. package/dist/{provisioning-BMJ3J0Vb.js → provisioning-9_MWLl8u.js} +4 -4
  65. package/dist/{provisioning-BMJ3J0Vb.js.map → provisioning-9_MWLl8u.js.map} +1 -1
  66. package/dist/provisioning-BXahZmpw.js +2 -0
  67. package/dist/{queue-tools-D8HPaGck.js → queue-tools-jFZ5kLU1.js} +4 -4
  68. package/dist/{queue-tools-D8HPaGck.js.map → queue-tools-jFZ5kLU1.js.map} +1 -1
  69. package/dist/{results-8xNiBbaP.js → results-CXTeEIUi.js} +2 -2
  70. package/dist/{results-8xNiBbaP.js.map → results-CXTeEIUi.js.map} +1 -1
  71. package/dist/{run-Dte7AuRg.js → run-Bnu1vqZG.js} +10 -10
  72. package/dist/{run-Dte7AuRg.js.map → run-Bnu1vqZG.js.map} +1 -1
  73. package/dist/run-tool-B0kgP7oA.js +2 -0
  74. package/dist/{run-tool-sdhoPp9H.js → run-tool-DOZz2dEJ.js} +37 -30
  75. package/dist/{run-tool-sdhoPp9H.js.map → run-tool-DOZz2dEJ.js.map} +1 -1
  76. package/dist/{run-DUcJFhzP.js → run-yiqaCX7y.js} +7 -7
  77. package/dist/{run-DUcJFhzP.js.map → run-yiqaCX7y.js.map} +1 -1
  78. package/dist/{runners-DxbNGuKH.js → runners-CVFLsNvO.js} +8 -8
  79. package/dist/{runners-DxbNGuKH.js.map → runners-CVFLsNvO.js.map} +1 -1
  80. package/dist/{security-BMqK129i.js → security-Bk0aumrm.js} +5 -5
  81. package/dist/{security-BMqK129i.js.map → security-Bk0aumrm.js.map} +1 -1
  82. package/dist/{setup-utils-DBOw3lnu.js → setup-utils-D5SquGvT.js} +3 -3
  83. package/dist/{setup-utils-DBOw3lnu.js.map → setup-utils-D5SquGvT.js.map} +1 -1
  84. package/dist/{start-playground-Uf3nte-P.js → start-playground-C__Gy1yk.js} +29 -14
  85. package/dist/start-playground-C__Gy1yk.js.map +1 -0
  86. package/dist/{subagent-DYza5kN6.js → subagent-DaSkUEg7.js} +3 -3
  87. package/dist/{subagent-DYza5kN6.js.map → subagent-DaSkUEg7.js.map} +1 -1
  88. package/dist/{task-CiStV2CD.js → task-Bv_o-lNo.js} +14 -14
  89. package/dist/{task-CiStV2CD.js.map → task-Bv_o-lNo.js.map} +1 -1
  90. package/dist/{telemetry-DLLuQiCt.js → telemetry-d_03gIpQ.js} +2 -2
  91. package/dist/{telemetry-DLLuQiCt.js.map → telemetry-d_03gIpQ.js.map} +1 -1
  92. package/dist/{terminal-B4EXuZra.js → terminal-BLGYQpSO.js} +583 -341
  93. package/dist/terminal-BLGYQpSO.js.map +1 -0
  94. package/dist/{tools-M5ENAiPc.js → tools-BE4Et6sl.js} +8 -8
  95. package/dist/{tools-M5ENAiPc.js.map → tools-BE4Et6sl.js.map} +1 -1
  96. package/dist/{tools-BTAi_RrA.js → tools-C8-l1rBv.js} +14 -14
  97. package/dist/{tools-BTAi_RrA.js.map → tools-C8-l1rBv.js.map} +1 -1
  98. package/dist/{tui-DigZ-Q1i.js → tui-DivYObcb.js} +5 -5
  99. package/dist/{tui-DigZ-Q1i.js.map → tui-DivYObcb.js.map} +1 -1
  100. package/dist/{tui-DU9MmsAK.js → tui-Zdby16pT.js} +1 -1
  101. package/dist/{upload-step-VNWq-3aL.js → upload-step-BfAUAEYC.js} +3 -3
  102. package/dist/{upload-step-VNWq-3aL.js.map → upload-step-BfAUAEYC.js.map} +1 -1
  103. package/dist/{urls-Bgngk5HI.js → urls-CvKF1P3f.js} +2 -2
  104. package/dist/{urls-Bgngk5HI.js.map → urls-CvKF1P3f.js.map} +1 -1
  105. package/dist/{wizard-abort-CdKk1lpi.js → wizard-abort-DTn9HFAi.js} +4 -4
  106. package/dist/{wizard-abort-CdKk1lpi.js.map → wizard-abort-DTn9HFAi.js.map} +1 -1
  107. package/dist/{yara-hooks-DPqy6eVo.js → yara-hooks-CA_ZEpAV.js} +4 -4
  108. package/dist/{yara-hooks-DPqy6eVo.js.map → yara-hooks-CA_ZEpAV.js.map} +1 -1
  109. package/dist/{yara-hooks-DCgSsXFP.js → yara-hooks-DXIqi0Km.js} +1 -1
  110. package/package.json +1 -1
  111. package/dist/PickerMenu-BtheKi1o.js.map +0 -1
  112. package/dist/agent-interface-D8mrarFD.js.map +0 -1
  113. package/dist/analytics-DgLAjlIK.js +0 -2
  114. package/dist/api-BphZo4f2.js +0 -2
  115. package/dist/api-key-login-BEi3wymJ.js +0 -2
  116. package/dist/bounded-fs-BENh-Jzc.js.map +0 -1
  117. package/dist/debug-C_9xDg9j.js.map +0 -1
  118. package/dist/install-Dayhuaun.js.map +0 -1
  119. package/dist/programs-7aIrstFy.js.map +0 -1
  120. package/dist/programs-B9Iu3Mye.js +0 -3
  121. package/dist/provisioning-BG_lh4hk.js +0 -2
  122. package/dist/run-tool-BXpuefYa.js +0 -2
  123. package/dist/start-playground-Uf3nte-P.js.map +0 -1
  124. package/dist/terminal-B4EXuZra.js.map +0 -1
@@ -1,2 +0,0 @@
1
- import { n as analytics } from "./analytics-CX2kvq0R.js";
2
- export { analytics };
@@ -1,2 +0,0 @@
1
- import { n as ApiError } from "./api-BOP8gF35.js";
2
- export { ApiError };
@@ -1,2 +0,0 @@
1
- import { t as resolveApiKeyProject } from "./api-key-login-DbrZknHp.js";
2
- export { resolveApiKeyProject };
@@ -1 +0,0 @@
1
- {"version":3,"file":"bounded-fs-BENh-Jzc.js","names":[],"sources":["../src/shared/utils/bounded-fs.ts"],"sourcesContent":["/**\n * Bounded filesystem primitives for scanning USER project trees. Every\n * detection-time glob, walk, and project-file read goes through here so the\n * worst case is a constant, never a function of the user's repo.\n */\nimport path from 'path';\nimport fs from 'fs';\nimport type { Dirent } from 'fs';\nimport fg from 'fast-glob';\nimport { analytics } from './analytics';\nimport { logToFile } from './debug';\nimport type { WizardRunOptions } from './types';\n\n/**\n * Errno codes that are expected while walking an arbitrary tree and mean\n * \"skip this entry\", not \"something is broken\". Scanning from a broad dir\n * (e.g. `~`) routinely hits OS-protected paths (macOS `Library/Group\n * Containers/group.com.apple.*`) that throw EPERM/EACCES per entry — capturing\n * each as an exception buried real errors under thousands of noise events.\n */\nconst BENIGN_FS_ERROR_CODES = new Set<string>([\n 'EACCES', // permission denied\n 'EPERM', // operation not permitted (macOS-protected dirs)\n 'ENOENT', // entry vanished mid-walk\n 'ENOTDIR', // path component isn't a directory\n 'ELOOP', // symlink loop\n 'ENAMETOOLONG', // path too long\n 'EMFILE', // too many open files (environmental, not a wizard bug)\n 'ENFILE',\n 'EBUSY', // file locked by another process (Windows)\n 'UNKNOWN', // libuv could not map the OS error (Windows locked/placeholder files)\n]);\n\n/**\n * Report a swallowed filesystem error. Traversal stays best-effort — the caller\n * still skips the failing entry. Expected errno codes (permission denied, entry\n * vanished, symlink loops…) are logged to the debug file only; anything else is\n * genuinely unexpected and gets captured to error tracking. Preserves the\n * original Error (and its `code`, e.g. EACCES / ENOENT) when available.\n */\nfunction reportFsError(step: string, filePath: string, error: unknown): void {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code && BENIGN_FS_ERROR_CODES.has(code)) {\n logToFile(`[bounded-fs] skipped ${step} (${code}): ${filePath}`);\n return;\n }\n analytics.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step, path: filePath },\n );\n}\n\nexport function getDotGitignore({\n installDir,\n}: Pick<WizardRunOptions, 'installDir'>) {\n const gitignorePath = path.join(installDir, '.gitignore');\n const gitignoreExists = fs.existsSync(gitignorePath);\n\n if (gitignoreExists) {\n return gitignorePath;\n }\n\n return undefined;\n}\n\n/**\n * Directory names to skip when scanning a project tree — dependency\n * directories, build output, virtual environments, vendored trees.\n * Used verbatim by walkProjectFiles and as glob patterns by boundedGlob.\n */\nexport const IGNORED_DIRS = new Set<string>([\n 'node_modules',\n '.git',\n '.next',\n '.nuxt',\n '.svelte-kit',\n '.turbo',\n '.cache',\n '.parcel-cache',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n '.coverage',\n 'venv',\n '.venv',\n '__pycache__',\n '.pytest_cache',\n 'vendor',\n 'target',\n '.gradle',\n '.idea',\n '.vscode',\n 'site-packages',\n 'DerivedData',\n 'Pods',\n]);\n\n/** IGNORED_DIRS as fast-glob ignore patterns. */\nexport const PROJECT_IGNORE_GLOBS: readonly string[] = [...IGNORED_DIRS].map(\n (dir) => `**/${dir}/**`,\n);\n\n// Files larger than this are skipped, never materialized.\nexport const MAX_PROJECT_FILE_BYTES = 2 * 1024 * 1024;\n\n// A glob returns at most this many entries.\nexport const MAX_GLOB_MATCHES = 500;\n\n// A glob's traversal is destroyed after this long, even when abandoned.\nexport const GLOB_DEADLINE_MS = 8_000;\n\n// A directory contributes at most this many entries to a walk.\nexport const MAX_DIR_ENTRIES = 10_000;\n\n// A walk fires at most this many onFile callbacks.\nexport const MAX_WALK_FILES = 100_000;\n\nexport interface BoundedGlobOptions {\n cwd: string;\n /** Appended to PROJECT_IGNORE_GLOBS. */\n extraIgnore?: readonly string[];\n /** Stop after this many matches. Defaults to MAX_GLOB_MATCHES. */\n limit?: number;\n /** Match dotfiles. Traversal of dot-DIRECTORIES stays blocked by the ignore set. */\n dot?: boolean;\n /** fast-glob `deep` — maximum directory depth. */\n deep?: number;\n}\n\n/**\n * Streams matches, stops at `limit`, destroys the crawl at GLOB_DEADLINE_MS.\n * Returns paths relative to `cwd`, possibly truncated.\n */\nexport async function boundedGlob(\n patterns: string | string[],\n options: BoundedGlobOptions,\n): Promise<string[]> {\n const limit = options.limit ?? MAX_GLOB_MATCHES;\n const stream = fg.stream(patterns, {\n cwd: options.cwd,\n dot: options.dot ?? false,\n onlyFiles: true,\n deep: options.deep,\n ignore: [...PROJECT_IGNORE_GLOBS, ...(options.extraIgnore ?? [])],\n suppressErrors: true,\n followSymbolicLinks: false,\n }) as NodeJS.ReadableStream & { destroy(): void };\n\n const matches: string[] = [];\n return new Promise((resolve) => {\n let settled = false;\n const finish = (): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(matches);\n };\n const timer = setTimeout(() => {\n stream.destroy();\n finish();\n }, GLOB_DEADLINE_MS);\n stream.on('data', (entry: string | Buffer) => {\n matches.push(String(entry));\n if (matches.length >= limit) {\n stream.destroy();\n finish();\n }\n });\n stream.once('error', finish);\n stream.once('end', finish);\n stream.once('close', finish);\n });\n}\n\nexport interface WalkOptions {\n /**\n * Follow symlinked files and directories. Defaults to true. A caller that\n * reports what it reads turns this off: a symlink can point anywhere on the\n * machine, outside the project it is scanning.\n */\n followSymlinks?: boolean;\n}\n\n/**\n * Walk a project tree, invoking `onFile(name, fullPath)` for every regular\n * file — including dotfiles like `.env` (the caller decides what it cares\n * about). Skips `IGNORED_DIRS` and hidden directories, follows symlinks\n * (unless `followSymlinks` is false) with realpath-based loop protection,\n * descends at most `maxDepth` levels below `rootDir`, and stops at the\n * per-directory and whole-walk caps. Filesystem errors are reported and\n * skipped (best-effort).\n *\n * Returns whether the walk saw the whole tree within `maxDepth`: false when it\n * stopped at a cap or skipped a directory it could not read.\n */\nexport function walkProjectFiles(\n rootDir: string,\n onFile: (name: string, fullPath: string) => void,\n maxDepth = 3,\n { followSymlinks = true }: WalkOptions = {},\n): boolean {\n const visited = new Set<string>();\n let filesSeen = 0;\n let complete = true;\n // Explicit stack — no call-stack recursion.\n const stack: Array<{ dir: string; depth: number }> = [\n { dir: rootDir, depth: 0 },\n ];\n\n while (stack.length > 0) {\n if (filesSeen >= MAX_WALK_FILES) {\n complete = false;\n break;\n }\n const { dir, depth } = stack.pop()!;\n\n // realpath both resolves symlinked dirs and gives us a stable key to\n // detect loops (symlink cycles, e.g. a -> ../a).\n let realDir: string;\n try {\n realDir = fs.realpathSync(dir);\n } catch (error) {\n reportFsError('walkProjectFiles.realpath', dir, error);\n complete = false;\n continue;\n }\n if (visited.has(realDir)) continue;\n visited.add(realDir);\n\n let handle: fs.Dir;\n try {\n handle = fs.opendirSync(dir);\n } catch (error) {\n reportFsError('walkProjectFiles.opendir', dir, error);\n complete = false;\n continue;\n }\n try {\n let entriesRead = 0;\n let entry: Dirent | null;\n while ((entry = handle.readSync()) !== null) {\n if (++entriesRead > MAX_DIR_ENTRIES || filesSeen >= MAX_WALK_FILES) {\n logToFile(\n `[bounded-fs] walk capped in ${dir} (entries=${entriesRead}, files=${filesSeen})`,\n );\n complete = false;\n break;\n }\n if (IGNORED_DIRS.has(entry.name)) continue;\n\n const fullPath = path.join(dir, entry.name);\n\n // Symlinks report isDirectory()/isFile() as false under withFileTypes,\n // so resolve the target before deciding how to handle the entry.\n let isDir = entry.isDirectory();\n let isFile = entry.isFile();\n if (entry.isSymbolicLink()) {\n if (!followSymlinks) continue;\n try {\n const st = fs.statSync(fullPath);\n isDir = st.isDirectory();\n isFile = st.isFile();\n } catch (error) {\n reportFsError('walkProjectFiles.stat', fullPath, error);\n continue;\n }\n }\n\n if (isDir) {\n if (entry.name.startsWith('.')) continue; // skip hidden directories\n if (depth < maxDepth) stack.push({ dir: fullPath, depth: depth + 1 });\n } else if (isFile) {\n filesSeen += 1;\n onFile(entry.name, fullPath);\n }\n }\n } finally {\n try {\n handle.closeSync();\n } catch {\n /* already closed */\n }\n }\n }\n return complete;\n}\n\n/**\n * Read a project file as UTF-8, or null when missing, unreadable, or over\n * `maxBytes` (stat-gated: an oversized file is never materialized).\n */\nexport function readProjectFile(\n filePath: string,\n maxBytes = MAX_PROJECT_FILE_BYTES,\n): string | null {\n try {\n if (fs.statSync(filePath).size > maxBytes) return null;\n return fs.readFileSync(filePath, 'utf-8');\n } catch {\n return null;\n }\n}\n\n/**\n * `readProjectFile` that also reports unexpected errors to error tracking.\n * For walk callbacks where a failing read is worth a telemetry breadcrumb.\n */\nexport function safeReadFile(fullPath: string): string | null {\n try {\n if (fs.statSync(fullPath).size > MAX_PROJECT_FILE_BYTES) {\n logToFile(`[bounded-fs] skipped oversized file: ${fullPath}`);\n return null;\n }\n return fs.readFileSync(fullPath, 'utf-8');\n } catch (error) {\n reportFsError('safeReadFile', fullPath, error);\n return null;\n }\n}\n\n/**\n * The first `bytes` of a file without materializing the rest.\n */\nexport function readFileHead(filePath: string, bytes: number): string | null {\n try {\n const fd = fs.openSync(filePath, 'r');\n try {\n const buffer = Buffer.alloc(bytes);\n const read = fs.readSync(fd, buffer, 0, bytes, 0);\n return buffer.toString('utf-8', 0, read);\n } finally {\n fs.closeSync(fd);\n }\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,MAAM,wBAA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AI,CAAC,eAAgB;AACrB,SAAI;MACF,MAAM,KAAK,GAAG,SAAS,SAAS;AAChC,cAAQ,GAAG,aAAa;AACxB,eAAS,GAAG,QAAQ;cACb,OAAO;AACd,oBAAc,yBAAyB,UAAU,MAAM;AACvD;;;AAIJ,QAAI,OAAO;AACT,SAAI,MAAM,KAAK,WAAW,IAAI,CAAE;AAChC,SAAI,QAAQ,SAAU,OAAM,KAAK;MAAE,KAAK;MAAU,OAAO,QAAQ;MAAG,CAAC;eAC5D,QAAQ;AACjB,kBAAa;AACb,YAAO,MAAM,MAAM,SAAS;;;YAGxB;AACR,OAAI;AACF,WAAO,WAAW;WACZ;;;AAKZ,QAAO;;;;;;AAOT,SAAgB,gBACd,UACA,WAAW,wBACI;AACf,KAAI;AACF,MAAI,GAAG,SAAS,SAAS,CAAC,OAAO,SAAU,QAAO;AAClD,SAAO,GAAG,aAAa,UAAU,QAAQ;SACnC;AACN,SAAO;;;;;;;AAQX,SAAgB,aAAa,UAAiC;AAC5D,KAAI;AACF,MAAI,GAAG,SAAS,SAAS,CAAC,OAAA,SAA+B;AACvD,aAAU,wCAAwC,WAAW;AAC7D,UAAO;;AAET,SAAO,GAAG,aAAa,UAAU,QAAQ;UAClC,OAAO;AACd,gBAAc,gBAAgB,UAAU,MAAM;AAC9C,SAAO;;;;;;AAOX,SAAgB,aAAa,UAAkB,OAA8B;AAC3E,KAAI;EACF,MAAM,KAAK,GAAG,SAAS,UAAU,IAAI;AACrC,MAAI;GACF,MAAM,SAAS,OAAO,MAAM,MAAM;GAClC,MAAM,OAAO,GAAG,SAAS,IAAI,QAAQ,GAAG,OAAO,EAAE;AACjD,UAAO,OAAO,SAAS,SAAS,GAAG,KAAK;YAChC;AACR,MAAG,UAAU,GAAG;;SAEZ;AACN,SAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"debug-C_9xDg9j.js","names":["join","sep"],"sources":["../src/env.ts","../src/shared/version.ts","../src/shared/utils/paths.ts","../src/shared/utils/debug.ts"],"sourcesContent":["/**\n * Central environment variable access for the PostHog wizard.\n *\n * ── Build-time constants ────────────────────────────────────────────\n * Inlined by tsdown's `env` option at compile time. After build, the\n * runtime value of these env vars has zero effect on the wizard.\n *\n * ── Runtime variables ───────────────────────────────────────────────\n * Read through `runtimeEnv()` with a typed allowlist. This makes every\n * runtime dependency on the environment explicit and grep-able.\n *\n * ── Direct process.env access ───────────────────────────────────────\n * Reserved for subprocess environment configuration (writes) and\n * vendored code. Production source outside those cases should use\n * this module instead.\n */\n\n/**\n * The on-CLI flag name. Intentionally ugly + undocumented; do not surface it in\n * `--help`, the README, or user-facing error messages.\n */\nexport const HEADLESS_FLAG = 'headless-DONOTUSE-EXPERIMENTAL';\n\n// ── Build-time constants ─────────────────────────────────────────────\n// tsdown replaces `process.env.NODE_ENV` with a string literal.\n// After build these are just `\"production\"`, `false`, etc.\n\nexport const NODE_ENV = process.env.NODE_ENV as string;\nexport const IS_DEV =\n process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';\n\n/**\n * True only in published/production builds. tsdown inlines\n * `process.env.NODE_ENV` as the literal `\"production\"` at build time, so this\n * collapses to `true` in `dist/` and stays `false` for `tsx`/dev/test runs\n * (where NODE_ENV is unset, `development`, or `test`). Used to gate features\n * that aren't supported in the shipped package — e.g. `--ci` mode.\n */\nexport const IS_PRODUCTION_BUILD = process.env.NODE_ENV === 'production';\n\n/** 'cloud' when launched with the experimental headless flag, else 'local' — resolved once from argv at launch. */\nexport const RUN_SURFACE: 'cloud' | 'local' = process.argv.some(\n (a) => a === `--${HEADLESS_FLAG}` || a.startsWith(`--${HEADLESS_FLAG}=`),\n)\n ? 'cloud'\n : 'local';\n\n// ── Runtime environment ──────────────────────────────────────────────\n\n/**\n * Exhaustive allowlist of env vars the wizard reads at runtime.\n * Add new keys here when a new runtime dependency is needed.\n */\ntype RuntimeEnvKey =\n // CI-build-only flag overrides (see utils/ci-flag-overrides.ts).\n // Deliberately NOT POSTHOG_WIZARD_-prefixed: yargs .env('POSTHOG_WIZARD')\n // would claim it as an unknown CLI option and strict-reject the run.\n | 'WIZARD_CI_FLAG_OVERRIDES'\n | 'WIZARD_CI_EXCLUDE_TASKS'\n | 'WIZARD_CI_GATEWAY_TOKEN_FILE'\n | 'WIZARD_CI_GATEWAY_URL'\n // Wizard CLI configuration (yargs POSTHOG_WIZARD_ prefix)\n | 'POSTHOG_WIZARD_BENCHMARK_CONFIG'\n | 'POSTHOG_WIZARD_BENCHMARK_FILE'\n | 'POSTHOG_WIZARD_LOG_DIR'\n | 'POSTHOG_WIZARD_DEBUG'\n // Identity of the PostHog task run whose sandbox launched this wizard. Set by\n // the sandbox for every run it starts, agent or wizard. Deliberately NOT\n // POSTHOG_WIZARD_-prefixed, for the same reason as the two keys above:\n // yargs .env('POSTHOG_WIZARD') would claim them as CLI options and\n // .strictOptions() would reject the run unless the wizard also declared them,\n // which would tie every sandbox deploy to an npm release of this package.\n | 'POSTHOG_WIZARD_RUN_ID'\n | 'POSTHOG_TASK_RUN_ID'\n | 'POSTHOG_TASK_ID'\n | 'POSTHOG_HANDOFF_OUTPUT_PATH'\n // Local/CI escape hatch to disable Warlock scanning without the PostHog flag.\n | 'POSTHOG_WIZARD_WARLOCK_DISABLED'\n // Dev-build override of the Decisions judgment service's mode: off, shadow or primary.\n | 'WIZARD_DECISIONS_DETECTION'\n | 'DEBUG'\n // Agent / MCP\n | 'MCP_URL'\n | 'POSTHOG_API_KEY'\n // Platform: terminal detection\n | 'TERM'\n | 'TERM_PROGRAM'\n | 'TERMINAL_EMULATOR'\n | 'CI'\n | 'WT_SESSION'\n | 'TERMINUS_SUBLIME'\n | 'ConEmuTask'\n // Platform: paths\n | 'APPDATA'\n | 'OPENCODE_CONFIG_DIR'\n | 'XDG_CONFIG_HOME';\n\n/** Read a runtime environment variable. Only allowlisted keys compile. */\nexport function runtimeEnv(key: RuntimeEnvKey): string | undefined {\n return process.env[key];\n}\n\n/**\n * The PostHog task run that launched this wizard, when one did. A cloud run's\n * sandbox exports both ids into the wizard's environment; every local run\n * leaves them undefined. Resolved once at launch, like RUN_SURFACE above.\n */\nexport const TASK_RUN_ID: string | undefined =\n runtimeEnv('POSTHOG_TASK_RUN_ID') || undefined;\nexport const TASK_ID: string | undefined =\n runtimeEnv('POSTHOG_TASK_ID') || undefined;\n","// Auto-generated by scripts/generate-version.js — do not edit\nexport const VERSION = '2.84.1';\n","import { tmpdir } from 'node:os';\nimport { join, sep } from 'node:path';\n\n// /tmp is stable and discoverable on macOS/Linux; Windows needs os.tmpdir()\nconst TMP = process.platform === 'win32' ? tmpdir() : '/tmp';\n\nexport const WIZARD_LOG_FILE = join(TMP, 'posthog-wizard.log');\nexport const WIZARD_BENCHMARK_FILE = join(TMP, 'posthog-wizard-benchmark.json');\n/** Default target of `--task-stream-log`. Dev builds only. */\nexport const WIZARD_TASK_STREAM_FILE = join(\n TMP,\n 'posthog-wizard-task-stream.jsonl',\n);\nexport const WIZARD_YARA_REPORT_FILE = join(\n TMP,\n 'posthog-wizard-yara-report.json',\n);\n/**\n * Strip an absolute installDir prefix off a project file path so the UI\n * renders `index.js:12` instead of `/Users/.../index.js:12`. Defends\n * against false matches like `/Users/foo` ⊂ `/Users/foobar/x.js` by\n * normalizing to a trailing path separator before the prefix check.\n */\nexport function relativeToInstallDir(file: string, installDir: string): string {\n const prefix = installDir.endsWith(sep) ? installDir : installDir + sep;\n return file.startsWith(prefix) ? file.slice(prefix.length) : file;\n}\n","import { appendFileSync, mkdirSync } from 'fs';\nimport path from 'path';\nimport { inspect } from 'node:util';\nimport { IS_DEV, runtimeEnv } from '@env';\nimport { WIZARD_LOG_FILE } from './paths';\n\n// Dev builds may redirect the log so concurrent runs don't interleave one file.\nlet logFilePath =\n (IS_DEV && process.env.POSTHOG_WIZARD_LOG_FILE) || WIZARD_LOG_FILE;\nlet fileLoggingEnabled = true;\n// An explicit --log-file wins over every later path change while pinned.\nlet logFilePinned = false;\n\nfunction stringify(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value instanceof Error) return value.stack ?? String(value);\n try {\n // JSON.stringify throws on cycles and skips some values — fall back to\n // inspect so a crash log line is never dropped.\n return JSON.stringify(value, null, 2) ?? inspect(value, { depth: 3 });\n } catch {\n return inspect(value, { depth: 3 });\n }\n}\n\n/** One log line from `logToFile`-style arguments: strings as they are, errors as their stack, the rest as JSON. */\nexport function formatLogLine(...args: readonly unknown[]): string {\n return args.map(stringify).join(' ');\n}\n\nexport function getLogFilePath(): string {\n return logFilePath;\n}\n\nexport function configureLogFile(opts: {\n path?: string;\n enabled?: boolean;\n pin?: boolean;\n}): void {\n if (opts.pin === false) logFilePinned = false;\n if (opts.path !== undefined && !logFilePinned) {\n logFilePath = opts.path;\n ensuredLogDir = false;\n }\n if (opts.pin === true) logFilePinned = true;\n if (opts.enabled !== undefined) fileLoggingEnabled = opts.enabled;\n}\n\nlet ensuredLogDir = false;\nlet reportedLogFailure = false;\n\n// Failed log writes go to error tracking, once per process. Dynamic import:\n// analytics logs through this module, so a static import would be a cycle.\nfunction reportLogFailureOnce(err: unknown): void {\n if (reportedLogFailure) return;\n reportedLogFailure = true;\n void import('./analytics')\n .then(({ analytics }) =>\n analytics.captureException(\n err instanceof Error ? err : new Error(String(err)),\n {\n source: 'log-file-write',\n log_path: logFilePath,\n platform: process.platform,\n },\n ),\n )\n .catch(() => {\n // Reporting must never crash the wizard either.\n });\n}\n\n// The log's directory isn't guaranteed to exist (Windows %TEMP%,\n// POSTHOG_WIZARD_LOG_DIR) — create it on first failure.\nfunction appendLine(text: string): void {\n try {\n appendFileSync(logFilePath, text);\n } catch (err) {\n if (ensuredLogDir) {\n reportLogFailureOnce(err);\n return;\n }\n ensuredLogDir = true;\n try {\n mkdirSync(path.dirname(logFilePath), { recursive: true });\n appendFileSync(logFilePath, text);\n } catch (retryErr) {\n reportLogFailureOnce(retryErr);\n }\n }\n}\n\nexport function configureLogFileFromEnvironment(): void {\n const dir = runtimeEnv('POSTHOG_WIZARD_LOG_DIR');\n if (dir) {\n configureLogFile({ path: path.join(dir, 'posthog-wizard.log') });\n }\n}\n\nexport function initLogFile(): void {\n if (!fileLoggingEnabled) return;\n const divider = '='.repeat(60);\n appendLine(\n `\\n${divider}\\nPostHog Wizard Run: ${new Date().toISOString()}\\n${divider}\\n`,\n );\n}\n\nexport function logToFile(...args: unknown[]): void {\n if (!fileLoggingEnabled) return;\n const ts = new Date().toISOString();\n appendLine(`[${ts}] ${formatLogLine(...args)}\\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAAgB;AAM7B,MAAa,WAAA;;AAcb,MAAa,cAAiC,QAAQ,KAAK,MACxD,MAAM,MAAM,sCAAwB,EAAE,WAAW,oCAAsB,CACzE,GACG,UACA;;AAqDJ,SAAgB,WAAW,KAAwC;AACjE,QAAO,QAAQ,IAAI;;;;;;;AAQrB,MAAa,cACX,WAAW,sBAAsB,IAAI,KAAA;AACvC,MAAa,UACX,WAAW,kBAAkB,IAAI,KAAA;;;AC7GnC,MAAa,UAAU;;;ACGvB,MAAM,MAAM,QAAQ,aAAa,UAAU,QAAQ,GAAG;AAEtD,MAAa,kBAAkBA,OAAK,KAAK,qBAAqB;AAC9D,MAAa,wBAAwBA,OAAK,KAAK,gCAAgC;;AAE/E,MAAa,0BAA0BA,OACrC,KACA,mCACD;AACD,MAAa,0BAA0BA,OACrC,KACA,kCACD;;;;;;;AAOD,SAAgB,qBAAqB,MAAc,YAA4B;CAC7E,MAAM,SAAS,WAAW,SAASC,MAAI,GAAG,aAAa,aAAaA;AACpE,QAAO,KAAK,WAAW,OAAO,GAAG,KAAK,MAAM,OAAO,OAAO,GAAG;;;;AClB/D,IAAI,cACiD;AACrD,IAAI,qBAAqB;AAEzB,IAAI,gBAAgB;AAEpB,SAAS,UAAU,OAAwB;AACzC,KAAI,OAAO,UAAU,SAAU,QAAO;AACtC,KAAI,iBAAiB,MAAO,QAAO,MAAM,SAAS,OAAO,MAAM;AAC/D,KAAI;AAGF,SAAO,KAAK,U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,UAAU,IAAI,OAAO,GAAG;AAC9B,YACE,KAAK,QAAQ,yCAAwB,IAAI,MAAM,EAAC,aAAa,CAAC,IAAI,QAAQ,IAC3E;;AAGH,SAAgB,UAAU,GAAG,MAAuB;AAClD,KAAI,CAAC,mBAAoB;AAEzB,YAAW,qBADA,IAAI,MAAM,EAAC,aAAa,CACjB,IAAI,cAAc,GAAG,KAAK,CAAC,IAAI"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"install-Dayhuaun.js","names":["fs","path","path","os","PLUGIN_MARKETPLACE","PLUGIN_MARKETPLACE_SOURCE","PLUGIN_REF","EXPECTED_FAILURES","RUN_TIMEOUT_MS","MAX_OUTPUT_BYTES","path","os","fs","execSync","reportSpawnFailure","z","os","path","z","os","path","reportFailure","path","fs","z","path","fs","os"],"sources":["../src/shared/mcp-clients/MCPClient.ts","../src/shared/mcp-clients/clients/cursor.ts","../src/shared/mcp-clients/clients/claude-code.ts","../src/shared/mcp-clients/clients/claude-web.ts","../src/shared/mcp-clients/clients/visual-studio-code.ts","../src/shared/mcp-clients/clients/zed.ts","../src/shared/mcp-clients/clients/codex.ts","../src/shared/mcp-clients/clients/opencode.ts","../src/shared/mcp-clients/plugin-client.ts","../src/shared/mcp-clients/install.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as jsonc from 'jsonc-parser';\nimport { getDefaultServerConfig } from './defaults';\nimport type { InstallResult } from './results';\n\nexport type MCPServerConfig = Record<string, unknown>;\n\nexport abstract class MCPClient {\n name: string;\n abstract getConfigPath(): Promise<string>;\n abstract getServerPropertyName(): string;\n abstract isServerInstalled(local?: boolean): Promise<boolean>;\n abstract addServer(\n apiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n ): Promise<InstallResult>;\n abstract removeServer(local?: boolean): Promise<InstallResult>;\n abstract isClientSupported(): Promise<boolean>;\n}\n\nexport abstract class DefaultMCPClient extends MCPClient {\n name = 'Default';\n\n constructor() {\n super();\n }\n\n getServerPropertyName(): string {\n return 'mcpServers';\n }\n\n getServerConfig(\n apiKey: string | undefined,\n selectedFeatures?: string[],\n local?: boolean,\n ): MCPServerConfig {\n return getDefaultServerConfig(apiKey, selectedFeatures, local);\n }\n\n async isServerInstalled(local?: boolean): Promise<boolean> {\n try {\n const configPath = await this.getConfigPath();\n\n if (!fs.existsSync(configPath)) {\n return false;\n }\n\n const configContent = await fs.promises.readFile(configPath, 'utf8');\n const config = jsonc.parse(configContent) as Record<string, any>;\n const serverPropertyName = this.getServerPropertyName();\n const serverName = local ? 'posthog-local' : 'posthog';\n\n return (\n serverPropertyName in config && serverName in config[serverPropertyName]\n );\n } catch {\n return false;\n }\n }\n\n async addServer(\n apiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n ): Promise<InstallResult> {\n try {\n const configPath = await this.getConfigPath();\n const configDir = path.dirname(configPath);\n\n await fs.promises.mkdir(configDir, { recursive: true });\n\n const serverPropertyName = this.getServerPropertyName();\n let configContent = '';\n let existingConfig = {};\n\n if (fs.existsSync(configPath)) {\n configContent = await fs.promises.readFile(configPath, 'utf8');\n existingConfig = jsonc.parse(configContent) || {};\n }\n\n const newServerConfig = this.getServerConfig(\n apiKey,\n selectedFeatures,\n local,\n );\n const typedConfig = existingConfig as Record<string, any>;\n if (!typedConfig[serverPropertyName]) {\n typedConfig[serverPropertyName] = {};\n }\n const serverName = local ? 'posthog-local' : 'posthog';\n\n // An identical entry means this config is already set up — leave the file\n // untouched and report it, so a re-run says \"already installed\" instead of\n // claiming a write that changed nothing. A differing entry (new features,\n // new key) still gets overwritten and reported as installed.\n const existingServerConfig = typedConfig[serverPropertyName][serverName];\n if (\n existingServerConfig !== undefined &&\n JSON.stringify(existingServerConfig) === JSON.stringify(newServerConfig)\n ) {\n return { success: true, alreadyInstalled: true };\n }\n\n typedConfig[serverPropertyName][serverName] = newServerConfig;\n\n const edits = jsonc.modify(\n configContent,\n [serverPropertyName, serverName],\n newServerConfig,\n {\n formattingOptions: {\n tabSize: 2,\n insertSpaces: true,\n },\n },\n );\n\n const modifiedContent = jsonc.applyEdits(configContent, edits);\n\n await fs.promises.writeFile(configPath, modifiedContent, 'utf8');\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async removeServer(local?: boolean): Promise<InstallResult> {\n let configPath = '';\n try {\n configPath = await this.getConfigPath();\n\n if (!fs.existsSync(configPath)) {\n return { success: true, alreadyInstalled: true };\n }\n\n const configContent = await fs.promises.readFile(configPath, 'utf8');\n const config = jsonc.parse(configContent) as Record<string, any>;\n const serverPropertyName = this.getServerPropertyName();\n\n const serverName = local ? 'posthog-local' : 'posthog';\n\n if (\n serverPropertyName in config &&\n serverName in config[serverPropertyName]\n ) {\n const edits = jsonc.modify(\n configContent,\n [serverPropertyName, serverName],\n undefined,\n {\n formattingOptions: {\n tabSize: 2,\n insertSpaces: true,\n },\n },\n );\n\n const modifiedContent = jsonc.applyEdits(configContent, edits);\n\n await fs.promises.writeFile(configPath, modifiedContent, 'utf8');\n\n return { success: true };\n }\n // No PostHog entry to delete — the config changed under us between the\n // detection pass and now. Nothing failed, so don't report a failure.\n return { success: true, alreadyInstalled: true };\n } catch (error) {\n return {\n success: false,\n reason: `${configPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n };\n }\n }\n}\n","import {\n DefaultMCPClient,\n MCPServerConfig,\n} from '@shared/mcp-clients/MCPClient';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n DefaultMCPClientConfig,\n getNativeHTTPServerConfig,\n} from '@shared/mcp-clients/defaults';\nimport { z } from 'zod';\n\nexport const CursorMCPConfig = DefaultMCPClientConfig;\n\nexport type CursorMCPConfig = z.infer<typeof DefaultMCPClientConfig>;\n\nexport class CursorMCPClient extends DefaultMCPClient {\n name = 'Cursor';\n\n constructor() {\n super();\n }\n\n async isClientSupported(): Promise<boolean> {\n return Promise.resolve(\n process.platform === 'darwin' || process.platform === 'win32',\n );\n }\n\n async getConfigPath(): Promise<string> {\n return Promise.resolve(path.join(os.homedir(), '.cursor', 'mcp.json'));\n }\n\n getServerConfig(\n apiKey: string | undefined,\n selectedFeatures?: string[],\n local?: boolean,\n ): MCPServerConfig {\n return getNativeHTTPServerConfig(apiKey, selectedFeatures, local);\n }\n}\n","import { DefaultMCPClient } from '@shared/mcp-clients/MCPClient';\nimport {\n DefaultMCPClientConfig,\n buildMCPUrl,\n} from '@shared/mcp-clients/defaults';\nimport {\n PluginCapable,\n PluginInstallResult,\n} from '@shared/mcp-clients/plugin-client';\nimport {\n reportSpawnFailure,\n redactSecrets,\n scrubHomePaths,\n type ExpectedFailure,\n type InstallResult,\n} from '@shared/mcp-clients/results';\nimport { LoginCapable } from '@shared/mcp-clients/login-client';\nimport { z } from 'zod';\nimport { execSync, execFile } from 'child_process';\nimport { logToFile } from '@utils/debug';\nimport * as os from 'os';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\nexport const ClaudeCodeMCPConfig = DefaultMCPClientConfig;\n\nexport type ClaudeCodeMCPConfig = z.infer<typeof DefaultMCPClientConfig>;\n\n// `plugin install <name>` only resolves against marketplaces the user already\n// registered, and the wizard never opens Claude Code interactively — so without\n// the add below the install dies with `not found in any configured marketplace`.\n// Our own marketplace, not Anthropic's: that one carries us as a pinned sha, so\n// installing through it would gate plugin releases on Anthropic bumping the pin.\nconst PLUGIN_NAME = 'posthog';\nconst PLUGIN_MARKETPLACE = 'posthog';\nconst PLUGIN_MARKETPLACE_SOURCE = 'PostHog/ai-plugin';\nconst PLUGIN_REF = `${PLUGIN_NAME}@${PLUGIN_MARKETPLACE}`;\n\n/** The plugin is missing from every catalog the CLI can currently see. */\nconst NOT_IN_A_MARKETPLACE = /not found in/i;\n\n/**\n * What a failing `claude` call was doing, for hint scoping and for the report.\n * A union rather than loose strings: a hint scoped to a stage nobody passes is\n * silently dead.\n */\ntype ClaudeCodeStage =\n | 'MCP add'\n | 'MCP remove'\n | 'plugin install'\n | 'plugin uninstall';\n\n/**\n * Failures in the user's own environment during `plugin install`. Reporting\n * them files issues nobody can action, so hand back a hint instead.\n */\ninterface ClaudeCodeExpectedFailure extends ExpectedFailure {\n stages?: ClaudeCodeStage[];\n}\n\nconst EXPECTED_FAILURES: ClaudeCodeExpectedFailure[] = [\n {\n // Only the user-level file: a project settings file is not one we can name.\n match:\n /invalid JSON syntax in settings file at ~[\\\\/]\\.claude[\\\\/]settings\\.json/i,\n stages: ['plugin install'],\n hint: 'Claude Code could not read its settings — fix the invalid JSON in ~/.claude/settings.json, then retry',\n },\n];\n\n/** One `plugin list --json` row; the CLI returns more fields than we read. */\ninterface ListedPlugin {\n /** `<plugin>@<marketplace>`, e.g. `posthog@posthog`. */\n id: string;\n /**\n * A plugin disabled in `/plugin` stays listed with `enabled: false`. It is\n * still installed, but it contributes no MCP server, so treating it as\n * installed reports \"you are good to go\" with nothing serving posthog.\n */\n enabled?: boolean;\n}\n\ninterface ListedMarketplace {\n name: string;\n /**\n * `owner/repo`, present since the CLI started emitting `--json`. A\n * marketplace merely *named* `posthog` may be someone else's, and installing\n * from it would ship a different plugin under our name.\n */\n repo?: string;\n}\n\ntype ClaudeRun = { ok: boolean; output: string };\n\n/**\n * `plugin marketplace add` clones a git repository, the slowest thing we run.\n * Past this the command is not slow, it is stuck, and a clone waiting on a\n * credential prompt would otherwise hang the wizard with the spinner frozen.\n */\nconst RUN_TIMEOUT_MS = 120_000;\n\n/**\n * `execFile` kills the child once output passes this. The default is 1 MB,\n * which a verbose clone can reach, and the kill then looks like Claude Code\n * rejecting the install rather than us cutting it off.\n */\nconst MAX_OUTPUT_BYTES = 16 * 1024 * 1024;\n\n/**\n * Our catalog, by name *and* repository. A marketplace merely called `posthog`\n * may be someone else's, and neither installing from it nor removing it is\n * ours to do. `repo` is absent on CLIs predating it, where the name is all\n * there is.\n */\nconst isOurMarketplace = (m: ListedMarketplace | undefined): boolean =>\n m?.name === PLUGIN_MARKETPLACE &&\n (m.repo === undefined ||\n m.repo.toLowerCase() === PLUGIN_MARKETPLACE_SOURCE.toLowerCase());\n\nexport class ClaudeCodeMCPClient\n extends DefaultMCPClient\n implements PluginCapable, LoginCapable\n{\n name = 'Claude Code';\n private claudeBinaryPath: string | null = null;\n\n constructor() {\n super();\n }\n\n private findClaudeBinary(): string | null {\n if (this.claudeBinaryPath) {\n return this.claudeBinaryPath;\n }\n\n // Common installation paths for Claude Code CLI\n const possiblePaths = [\n path.join(os.homedir(), '.claude', 'local', 'claude'),\n '/usr/local/bin/claude',\n '/opt/homebrew/bin/claude',\n ];\n\n for (const claudePath of possiblePaths) {\n if (fs.existsSync(claudePath)) {\n logToFile(` Found claude binary at: ${claudePath}`);\n this.claudeBinaryPath = claudePath;\n return claudePath;\n }\n }\n\n // Try PATH as fallback\n try {\n execSync('command -v claude', { stdio: 'pipe' });\n logToFile(' Found claude in PATH');\n this.claudeBinaryPath = 'claude';\n return 'claude';\n } catch {\n // Not in PATH\n }\n\n return null;\n }\n\n isClientSupported(): Promise<boolean> {\n try {\n logToFile(' Checking for Claude Code...');\n const claudeBinary = this.findClaudeBinary();\n\n if (!claudeBinary) {\n logToFile(' Claude Code not found. Installation paths checked:');\n logToFile(\n ` - ${path.join(os.homedir(), '.claude', 'local', 'claude')}`,\n );\n logToFile(` - /usr/local/bin/claude`);\n logToFile(` - /opt/homebrew/bin/claude`);\n logToFile(` - PATH`);\n return Promise.resolve(false);\n }\n\n const output = execSync(`${claudeBinary} --version`, { stdio: 'pipe' });\n const version = output.toString().trim();\n logToFile(` Claude Code detected: ${version}`);\n return Promise.resolve(true);\n } catch (error) {\n logToFile(\n ` Claude Code check failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return Promise.resolve(false);\n }\n }\n\n isServerInstalled(local?: boolean): Promise<boolean> {\n const binary = this.findClaudeBinary();\n if (!binary) return Promise.resolve(false);\n const serverName = local ? 'posthog-local' : 'posthog';\n // `mcp get <name>` exits non-zero when the entry doesn't exist. A substring\n // scan of `mcp list` also matches the claude.ai \"PostHog\" connector and the\n // plugin's `plugin:posthog:posthog`, reporting installed forever.\n try {\n execSync(`${binary} mcp get ${serverName}`, { stdio: 'pipe' });\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n getConfigPath(): Promise<string> {\n throw new Error('Not implemented');\n }\n\n addServer(\n apiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n ): Promise<InstallResult> {\n const binary = this.findClaudeBinary();\n if (!binary)\n return Promise.resolve({\n success: false,\n reason: 'The claude CLI is no longer on your PATH.',\n });\n\n const serverName = local ? 'posthog-local' : 'posthog';\n const url = buildMCPUrl(selectedFeatures, local);\n const args = [\n 'mcp',\n 'add',\n '--transport',\n 'http',\n '--scope',\n 'user',\n serverName,\n url,\n ];\n if (apiKey) {\n args.push('--header', `Authorization: Bearer ${apiKey}`);\n }\n\n try {\n execSync(`${binary} ${args.map((a) => JSON.stringify(a)).join(' ')}`, {\n stdio: 'pipe',\n });\n return Promise.resolve({ success: true });\n } catch (error) {\n // The failing command echoes back the Authorization header we passed, so\n // redact before this reaches a log, the screen, or an exception report.\n const msg = redactSecrets(\n error instanceof Error ? error.message : String(error),\n );\n if (msg.includes('already exists')) {\n return Promise.resolve({ success: true, alreadyInstalled: true });\n }\n return Promise.resolve(\n reportSpawnFailure<ClaudeCodeStage>({\n client: this.name,\n stage: 'MCP add',\n details: msg,\n table: EXPECTED_FAILURES,\n }),\n );\n }\n }\n\n /** Claude Code's own login runs its OAuth and owns the token; the wizard only surfaces the command. */\n loginCommand(local?: boolean): string {\n return `claude mcp login ${local ? 'posthog-local' : 'posthog'}`;\n }\n\n /** The plugin bundles its own `posthog` server, addressed as `plugin:<plugin>:<server>`. */\n pluginLoginCommand(): string {\n return 'claude mcp login plugin:posthog:posthog';\n }\n\n async removePlugin(): Promise<PluginInstallResult> {\n const binary = this.findClaudeBinary();\n if (!binary)\n return {\n success: false,\n reason: 'The claude CLI is no longer on your PATH.',\n };\n\n // `plugin uninstall posthog` removes exactly one match, so with both\n // `posthog@posthog` and `posthog@claude-plugins-official` installed the bare\n // call leaves the other copy enabled — and `mcp remove` would be lying.\n const ids = await this.installedPluginIds(binary);\n // `installPlugin` registers the marketplace, so removal owes the user the\n // other half: a machine left with our catalog and no plugin is a state the\n // wizard created. `codex.ts` clears both on the same call.\n const marketplace = await this.ourMarketplaceRegistered(binary);\n\n const nothingInstalled =\n ids?.length === 0 || (ids === null && !(await this.isPluginInstalled()));\n if (nothingInstalled && !marketplace) {\n return { success: true, alreadyInstalled: true };\n }\n\n const targets = nothingInstalled ? [] : ids?.length ? ids : [PLUGIN_NAME];\n const failures: string[] = [];\n for (const target of targets) {\n const run = await this.runClaude(binary, ['plugin', 'uninstall', target]);\n if (!run.ok) failures.push(`${target}: ${run.output}`);\n }\n\n // Only when we know it is there: `marketplace remove` exits non-zero on a\n // marketplace that is absent, which would report a failure for a no-op.\n if (marketplace) {\n const run = await this.runClaude(binary, [\n 'plugin',\n 'marketplace',\n 'remove',\n PLUGIN_MARKETPLACE,\n ]);\n if (!run.ok) failures.push(`${PLUGIN_MARKETPLACE}: ${run.output}`);\n }\n\n if (failures.length === 0) return { success: true };\n\n const reason = failures.join('; ');\n return reportSpawnFailure<ClaudeCodeStage>({\n client: this.name,\n stage: 'plugin uninstall',\n details: reason,\n table: EXPECTED_FAILURES,\n });\n }\n\n removeServer(local?: boolean): Promise<InstallResult> {\n const claudeBinary = this.findClaudeBinary();\n if (!claudeBinary) {\n return Promise.resolve({\n success: false,\n reason: 'The claude CLI is no longer on your PATH.',\n });\n }\n\n const serverName = local ? 'posthog-local' : 'posthog';\n const command = `${claudeBinary} mcp remove --scope user ${serverName}`;\n\n try {\n execSync(command, { stdio: 'pipe' });\n } catch (error) {\n const reason = redactSecrets(\n error instanceof Error ? error.message : String(error),\n );\n // Removing something that isn't there is the requested end state, not a\n // failure to report.\n if (/no( such)? mcp server|not found/i.test(reason)) {\n return Promise.resolve({ success: true, alreadyInstalled: true });\n }\n return Promise.resolve(\n reportSpawnFailure<ClaudeCodeStage>({\n client: this.name,\n stage: 'MCP remove',\n details: reason,\n table: EXPECTED_FAILURES,\n }),\n );\n }\n\n return Promise.resolve({ success: true });\n }\n\n /** The plugin ships mcp.json with the posthog server — no direct entry needed. */\n pluginBundlesMcpServer(): boolean {\n return true;\n }\n\n supportsPlugin(): boolean {\n return this.findClaudeBinary() !== null;\n }\n\n // Async on purpose: these calls clone git repos and take seconds, and\n // execSync would block the event loop and freeze the TUI spinner. Never\n // throws; the caller decides what a failure means.\n private runClaude(binary: string, args: string[]): Promise<ClaudeRun> {\n return new Promise((resolve) => {\n execFile(\n binary,\n args,\n { timeout: RUN_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES },\n (error, stdout) => {\n if (!error)\n return resolve({ ok: true, output: stdout?.toString() ?? '' });\n if (error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')\n return resolve({\n ok: false,\n output:\n 'claude produced more output than the wizard can hold, so it was stopped',\n });\n if (error.killed || error.signal)\n return resolve({\n ok: false,\n output: `claude did not finish within ${\n RUN_TIMEOUT_MS / 1000\n }s, so it was stopped`,\n });\n // execFile puts `Command failed: <cmd>` and stderr in the message, the\n // same text execSync produced, so failure matching is unchanged.\n resolve({\n ok: false,\n output: scrubHomePaths(redactSecrets(error.message)),\n });\n },\n );\n });\n }\n\n /** Null when `--json` is unsupported, the command failed, or output didn't parse — never \"nothing installed\". */\n private async listJson<T>(\n binary: string,\n args: string[],\n ): Promise<T[] | null> {\n const result = await this.runClaude(binary, [...args, '--json']);\n if (!result.ok) return null;\n try {\n const parsed: unknown = JSON.parse(result.output);\n return Array.isArray(parsed) ? (parsed as T[]) : null;\n } catch {\n return null;\n }\n }\n\n // Every installed copy, from any marketplace: Claude Code permits\n // `posthog@posthog` and `posthog@claude-plugins-official` at the same time.\n // Null means the probe is unavailable, which is not the same as none.\n private async installedPlugins(\n binary: string,\n ): Promise<ListedPlugin[] | null> {\n const listed = await this.listJson<ListedPlugin>(binary, [\n 'plugin',\n 'list',\n ]);\n if (!listed) return null;\n return listed.filter(\n (p): p is ListedPlugin =>\n typeof p?.id === 'string' && p.id.split('@')[0] === PLUGIN_NAME,\n );\n }\n\n private async installedPluginIds(binary: string): Promise<string[] | null> {\n const listed = await this.installedPlugins(binary);\n return listed?.map((p) => p.id) ?? null;\n }\n\n async isPluginInstalled(): Promise<boolean> {\n const binary = this.findClaudeBinary();\n if (!binary) return false;\n\n // Presence, not health: `index.ts` asks this to decide whether there is\n // anything to remove, and a disabled plugin still has to be uninstalled.\n // Whether it actually serves is `installPlugin`'s question, not this one.\n const listed = await this.installedPlugins(binary);\n if (listed) return listed.length > 0;\n\n // Older CLI without `--json`. A substring scan also matches a plugin merely\n // named `posthog-something`, which is why it's the fallback and not the path.\n const plain = await this.runClaude(binary, ['plugin', 'list']);\n return plain.ok && plain.output.toLowerCase().includes(PLUGIN_NAME);\n }\n\n async installPlugin(): Promise<PluginInstallResult> {\n const binary = this.findClaudeBinary();\n if (!binary)\n return {\n success: false,\n reason: 'The claude CLI is no longer on your PATH.',\n };\n\n // Ask before installing so a re-run reports \"already installed\" rather than\n // relying on the CLI's error text to spot the no-op.\n //\n // A plugin disabled in `/plugin` is installed but serves nothing, and\n // Claude Code takes its MCP server from the plugin. Reporting it as\n // already installed leaves the user with no server and a screen saying\n // they are done, so fall through and install: the CLI re-enables it.\n const listed = await this.installedPlugins(binary);\n const serving = listed\n ? listed.some((p) => p.enabled !== false)\n : await this.isPluginInstalled();\n if (serving) {\n return { success: true, alreadyInstalled: true };\n }\n\n const marketplaceFailure = await this.ensurePluginMarketplace(binary);\n\n let result = await this.runClaude(binary, [\n 'plugin',\n 'install',\n PLUGIN_REF,\n ]);\n\n // A registered but stale catalog still reports the plugin as missing.\n if (!result.ok && NOT_IN_A_MARKETPLACE.test(result.output)) {\n await this.runClaude(binary, [\n 'plugin',\n 'marketplace',\n 'update',\n PLUGIN_MARKETPLACE,\n ]);\n result = await this.runClaude(binary, ['plugin', 'install', PLUGIN_REF]);\n }\n\n // Last resort: let Claude Code resolve the bare name against whatever the\n // user does have, the way the wizard always did. Never worse than before.\n if (!result.ok && NOT_IN_A_MARKETPLACE.test(result.output)) {\n result = await this.runClaude(binary, ['plugin', 'install', PLUGIN_NAME]);\n }\n\n if (result.ok) return { success: true };\n\n const msg = result.output;\n if (msg.includes('already installed') || msg.includes('already exists')) {\n return { success: true, alreadyInstalled: true };\n }\n // `not found in any configured marketplace` is also what the pre-PR bug\n // produced, so the marketplace-add failure travels beside it to tell the\n // two apart.\n return reportSpawnFailure<ClaudeCodeStage>({\n client: this.name,\n stage: 'plugin install',\n details: msg,\n table: EXPECTED_FAILURES,\n extra: marketplaceFailure ? { marketplaceFailure } : undefined,\n });\n }\n\n // Best-effort: a failure here only matters if the install also fails, since\n // the user may hold the plugin in another catalog that the fallback finds.\n /** Registered, and ours: a catalog merely named `posthog` is someone else's. */\n private async ourMarketplaceRegistered(\n binary: string,\n ): Promise<boolean | null> {\n const listed = await this.listJson<ListedMarketplace>(binary, [\n 'plugin',\n 'marketplace',\n 'list',\n ]);\n return listed ? listed.some(isOurMarketplace) : null;\n }\n\n private async ensurePluginMarketplace(\n binary: string,\n ): Promise<string | undefined> {\n const listed = await this.listJson<ListedMarketplace>(binary, [\n 'plugin',\n 'marketplace',\n 'list',\n ]);\n if (listed?.some(isOurMarketplace)) {\n logToFile(` Marketplace ${PLUGIN_MARKETPLACE} already registered`);\n return undefined;\n }\n\n // `marketplace add` is idempotent on Claude Code and exits 0 when the\n // marketplace is already on disk, so there's no \"already added\" text to\n // special-case here — unlike the Codex CLI, where it exits non-zero.\n const added = await this.runClaude(binary, [\n 'plugin',\n 'marketplace',\n 'add',\n PLUGIN_MARKETPLACE_SOURCE,\n ]);\n if (!added.ok) {\n logToFile(` Marketplace add failed: ${added.output}`);\n return added.output;\n }\n return undefined;\n }\n}\n","import { MCPClient } from '@shared/mcp-clients/MCPClient';\nimport type { InstallResult } from '@shared/mcp-clients/results';\nimport { BrowserFinishable } from '@shared/mcp-clients/browser-client';\nimport { openTrackedLink } from '@utils/links';\n\n/**\n * Claude Desktop / Claude.ai (web). PostHog ships here as a hosted connector,\n * not a local config — so instead of writing files we open the connector\n * directory page and let the user sign in and click \"Connect\".\n */\nexport class ClaudeWebMCPClient extends MCPClient implements BrowserFinishable {\n name = 'Claude Desktop/Web';\n connectorUrl = 'https://claude.ai/directory/connectors/posthog';\n finishInstruction = 'Sign in and click \"Connect\" to finish.';\n\n isClientSupported(): Promise<boolean> {\n // Browser-based — available on every platform.\n return Promise.resolve(true);\n }\n\n isServerInstalled(): Promise<boolean> {\n // The connector lives in the user's Claude account; nothing local to\n // inspect. Returning false also keeps it out of `mcp remove`.\n return Promise.resolve(false);\n }\n\n addServer(): Promise<InstallResult> {\n // Not a PostHog property, so no UTMs — just the tracked open.\n openTrackedLink(this.connectorUrl, 'claude-web-connector', {\n auto: true,\n skipUtm: true,\n });\n return Promise.resolve({ success: true });\n }\n\n removeServer(): Promise<InstallResult> {\n // The connector lives in the user's Claude account, so `mcp remove` can't\n // touch it. It never reaches here today (isServerInstalled is always\n // false), but say where to go if it ever does.\n return Promise.resolve({\n success: false,\n reason:\n 'This connector is managed in your Claude account — remove it at claude.ai/settings/connectors.',\n });\n }\n\n getConfigPath(): Promise<string> {\n throw new Error('Not implemented');\n }\n\n getServerPropertyName(): string {\n throw new Error('Not implemented');\n }\n}\n\nexport default ClaudeWebMCPClient;\n","import z from 'zod';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n DefaultMCPClient,\n MCPServerConfig,\n} from '@shared/mcp-clients/MCPClient';\nimport { getNativeHTTPServerConfig } from '@shared/mcp-clients/defaults';\nimport { runtimeEnv } from '@env';\n\nexport const VisualStudioCodeMCPConfig = z\n .object({\n servers: z.record(\n z.string(),\n z.union([\n z.object({\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n }),\n z.object({\n type: z.enum(['http', 'sse']),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n ]),\n ),\n })\n .passthrough();\n\nexport type VisualStudioCodeMCPConfig = z.infer<\n typeof VisualStudioCodeMCPConfig\n>;\n\nexport class VisualStudioCodeClient extends DefaultMCPClient {\n name = 'Visual Studio Code';\n\n getServerPropertyName(): string {\n return 'servers';\n }\n\n async isClientSupported(): Promise<boolean> {\n return Promise.resolve(\n process.platform === 'darwin' ||\n process.platform === 'win32' ||\n process.platform === 'linux',\n );\n }\n\n async getConfigPath(): Promise<string> {\n const homeDir = os.homedir();\n const isWindows = process.platform === 'win32';\n const isMac = process.platform === 'darwin';\n const isLinux = process.platform === 'linux';\n\n if (isMac) {\n return Promise.resolve(\n path.join(\n homeDir,\n 'Library',\n 'Application Support',\n 'Code',\n 'User',\n 'mcp.json',\n ),\n );\n }\n\n if (isWindows) {\n return Promise.resolve(\n path.join(runtimeEnv('APPDATA') || '', 'Code', 'User', 'mcp.json'),\n );\n }\n\n if (isLinux) {\n return Promise.resolve(\n path.join(homeDir, '.config', 'Code', 'User', 'mcp.json'),\n );\n }\n\n throw new Error(`Unsupported platform: ${process.platform}`);\n }\n\n getServerConfig(\n apiKey: string | undefined,\n selectedFeatures?: string[],\n local?: boolean,\n ): MCPServerConfig {\n return {\n type: 'http',\n ...getNativeHTTPServerConfig(apiKey, selectedFeatures, local),\n };\n }\n}\n","import z from 'zod';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n DefaultMCPClient,\n MCPServerConfig,\n} from '@shared/mcp-clients/MCPClient';\nimport { getNativeHTTPServerConfig } from '@shared/mcp-clients/defaults';\nimport { runtimeEnv } from '@env';\n\nexport const ZedMCPConfig = z\n .object({\n context_servers: z.record(\n z.string(),\n z.union([\n z.object({\n enabled: z.boolean().optional(),\n source: z.string().optional(),\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n }),\n z.object({\n enabled: z.boolean().optional(),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n ]),\n ),\n })\n .passthrough();\n\nexport type ZedMCPConfig = z.infer<typeof ZedMCPConfig>;\n\nexport class ZedClient extends DefaultMCPClient {\n name = 'Zed';\n\n getServerPropertyName(): string {\n return 'context_servers';\n }\n\n async isClientSupported(): Promise<boolean> {\n return Promise.resolve(\n process.platform === 'darwin' || process.platform === 'linux',\n );\n }\n\n async getConfigPath(): Promise<string> {\n const homeDir = os.homedir();\n const isMac = process.platform === 'darwin';\n const isLinux = process.platform === 'linux';\n\n if (isMac) {\n return Promise.resolve(\n path.join(homeDir, '.config', 'zed', 'settings.json'),\n );\n }\n\n if (isLinux) {\n // https://zed.dev/docs/configuring-zed#settings-files\n const xdgConfigHome = runtimeEnv('XDG_CONFIG_HOME');\n if (xdgConfigHome) {\n return Promise.resolve(\n path.join(xdgConfigHome, 'zed', 'settings.json'),\n );\n }\n return Promise.resolve(\n path.join(homeDir, '.config', 'zed', 'settings.json'),\n );\n }\n\n throw new Error(`Unsupported platform: ${process.platform}`);\n }\n\n getServerConfig(\n apiKey: string | undefined,\n selectedFeatures?: string[],\n local?: boolean,\n ): MCPServerConfig {\n return {\n enabled: true,\n ...getNativeHTTPServerConfig(apiKey, selectedFeatures, local),\n };\n }\n}\n","import { z } from 'zod';\nimport { execSync, execFile, type ExecFileException } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nimport { LoginCapable } from '@shared/mcp-clients/login-client';\nimport { DefaultMCPClient } from '@shared/mcp-clients/MCPClient';\nimport {\n DefaultMCPClientConfig,\n buildMCPUrl,\n} from '@shared/mcp-clients/defaults';\nimport {\n PluginCapable,\n PluginInstallResult,\n} from '@shared/mcp-clients/plugin-client';\nimport {\n redactSecrets,\n scrubHomePaths,\n reportSpawnFailure as reportFailure,\n type ExpectedFailure,\n type InstallResult,\n} from '@shared/mcp-clients/results';\n\nimport { analytics } from '@utils/analytics';\n\nconst PLUGIN_MARKETPLACE = 'posthog';\nconst PLUGIN_MARKETPLACE_SOURCE = 'PostHog/ai-plugin';\nconst PLUGIN_REF = `posthog@${PLUGIN_MARKETPLACE}`;\n\n/**\n * The plugin's row in `codex plugin list`, whose STATUS column reads\n * `installed, enabled` or `not installed`. Registering the marketplace only\n * publishes the catalog, so the marketplace section in config.toml says nothing\n * about whether the plugin itself is there.\n */\nconst listedAsInstalled = (stdout: string): boolean => {\n const row = new RegExp(`^${PLUGIN_REF}\\\\s+(.*)$`, 'm').exec(stdout)?.[1];\n return !!row && /\\binstalled\\b/.test(row) && !/\\bnot installed\\b/.test(row);\n};\n\n/**\n * What `reportSpawnFailure` was doing, for hint scoping and for the report.\n * A union rather than loose strings: a hint scoped to a stage nobody passes is\n * silently dead, which is how `marketplace add` lost its hint the first time.\n */\ntype CodexStage =\n | 'MCP add'\n | 'MCP remove'\n | 'plugin install'\n | 'plugin uninstall'\n | 'marketplace add';\n\nconst PLUGIN_STAGES: CodexStage[] = [\n 'plugin install',\n 'plugin uninstall',\n 'marketplace add',\n];\nconst MCP_STAGES: CodexStage[] = ['MCP add', 'MCP remove'];\nconst ALL_STAGES: CodexStage[] = [...PLUGIN_STAGES, ...MCP_STAGES];\n\n/**\n * Wording that proves the file codex choked on is the plugin's, not the user's.\n * Serde phrasing alone (\"invalid type\", \"is no longer supported\") says nothing\n * about whose file it came from, and blaming `~/.codex/config.toml` for our own\n * broken manifest sends the user to edit a file that is fine.\n */\nconst OUR_MANIFEST =\n /ai-plugin|plugin\\.toml|plugin\\.json|marketplace\\.toml|posthog@posthog/i;\n\n/**\n * Failures in the user's own environment. Reporting them files issues nobody\n * can action, so hand back a hint instead. Drawn from what the codex install\n * path actually produced in the field.\n *\n * Every entry is scoped: a hint that fires on the wrong stage tells the user to\n * run a command that has nothing to do with what just failed.\n */\nconst EXPECTED_FAILURES: ExpectedFailure[] = [\n {\n // `plugin`/`marketplace` subcommands a pre-plugin codex doesn't have.\n match:\n /unexpected argument|unknown (command|option|argument)|Missing option/i,\n stages: PLUGIN_STAGES,\n hint: 'your codex CLI is too old for plugins — update codex, then run `codex plugin marketplace add PostHog/ai-plugin`',\n },\n {\n // The same wording during `mcp add` is a flag we passed, not a plugin\n // subcommand, so the plugin advice above would send the user nowhere.\n match:\n /unexpected argument|unknown (command|option|argument)|Missing option/i,\n stages: MCP_STAGES,\n hint: 'your codex CLI is too old for this install — update codex, then run `npx @posthog/wizard mcp add` again',\n },\n {\n match: /ENOENT|not found in PATH|spawn .* ENOENT/i,\n stages: ALL_STAGES,\n hint: 'your codex install looks broken — reinstall codex, then run `codex plugin marketplace add PostHog/ai-plugin`',\n },\n {\n // Either codex says outright that it could not load its configuration, or\n // serde phrasing appears alongside `config.toml`. Bare serde wording cannot\n // tell the user's file from the plugin's, and `config.toml` on its own\n // silences any failure that merely mentions the path — both send someone to\n // edit a file that is fine, so the ambiguous case stays reportable.\n match:\n /failed to load (bootstrap )?configuration|OPENAI_API_KEY|Missing OpenAI API key|(?=[\\s\\S]*config\\.toml)[\\s\\S]*(invalid type|unknown field|is no longer supported|must contain at least one)/i,\n stages: ALL_STAGES,\n unless: OUR_MANIFEST,\n hint: 'codex could not read its own config — fix what it reports in ~/.codex/config.toml, then retry',\n },\n {\n match:\n /EACCES|EPERM|permission denied|read-only file system|not permitted/i,\n stages: ALL_STAGES,\n // git says `Permission denied (publickey)` when an SSH clone of the\n // marketplace cannot authenticate to GitHub. Nothing on ~/.codex is wrong\n // there, so the hint below would send the user to chmod a directory that\n // is already fine while the real cause goes unreported.\n unless: /permission denied \\((?:publickey|password|gssapi)/i,\n hint: 'codex could not write to its config — fix the permissions on ~/.codex, then retry',\n },\n {\n match: /ENOSPC|no space left/i,\n stages: ALL_STAGES,\n hint: 'the disk is full — free some space, then retry',\n },\n {\n // A clone that fails because the repo is missing is our publishing problem,\n // not the user's network, and telling them to check their connection buries\n // a renamed or deleted PostHog/ai-plugin where nobody will see it.\n match:\n /git clone .* failed|ENOTFOUND|ETIMEDOUT|ECONNREFUSED|could not resolve host/i,\n stages: ALL_STAGES,\n unless:\n /repository not found|not found|404|does not exist|authentication failed/i,\n hint: 'codex could not reach GitHub to download the plugin — check your network, then retry',\n },\n];\n\ninterface CodexRun {\n ok: boolean;\n /** Never blank on a failure: the cause, or the exit status when there is none. */\n output: string;\n}\n\n/**\n * A clone of the plugin marketplace is the slowest thing we run. Past this the\n * command is not slow, it is stuck, and the wizard should say so rather than\n * wait forever.\n */\nconst RUN_TIMEOUT_MS = 120_000;\n\n/**\n * `execFile` kills the child once output passes this. The default is 1 MB,\n * which a verbose clone can reach, and the kill then looks like codex rejecting\n * the install rather than us cutting it off.\n */\nconst MAX_OUTPUT_BYTES = 16 * 1024 * 1024;\n\n/**\n * What `execFile` puts in `error.message` when the command itself never spoke:\n * the full binary path and arguments. That path contains the user's home\n * directory, so reporting it fingerprints one root cause per machine — the\n * failure this reporting was built to stop. Never send it onward.\n */\nconst COMMAND_FAILED_PREAMBLE = /^Command failed:.*$/m;\n\n/**\n * The cause when neither stream carried one. `execFile` always sets a message,\n * so there is no \"empty error\" case to fall through — the message just isn't\n * usable as it stands.\n */\nconst describeExecFailure = (error: ExecFileException): string => {\n if (error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')\n return 'codex produced more output than the wizard can hold, so it was stopped';\n if (error.killed)\n return `codex did not finish within ${\n RUN_TIMEOUT_MS / 1000\n }s, so it was stopped`;\n if (error.signal) return `codex was killed by ${error.signal}`;\n\n const said = error.message.replace(COMMAND_FAILED_PREAMBLE, '').trim();\n if (said) return said;\n if (typeof error.code === 'number')\n return `codex exited with code ${error.code}`;\n if (error.code) return `codex failed with ${error.code}`;\n return 'codex failed without reporting a reason';\n};\n\n/**\n * One codex invocation. Async on purpose: `plugin marketplace add` and\n * `plugin add` clone git repositories and take seconds, and a synchronous child\n * process blocks the event loop, which freezes the TUI spinner on its first\n * frame. Never throws; the caller decides what a failure means.\n *\n * A failure's cause is split across the error and the two streams, and none of\n * them carries it when the process merely exits non-zero — reading one alone\n * reported a blank reason and filed an exception carrying nothing.\n */\nconst runCodex = (\n binary: string,\n args: string[],\n env?: NodeJS.ProcessEnv,\n): Promise<CodexRun> =>\n new Promise((resolve) => {\n const child = execFile(\n binary,\n args,\n { env, timeout: RUN_TIMEOUT_MS, maxBuffer: MAX_OUTPUT_BYTES },\n (error, stdout, stderr) => {\n if (!error) return resolve({ ok: true, output: stdout ?? '' });\n // stderr first: it carries what codex actually said, and the TUI shows\n // the first line. `error.message` leads with our own invocation, so\n // preferring it would show the user the command instead of the cause.\n const said = [stderr, stdout]\n .map((p) => (p ? String(p).trim() : ''))\n .filter(Boolean)\n .join('\\n');\n // A kill is ours, not codex's, so it outranks whatever the streams got\n // out before we cut them off.\n const stopped =\n error.killed ||\n !!error.signal ||\n error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER';\n resolve({\n ok: false,\n output: redactSecrets(\n stopped || !said ? describeExecFailure(error) : said,\n ),\n });\n },\n );\n // codex asks for nothing on stdin here. Leaving the pipe open means a\n // command that does ask waits on input that never comes, and the promise\n // never settles. `spawnSync` closed it for us.\n child.stdin?.end();\n });\n\nconst reportSpawnFailure = (\n stage: CodexStage,\n details: string,\n): InstallResult =>\n reportFailure({ client: 'Codex', stage, details, table: EXPECTED_FAILURES });\n\n/** Wording codex uses when the thing we're adding is already registered. */\nconst ALREADY_INSTALLED_PATTERN =\n /already (installed|exists|added|registered)/i;\n/** Wording that means the opposite: a cache entry exists but the plugin doesn't. */\nconst STALE_MARKETPLACE_CACHE = /already added from a different source/i;\n\n/**\n * Codex allows servers 10s to finish the MCP initialize handshake, and a remote\n * OAuth handshake can exceed that on a cold start — the \"servers were not\n * initialized\" warning.\n */\nconst STARTUP_TIMEOUT_SEC = 30;\n\n/**\n * The server's table header. TOML accepts a bare or quoted key for the same\n * table, and matching only the bare form means we append a second definition of\n * a table that already exists — a duplicate-key error that takes the user's\n * whole config down, not just PostHog's entry.\n */\nconst sectionHeader = (serverName: string): RegExp =>\n new RegExp(\n `^\\\\[mcp_servers\\\\.(?:${serverName}|\"${serverName}\")\\\\][ \\\\t]*$`,\n 'm',\n );\n\n/**\n * Set `key = value` inside a section body, inserting it when absent. Scans the\n * whole body rather than the line after the header: TOML does not care about\n * key order, and assuming it does means silently matching nothing.\n */\nconst setKey = (body: string, key: string, value: string): string => {\n const existing = new RegExp(`^[ \\\\t]*${key}[ \\\\t]*=.*$`, 'm');\n return existing.test(body)\n ? body.replace(existing, `${key} = ${value}`)\n : `\\n${key} = ${value}${body}`;\n};\n\nexport const CodexMCPConfig = DefaultMCPClientConfig;\n\nexport type CodexMCPConfig = z.infer<typeof DefaultMCPClientConfig>;\n\nexport class CodexMCPClient\n extends DefaultMCPClient\n implements PluginCapable, LoginCapable\n{\n name = 'Codex';\n private codexBinaryPath: string | null = null;\n\n constructor() {\n super();\n }\n\n private findCodexBinary(): string | null {\n if (this.codexBinaryPath) return this.codexBinaryPath;\n try {\n const resolved = execSync('command -v codex', { stdio: 'pipe' })\n .toString()\n .trim();\n if (resolved) {\n this.codexBinaryPath = resolved;\n return resolved;\n }\n } catch {\n // not in PATH\n }\n return null;\n }\n\n private configPath(): string {\n return path.join(os.homedir(), '.codex', 'config.toml');\n }\n\n isClientSupported(): Promise<boolean> {\n return Promise.resolve(this.findCodexBinary() !== null);\n }\n\n getConfigPath(): Promise<string> {\n throw new Error('Not implemented');\n }\n\n isServerInstalled(local?: boolean): Promise<boolean> {\n const serverName = local ? 'posthog-local' : 'posthog';\n // The `[mcp_servers.<name>]` section in config.toml — both the CLI and the\n // desktop app read (and `codex mcp add` writes) this file, and a substring\n // scan of `mcp list` matches unrelated posthog-ish servers.\n try {\n const contents = fs.readFileSync(this.configPath(), 'utf-8');\n return Promise.resolve(sectionHeader(serverName).test(contents));\n } catch {\n return Promise.resolve(false);\n }\n }\n\n async addServer(\n apiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n ): Promise<InstallResult> {\n const serverName = local ? 'posthog-local' : 'posthog';\n const url = buildMCPUrl(selectedFeatures, local);\n\n // Api-key installs go through the CLI for its bearer-token env wiring.\n if (apiKey) {\n const binary = this.findCodexBinary();\n if (!binary)\n return {\n success: false,\n reason: 'An API-key install into Codex needs the codex CLI.',\n };\n const args = [\n 'mcp',\n 'add',\n serverName,\n '--url',\n url,\n '--bearer-token-env-var',\n 'POSTHOG_AUTH_HEADER',\n ];\n const env = { ...process.env, POSTHOG_AUTH_HEADER: `Bearer ${apiKey}` };\n const result = await runCodex(binary, args, env);\n if (!result.ok) {\n if (ALREADY_INSTALLED_PATTERN.test(result.output)) {\n return { success: true, alreadyInstalled: true };\n }\n return reportSpawnFailure('MCP add', result.output);\n }\n return { success: true };\n }\n\n // OAuth installs write config.toml directly: running `codex mcp add` here\n // would hang the wizard on its built-in OAuth browser wait. Codex nags\n // about the unauthenticated server until the surfaced `codex mcp login`\n // runs — the same interim state as Claude Code's \"needs authentication\".\n return this.writeServerSection(serverName, url);\n }\n\n /**\n * Create or update the `[mcp_servers.<name>]` section in config.toml, editing\n * in place so the user's other servers, key order, and comments survive.\n */\n private writeServerSection(serverName: string, url: string): InstallResult {\n const configPath = this.configPath();\n try {\n // A machine that has codex installed but has never run it has no\n // ~/.codex at all — `codex mcp add` used to create it for us.\n fs.mkdirSync(path.dirname(configPath), { recursive: true });\n const contents = fs.existsSync(configPath)\n ? fs.readFileSync(configPath, 'utf-8')\n : '';\n\n const header = sectionHeader(serverName).exec(contents);\n if (!header) {\n const gap = contents === '' || contents.endsWith('\\n\\n') ? '' : '\\n';\n const pad = contents === '' || contents.endsWith('\\n') ? '' : '\\n';\n this.write(\n configPath,\n `${contents}${pad}${gap}[mcp_servers.${serverName}]\\n` +\n `url = \"${url}\"\\nstartup_timeout_sec = ${STARTUP_TIMEOUT_SEC}\\n`,\n );\n return { success: true };\n }\n\n // Everything up to the next table header belongs to this server.\n const start = header.index + header[0].length;\n const rest = contents.slice(start);\n const next = /^\\[/m.exec(rest);\n const end = next ? start + next.index : contents.length;\n\n const body = contents.slice(start, end);\n const updated = setKey(\n setKey(body, 'url', `\"${url}\"`),\n 'startup_timeout_sec',\n String(STARTUP_TIMEOUT_SEC),\n );\n if (updated === body) return { success: true, alreadyInstalled: true };\n\n this.write(\n configPath,\n contents.slice(0, start) + updated + contents.slice(end),\n );\n return { success: true };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n // Constant message, varying detail in properties: the reason carries the\n // config path, so interpolating it filed one issue per user.\n analytics.captureException(new Error('Codex config.toml write failed'), {\n details: scrubHomePaths(reason),\n });\n return { success: false, reason };\n }\n }\n\n /** Write via a sibling temp file: a crash mid-write must not truncate the config. */\n private write(configPath: string, contents: string): void {\n const tmp = `${configPath}.wizard-tmp`;\n fs.writeFileSync(tmp, contents);\n fs.renameSync(tmp, configPath);\n }\n\n /** Codex's own login runs its OAuth and owns the token; the wizard only surfaces the command. */\n loginCommand(local?: boolean): string | null {\n if (!this.findCodexBinary()) return null;\n return `codex mcp login ${local ? 'posthog-local' : 'posthog'}`;\n }\n\n async removeServer(local?: boolean): Promise<InstallResult> {\n const binary = this.findCodexBinary();\n if (!binary)\n return {\n success: false,\n reason: 'The codex CLI is no longer on your PATH.',\n };\n\n // `local` was ignored here, so `mcp remove --local` reported success while\n // leaving the posthog-local server in place.\n const serverName = local ? 'posthog-local' : 'posthog';\n const result = await runCodex(binary, ['mcp', 'remove', serverName]);\n\n if (!result.ok) {\n return reportSpawnFailure('MCP remove', result.output);\n }\n\n return { success: true };\n }\n\n /** The codex marketplace plugin ships skills only — the MCP server needs its own entry. */\n pluginBundlesMcpServer(): boolean {\n return false;\n }\n\n supportsPlugin(): boolean {\n return this.findCodexBinary() !== null;\n }\n\n /** The plugin itself, as the CLI reports it. The install decision's question. */\n private async isPluginPresent(): Promise<boolean> {\n const binary = this.findCodexBinary();\n if (!binary) return false;\n const result = await runCodex(binary, [\n 'plugin',\n 'list',\n '-m',\n PLUGIN_MARKETPLACE,\n ]);\n return result.ok && listedAsInstalled(result.output);\n }\n\n /**\n * Anything of ours left on the machine, which is what `index.ts` asks before\n * offering removal. A registered marketplace with no plugin is a state the\n * wizard created — and the state this branch exists to correct — so removal\n * has to see it, or `removePlugin` never runs and the catalog stays forever.\n */\n async isPluginInstalled(): Promise<boolean> {\n return (await this.isPluginPresent()) || this.isMarketplaceRegistered();\n }\n\n /** The catalog, which the plugin is installed *from* — not the plugin. */\n private isMarketplaceRegistered(): boolean {\n try {\n const contents = fs.readFileSync(this.configPath(), 'utf-8');\n return contents\n .toLowerCase()\n .includes(`[marketplaces.${PLUGIN_MARKETPLACE}]`);\n } catch {\n return false;\n }\n }\n\n async removePlugin(): Promise<PluginInstallResult> {\n const binary = this.findCodexBinary();\n if (!binary)\n return {\n success: false,\n reason: 'The codex CLI is no longer on your PATH.',\n };\n\n // Both halves are removed, and either alone is enough to act on: a user\n // left with a registered marketplace and no plugin still needs it cleared.\n const steps: string[][] = [];\n if (await this.isPluginPresent())\n steps.push(['plugin', 'remove', PLUGIN_REF]);\n if (this.isMarketplaceRegistered())\n steps.push(['plugin', 'marketplace', 'remove', PLUGIN_MARKETPLACE]);\n\n if (steps.length === 0) return { success: true, alreadyInstalled: true };\n\n for (const args of steps) {\n const result = await runCodex(binary, args);\n if (!result.ok) {\n return reportSpawnFailure('plugin uninstall', result.output);\n }\n }\n return { success: true };\n }\n\n async installPlugin(): Promise<PluginInstallResult> {\n const binary = this.findCodexBinary();\n if (!binary)\n return {\n success: false,\n reason: 'The codex CLI is no longer on your PATH.',\n };\n\n // The plugin, not the catalog: a registered marketplace with no plugin is\n // exactly the broken state this installs over, so asking the wider question\n // here would skip the install and leave it broken.\n if (await this.isPluginPresent()) {\n return { success: true, alreadyInstalled: true };\n }\n\n // `codex plugin marketplace add` exits non-zero once the marketplace is\n // registered, so ask config.toml first. Without this the second run of\n // `mcp add` looked like a failure and reported nothing at all.\n const marketplace = this.isMarketplaceRegistered()\n ? null\n : await this.registerMarketplace(binary);\n if (marketplace && !marketplace.success) return marketplace;\n\n // Registering the catalog does not install from it. Skipping this left the\n // user with a marketplace, no skills, and a wizard reporting success.\n const result = await runCodex(binary, ['plugin', 'add', PLUGIN_REF]);\n\n if (!result.ok) {\n // The listing above can report \"not installed\" when it merely failed to\n // run, and every other spawn here reads codex's own wording rather than\n // turning a no-op into a reported failure.\n if (ALREADY_INSTALLED_PATTERN.test(result.output)) {\n return { success: true, alreadyInstalled: true };\n }\n return reportSpawnFailure('plugin install', result.output);\n }\n\n return { success: true };\n }\n\n /**\n * Add the catalog the plugin is published in. A stale cache directory with no\n * config.toml entry reports the marketplace as added from a different source;\n * clear it and retry once.\n */\n private async registerMarketplace(\n binary: string,\n ): Promise<PluginInstallResult> {\n const run = () =>\n runCodex(binary, [\n 'plugin',\n 'marketplace',\n 'add',\n PLUGIN_MARKETPLACE_SOURCE,\n ]);\n\n let result = await run();\n\n if (!result.ok && STALE_MARKETPLACE_CACHE.test(result.output)) {\n const staleDir = path.join(\n os.homedir(),\n '.codex',\n '.tmp',\n 'marketplaces',\n PLUGIN_MARKETPLACE,\n );\n try {\n fs.rmSync(staleDir, { recursive: true, force: true });\n } catch {\n // ignore — retry anyway\n }\n result = await run();\n }\n\n if (!result.ok) {\n const details = result.output;\n // Registered by something other than us — the plugin add below can still\n // resolve against it. The stale-cache wording is excluded: that one means\n // the marketplace is NOT usable, and only reaches here if the retry failed.\n if (\n ALREADY_INSTALLED_PATTERN.test(details) &&\n !STALE_MARKETPLACE_CACHE.test(details)\n ) {\n return { success: true };\n }\n return reportSpawnFailure('marketplace add', details);\n }\n return { success: true };\n }\n}\n\nexport default CodexMCPClient;\n","import z from 'zod';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as fs from 'fs';\nimport { execSync } from 'node:child_process';\nimport {\n DefaultMCPClient,\n MCPServerConfig,\n} from '@shared/mcp-clients/MCPClient';\nimport { getNativeHTTPServerConfig } from '@shared/mcp-clients/defaults';\nimport { runtimeEnv } from '@env';\n\nexport const OpenCodeMCPConfig = z\n .object({\n mcp: z.record(\n z.string(),\n z.object({\n type: z.literal('remote'),\n url: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n }),\n ),\n })\n .passthrough();\n\nexport type OpenCodeMCPConfig = z.infer<typeof OpenCodeMCPConfig>;\n\nexport class OpenCodeMCPClient extends DefaultMCPClient {\n name = 'OpenCode';\n private opencodeBinaryPath: string | null = null;\n\n override getServerPropertyName(): string {\n return 'mcp';\n }\n\n private findOpenCodeBinary(): string | null {\n if (this.opencodeBinaryPath) return this.opencodeBinaryPath;\n try {\n const resolved = execSync('command -v opencode', { stdio: 'pipe' })\n .toString()\n .trim();\n if (resolved) {\n this.opencodeBinaryPath = resolved;\n return resolved;\n }\n } catch {\n // not in PATH\n }\n return null;\n }\n\n isClientSupported(): Promise<boolean> {\n return Promise.resolve(this.findOpenCodeBinary() !== null);\n }\n\n getConfigPath(): Promise<string> {\n const configDir = this.resolveConfigDir();\n const jsoncPath = path.join(configDir, 'opencode.jsonc');\n const jsonPath = path.join(configDir, 'opencode.json');\n if (fs.existsSync(jsoncPath)) return Promise.resolve(jsoncPath);\n return Promise.resolve(jsonPath);\n }\n\n private resolveConfigDir(): string {\n const envDir = runtimeEnv('OPENCODE_CONFIG_DIR');\n if (envDir) return envDir;\n\n const xdgHome = runtimeEnv('XDG_CONFIG_HOME');\n if (xdgHome) return path.join(xdgHome, 'opencode');\n\n return path.join(os.homedir(), '.config', 'opencode');\n }\n\n override getServerConfig(\n apiKey: string | undefined,\n selectedFeatures?: string[],\n local?: boolean,\n ): MCPServerConfig {\n return {\n type: 'remote',\n ...getNativeHTTPServerConfig(apiKey, selectedFeatures, local),\n };\n }\n}\n","import type { InstallResult } from './results';\n\nexport type PluginInstallResult = InstallResult;\n\nexport interface PluginCapable {\n supportsPlugin(): boolean;\n isPluginInstalled(): Promise<boolean>;\n installPlugin(): Promise<PluginInstallResult>;\n /** Uninstall the plugin. Absent when the client CLI has no uninstall surface. */\n removePlugin?(): Promise<PluginInstallResult>;\n /** True when the plugin ships its own posthog MCP server, making a direct entry redundant. */\n pluginBundlesMcpServer(): boolean;\n}\n\nexport function isPluginCapable<T>(client: T): client is T & PluginCapable {\n return (\n typeof client === 'object' &&\n client !== null &&\n 'supportsPlugin' in client &&\n 'installPlugin' in client\n );\n}\n","// The MCP client operations every MCP surface shares: detect, add, remove or check, one result per client.\nimport { logToFile } from '../utils/debug';\nimport { MCPClient } from './MCPClient';\nimport { CursorMCPClient } from './clients/cursor';\nimport { ClaudeCodeMCPClient } from './clients/claude-code';\nimport { ClaudeWebMCPClient } from './clients/claude-web';\nimport { VisualStudioCodeClient } from './clients/visual-studio-code';\nimport { ZedClient } from './clients/zed';\nimport { CodexMCPClient } from './clients/codex';\nimport { OpenCodeMCPClient } from './clients/opencode';\nimport { isPluginCapable, PluginCapable } from './plugin-client';\nimport { toClientResult, type McpClientResult } from './results';\n\nexport const getSupportedClients = async (): Promise<MCPClient[]> => {\n const allClients = [\n new ClaudeCodeMCPClient(),\n new ClaudeWebMCPClient(),\n new CodexMCPClient(),\n new CursorMCPClient(),\n new VisualStudioCodeClient(),\n new ZedClient(),\n new OpenCodeMCPClient(),\n ];\n const supportedClients: MCPClient[] = [];\n\n logToFile('Checking for supported MCP clients...');\n for (const client of allClients) {\n const isSupported = await client.isClientSupported();\n logToFile(\n `${client.name}: ${isSupported ? '✓ supported' : '✗ not supported'}`,\n );\n if (isSupported) {\n supportedClients.push(client);\n }\n }\n logToFile(\n `Found ${supportedClients.length} supported client(s): ${supportedClients\n .map((c) => c.name)\n .join(', ')}`,\n );\n\n return supportedClients;\n};\n\nexport const getInstalledClients = async (\n local?: boolean,\n): Promise<MCPClient[]> => {\n const clients = await getSupportedClients();\n const installedClients: MCPClient[] = [];\n\n for (const client of clients) {\n // The plugin bundles its own posthog MCP server, so for removal purposes a\n // plugin install counts as installed even with no config entry (`--local`\n // targets only the local-dev entry and leaves the plugin alone).\n const pluginInstalled =\n !local && isPluginCapable(client) && (await client.isPluginInstalled());\n if ((await client.isServerInstalled(local)) || pluginInstalled) {\n installedClients.push(client);\n }\n }\n\n return installedClients;\n};\n\nexport const addMCPServer = async (\n clients: MCPClient[],\n personalApiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n): Promise<McpClientResult[]> => {\n const results: McpClientResult[] = [];\n for (const client of clients) {\n try {\n const result = await client.addServer(\n personalApiKey,\n selectedFeatures,\n local,\n );\n results.push(toClientResult(client.name, result));\n } catch (err) {\n logToFile(`[addMCPServer] addServer threw for ${client.name}: ${err}`);\n results.push(\n toClientResult(client.name, {\n success: false,\n reason: err instanceof Error ? err.message : String(err),\n }),\n );\n }\n }\n return results;\n};\n\nexport const getSupportedPluginClients = (\n clients: MCPClient[],\n): Array<MCPClient & PluginCapable> => {\n return clients.filter(isPluginCapable).filter((c) => c.supportsPlugin());\n};\n\nexport const installPlugins = async (\n clients: Array<MCPClient & PluginCapable>,\n): Promise<McpClientResult[]> => {\n const results: McpClientResult[] = [];\n for (const client of clients) {\n try {\n results.push(toClientResult(client.name, await client.installPlugin()));\n } catch (err) {\n logToFile(\n `[installPlugins] installPlugin threw for ${client.name}: ${err}`,\n );\n results.push(\n toClientResult(client.name, {\n success: false,\n reason: err instanceof Error ? err.message : String(err),\n }),\n );\n }\n }\n return results;\n};\n\nexport const removeMCPServer = async (\n clients: MCPClient[],\n local?: boolean,\n): Promise<McpClientResult[]> => {\n const results: McpClientResult[] = [];\n for (const client of clients) {\n try {\n let result = await client.removeServer(local);\n // The plugin bundles its own posthog server — leaving it installed makes\n // the removal a lie (`--local` never touches the plugin).\n if (!local && isPluginCapable(client) && client.removePlugin) {\n const plugin = await client.removePlugin();\n result =\n !result.success || !plugin.success\n ? {\n success: false,\n reason: [result.reason, plugin.reason]\n .filter(Boolean)\n .join('; '),\n }\n : {\n success: true,\n ...(result.alreadyInstalled && plugin.alreadyInstalled\n ? { alreadyInstalled: true }\n : {}),\n };\n }\n results.push(toClientResult(client.name, result));\n } catch (err) {\n logToFile(\n `[removeMCPServer] removeServer threw for ${client.name}: ${err}`,\n );\n results.push(\n toClientResult(client.name, {\n success: false,\n reason: err instanceof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