@posthog/wizard 2.80.1 → 2.81.1

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 (134) hide show
  1. package/README.md +19 -17
  2. package/dist/README.md +6 -4
  3. package/dist/{agent-interface-CemBvTAA.js → agent-interface-DMP3DZRd.js} +184 -25
  4. package/dist/agent-interface-DMP3DZRd.js.map +1 -0
  5. package/dist/{agent-prompt-loader-DPnj6SwU.js → agent-prompt-loader-BrivWIna.js} +6 -6
  6. package/dist/{agent-prompt-loader-DPnj6SwU.js.map → agent-prompt-loader-BrivWIna.js.map} +1 -1
  7. package/dist/{analytics-D21z3E5l.js → analytics-X7JfAmh6.js} +6 -3
  8. package/dist/analytics-X7JfAmh6.js.map +1 -0
  9. package/dist/analytics-dcL9EQ4r.js +2 -0
  10. package/dist/{api-DtGIqQ2U.js → api-BkDwZoL4.js} +3 -2
  11. package/dist/{api-DtGIqQ2U.js.map → api-BkDwZoL4.js.map} +1 -1
  12. package/dist/api-BrMGAI-b.js +2 -0
  13. package/dist/api-key-login-CZEgx2jb.js +2 -0
  14. package/dist/{api-key-login-h3E2G3zu.js → api-key-login-DE0yKkP4.js} +5 -5
  15. package/dist/{api-key-login-h3E2G3zu.js.map → api-key-login-DE0yKkP4.js.map} +1 -1
  16. package/dist/bin.js +2 -2
  17. package/dist/{bounded-fs-CAsuF6al.js → bounded-fs-iDiqDQ9v.js} +3 -3
  18. package/dist/{bounded-fs-CAsuF6al.js.map → bounded-fs-iDiqDQ9v.js.map} +1 -1
  19. package/dist/{ci-install-CEYE02t-.js → ci-install-BAftKh2Z.js} +7 -7
  20. package/dist/{ci-install-CEYE02t-.js.map → ci-install-BAftKh2Z.js.map} +1 -1
  21. package/dist/{console-log-O828zyiq.js → console-log-DJiTqYT2.js} +3 -3
  22. package/dist/{console-log-O828zyiq.js.map → console-log-DJiTqYT2.js.map} +1 -1
  23. package/dist/{debug-BfQPD2Hg.js → debug-C3tLP-ZW.js} +3 -3
  24. package/dist/{debug-BfQPD2Hg.js.map → debug-C3tLP-ZW.js.map} +1 -1
  25. package/dist/{emit-RfAewcWv.js → emit-BqLCdV8Y.js} +2 -1
  26. package/dist/{emit-RfAewcWv.js.map → emit-BqLCdV8Y.js.map} +1 -1
  27. package/dist/{errors-CHrJzAZb.js → errors-DhFeR8Sp.js} +3 -3
  28. package/dist/{errors-CHrJzAZb.js.map → errors-DhFeR8Sp.js.map} +1 -1
  29. package/dist/{gateway-D3gIlR6b.js → gateway-IQjQ582o.js} +7 -7
  30. package/dist/{gateway-D3gIlR6b.js.map → gateway-IQjQ582o.js.map} +1 -1
  31. package/dist/{headless-BJjhP0SI.js → headless-DOhxEmw5.js} +2 -2
  32. package/dist/{headless-BJjhP0SI.js.map → headless-DOhxEmw5.js.map} +1 -1
  33. package/dist/{headless-DIX68UUA.js → headless-XNvdWVEp.js} +1 -1
  34. package/dist/{host-resolution-D8GhEVoX.js → host-resolution-DI2oucSK.js} +4 -4
  35. package/dist/{host-resolution-D8GhEVoX.js.map → host-resolution-DI2oucSK.js.map} +1 -1
  36. package/dist/{install-paPCzPHI.js → install-BixbBDLR.js} +41 -55
  37. package/dist/install-BixbBDLR.js.map +1 -0
  38. package/dist/{install-Bw8tvDvS.js → install-DaZ6pvEl.js} +1 -1
  39. package/dist/{interactive-tdxZKWax.js → interactive-WLNQWF0D.js} +3 -3
  40. package/dist/{interactive-tdxZKWax.js.map → interactive-WLNQWF0D.js.map} +1 -1
  41. package/dist/{links-Cyj6v8kg.js → links-Bye4fsrj.js} +3 -3
  42. package/dist/{links-Cyj6v8kg.js.map → links-Bye4fsrj.js.map} +1 -1
  43. package/dist/{main-0p-YxUNa.js → main-CN8nbuZO.js} +25 -25
  44. package/dist/main-CN8nbuZO.js.map +1 -0
  45. package/dist/{mcp-D3Z5MXhA.js → mcp-B2o4d9DS.js} +3 -3
  46. package/dist/{mcp-D3Z5MXhA.js.map → mcp-B2o4d9DS.js.map} +1 -1
  47. package/dist/{mcp-prompt-streaming-COVbWnHt.js → mcp-prompt-streaming-COs1DfAm.js} +5 -5
  48. package/dist/{mcp-prompt-streaming-COVbWnHt.js.map → mcp-prompt-streaming-COs1DfAm.js.map} +1 -1
  49. package/dist/{models-D1SnCzvl.js → models-Cow22jET.js} +2 -2
  50. package/dist/{models-D1SnCzvl.js.map → models-Cow22jET.js.map} +1 -1
  51. package/dist/{non-interactive-DxRBc73O.js → non-interactive-DkldwWDM.js} +4 -4
  52. package/dist/{non-interactive-DxRBc73O.js.map → non-interactive-DkldwWDM.js.map} +1 -1
  53. package/dist/{oauth-session-Dde79Ycm.js → oauth-session-Bj_-BY7o.js} +2 -2
  54. package/dist/{oauth-session-Dde79Ycm.js.map → oauth-session-Bj_-BY7o.js.map} +1 -1
  55. package/dist/{orchestrator-tools-BSNhzzkT.js → orchestrator-tools-lhFIBGnp.js} +3 -3
  56. package/dist/{orchestrator-tools-BSNhzzkT.js.map → orchestrator-tools-lhFIBGnp.js.map} +1 -1
  57. package/dist/{package-manager-BRXlXo0p.js → package-manager-DZ4wcTz3.js} +4 -4
  58. package/dist/{package-manager-BRXlXo0p.js.map → package-manager-DZ4wcTz3.js.map} +1 -1
  59. package/dist/{pi-cM_4Gd_9.js → pi-DREdQRPP.js} +15 -15
  60. package/dist/{pi-cM_4Gd_9.js.map → pi-DREdQRPP.js.map} +1 -1
  61. package/dist/{playground-DTKy0XHT.js → playground-CJx3lwTH.js} +4 -4
  62. package/dist/{playground-DTKy0XHT.js.map → playground-CJx3lwTH.js.map} +1 -1
  63. package/dist/{posthog-integration-bwHwE87a.js → posthog-integration-DDSPdbpw.js} +63 -50
  64. package/dist/posthog-integration-DDSPdbpw.js.map +1 -0
  65. package/dist/{programs-SeT1qNik.js → programs-6SFfUBmm.js} +88 -34
  66. package/dist/programs-6SFfUBmm.js.map +1 -0
  67. package/dist/programs-DvlhdeM_.js +3 -0
  68. package/dist/provisioning-CPGWgv7p.js +2 -0
  69. package/dist/{provisioning-JbJtq7hq.js → provisioning-tRDPH7EQ.js} +4 -4
  70. package/dist/{provisioning-JbJtq7hq.js.map → provisioning-tRDPH7EQ.js.map} +1 -1
  71. package/dist/{queue-tools-BIZSJyt6.js → queue-tools-DrJKvFHZ.js} +4 -4
  72. package/dist/{queue-tools-BIZSJyt6.js.map → queue-tools-DrJKvFHZ.js.map} +1 -1
  73. package/dist/{results-DtKICAdz.js → results-Crcubw0Q.js} +37 -2
  74. package/dist/results-Crcubw0Q.js.map +1 -0
  75. package/dist/{run-DDCvLILJ.js → run-BrIGaPy7.js} +10 -10
  76. package/dist/run-BrIGaPy7.js.map +1 -0
  77. package/dist/{run-CDurA5tO.js → run-DVFTMbxf.js} +31 -15
  78. package/dist/run-DVFTMbxf.js.map +1 -0
  79. package/dist/{run-tool-DML8JJvt.js → run-tool-CxdPXmlY.js} +37 -21
  80. package/dist/{run-tool-DML8JJvt.js.map → run-tool-CxdPXmlY.js.map} +1 -1
  81. package/dist/run-tool-GfISLgEs.js +2 -0
  82. package/dist/{runners-Dhu4pZTN.js → runners-loOOmHyc.js} +37 -19
  83. package/dist/runners-loOOmHyc.js.map +1 -0
  84. package/dist/{security-DEH8Rn0_.js → security-C_grSgIM.js} +44 -52
  85. package/dist/security-C_grSgIM.js.map +1 -0
  86. package/dist/{setup-utils-C5-WM-hS.js → setup-utils-BYXbb9NM.js} +3 -3
  87. package/dist/{setup-utils-C5-WM-hS.js.map → setup-utils-BYXbb9NM.js.map} +1 -1
  88. package/dist/{start-playground-DL4mVEUx.js → start-playground-Blh0Swil.js} +13 -12
  89. package/dist/{start-playground-DL4mVEUx.js.map → start-playground-Blh0Swil.js.map} +1 -1
  90. package/dist/{subagent-CnFvAq6E.js → subagent-DQ_enM8C.js} +7 -7
  91. package/dist/subagent-DQ_enM8C.js.map +1 -0
  92. package/dist/{task-BOScSm4W.js → task-Dm9wZbVW.js} +18 -17
  93. package/dist/task-Dm9wZbVW.js.map +1 -0
  94. package/dist/{telemetry-CP4rGicd.js → telemetry-NeZhrBeW.js} +2 -2
  95. package/dist/{telemetry-CP4rGicd.js.map → telemetry-NeZhrBeW.js.map} +1 -1
  96. package/dist/{terminal-J3OD3dN0.js → terminal-Z4hCXfie.js} +186 -134
  97. package/dist/terminal-Z4hCXfie.js.map +1 -0
  98. package/dist/{tools-Cz8tDptL.js → tools-1aM6bI9Y.js} +8 -8
  99. package/dist/{tools-Cz8tDptL.js.map → tools-1aM6bI9Y.js.map} +1 -1
  100. package/dist/{tools-CCMV3DmB.js → tools-dUJHRo6X.js} +15 -15
  101. package/dist/{tools-CCMV3DmB.js.map → tools-dUJHRo6X.js.map} +1 -1
  102. package/dist/{tui-BUZ2PWqN.js → tui-CCO7VVTA.js} +1 -1
  103. package/dist/{tui-Csf7VJxt.js → tui-Cmi_ckGg.js} +4 -4
  104. package/dist/{tui-Csf7VJxt.js.map → tui-Cmi_ckGg.js.map} +1 -1
  105. package/dist/{upload-step-CEacB2RV.js → upload-step-e2Jp2fcr.js} +3 -3
  106. package/dist/{upload-step-CEacB2RV.js.map → upload-step-e2Jp2fcr.js.map} +1 -1
  107. package/dist/{urls-BDELGZHq.js → urls-Cu4RO30x.js} +2 -2
  108. package/dist/{urls-BDELGZHq.js.map → urls-Cu4RO30x.js.map} +1 -1
  109. package/dist/{wizard-abort-D3-75KyV.js → wizard-abort-BPEiPCXk.js} +5 -5
  110. package/dist/{wizard-abort-D3-75KyV.js.map → wizard-abort-BPEiPCXk.js.map} +1 -1
  111. package/dist/{yara-hooks-CZ1tKxy_.js → yara-hooks-CFD60h78.js} +1 -1
  112. package/dist/{yara-hooks-D8YDyX7o.js → yara-hooks-canFIYTc.js} +4 -4
  113. package/dist/{yara-hooks-D8YDyX7o.js.map → yara-hooks-canFIYTc.js.map} +1 -1
  114. package/package.json +2 -1
  115. package/dist/agent-interface-CemBvTAA.js.map +0 -1
  116. package/dist/analytics-B3ROGuIr.js +0 -2
  117. package/dist/analytics-D21z3E5l.js.map +0 -1
  118. package/dist/api-IhROOQNv.js +0 -2
  119. package/dist/api-key-login-OEntFvu5.js +0 -2
  120. package/dist/install-paPCzPHI.js.map +0 -1
  121. package/dist/main-0p-YxUNa.js.map +0 -1
  122. package/dist/posthog-integration-bwHwE87a.js.map +0 -1
  123. package/dist/programs-BhtyA3lE.js +0 -3
  124. package/dist/programs-SeT1qNik.js.map +0 -1
  125. package/dist/provisioning-BcXfeCMc.js +0 -2
  126. package/dist/results-DtKICAdz.js.map +0 -1
  127. package/dist/run-CDurA5tO.js.map +0 -1
  128. package/dist/run-DDCvLILJ.js.map +0 -1
  129. package/dist/run-tool-CTq9OOdT.js +0 -2
  130. package/dist/runners-Dhu4pZTN.js.map +0 -1
  131. package/dist/security-DEH8Rn0_.js.map +0 -1
  132. package/dist/subagent-CnFvAq6E.js.map +0 -1
  133. package/dist/task-BOScSm4W.js.map +0 -1
  134. package/dist/terminal-J3OD3dN0.js.map +0 -1
@@ -1,2 +0,0 @@
1
- import { n as analytics } from "./analytics-D21z3E5l.js";
2
- export { analytics };
@@ -1 +0,0 @@
1
- {"version":3,"file":"analytics-D21z3E5l.js","names":["uuidv4"],"sources":["../src/shared/local-dev.ts","../src/shared/constants.ts","../src/shared/run-state.ts","../src/shared/utils/ci-flag-overrides.ts","../src/shared/utils/analytics.ts"],"sourcesContent":["/**\n * Local development targets: context-mill (skills), MCP, and PostHog. Each is\n * independently switchable — CI runs local skills against the *production* MCP\n * — with `--local-dev` as a shorthand for all three.\n *\n * `wizard mcp add --local` is unrelated: it writes a `posthog-local` entry into\n * the user's editor config rather than retargeting this run. Hence no\n * `--local` here.\n */\n\nexport const CONTEXT_MILL_LOCAL_URL = 'http://localhost:8765';\nexport const MCP_LOCAL_URL = 'http://localhost:8787/mcp';\n/** Pins the API, app, OAuth, and the LLM gateway derived from them. */\nexport const POSTHOG_LOCAL_URL = 'http://localhost:8010';\n\n/**\n * Raw yargs values. The three specific flags are declared without a `default`\n * so they stay `undefined` when absent — see `resolveLocalDev`.\n */\nexport type LocalDevFlags = {\n localDev?: boolean;\n localMcp?: boolean;\n localContextMill?: boolean;\n localPosthog?: boolean;\n};\n\nexport type ResolvedLocalDev = {\n localMcp: boolean;\n localContextMill: boolean;\n localPosthog: boolean;\n};\n\n/**\n * A specific flag beats `--local-dev` in both directions. `??` is load-bearing:\n * it falls through only on `undefined`, so giving the specific flags a yargs\n * `default: false` would silently break both the umbrella and `--no-local-mcp`.\n */\nexport function resolveLocalDev(flags: LocalDevFlags): ResolvedLocalDev {\n const umbrella = flags.localDev ?? false;\n return {\n localMcp: flags.localMcp ?? umbrella,\n localContextMill: flags.localContextMill ?? umbrella,\n localPosthog: flags.localPosthog ?? umbrella,\n };\n}\n\n/** yargs populates both spellings, so read either. */\nexport function localDevFromArgv(\n argv: Record<string, unknown>,\n): ResolvedLocalDev {\n const read = (kebab: string, camel: string): boolean | undefined => {\n const value = argv[camel] ?? argv[kebab];\n return typeof value === 'boolean' ? value : undefined;\n };\n return resolveLocalDev({\n localDev: read('local-dev', 'localDev'),\n localMcp: read('local-mcp', 'localMcp'),\n localContextMill: read('local-context-mill', 'localContextMill'),\n localPosthog: read('local-posthog', 'localPosthog'),\n });\n}\n\nconst PRODUCTION_TARGETS: ResolvedLocalDev = {\n localMcp: false,\n localContextMill: false,\n localPosthog: false,\n};\n\nlet resolved: ResolvedLocalDev | null = null;\n\n/**\n * Resolve this process's targets. Called once from the yargs middleware, which\n * covers every command and the env-var spellings alike.\n */\nexport function initLocalDev(argv: Record<string, unknown>): ResolvedLocalDev {\n resolved = localDevFromArgv(argv);\n return resolved;\n}\n\n/**\n * Where this run points. Resolved once because the flags are parsed at startup\n * and never change; threading them through state let call sites read whichever\n * field they happened to have, which is how the intro screens ended up asking\n * the MCP flag where to fetch skills.\n *\n * Uninitialized means no CLI parse ran (a direct-call test) — production.\n */\nexport function getLocalDev(): ResolvedLocalDev {\n return resolved ?? PRODUCTION_TARGETS;\n}\n\n/** Tests only. */\nexport function resetLocalDev(): void {\n resolved = null;\n}\n\ntype LocalService = {\n key: keyof ResolvedLocalDev;\n label: string;\n flag: string;\n /** Probed for reachability — any HTTP reply proves the port is bound. */\n url: string;\n startHint: string;\n};\n\nconst LOCAL_SERVICES: readonly LocalService[] = [\n {\n key: 'localContextMill',\n label: 'context-mill',\n flag: '--local-context-mill',\n url: `${CONTEXT_MILL_LOCAL_URL}/skill-menu.json`,\n startHint: 'npm run dev (in the context-mill repo)',\n },\n {\n key: 'localMcp',\n label: 'MCP server',\n flag: '--local-mcp',\n url: MCP_LOCAL_URL,\n startHint:\n 'hogli start (or pnpm dev:local-resources in posthog/services/mcp)',\n },\n {\n key: 'localPosthog',\n label: 'PostHog',\n flag: '--local-posthog',\n url: POSTHOG_LOCAL_URL,\n startHint: './bin/start (in the posthog repo)',\n },\n] as const;\n\n// Retries because this gate gates `fetchWithRetry` (see fetch-retry.ts) — a\n// blip it would ride out must not abort the run instead. A missing server\n// refuses instantly, so the retries only cost time when one is slow to answer,\n// which is exactly when they're worth paying for.\nconst PROBE_TIMEOUT_MS = 2_000;\nconst PROBE_ATTEMPTS = 3;\nconst PROBE_BACKOFF_MS = 250;\n\nasync function isReachable(url: string): Promise<boolean> {\n for (let attempt = 1; attempt <= PROBE_ATTEMPTS; attempt++) {\n try {\n // Any reply — including 404 or 405 — proves something is listening, which\n // is the only question here. Deliberately not `fetchWithRetry`: that\n // treats a non-ok status as failure, and here it is a pass.\n await fetch(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });\n return true;\n } catch {\n if (attempt < PROBE_ATTEMPTS) {\n await new Promise((r) =>\n setTimeout(r, PROBE_BACKOFF_MS * 2 ** (attempt - 1)),\n );\n }\n }\n }\n return false;\n}\n\n/**\n * Probe every service the flags asked to be local. Returns one message naming\n * each unreachable one, or undefined if all are up (or none were requested).\n *\n * Without this a dead local server surfaces late and badly: a missing\n * context-mill looks like a registry outage, a missing MCP fails mid-run after\n * the agent has already edited files.\n */\nexport async function checkLocalServices(\n resolved: ResolvedLocalDev,\n): Promise<string | undefined> {\n const requested = LOCAL_SERVICES.filter((s) => resolved[s.key]);\n if (requested.length === 0) return undefined;\n\n const reachable = await Promise.all(requested.map((s) => isReachable(s.url)));\n const dead = requested.filter((_, i) => !reachable[i]);\n if (dead.length === 0) return undefined;\n\n return [\n `Local ${dead.length === 1 ? 'service is' : 'services are'} not running:`,\n '',\n ...dead.map(\n (s) =>\n ` ${s.label} — nothing listening at ${new URL(s.url).origin}\\n` +\n ` requested by ${s.flag}\\n` +\n ` start it with: ${s.startHint}`,\n ),\n '',\n 'Start the missing services, or drop the flag to use production.',\n ].join('\\n');\n}\n\n/**\n * `--local-mcp` used to select local skills too; anyone still relying on that\n * would silently get production skills. Temporary — drop after a release or two.\n */\nexport function localMcpSkillsNotice(flags: LocalDevFlags): string | undefined {\n if (flags.localMcp !== true) return undefined;\n if (flags.localContextMill !== undefined || flags.localDev === true) {\n return undefined;\n }\n return (\n '--local-mcp now points only at the local MCP server. ' +\n 'For local skills, add --local-context-mill (or use --local-dev for both).'\n );\n}\n","/**\n * Shared constants for the PostHog wizard.\n */\n\nimport { VERSION } from './version';\n\n// ── Models ──────────────────────────────────────────────────────────\n// Coordinate IDs/efforts with the mint allowlists and gateway transport/required prompt policy; see agent/runner/README.md.\n\n/** Next sonnet generation (a `MODEL_FLAG_VARIANTS` key in the switchboard). */\nexport const SONNET_5_MODEL = 'claude-sonnet-5';\n\n/**\n * Default model for agent runs. Bare model IDs (no `anthropic/` prefix) so the\n * LLM gateway's Bedrock fallback can match map_to_bedrock_model().\n */\nexport const DEFAULT_AGENT_MODEL = SONNET_5_MODEL;\n\n/** Undated haiku, for scan triage. The alias tracks the current 4.5 release rather than pinning one. */\nexport const HAIKU_TRIAGE_MODEL = 'claude-haiku-4-5';\n\n/**\n * Cheaper, faster model for mechanical agent work (e.g. repo classification\n * during source-map detection). Passed via AgentConfig.modelOverride.\n */\nexport const HAIKU_MODEL = HAIKU_TRIAGE_MODEL;\n\n// Locally supported OpenAI models; constants alone do not authorize gateway use.\nexport const GPT5_6_LUNA_MODEL = 'openai/gpt-5.6-luna';\nexport const GPT5_6_TERRA_MODEL = 'openai/gpt-5.6-terra';\nexport const GPT5_6_SOL_MODEL = 'openai/gpt-5.6-sol';\n\n// ── Agent runner routing axes ────────────────────────────────────────\n\n/**\n * The two agent runner routing axes: **harness** (which agent SDK drives the LLM)\n * and **sequence** (which pipeline shape orchestrates the work). Single source\n * of truth for yargs `choices`, session fields, the runner registry, and tests\n * — `Object.values(Harness)` gives an iterable of the values when an array is\n * needed. Adding a member is enough to pick it up everywhere.\n *\n * Naming matches the directory layout — see `src/agent/runner/harness/`\n * and `src/agent/runner/sequence/`.\n */\nexport enum Harness {\n anthropic = 'anthropic',\n pi = 'pi',\n}\n\nexport enum Sequence {\n linear = 'linear',\n orchestrator = 'orchestrator',\n}\n\n/**\n * What kind of call produced a gateway generation — the `call_type` trace tag.\n * Splits a program's LLM spend by workload. Every member is sent explicitly so\n * an absent value means \"old build\", not \"agent\".\n */\nexport enum CallType {\n /** The agent doing the work the user asked for. */\n agent = 'agent',\n /** Warlock's classifier deciding whether a YARA match is a true positive. */\n yaraTriage = 'yara-triage',\n /** The cheap repo scan that classifies which projects a program acts on. */\n detection = 'detection',\n}\n\n// ── Integration / CLI ───────────────────────────────────────────────\n\n/**\n * Detection order matters: put framework-specific integrations BEFORE basic language fallbacks.\n */\nexport enum Integration {\n // Frameworks\n nextjs = 'nextjs',\n nuxt = 'nuxt',\n vue = 'vue',\n reactRouter = 'react-router',\n tanstackStart = 'tanstack-start',\n tanstackRouter = 'tanstack-router',\n reactNative = 'react-native',\n angular = 'angular',\n astro = 'astro',\n django = 'django',\n flask = 'flask',\n fastapi = 'fastapi',\n laravel = 'laravel',\n sveltekit = 'sveltekit',\n flutter = 'flutter',\n kmp = 'kmp',\n swift = 'swift',\n android = 'android',\n rails = 'rails',\n elixir = 'elixir',\n go = 'go',\n rust = 'rust',\n // Must stay after kmp/swift/android: those claim gradle projects first.\n java = 'java',\n\n // Language fallbacks. Keep javascriptNode last: it matches any package.json.\n python = 'python',\n ruby = 'ruby',\n javascript_web = 'javascript_web',\n javascriptNode = 'javascript_node',\n}\n\n/**\n * The platforms session replay can actually record on. Replay vision watches\n * recordings, so a platform with no recordings has nothing to set up — the\n * run must stop before any work, not after a pointless agent run.\n *\n * Web frameworks record through posthog-js (server-rendered frameworks\n * included — they serve pages), and the mobile SDKs with replay support are\n * React Native, Android, iOS, and Flutter. Excluded: pure backend targets\n * (`javascript_node`, `python`, `ruby`) and KMP, which has no replay support\n * yet.\n */\nexport const REPLAY_VISION_SUPPORTED: ReadonlySet<Integration> = new Set([\n Integration.nextjs,\n Integration.nuxt,\n Integration.vue,\n Integration.reactRouter,\n Integration.tanstackStart,\n Integration.tanstackRouter,\n Integration.angular,\n Integration.astro,\n Integration.sveltekit,\n Integration.javascript_web,\n Integration.django,\n Integration.flask,\n Integration.fastapi,\n Integration.laravel,\n Integration.rails,\n Integration.reactNative,\n Integration.android,\n Integration.swift,\n Integration.flutter,\n]);\n\n// ── Documents the wizard's programs write into the user's project ────\n// Named here so the scanner's documentation allowlist can list them without\n// importing a program; each program re-exports its own.\n/** The events-audit report. */\nexport const EVENTS_AUDIT_REPORT_FILE = 'posthog-events-audit-report.md';\nexport const EVENT_INVENTORY_FILE = '.posthog-events-inventory.json';\n/** Per-part filename pattern emitted by events-audit subagents (e.g. `.posthog-events-inventory.part-3.json`). */\nexport const EVENT_INVENTORY_PART_PATTERN =\n /^\\.posthog-events-inventory\\.part-\\d+\\.json$/;\n/** The integration program's event plan. */\nexport const EVENT_PLAN_FILE = '.posthog-events.json';\n/** The integration program's setup report; Self-driving reads it as a hint. */\nexport const SETUP_REPORT_FILE = 'posthog-setup-report.md';\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\n// ── Environment ──────────────────────────────────────────────────────\n\nimport { IS_DEV } from '@env';\nimport {\n CONTEXT_MILL_LOCAL_URL,\n getLocalDev,\n POSTHOG_LOCAL_URL,\n} from './local-dev';\nexport { IS_DEV };\nexport const DEBUG = false;\n\n// ── URLs ─────────────────────────────────────────────────────────────\n\nexport const DEFAULT_URL = IS_DEV\n ? POSTHOG_LOCAL_URL\n : 'https://us.posthog.com';\n/**\n * Region-agnostic PostHog app URL. Resolves to us.posthog.com or\n * eu.posthog.com server-side based on the signed-in user's profile.\n * Use this for share-with-user links (e.g. settings pages) so they\n * land on the right region without us needing to know it client-side.\n */\nexport const POSTHOG_APP_URL = IS_DEV\n ? POSTHOG_LOCAL_URL\n : 'https://app.posthog.com';\nexport const DEFAULT_HOST_URL = IS_DEV\n ? POSTHOG_LOCAL_URL\n : 'https://us.i.posthog.com';\nexport const ISSUES_URL = 'https://github.com/posthog/wizard/issues';\n/** Public status page, linked from transient-failure guidance (e.g. OAuth server_error). */\nexport const POSTHOG_STATUS_PAGE_URL = 'https://www.posthogstatus.com';\nexport const CONTEXT_MILL_URL = 'https://github.com/PostHog/context-mill';\n/**\n * Latest context-mill release page — the BYOAI download link shown in\n * the privacy panel. Deliberately the release PAGE, not a direct asset\n * URL: asset URLs are ~89 chars and hard-wrap inside the 64-col panel,\n * which corrupts terminal copy/paste with a mid-URL line break. This\n * stays under one line; the panel names the exact asset to grab.\n */\nexport const CONTEXT_MILL_RELEASES_URL =\n 'https://github.com/PostHog/context-mill/releases/latest';\nexport const POSTHOG_DOCS_URL = 'https://posthog.com/docs';\nexport const POSTHOG_WIZARD_REPO_URL = 'https://github.com/PostHog/wizard';\nexport const POSTHOG_TERMS_URL = 'https://posthog.com/terms';\nexport const POSTHOG_PRIVACY_URL = 'https://posthog.com/privacy';\nexport const POSTHOG_ORG_AI_SETTINGS_URL =\n 'https://app.posthog.com/settings/organization-details#setting=organization-ai-consent';\nexport const WIZARD_CONTACT_EMAIL = 'wizard@posthog.com';\n\n/**\n * Two origins for the same release, same filenames. Interchangeable bases, so\n * making AWS primary is a `getSkillsBaseUrl` change, not a code change.\n */\nexport const GITHUB_SKILLS_BASE_URL =\n 'https://github.com/PostHog/context-mill/releases/latest/download';\nexport const AWS_SKILLS_BASE_URL = 'https://context-mill.posthog.com/latest';\n/** Alias of `@shared/local-dev`'s constant, kept for existing importers. */\nexport const LOCAL_SKILLS_BASE_URL = CONTEXT_MILL_LOCAL_URL;\n\n/**\n * Driven by `--local-context-mill`, NOT `--local-mcp` (which used to select\n * both). Takes no argument on purpose: callers can't pass the wrong flag.\n */\nexport function getSkillsBaseUrl(): string {\n return getLocalDev().localContextMill\n ? LOCAL_SKILLS_BASE_URL\n : GITHUB_SKILLS_BASE_URL;\n}\n\n// ── Analytics (internal) ──────────────────────────────────────────────\n\nexport const ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = 'sTMFPsFhdP1Ssg';\nexport const ANALYTICS_HOST_URL = 'https://internal-j.posthog.com';\nexport const ANALYTICS_TEAM_TAG = 'docs-and-wizard';\n\n// ── OAuth / Auth ────────────────────────────────────────────────────\n\nexport const OAUTH_PORTS = [8239, 8238, 8240, 8237, 8236, 8235] as const;\nexport const POSTHOG_US_CLIENT_ID = 'c4Rdw8DIxgtQfA80IiSnGKlNX8QN00cFWF00QQhM';\nexport const POSTHOG_EU_CLIENT_ID = 'bx2C5sZRN03TkdjraCcetvQFPGH6N2Y9vRLkcKEy';\nexport const POSTHOG_DEV_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ';\nexport const POSTHOG_PROXY_CLIENT_ID = POSTHOG_US_CLIENT_ID;\nexport const DUMMY_PROJECT_API_KEY = '_YOUR_POSTHOG_PROJECT_TOKEN_';\n\n/**\n * Scopes the wizard requests during the agentic provisioning signup flow.\n *\n * Each entry is justified by what the wizard's agent step does after signup:\n * - user:read identify the user for analytics + agent context\n * - project:read look up the freshly-provisioned project\n * - llm_gateway:read authenticate to gateway.{us,eu}.posthog.com/wizard\n * (the agent's LLM calls — without this scope, every\n * agent message returns 401)\n * - query:read run HogQL queries when the agent needs data\n * - dashboard:write create the onboarding dashboard during setup\n * - insight:write create the onboarding insights during setup\n * - notebook:write upload the events-audit report as a PostHog notebook\n * in step 6 of the events-audit skill (notebooks-create\n * MCP tool requires this scope)\n * - event_definition:write\n * create event definitions from the completed wizard\n * session's event plan\n *\n * Must be a subset of `ALLOWED_PROVISIONING_SCOPES` in\n * `ee/api/agentic_provisioning/views.py` on the backend.\n */\nexport const WIZARD_PROVISIONING_SCOPES = [\n 'user:read',\n 'project:read',\n 'llm_gateway:read',\n 'dashboard:write',\n 'insight:write',\n 'query:read',\n 'notebook:write',\n 'event_definition:write',\n] as const;\n\n/**\n * Scopes the wizard requests during the OAuth login flow. Superset of\n * `WIZARD_PROVISIONING_SCOPES` with scopes that only apply to the login\n * path and are not in the provisioning allowlist:\n * - health_issue:read used by `wizard doctor`\n * - wizard_session:read list / retrieve / stream sessions\n * - wizard_session:write stream run state to /api/projects/{id}/wizard/sessions/\n * - event_definition:write\n * create event definitions when a session completes\n * - organization:read read `organization.is_ai_data_processing_approved`\n * from /api/users/@me/ for the AI opt-in gate\n *\n * NOTE: every scope here must be within the wizard OAuth application's\n * server-side scope ceiling (`OAuthApplication.scopes` in posthog, set\n * via Django admin on BOTH prod regions). A scope outside the ceiling\n * does NOT fail the authorize request — the server silently clamps the\n * request to the ceiling (`clamp_scopes_to_ceiling` in posthog) and the\n * token comes back without it. Separately, the consent screen lets the\n * user deselect any scope the app doesn't mark required. Both paths\n * yield a granted `scope` narrower than requested, with no error, so\n * never assume the token carries this list — the token response's\n * `scope` field is the truth, and `missingOAuthScopes` (utils/oauth.ts)\n * diffs it at login. Ceiling procedure: the \"scope-ceiling-invalid-scope\"\n * runbook in PostHog/runbooks. Keep its worked example in sync when this\n * list changes.\n */\nexport const WIZARD_OAUTH_SCOPES = [\n ...WIZARD_PROVISIONING_SCOPES,\n 'health_issue:read',\n 'wizard_session:read',\n 'wizard_session:write',\n 'wizard_run:write',\n 'organization:read',\n] as const;\n\n// ── Wizard run / variants ───────────────────────────────────────────\n\nexport const WIZARD_INTERACTION_EVENT_NAME = 'wizard interaction';\nexport const WIZARD_REMARK_EVENT_NAME = 'wizard remark';\n/** Multivariate flag: `wizard-run` publishes to WizardRun, anything else to WizardSession. */\nexport const WIZARD_RUN_SYNC_FLAG_KEY = 'wizard-run-sync';\n/** Boolean feature flag that routes a run to the experimental orchestrator runner. */\nexport const WIZARD_ORCHESTRATOR_FLAG_KEY = 'wizard-orchestrator';\n/** Multivariate flag: per-stage orchestrator overrides ride each variant's JSON payload (`{stage: {model?, effort?}}`). */\nexport const WIZARD_ORCHESTRATOR_OVERRIDE_FLAG_KEY =\n 'wizard-orchestrator-override';\n/** Boolean flag: on → pi for self-driving. Payload carries `{model, effort?, harness?, sequence?}` (model = a `MODEL_FLAG_VARIANTS` key); missing/invalid payload keeps the non-flagged default. */\nexport const WIZARD_SELF_DRIVING_USE_PI_HARNESS_FLAG_KEY =\n 'wizard-self-driving-use-pi-harness';\n/** Boolean flag: agentic project scoping for non-interactive basic-integration runs. */\nexport const WIZARD_BASIC_INTEGRATION_AGENTIC_DETECTION_FLAG_KEY =\n 'wizard-basic-integration-agentic-detection';\n/** Boolean flag: the orchestrator queues the program's runner-seeded tasks (the warehouse step). Off, no task is queued and the run is byte-identical to a no-sources project. */\nexport const WIZARD_ORCHESTRATOR_SEEDED_TASKS_FLAG_KEY =\n 'wizard-orchestrator-seeded-tasks';\n/** Kill switch over a shipped default: ONLY an explicit 'false' excludes the AI Observability and Logs tasks from default integration runs — absent or fetch-failed means include, so the default never vanishes on a network hiccup. */\nexport const WIZARD_DEFAULT_AIO_LOGS_FLAG_KEY = 'wizard-default-aio-logs';\n// Reading a flag enters this run into that flag's experiment, so a closed set — not a\n// `wizard-` prefix anyone can name into — decides what a run evaluates. Test-pinned exhaustive.\nexport const WIZARD_FLAG_KEYS = [\n WIZARD_RUN_SYNC_FLAG_KEY,\n WIZARD_ORCHESTRATOR_FLAG_KEY,\n WIZARD_ORCHESTRATOR_OVERRIDE_FLAG_KEY,\n WIZARD_ORCHESTRATOR_SEEDED_TASKS_FLAG_KEY,\n WIZARD_SELF_DRIVING_USE_PI_HARNESS_FLAG_KEY,\n WIZARD_BASIC_INTEGRATION_AGENTIC_DETECTION_FLAG_KEY,\n WIZARD_DEFAULT_AIO_LOGS_FLAG_KEY,\n] as const;\n/** User-Agent for wizard HTTP requests and MCP server identification. */\nexport const WIZARD_USER_AGENT = `posthog/wizard; version: ${VERSION}`;\n\n/**\n * User-Agent for a specific program's MCP calls, tagged with `program: <id>` so the\n * backend can attribute work per program (e.g. the `self-driving` program's warehouse\n * sources are recorded as `created_via=self_driving` rather than plain `wizard`). The\n * base `posthog/wizard` token is preserved, so anything keying only on that still matches.\n */\nexport function wizardUserAgentForProgram(programId?: string): string {\n return programId\n ? `${WIZARD_USER_AGENT}; program: ${programId}`\n : WIZARD_USER_AGENT;\n}\n\n// ── Timeouts ─────────────────────────────────────────────────────────\n\n/** Timeout for framework / project detection probes (ms). */\nexport const DETECTION_TIMEOUT_MS = 10_000;\n\n/** Timeout for the agentic project scan (ms); past it the run falls back to root detection. */\nexport const AGENTIC_DETECTION_FIRST_ATTEMPT_TIMEOUT_MS = 60_000;\nexport const AGENTIC_DETECTION_RETRY_TIMEOUT_MS = 90_000;\n\n/**\n * Timeout for the OAuth authorization flow (ms).\n *\n * How long the user has to complete the browser login. The authorization\n * code is minted at approval and exchanged immediately on callback, so the\n * server-side code expiry (`AUTHORIZATION_CODE_EXPIRE_SECONDS`, 5 minutes)\n * bounds only the approval→exchange gap — manual-paste users have 5 minutes\n * from approval to submit the code — not how long this window may stay open.\n */\nexport const OAUTH_TIMEOUT_MS = 1_800_000;\n","/** Run lifecycle and consent states the TUI, the CLI and programs share. */\n\nimport type { DiscoveredFeature } from './discovered-feature';\n\n/** How an agent run ended: the agent decides it, and the programs and hosts read it. */\nexport enum RunOutcome {\n Success = 'success',\n Aborted = 'aborted',\n Failed = 'failed',\n Crashed = 'crashed',\n}\n\n/** Lifecycle phase of the main work (agent run, MCP install, etc.) */\nexport enum RunPhase {\n /** Still gathering input (intro, setup screens) */\n Idle = 'idle',\n /** Main work is in progress */\n Running = 'running',\n /** Main work finished successfully */\n Completed = 'completed',\n /** Main work finished with an error */\n Error = 'error',\n}\n\n/** Consent to report what local detection found (see `scanConsent` below). */\nexport enum ScanConsent {\n Undecided = 'undecided',\n Granted = 'granted',\n Declined = 'declined',\n}\n\n/** Outcome of the MCP server installation step */\nexport enum McpOutcome {\n NoClients = 'no_clients',\n Skipped = 'skipped',\n Installed = 'installed',\n Failed = 'failed',\n}\n\n/** One place to ask, so a new consent state does not need three edits. */\nexport function mayReportScanResults(session: {\n scanConsent: ScanConsent;\n}): boolean {\n return session.scanConsent === ScanConsent.Granted;\n}\n\n/** Lives here so analytics infrastructure never learns what consent means. */\nexport function reportableDiscoveredFeatures(session: {\n scanConsent: ScanConsent;\n discoveredFeatures: DiscoveredFeature[];\n}): DiscoveredFeature[] | undefined {\n return mayReportScanResults(session) ? session.discoveredFeatures : undefined;\n}\n\n/** Also a scan result, so it travels under the same consent as the rest. */\nexport function reportablePosthogSdkDetected(session: {\n scanConsent: ScanConsent;\n posthogSdkDetected: boolean;\n}): boolean | undefined {\n return mayReportScanResults(session) ? session.posthogSdkDetected : undefined;\n}\n","/**\n * CI-only feature-flag overrides.\n *\n * CI must route deterministically: a run that tests the orchestrator arm says\n * so explicitly instead of depending on a live feature flag someone can edit\n * mid-week. The override env var (see the allowlist in `env.ts`) is a JSON\n * object of flag key → value, merged over whatever PostHog returned.\n *\n * The override path exists only in CI builds (`pnpm build:ci`). Published\n * builds inline NODE_ENV as the literal \"production\", the guards collapse,\n * and tsdown strips the rest from the bundle — and the smoke test asserts the\n * env var names are physically absent from production output (which is also\n * why no comment in this file may spell them out), so this can never quietly\n * become a production surface.\n */\nimport { runtimeEnv } from '@env';\nimport { logToFile } from './debug';\n\nexport function applyCiFlagOverrides(\n flags: Record<string, string>,\n payloads: Record<string, unknown> = {},\n): { flags: Record<string, string>; payloads: Record<string, unknown> } {\n // Compared inline (not via env.ts's IS_PRODUCTION_BUILD) so tsdown replaces\n // it with a literal right here and the bundler can prove the rest of this\n // function unreachable in production builds. The smoke test enforces that.\n if (process.env.NODE_ENV === 'production') return { flags, payloads };\n\n const raw = runtimeEnv('WIZARD_CI_FLAG_OVERRIDES');\n if (!raw) return { flags, payloads };\n\n let overrides: Record<string, unknown>;\n try {\n overrides = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n // A malformed override is a CI misconfiguration. Fail the run loudly\n // rather than silently testing whatever the live flags happen to say.\n throw new Error(\n 'The CI flag-override env var is not valid JSON (expected {\"flag-key\": value, ...}).',\n );\n }\n\n const mergedFlags = { ...flags };\n const mergedPayloads = { ...payloads };\n for (const [key, value] of Object.entries(overrides)) {\n // An object/array override is a flag payload: the flag reads 'true' and\n // the value rides the payload channel, matching a payload-carrying flag.\n if (typeof value === 'object' && value !== null) {\n mergedFlags[key] = 'true';\n mergedPayloads[key] = value;\n } else {\n mergedFlags[key] = String(value);\n }\n }\n logToFile('[flags] CI overrides applied', overrides);\n return { flags: mergedFlags, payloads: mergedPayloads };\n}\n\n/**\n * Task types excluded from this run. The exclusion env var (see the allowlist\n * in `env.ts`) is a comma-separated list (e.g. `dashboard`), set by the CI\n * harness that owns the policy — the wizard and the served content stay\n * run-mode agnostic. CI-build only, same as the flag overrides: published\n * builds strip this path.\n */\nexport function ciExcludedTaskTypes(): readonly string[] {\n if (process.env.NODE_ENV === 'production') return [];\n\n const raw = runtimeEnv('WIZARD_CI_EXCLUDE_TASKS');\n if (!raw) return [];\n const types = raw\n .split(',')\n .map((t) => t.trim())\n .filter(Boolean);\n if (types.length > 0) logToFile('[flags] CI task exclusions', types);\n return types;\n}\n","import { PostHog } from 'posthog-node';\nimport {\n ANALYTICS_HOST_URL,\n ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY,\n ANALYTICS_TEAM_TAG,\n WIZARD_FLAG_KEYS,\n} from '@shared/constants';\nimport {\n reportableDiscoveredFeatures,\n reportablePosthogSdkDetected,\n type RunPhase,\n type ScanConsent,\n} from '@shared/run-state';\nimport type { DiscoveredFeature } from '@shared/discovered-feature';\nimport type { Integration } from '@shared/constants';\nimport type { ApiUser } from '@shared/api';\nimport { v4 as uuidv4 } from 'uuid';\nimport { IS_PRODUCTION_BUILD, RUN_SURFACE, TASK_ID, TASK_RUN_ID } from '@env';\nimport { VERSION } from '@shared/version';\nimport { logToFile } from './debug';\nimport { applyCiFlagOverrides } from './ci-flag-overrides';\n\n/**\n * The invocation, reduced to flag-safe strings: the command word (first\n * positional, 'default' for the bare flow) and the sorted option NAMES.\n * Option values never leave the machine — they carry paths, emails, keys.\n */\nfunction invocationProperties(): { command: string; cli_flags: string } {\n const args = process.argv.slice(2);\n const command = args.find((a) => !a.startsWith('-')) ?? 'default';\n const flags = [\n ...new Set(\n args\n .filter((a) => a.startsWith('--'))\n .map((a) => a.slice(2).split('=')[0]),\n ),\n ].sort();\n return { command, cli_flags: flags.join(',') };\n}\n\n/** The session facts analytics reports on every capture. */\nexport type SessionFacts = {\n integration: Integration | null;\n skillId: string | null;\n detectedFrameworkLabel: string | null;\n typescript: boolean;\n credentials: { projectId: number } | null;\n discoveredFeatures: DiscoveredFeature[];\n scanConsent: ScanConsent;\n runPhase: RunPhase;\n posthogSdkDetected: boolean;\n};\n\n/**\n * Extract a standard property bag from the current session.\n * Used by store-level analytics and available for ad-hoc captures.\n */\nexport function sessionProperties(\n session: SessionFacts,\n): Record<string, unknown> {\n // reportableDiscoveredFeatures() owns the consent decision; this file\n // never needs to know what `scanConsent` means, only that the result\n // might be absent. An absent key is unambiguous, while an empty array\n // would read as \"we looked and found nothing\" instead of \"not reported\".\n const discoveredFeatures = reportableDiscoveredFeatures(session);\n const posthogSdkDetected = reportablePosthogSdkDetected(session);\n\n return {\n integration: session.integration,\n // Discriminates a family leaf: `command` is the first positional, so every\n // `wizard audit <leaf>` reports the same `audit`.\n skill_id: session.skillId,\n detected_framework: session.detectedFrameworkLabel,\n typescript: session.typescript,\n project_id: session.credentials?.projectId,\n ...(discoveredFeatures !== undefined\n ? { discovered_features: discoveredFeatures }\n : {}),\n scan_consent: session.scanConsent,\n run_phase: session.runPhase,\n ...(posthogSdkDetected !== undefined\n ? { posthog_sdk_detected: posthogSdkDetected }\n : {}),\n };\n}\n\nexport function groupsFromUser(\n user: ApiUser | null,\n host: string,\n): Record<string, string> {\n const groups: Record<string, string> = { instance: host };\n if (!user) return groups;\n\n const organizationId = user.organization?.id;\n if (organizationId) groups.organization = organizationId;\n\n const customerId = user.organization?.customer_id;\n if (customerId) groups.customer = customerId;\n\n const projectUuid = user.team?.uuid;\n if (projectUuid) groups.project = projectUuid;\n\n return groups;\n}\n\nconst WIZARD_FLAGS: ReadonlySet<string> = new Set(WIZARD_FLAG_KEYS);\n\n// Widen back to the SDK's shape — a filter on `true` never matches `'true'`.\nfunction flagResponseValue(value: string): string | boolean {\n if (value === 'true') return true;\n if (value === 'false') return false;\n return value;\n}\n\nexport class Analytics {\n private client: PostHog;\n private tags: Record<string, string | boolean | number | null | undefined> =\n {};\n private distinctId?: string;\n private anonymousId: string;\n private _runId: string;\n private sessionId: string | null = null;\n private appName = 'wizard';\n private activeFlags: Record<string, string> | null = null;\n private activeFlagPayloads: Record<string, unknown> = {};\n private groups: Record<string, string> = {};\n private personProperties: Record<string, string> = {};\n private terminalEventSent = false;\n\n constructor() {\n this.client = new PostHog(ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY, {\n host: ANALYTICS_HOST_URL,\n flushAt: 1,\n flushInterval: 0,\n enableExceptionAutocapture: true,\n before_send: (event) => {\n if (!event) return event;\n if (Object.keys(this.groups).length > 0) {\n event.groups = { ...this.groups, ...event.groups };\n }\n // Autocaptured exceptions arrive with a random uuid and\n // `$process_person_profile: false` — reattach the run's identity\n // and tags so they land on the same person as everything else.\n if (event.event === '$exception') {\n event.distinctId = this.distinctId ?? this.anonymousId;\n const { $process_person_profile, ...properties } =\n event.properties ?? {};\n void $process_person_profile;\n event.properties = { ...this.tags, ...properties };\n }\n // The SDK captures this one itself, bypassing capture(), so tags merge here.\n if (event.event === '$feature_flag_called') {\n event.properties = { ...this.tags, ...(event.properties ?? {}) };\n }\n return event;\n },\n });\n\n this.tags = { $app_name: this.appName };\n // Tag every run with its build type so prod / dev / ci / headless segment\n // cleanly in analytics. tsdown inlines IS_PRODUCTION_BUILD to `true` in\n // published builds and `false` for dev/tsx/test runs. Non-interactive runs\n // upgrade this in runWizardCI: dev `--ci` runs to 'ci', published headless\n // runs to 'headless'.\n this.tags.build = IS_PRODUCTION_BUILD ? 'prod' : 'dev';\n\n this.tags.run_surface = RUN_SURFACE;\n\n // The build this run came from. Already sent as a flag-evaluation person\n // property; tagging it makes every event attributable to a release, so a\n // regression can be bounded to the versions that carry it.\n this.tags.version = VERSION;\n\n // Cloud runs only: the task run that owns the sandbox. Without these the\n // wizard's events and the run that launched it are two unrelated streams,\n // since run_id above is minted per process and never leaves the wizard.\n // Left unset for local runs so the properties stay absent rather than null.\n if (TASK_RUN_ID) this.tags.task_run_id = TASK_RUN_ID;\n if (TASK_ID) this.tags.task_id = TASK_ID;\n\n this.anonymousId = uuidv4();\n\n // One id per process = one id per wizard run, registered in the tag bag\n // so it rides on every capture, exception, and autocaptured exception\n // (all of which merge `this.tags`). Lets you separate two runs by the\n // same logged-in user, who otherwise share one distinct id. Distinct\n // from `anonymousId`, the pre-login *person* id that gets aliased onto\n // the real user at login. `$session_id` is intentionally not set here —\n // it stays null until OAuth completes (see identifyUser).\n this._runId = uuidv4();\n this.tags.run_id = this._runId;\n\n this.distinctId = undefined;\n }\n\n /** Per-process run id, tagged on every event and gateway trace. */\n get runId(): string {\n return this._runId;\n }\n\n /** Build type for this run ('prod' | 'dev' | 'ci' | 'headless') — the same value tagged on every analytics event. */\n get build(): string {\n return String(this.tags.build ?? 'dev');\n }\n\n /**\n * Associate the run with the logged-in user, once per id. Identifies them\n * (email, name) and records those person properties so events carry them and\n * feature flags can target the individual user — without the email here the\n * wizard only sends `$app_name`, so email-targeted flags never match. Opens\n * the analytics session on first login, then aliases the run's anonymous id\n * onto the identified person so pre-login events merge in.\n */\n identifyUser(user: ApiUser) {\n const distinctId = user.distinct_id;\n if (this.distinctId === distinctId || distinctId === this.anonymousId) {\n return;\n }\n this.distinctId = distinctId;\n // Open the analytics session on first login. Null until here, so\n // pre-OAuth events carry only `run_id`; from now on every event also\n // carries `$session_id` and PostHog groups the authenticated run into a\n // native Session. Stored in the tag bag so it rides on every subsequent\n // capture and exception.\n if (!this.sessionId) {\n this.sessionId = uuidv4();\n this.tags.$session_id = this.sessionId;\n }\n const props: Record<string, string> = {};\n if (user.email) props.email = user.email;\n const name = [user.first_name, user.last_name]\n .filter(Boolean)\n .join(' ')\n .trim();\n if (name) props.name = name;\n this.personProperties = props;\n this.client.identify({ distinctId, properties: { $set: props } });\n this.client.alias({\n distinctId,\n alias: this.anonymousId,\n });\n // The flag snapshot is per identity. Anything evaluated before login (the\n // intro screen reads the tools-menu flag) was anonymous — drop it so the\n // next read re-evaluates as this user.\n this.activeFlags = null;\n this.activeFlagPayloads = {};\n }\n\n /** Person properties sent with flag evaluation: app name plus the user's. */\n private flagPersonProperties(): Record<string, string> {\n // Environment facts flag conditions can scope on — evaluation-time only,\n // never persisted onto the person. `version` gates an experiment to\n // releases that implement it (a condition on a property older builds\n // don't send silently never matches them); `run_surface`/`build` scope\n // by invocation surface; `command`/`cli_flags` by subcommand; `os`/\n // `node_major` by platform.\n return {\n $app_name: this.appName,\n version: VERSION,\n run_surface: RUN_SURFACE,\n build: String(this.tags.build ?? 'dev'),\n os: process.platform,\n node_major: process.versions.node.split('.')[0],\n ...invocationProperties(),\n ...this.personProperties,\n };\n }\n\n setTag(key: string, value: string | boolean | number | null | undefined) {\n this.tags[key] = value;\n }\n\n setGroups(groups: Record<string, string>) {\n this.groups = groups;\n }\n\n captureException(error: Error, properties: Record<string, unknown> = {}) {\n this.client.captureException(error, this.distinctId ?? this.anonymousId, {\n team: ANALYTICS_TEAM_TAG,\n ...this.tags,\n ...properties,\n });\n }\n\n capture(eventName: string, properties?: Record<string, unknown>) {\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: eventName,\n properties: {\n ...this.tags,\n ...this.wizardFlagFeatureProperties(),\n ...properties,\n },\n });\n }\n\n groupIdentify(\n groupType: string,\n groupKey: string,\n properties: Record<string, unknown>,\n ) {\n this.client.groupIdentify({ groupType, groupKey, properties });\n }\n\n // Built from the resolved map, not the SDK snapshot: a CI-forced variant must own its events.\n private wizardFlagFeatureProperties(): Record<string, unknown> {\n if (this.activeFlags === null) return {};\n const props: Record<string, unknown> = {};\n const active: string[] = [];\n for (const [key, value] of Object.entries(this.activeFlags)) {\n if (!WIZARD_FLAGS.has(key)) continue;\n const resolved = flagResponseValue(value);\n props[`$feature/${key}`] = resolved;\n if (resolved !== false) active.push(key);\n }\n if (active.length > 0) props.$active_feature_flags = active.sort();\n return props;\n }\n\n /**\n * Capture a wizard-specific event. Automatically prepends \"wizard: \" to the event name.\n * All new wizard analytics should use this method instead of capture() directly.\n */\n wizardCapture(eventName: string, properties?: Record<string, unknown>): void {\n this.capture(`wizard: ${eventName}`, properties);\n }\n\n /**\n * Flush pending events without firing the \"setup wizard finished\" terminal\n * event. Use this from CLI error paths that exit before any wizard run\n * starts — `shutdown()` would inflate the run count with a \"finished\" event\n * for a parse error that never actually ran the wizard.\n */\n async flush(): Promise<void> {\n await this.client.shutdown();\n }\n\n /**\n * Evaluate all feature flags for the current user at the start of a run.\n * Result is cached; subsequent calls in the same run return the same map.\n * Returns flag key -> string value (booleans become 'true'/'false').\n */\n // Only a getFlag read records an exposure; the bulk response records none.\n async getAllFlagsForWizard(): Promise<Record<string, string>> {\n if (this.activeFlags !== null) {\n return this.activeFlags;\n }\n const out: Record<string, string> = {};\n const payloads: Record<string, unknown> = {};\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n logToFile('[flags] evaluating as', {\n distinctId,\n identified: this.distinctId !== undefined,\n personProperties: this.flagPersonProperties(),\n });\n const evaluation = await this.client.evaluateFlags(distinctId, {\n personProperties: this.flagPersonProperties(),\n });\n for (const key of WIZARD_FLAG_KEYS) {\n const value = evaluation.getFlag(key);\n if (value === undefined) continue;\n out[key] = String(value);\n const payload = evaluation.getFlagPayload(key);\n if (payload !== undefined) payloads[key] = payload;\n }\n } catch (error) {\n logToFile('Failed to get all feature flags:', error);\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'get_all_flags' },\n );\n }\n // Outside the fetch guard on purpose: a malformed CI override must fail\n // the run loudly, and a valid one applies even when the fetch failed —\n // CI routing stays deterministic either way.\n const merged = applyCiFlagOverrides(out, payloads);\n this.activeFlags = merged.flags;\n this.activeFlagPayloads = merged.payloads;\n logToFile('[flags] evaluated', this.activeFlags);\n return this.activeFlags;\n }\n\n getCachedWizardFlags(): Readonly<Record<string, string>> | null {\n return this.activeFlags;\n }\n\n /** Flag payloads from the same snapshot; empty until the flags are fetched. */\n getWizardFlagPayloads(): Record<string, unknown> {\n return this.activeFlagPayloads;\n }\n\n async shutdown(status: 'success' | 'error' | 'cancelled') {\n if (Object.keys(this.tags).length === 0) {\n return;\n }\n\n // First status wins. The interrupt fallback in start-tui fires\n // shutdown('cancelled') on every TUI teardown; without this guard a run\n // that already reported 'success' would emit a second, contradicting\n // terminal event when the user dismisses the outro.\n if (this.terminalEventSent) {\n return;\n }\n this.terminalEventSent = true;\n\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: 'setup wizard finished',\n properties: {\n // Flat for filtering; the nested `tags` snapshot stays for back-compat.\n ...this.tags,\n run_id: this._runId,\n ...(this.sessionId ? { $session_id: this.sessionId } : {}),\n status,\n tags: this.tags,\n },\n });\n\n await this.client.shutdown();\n }\n}\n\nexport const analytics = new Analytics();\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAa,yBAAyB;AACtC,MAAa,gBAAgB;;AAE7B,MAAa,oBAAoB;;;;;;AAwBjC,SAAgB,gBAAgB,OAAwC;CACtE,MAAM,WAAW,MAAM,Y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KAAK;IACb,GAAI,KAAK,YAAY,EAAE,aAAa,KAAK,WAAW,GAAG,EAAE;IACzD;IACA,MAAM,KAAK;IACZ;GACF,CAAC;AAEF,QAAM,KAAK,OAAO,UAAU;;;AAIhC,MAAa,YAAY,IAAI,WAAW"}
@@ -1,2 +0,0 @@
1
- import { n as ApiError } from "./api-DtGIqQ2U.js";
2
- export { ApiError };
@@ -1,2 +0,0 @@
1
- import { t as resolveApiKeyProject } from "./api-key-login-h3E2G3zu.js";
2
- export { resolveApiKeyProject };
@@ -1 +0,0 @@
1
- {"version":3,"file":"install-paPCzPHI.js","names":["fs","path","path","os","PLUGIN_MARKETPLACE","PLUGIN_MARKETPLACE_SOURCE","PLUGIN_REF","RUN_TIMEOUT_MS","MAX_OUTPUT_BYTES","path","os","fs","execSync","z","os","path","z","os","path","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 redactSecrets,\n scrubHomePaths,\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 { analytics } from '@utils/analytics';\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/** 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 analytics.captureException(\n new Error(`Claude Code MCP add failed: ${msg}`),\n );\n return Promise.resolve({ success: false, reason: msg });\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 analytics.captureException(\n new Error(`Claude Code plugin uninstall failed: ${reason}`),\n );\n return { success: false, reason };\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 analytics.captureException(\n new Error(`Failed to remove server from Claude Code: ${reason}`),\n );\n return Promise.resolve({ success: false, reason });\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 without the marketplace-add failure beside it the new root\n // cause is indistinguishable from the old one in error tracking.\n const failure = new Error(`Claude Code plugin install failed: ${msg}`);\n if (marketplaceFailure) {\n analytics.captureException(failure, { marketplaceFailure });\n } else {\n analytics.captureException(failure);\n }\n return { success: false, reason: msg };\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 expectedFailureHint,\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\n/**\n * Turn a failed spawn into a result: an expected local failure becomes a hint,\n * anything else is reported under a constant message so one root cause stays\n * one issue, with the varying detail in properties.\n */\nconst reportSpawnFailure = (\n stage: CodexStage,\n details: string,\n): InstallResult => {\n const hint = expectedFailureHint(details, EXPECTED_FAILURES, stage);\n if (hint) {\n // Hinting takes a failure out of error tracking, so without this the only\n // evidence a pattern has started over-matching is that our exception count\n // fell, which reads as the fix working. An event keeps the count.\n analytics.wizardCapture('mcp expected failure hinted', {\n client: 'Codex',\n stage,\n hint,\n details: scrubHomePaths(details),\n });\n return { success: false, reason: hint };\n }\n analytics.captureException(new Error(`Codex ${stage} failed`), {\n stage,\n details: scrubHomePaths(details),\n });\n return { success: false, reason: details };\n};\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 Error ? err.message : String(err),\n }),\n );\n }\n }\n return results;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAQA,IAAsB,YAAtB,MAAgC;CAC9B;;AAaF,IAAsB,mBAAtB,cAA+C,UAAU;CACvD,OAAO;CAEP,cAAc;AACZ,SAAO;;CAGT,wBAAgC;AAC9B,SAAO;;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