@posthog/wizard 2.21.0 → 2.22.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 (65) hide show
  1. package/README.md +14 -1
  2. package/dist/{OutroScreen-CqF6SdBo.js → AiOptInRequiredScreen-B8mgZbe5.js} +482 -59
  3. package/dist/AiOptInRequiredScreen-B8mgZbe5.js.map +1 -0
  4. package/dist/{add-mcp-server-to-clients-DQHGhzt6.js → add-mcp-server-to-clients-lCxOS1A1.js} +12 -10
  5. package/dist/add-mcp-server-to-clients-lCxOS1A1.js.map +1 -0
  6. package/dist/{agent-interface-DE7txTqh.js → agent-interface-BPCzPvK-.js} +6 -5
  7. package/dist/{agent-interface-DE7txTqh.js.map → agent-interface-BPCzPvK-.js.map} +1 -1
  8. package/dist/{agent-runner-DUZ5OD6e.js → agent-runner-DgzF2mga.js} +13 -9
  9. package/dist/{agent-runner-DUZ5OD6e.js.map → agent-runner-DgzF2mga.js.map} +1 -1
  10. package/dist/{analytics-Bl5DPj_0.js → analytics-BZv-cKyn.js} +28 -4
  11. package/dist/analytics-BZv-cKyn.js.map +1 -0
  12. package/dist/{api-DuA0_88V.js → api-BkLZ8BWm.js} +3 -3
  13. package/dist/{api-DuA0_88V.js.map → api-BkLZ8BWm.js.map} +1 -1
  14. package/dist/bin.js +160 -49
  15. package/dist/bin.js.map +1 -1
  16. package/dist/{ci-install-BnOYI4mZ.js → ci-install-DBARq5LX.js} +4 -4
  17. package/dist/{ci-install-BnOYI4mZ.js.map → ci-install-DBARq5LX.js.map} +1 -1
  18. package/dist/{debug-h7Z9zEbD.js → debug-Ckumcrye.js} +189 -40
  19. package/dist/debug-Ckumcrye.js.map +1 -0
  20. package/dist/{debug-BVC48wlb.js → debug-DLsuyfln.js} +1 -1
  21. package/dist/{environment-uaLmtlH_.js → environment-DUh_8hqW.js} +3 -3
  22. package/dist/{environment-uaLmtlH_.js.map → environment-DUh_8hqW.js.map} +1 -1
  23. package/dist/{interactive-CW5gjyDd.js → interactive-DeiHgviS.js} +2 -2
  24. package/dist/{interactive-CW5gjyDd.js.map → interactive-DeiHgviS.js.map} +1 -1
  25. package/dist/{mcp-prompt-streaming-DMDwaark.js → mcp-prompt-streaming-kEJgmB30.js} +4 -4
  26. package/dist/{mcp-prompt-streaming-DMDwaark.js.map → mcp-prompt-streaming-kEJgmB30.js.map} +1 -1
  27. package/dist/{non-interactive-DJrVQ4nS.js → non-interactive-I4ifOSau.js} +2 -2
  28. package/dist/{non-interactive-DJrVQ4nS.js.map → non-interactive-I4ifOSau.js.map} +1 -1
  29. package/dist/{package-manager-DCUBRbr-.js → package-manager-fUeLORHg.js} +2 -2
  30. package/dist/{package-manager-DCUBRbr-.js.map → package-manager-fUeLORHg.js.map} +1 -1
  31. package/dist/{playground-DCVaVeVD.js → playground-DLLIz4Ql.js} +135 -19
  32. package/dist/playground-DLLIz4Ql.js.map +1 -0
  33. package/dist/{posthog-integration-ChdwFPMj.js → posthog-integration-COcPewVt.js} +48 -16
  34. package/dist/posthog-integration-COcPewVt.js.map +1 -0
  35. package/dist/{provisioning-GeMkBMSR.js → provisioning-7xU12_S9.js} +3 -3
  36. package/dist/{provisioning-GeMkBMSR.js.map → provisioning-7xU12_S9.js.map} +1 -1
  37. package/dist/{registry-VSSRH3sU.js → registry-YwaF-aD8.js} +7 -20
  38. package/dist/registry-YwaF-aD8.js.map +1 -0
  39. package/dist/{setup-utils-BfV4pydt.js → setup-utils-Cr4FxJDl.js} +114 -58
  40. package/dist/setup-utils-Cr4FxJDl.js.map +1 -0
  41. package/dist/{start-tui-BRvm5VP9.js → start-tui--E4PXdwG.js} +323 -134
  42. package/dist/start-tui--E4PXdwG.js.map +1 -0
  43. package/dist/{steps-DA4uvSbg.js → steps-CxUxdK4V.js} +6 -6
  44. package/dist/{steps-DA4uvSbg.js.map → steps-CxUxdK4V.js.map} +1 -1
  45. package/dist/telemetry-BS7yw3TP.js +68 -0
  46. package/dist/telemetry-BS7yw3TP.js.map +1 -0
  47. package/dist/{urls-B66Ib2jT.js → urls-BW23_XbC.js} +2 -2
  48. package/dist/{urls-B66Ib2jT.js.map → urls-BW23_XbC.js.map} +1 -1
  49. package/dist/{wizard-abort-gMB1eV6T.js → wizard-abort-BPsnXKY5.js} +1 -1
  50. package/dist/{wizard-abort-D1_DnFjm.js → wizard-abort-E66_R4S7.js} +3 -3
  51. package/dist/{wizard-abort-D1_DnFjm.js.map → wizard-abort-E66_R4S7.js.map} +1 -1
  52. package/dist/wizard-session-G3VWD6hv.js.map +1 -1
  53. package/dist/wizard-ui-YdGFRyu_.js.map +1 -1
  54. package/package.json +1 -1
  55. package/dist/OutroScreen-CqF6SdBo.js.map +0 -1
  56. package/dist/add-mcp-server-to-clients-DQHGhzt6.js.map +0 -1
  57. package/dist/analytics-Bl5DPj_0.js.map +0 -1
  58. package/dist/debug-h7Z9zEbD.js.map +0 -1
  59. package/dist/playground-DCVaVeVD.js.map +0 -1
  60. package/dist/posthog-integration-ChdwFPMj.js.map +0 -1
  61. package/dist/registry-VSSRH3sU.js.map +0 -1
  62. package/dist/setup-utils-BfV4pydt.js.map +0 -1
  63. package/dist/start-tui-BRvm5VP9.js.map +0 -1
  64. package/dist/telemetry-BRAonUea.js +0 -13
  65. package/dist/telemetry-BRAonUea.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"add-mcp-server-to-clients-DQHGhzt6.js","names":["fs","path","path","os","path","os","fs","execSync","z","os","path","z","os","path","path","fs"],"sources":["../src/steps/add-mcp-server-to-clients/MCPClient.ts","../src/steps/add-mcp-server-to-clients/clients/cursor.ts","../src/steps/add-mcp-server-to-clients/clients/claude-code.ts","../src/steps/add-mcp-server-to-clients/clients/claude-web.ts","../src/steps/add-mcp-server-to-clients/clients/visual-studio-code.ts","../src/steps/add-mcp-server-to-clients/clients/zed.ts","../src/steps/add-mcp-server-to-clients/clients/codex.ts","../src/steps/add-mcp-server-to-clients/plugin-client.ts","../src/steps/add-mcp-server-to-clients/index.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as jsonc from 'jsonc-parser';\nimport { getDefaultServerConfig } from './defaults';\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<{ success: boolean }>;\n abstract removeServer(local?: boolean): Promise<{ success: boolean }>;\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<{ success: boolean }> {\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 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 {\n return { success: false };\n }\n }\n\n async removeServer(local?: boolean): Promise<{ success: boolean }> {\n try {\n const configPath = await this.getConfigPath();\n\n if (!fs.existsSync(configPath)) {\n return { success: 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\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 } catch {\n //\n }\n\n return { success: false };\n }\n}\n","import {\n DefaultMCPClient,\n MCPServerConfig,\n} from '@steps/add-mcp-server-to-clients/MCPClient';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n DefaultMCPClientConfig,\n getNativeHTTPServerConfig,\n} from '@steps/add-mcp-server-to-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 '@steps/add-mcp-server-to-clients/MCPClient';\nimport {\n DefaultMCPClientConfig,\n buildMCPUrl,\n} from '@steps/add-mcp-server-to-clients/defaults';\nimport {\n PluginCapable,\n PluginInstallResult,\n} from '@steps/add-mcp-server-to-clients/plugin-client';\nimport { z } from 'zod';\nimport { execSync } from 'child_process';\nimport { analytics } from '@utils/analytics';\nimport { debug } 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\nexport class ClaudeCodeMCPClient\n extends DefaultMCPClient\n implements PluginCapable\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 debug(` 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 debug(' 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 debug(' Checking for Claude Code...');\n const claudeBinary = this.findClaudeBinary();\n\n if (!claudeBinary) {\n debug(' Claude Code not found. Installation paths checked:');\n debug(` - ${path.join(os.homedir(), '.claude', 'local', 'claude')}`);\n debug(` - /usr/local/bin/claude`);\n debug(` - /opt/homebrew/bin/claude`);\n debug(` - PATH`);\n return Promise.resolve(false);\n }\n\n const output = execSync(`${claudeBinary} --version`, { stdio: 'pipe' });\n const version = output.toString().trim();\n debug(` Claude Code detected: ${version}`);\n return Promise.resolve(true);\n } catch (error) {\n debug(\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 try {\n const output = execSync(`${binary} mcp list`, { stdio: 'pipe' })\n .toString()\n .toLowerCase();\n return Promise.resolve(output.includes(serverName));\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<{ success: boolean }> {\n const binary = this.findClaudeBinary();\n if (!binary) return Promise.resolve({ success: false });\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 const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('already exists')) {\n return Promise.resolve({ success: true });\n }\n analytics.captureException(\n new Error(`Claude Code MCP add failed: ${msg}`),\n );\n return Promise.resolve({ success: false });\n }\n }\n\n removeServer(local?: boolean): Promise<{ success: boolean }> {\n const claudeBinary = this.findClaudeBinary();\n if (!claudeBinary) {\n return Promise.resolve({ success: false });\n }\n\n const serverName = local ? 'posthog-local' : 'posthog';\n const command = `${claudeBinary} mcp remove --scope user ${serverName}`;\n\n try {\n execSync(command);\n } catch (error) {\n analytics.captureException(\n new Error(\n `Failed to remove server from Claude Code: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ),\n );\n return Promise.resolve({ success: false });\n }\n\n return Promise.resolve({ success: true });\n }\n\n supportsPlugin(): boolean {\n return this.findClaudeBinary() !== null;\n }\n\n isPluginInstalled(): Promise<boolean> {\n const binary = this.findClaudeBinary();\n if (!binary) return Promise.resolve(false);\n try {\n const output = execSync(`${binary} plugin list`, {\n stdio: 'pipe',\n }).toString();\n return Promise.resolve(output.toLowerCase().includes('posthog'));\n } catch {\n return Promise.resolve(false);\n }\n }\n\n installPlugin(): Promise<PluginInstallResult> {\n const binary = this.findClaudeBinary();\n if (!binary) return Promise.resolve({ success: false });\n try {\n execSync(`${binary} plugin install posthog`, { stdio: 'pipe' });\n return Promise.resolve({ success: true });\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes('already installed') || msg.includes('already exists')) {\n return Promise.resolve({ success: true, alreadyInstalled: true });\n }\n analytics.captureException(\n new Error(`Claude Code plugin install failed: ${msg}`),\n );\n return Promise.resolve({ success: false });\n }\n }\n}\n","import opn from 'opn';\nimport { MCPClient } from '@steps/add-mcp-server-to-clients/MCPClient';\nimport { BrowserFinishable } from '@steps/add-mcp-server-to-clients/browser-client';\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<{ success: boolean }> {\n void opn(this.connectorUrl, { wait: false }).catch(() => {\n // opn throws in environments without a browser (e.g. CI) — swallow it;\n // the URL is still surfaced to the user on the Done screen.\n });\n return Promise.resolve({ success: true });\n }\n\n removeServer(): Promise<{ success: boolean }> {\n return Promise.resolve({ success: false });\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 '@steps/add-mcp-server-to-clients/MCPClient';\nimport { getNativeHTTPServerConfig } from '@steps/add-mcp-server-to-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 '@steps/add-mcp-server-to-clients/MCPClient';\nimport { getNativeHTTPServerConfig } from '@steps/add-mcp-server-to-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, spawnSync } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nimport { DefaultMCPClient } from '@steps/add-mcp-server-to-clients/MCPClient';\nimport {\n DefaultMCPClientConfig,\n buildMCPUrl,\n} from '@steps/add-mcp-server-to-clients/defaults';\nimport {\n PluginCapable,\n PluginInstallResult,\n} from '@steps/add-mcp-server-to-clients/plugin-client';\n\nimport { analytics } from '@utils/analytics';\n\nexport const CodexMCPConfig = DefaultMCPClientConfig;\n\nexport type CodexMCPConfig = z.infer<typeof DefaultMCPClientConfig>;\n\nexport class CodexMCPClient extends DefaultMCPClient implements PluginCapable {\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 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 binary = this.findCodexBinary();\n if (!binary) return Promise.resolve(false);\n const serverName = local ? 'posthog-local' : 'posthog';\n const result = spawnSync(binary, ['mcp', 'list'], { encoding: 'utf-8' });\n if (result.status !== 0) return Promise.resolve(false);\n return Promise.resolve(\n (result.stdout ?? '').toLowerCase().includes(serverName),\n );\n }\n\n addServer(\n apiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n ): Promise<{ success: boolean }> {\n const binary = this.findCodexBinary();\n if (!binary) return Promise.resolve({ success: false });\n\n const serverName = local ? 'posthog-local' : 'posthog';\n const url = buildMCPUrl(selectedFeatures, local);\n const args = ['mcp', 'add', serverName, '--url', url];\n const env = { ...process.env };\n if (apiKey) {\n const tokenVar = 'POSTHOG_AUTH_HEADER';\n env[tokenVar] = `Bearer ${apiKey}`;\n args.push('--bearer-token-env-var', tokenVar);\n }\n\n const result = spawnSync(binary, args, { encoding: 'utf-8', env });\n if (result.status !== 0) {\n const stderr = result.stderr ?? '';\n if (stderr.toLowerCase().includes('already')) {\n return Promise.resolve({ success: true });\n }\n analytics.captureException(new Error(`Codex MCP add failed: ${stderr}`));\n return Promise.resolve({ success: false });\n }\n return Promise.resolve({ success: true });\n }\n\n removeServer(): Promise<{ success: boolean }> {\n const binary = this.findCodexBinary();\n if (!binary) return Promise.resolve({ success: false });\n\n const result = spawnSync(binary, ['mcp', 'remove', 'posthog'], {\n stdio: 'ignore',\n });\n\n if (result.error || result.status !== 0) {\n analytics.captureException(\n new Error('Failed to remove server from Codex CLI.'),\n );\n return Promise.resolve({ success: false });\n }\n\n return Promise.resolve({ success: true });\n }\n\n supportsPlugin(): boolean {\n return this.findCodexBinary() !== null;\n }\n\n isPluginInstalled(): Promise<boolean> {\n const configPath = path.join(os.homedir(), '.codex', 'config.toml');\n try {\n const contents = fs.readFileSync(configPath, 'utf-8');\n // Marketplace installs appear as [marketplaces.posthog] in config.toml\n return Promise.resolve(\n contents.toLowerCase().includes('[marketplaces.posthog]'),\n );\n } catch {\n return Promise.resolve(false);\n }\n }\n\n installPlugin(): Promise<PluginInstallResult> {\n const binary = this.findCodexBinary();\n if (!binary) return Promise.resolve({ success: false });\n\n const run = () =>\n spawnSync(binary, ['plugin', 'marketplace', 'add', 'PostHog/ai-plugin'], {\n encoding: 'utf-8',\n });\n\n let result = run();\n\n // Stale cache directory with no config.toml entry — clear it and retry\n if (\n result.status !== 0 &&\n (result.stderr ?? '').includes('already added from a different source')\n ) {\n const staleDir = path.join(\n os.homedir(),\n '.codex',\n '.tmp',\n 'marketplaces',\n 'posthog',\n );\n try {\n fs.rmSync(staleDir, { recursive: true, force: true });\n } catch {\n // ignore — retry anyway\n }\n result = run();\n }\n\n if (result.status !== 0) {\n analytics.captureException(\n new Error(`Codex plugin install failed: ${result.stderr ?? ''}`),\n );\n return Promise.resolve({ success: false });\n }\n\n return Promise.resolve({ success: true });\n }\n}\n\nexport default CodexMCPClient;\n","export interface PluginInstallResult {\n success: boolean;\n alreadyInstalled?: boolean;\n}\n\nexport interface PluginCapable {\n supportsPlugin(): boolean;\n isPluginInstalled(): Promise<boolean>;\n installPlugin(): Promise<PluginInstallResult>;\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","import type { Integration } from '@lib/constants';\nimport type { CloudRegion } from '@utils/types';\nimport { withProgress } from '../../telemetry';\nimport { analytics } from '@utils/analytics';\nimport { getUI } from '@ui';\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 { ALL_FEATURE_VALUES } from './defaults';\nimport { debug } from '@utils/debug';\nimport { isPluginCapable, PluginCapable } from './plugin-client';\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 ];\n const supportedClients: MCPClient[] = [];\n\n debug('Checking for supported MCP clients...');\n for (const client of allClients) {\n const isSupported = await client.isClientSupported();\n debug(`${client.name}: ${isSupported ? '✓ supported' : '✗ not supported'}`);\n if (isSupported) {\n supportedClients.push(client);\n }\n }\n debug(\n `Found ${supportedClients.length} supported client(s): ${supportedClients\n .map((c) => c.name)\n .join(', ')}`,\n );\n\n return supportedClients;\n};\n\n/**\n * Add MCP server to clients. No prompts — pure orchestration.\n * Prompts are handled by McpScreen (TUI) or auto-accepted (CI).\n */\nexport const addMCPServerToClientsStep = async ({\n integration,\n local = false,\n ci = false,\n cloudRegion: _cloudRegion,\n features,\n apiKey,\n}: {\n integration?: Integration;\n local?: boolean;\n ci?: boolean;\n cloudRegion?: CloudRegion;\n features?: string[];\n apiKey?: string;\n}): Promise<string[]> => {\n const ui = getUI();\n\n // CI mode: skip MCP installation entirely\n if (ci) {\n ui.log.info('Skipping MCP installation (CI mode)');\n return [];\n }\n\n const supportedClients = await getSupportedClients();\n\n if (supportedClients.length === 0) {\n ui.log.info(\n 'No supported MCP clients detected. Skipping MCP installation.',\n );\n return [];\n }\n\n // Auto-install to all supported clients\n await withProgress('adding mcp servers', async () => {\n await addMCPServer(\n supportedClients,\n apiKey,\n features ?? [...ALL_FEATURE_VALUES],\n local,\n );\n });\n\n ui.log.success(\n `Added the MCP server to:\n ${supportedClients.map((c) => `- ${c.name}`).join('\\n ')} `,\n );\n\n analytics.wizardCapture('mcp servers added', {\n clients: supportedClients.map((c) => c.name),\n integration,\n });\n\n return supportedClients.map((c) => c.name);\n};\n\nexport const removeMCPServerFromClientsStep = async ({\n integration,\n local = false,\n}: {\n integration?: Integration;\n local?: boolean;\n}): Promise<string[]> => {\n const installedClients = await getInstalledClients(local);\n if (installedClients.length === 0) {\n analytics.wizardCapture('mcp no servers to remove', {\n integration,\n });\n return [];\n }\n\n // Auto-remove from all installed clients\n const results = await withProgress('removing mcp servers', async () => {\n await removeMCPServer(installedClients, local);\n return installedClients.map((c) => c.name);\n });\n\n analytics.wizardCapture('mcp servers removed', {\n clients: results,\n integration,\n });\n\n return results;\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 if (await client.isServerInstalled(local)) {\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<void> => {\n for (const client of clients) {\n await client.addServer(personalApiKey, selectedFeatures, local);\n }\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<string[]> => {\n const installed: string[] = [];\n for (const client of clients) {\n try {\n const result = await client.installPlugin();\n if (result.success) installed.push(client.name);\n } catch (err) {\n debug(`[installPlugins] installPlugin threw for ${client.name}: ${err}`);\n }\n }\n return installed;\n};\n\nexport const removeMCPServer = async (\n clients: MCPClient[],\n local?: boolean,\n): Promise<void> => {\n for (const client of clients) {\n await client.removeServer(local);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,IAAsB,YAAtB,MAAgC;CAC9B;;AAaF,IAAsB,mBAAtB,cAA+C,UAAU;CACvD,OAAO;CAEP,cAAc;AACZ,SAAO;;CAGT,wBAAgC;AAC9B,SAAO;;CAGT,gBACE,QACA,kBACA,OACiB;AACjB,SAAO,uBAAuB,QAAQ,kBAAkB,MAAM;;CAGhE,MAAM,kBAAkB,OAAmC;AACzD,MAAI;GACF,MAAM,aAAa,MAAM,KAAK,eAAe;AAE7C,OAAI,CAACA,KAAG,WAAW,WAAW,CAC5B,QAAO;GAGT,MAAM,gBAAgB,MAAMA,KAAG,SAAS,SAAS,YAAY,OAAO;GACpE,MAAM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;AAG5E,QAAO;;AAGT,MAAa,kBAAkB,OAC7B,SACA,UACkB;AAClB,MAAK,MAAM,UAAU,QACnB,OAAM,OAAO,aAAa,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"analytics-Bl5DPj_0.js","names":["uuidv4"],"sources":["../src/utils/analytics.ts"],"sourcesContent":["import { PostHog } from 'posthog-node';\nimport {\n ANALYTICS_HOST_URL,\n ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY,\n ANALYTICS_TEAM_TAG,\n} from '@lib/constants';\nimport type { WizardSession } from '@lib/wizard-session';\nimport type { ApiUser } from '@lib/api';\nimport { v4 as uuidv4 } from 'uuid';\nimport { debug } from './debug';\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: WizardSession,\n): Record<string, unknown> {\n return {\n integration: session.integration,\n detected_framework: session.detectedFrameworkLabel,\n typescript: session.typescript,\n project_id: session.credentials?.projectId,\n discovered_features: session.discoveredFeatures,\n additional_features: session.additionalFeatureQueue,\n run_phase: session.runPhase,\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\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 appName = 'wizard';\n private activeFlags: Record<string, string> | null = null;\n private groups: Record<string, string> = {};\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 && Object.keys(this.groups).length > 0) {\n event.groups = { ...this.groups, ...event.groups };\n }\n return event;\n },\n });\n\n this.tags = { $app_name: this.appName };\n\n this.anonymousId = uuidv4();\n\n this.distinctId = undefined;\n }\n\n setDistinctId(distinctId: string) {\n this.distinctId = distinctId;\n this.client.alias({\n distinctId,\n alias: this.anonymousId,\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 ...properties,\n },\n });\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 async getFeatureFlag(flagKey: string): Promise<string | boolean | undefined> {\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n return await this.client.getFeatureFlag(flagKey, distinctId, {\n sendFeatureFlagEvents: true,\n personProperties: {\n $app_name: this.appName,\n },\n });\n } catch (error) {\n debug('Failed to get feature flag:', flagKey, error);\n return undefined;\n }\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 async getAllFlagsForWizard(): Promise<Record<string, string>> {\n if (this.activeFlags !== null) {\n return this.activeFlags;\n }\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n const result = await this.client.getAllFlagsAndPayloads(distinctId, {\n personProperties: { $app_name: this.appName },\n });\n const flags = result.featureFlags ?? {};\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(flags)) {\n if (value === undefined) continue;\n out[key] = typeof value === 'boolean' ? String(value) : String(value);\n }\n this.activeFlags = out;\n return out;\n } catch (error) {\n debug('Failed to get all feature flags:', error);\n return {};\n }\n }\n\n async shutdown(status: 'success' | 'error' | 'cancelled') {\n if (Object.keys(this.tags).length === 0) {\n return;\n }\n\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: 'setup wizard finished',\n properties: {\n status,\n tags: this.tags,\n },\n });\n\n await this.client.shutdown();\n }\n}\n\nexport const analytics = new Analytics();\n"],"mappings":";;;;;;;;AAeA,SAAgB,kBACd,SACyB;AACzB,QAAO;EACL,aAAa,QAAQ;EACrB,oBAAoB,QAAQ;EAC5B,YAAY,QAAQ;EACpB,YAAY,QAAQ,aAAa;EACjC,qBAAqB,QAAQ;EAC7B,qBAAqB,QAAQ;EAC7B,WAAW,QAAQ;EACpB;;AAGH,SAAgB,eACd,MACA,MACwB;CACxB,MAAM,SAAiC,EAAE,UAAU,MAAM;AACzD,KAAI,CAAC,KAAM,QAAO;CAElB,MAAM,iBAAiB,KAAK,cAAc;AAC1C,KAAI,eAAgB,QAAO,eAAe;CAE1C,MAAM,aAAa,KAAK,cAAc;AACtC,KAAI,WAAY,QAAO,WAAW;CAElC,MAAM,cAAc,KAAK,MAAM;AAC/B,KAAI,YAAa,QAAO,UAAU;AAElC,QAAO;;AAGT,IAAa,YAAb,MAAuB;CACrB;CACA,OACE,EAAE;CACJ;CACA;CACA,UAAkB;CAClB,cAAqD;CACrD,SAAyC,EAAE;CAE3C,cAAc;AACZ,OAAK,SAAS,IAAI,QAAQ,4CAA4C;GACpE,MAAM;GACN,SAAS;GACT,eAAe;GACf,4BAA4B;GAC5B,cAAc,UAAU;AACtB,QAAI,SAAS,OAAO,KAAK,KAAK,OAAO,CAAC,SAAS,EAC7C,OAAM,SAAS;KAAE,GAAG,KAAK;KAAQ,GAAG,MAAM;KAAQ;AAEpD,WAAO;;GAEV,CAAC;AA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D,QAAI,UAAU,KAAA,EAAW;AACzB,QAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,GAAG,OAAO,MAAM;;AAEvE,QAAK,cAAc;AACnB,UAAO;WACA,OAAO;AACd,SAAM,oCAAoC,MAAM;AAChD,UAAO,EAAE;;;CAIb,MAAM,SAAS,QAA2C;AACxD,MAAI,OAAO,KAAK,KAAK,KAAK,CAAC,WAAW,EACpC;AAGF,OAAK,OAAO,QAAQ;GAClB,YAAY,KAAK,cAAc,KAAK;GACpC,OAAO;GACP,YAAY;IACV;IACA,MAAM,KAAK;IACZ;GACF,CAAC;AAEF,QAAM,KAAK,OAAO,UAAU;;;AAIhC,MAAa,YAAY,IAAI,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"debug-h7Z9zEbD.js","names":["errResult"],"sources":["../src/env.ts","../src/lib/version.ts","../src/lib/constants.ts","../src/lib/health-checks/statuspage.ts","../src/lib/health-checks/incidentio.ts","../src/lib/health-checks/endpoints.ts","../src/lib/health-checks/readiness.ts","../src/ui/logging-ui.ts","../src/ui/index.ts","../src/utils/paths.ts","../src/utils/debug.ts"],"sourcesContent":["/**\n * Central environment variable access for the PostHog wizard.\n *\n * ── Build-time constants ────────────────────────────────────────────\n * Inlined by tsdown's `env` option at compile time. After build, the\n * runtime value of these env vars has zero effect on the wizard.\n *\n * ── Runtime variables ───────────────────────────────────────────────\n * Read through `runtimeEnv()` with a typed allowlist. This makes every\n * runtime dependency on the environment explicit and grep-able.\n *\n * ── Direct process.env access ───────────────────────────────────────\n * Reserved for subprocess environment configuration (writes) and\n * vendored code. Production source outside those cases should use\n * this module instead.\n */\n\n// ── Build-time constants ─────────────────────────────────────────────\n// tsdown replaces `process.env.NODE_ENV` with a string literal.\n// After build these are just `\"production\"`, `false`, etc.\n\nexport const NODE_ENV = process.env.NODE_ENV as string;\nexport const IS_DEV =\n process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';\n\n/**\n * True only in published/production builds. tsdown inlines\n * `process.env.NODE_ENV` as the literal `\"production\"` at build time, so this\n * collapses to `true` in `dist/` and stays `false` for `tsx`/dev/test runs\n * (where NODE_ENV is unset, `development`, or `test`). Used to gate features\n * that aren't supported in the shipped package — e.g. `--ci` mode.\n */\nexport const IS_PRODUCTION_BUILD = process.env.NODE_ENV === 'production';\n\n// ── Runtime environment ──────────────────────────────────────────────\n\n/**\n * Exhaustive allowlist of env vars the wizard reads at runtime.\n * Add new keys here when a new runtime dependency is needed.\n */\ntype RuntimeEnvKey =\n // Wizard CLI configuration (yargs POSTHOG_WIZARD_ prefix)\n | 'POSTHOG_WIZARD_BENCHMARK_CONFIG'\n | 'POSTHOG_WIZARD_BENCHMARK_FILE'\n | 'POSTHOG_WIZARD_LOG_DIR'\n | 'POSTHOG_WIZARD_DEBUG'\n | 'DEBUG'\n // Agent / MCP\n | 'MCP_URL'\n | 'POSTHOG_API_KEY'\n // Platform: terminal detection\n | 'TERM'\n | 'TERM_PROGRAM'\n | 'TERMINAL_EMULATOR'\n | 'CI'\n | 'WT_SESSION'\n | 'TERMINUS_SUBLIME'\n | 'ConEmuTask'\n // Platform: paths\n | 'APPDATA'\n | 'XDG_CONFIG_HOME';\n\n/** Read a runtime environment variable. Only allowlisted keys compile. */\nexport function runtimeEnv(key: RuntimeEnvKey): string | undefined {\n return process.env[key];\n}\n","// Auto-generated by scripts/generate-version.js — do not edit\nexport const VERSION = '2.21.0';\n","/**\n * Shared constants for the PostHog wizard.\n */\n\nimport { VERSION } from './version';\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 swift = 'swift',\n android = 'android',\n rails = 'rails',\n\n // Language fallbacks\n python = 'python',\n ruby = 'ruby',\n javascriptNode = 'javascript_node',\n javascript_web = 'javascript_web',\n}\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\n// ── Environment ──────────────────────────────────────────────────────\n\nimport { IS_DEV } from '@env';\nexport { IS_DEV };\nexport const DEBUG = false;\n\n// ── URLs ─────────────────────────────────────────────────────────────\n\nexport const DEFAULT_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.posthog.com';\nexport const DEFAULT_HOST_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.i.posthog.com';\nexport const ISSUES_URL = 'https://github.com/posthog/wizard/issues';\nexport const CONTEXT_MILL_URL = 'https://github.com/PostHog/context-mill';\nexport const POSTHOG_DOCS_URL = 'https://posthog.com/docs';\n\n/** Remote base URL for fetching the skill menu + downloading skills. */\nexport const REMOTE_SKILLS_BASE_URL =\n 'https://github.com/PostHog/context-mill/releases/latest/download';\n/** Local base URL when `--local-mcp` is set (served by context-mill dev server). */\nexport const LOCAL_SKILLS_BASE_URL = 'http://localhost:8765';\n\n/**\n * Pick the skills base URL based on the session's localMcp flag.\n * Single source of truth — do not inline this ternary anywhere.\n */\nexport function getSkillsBaseUrl(localMcp: boolean): string {\n return localMcp ? LOCAL_SKILLS_BASE_URL : REMOTE_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 POSTHOG_OAUTH_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://oauth.posthog.com';\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 *\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] 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 */\nexport const WIZARD_OAUTH_SCOPES = [\n ...WIZARD_PROVISIONING_SCOPES,\n 'health_issue:read',\n 'wizard_session:read',\n 'wizard_session:write',\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/** Feature flag key whose value selects a variant from WIZARD_VARIANTS. */\nexport const WIZARD_VARIANT_FLAG_KEY = 'wizard-variant';\n/** Feature flag key that gates the intro-screen \"Tools\" menu. */\nexport const WIZARD_TOOLS_MENU_FLAG_KEY = 'wizard-tools-menu';\n/** Variant key -> metadata for wizard run (VARIANT flag selects which entry to use). */\nexport const WIZARD_VARIANTS: Record<string, Record<string, string>> = {\n base: { VARIANT: 'base' },\n subagents: { VARIANT: 'subagents' },\n};\n/** User-Agent for wizard HTTP requests and MCP server identification. */\nexport const WIZARD_USER_AGENT = `posthog/wizard; version: ${VERSION}`;\n\n// ── HTTP headers ─────────────────────────────────────────────────────\n\n/** Header prefix for PostHog properties (e.g. X-POSTHOG-PROPERTY-VARIANT). */\nexport const POSTHOG_PROPERTY_HEADER_PREFIX = 'X-POSTHOG-PROPERTY-';\n/** Header prefix for PostHog feature flags. */\nexport const POSTHOG_FLAG_HEADER_PREFIX = 'X-POSTHOG-FLAG-';\n\n// ── Timeouts ─────────────────────────────────────────────────────────\n\n/** Timeout for framework / project detection probes (ms). */\nexport const DETECTION_TIMEOUT_MS = 10_000;\n\n/** Timeout for the OAuth authorization flow (ms). */\nexport const OAUTH_TIMEOUT_MS = 360_000;\n","import {\n ServiceHealthStatus,\n type BaseHealthResult,\n type ComponentHealthResult,\n} from './types';\n\n// ---------------------------------------------------------------------------\n// Statuspage.io v2 API helpers\n// https://metastatuspage.com/api\n//\n// status.json – page-level rollup; indicator is one of: none | minor | major | critical\n// summary.json – same rollup + component list; component status is one of:\n// operational | degraded_performance | partial_outage | major_outage | under_maintenance\n// https://support.atlassian.com/statuspage/docs/show-service-status-with-components\n// ---------------------------------------------------------------------------\n\ninterface StatuspageStatusResponse {\n status?: { indicator?: string; description?: string };\n}\n\ninterface StatuspageSummaryResponse extends StatuspageStatusResponse {\n components?: { id: string; name: string; status: string }[];\n}\n\nfunction mapIndicator(v: string | null | undefined): ServiceHealthStatus {\n switch (v) {\n case 'none':\n return ServiceHealthStatus.Healthy;\n case 'minor':\n return ServiceHealthStatus.Degraded;\n case 'major':\n case 'critical':\n return ServiceHealthStatus.Down;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction mapComponentRaw(v: string | null | undefined): ServiceHealthStatus {\n switch (v) {\n case 'operational':\n return ServiceHealthStatus.Healthy;\n case 'degraded_performance':\n case 'under_maintenance':\n return ServiceHealthStatus.Degraded;\n case 'partial_outage':\n case 'major_outage':\n return ServiceHealthStatus.Down;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction errResult(error: string): BaseHealthResult {\n return { status: ServiceHealthStatus.Degraded, error };\n}\n\nasync function fetchStatuspageIndicator(\n url: string,\n timeoutMs = 5000,\n): Promise<BaseHealthResult> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, { signal: controller.signal });\n clearTimeout(tid);\n\n if (!res.ok) return errResult(`HTTP ${res.status}`);\n\n const data = (await res.json()) as StatuspageStatusResponse;\n const indicator = data.status?.indicator ?? null;\n return {\n status: mapIndicator(indicator),\n rawIndicator: indicator ?? undefined,\n };\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError')\n return errResult('Request timed out');\n return errResult(e instanceof Error ? e.message : 'Unknown error');\n }\n}\n\nasync function fetchStatuspageSummary(\n url: string,\n timeoutMs = 5000,\n): Promise<ComponentHealthResult> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, { signal: controller.signal });\n clearTimeout(tid);\n\n if (!res.ok) return errResult(`HTTP ${res.status}`);\n\n const data = (await res.json()) as StatuspageSummaryResponse;\n const indicator = data.status?.indicator ?? null;\n const overall = mapIndicator(indicator);\n\n const affected = (data.components ?? [])\n .map((c) => ({\n name: c.name,\n status: mapComponentRaw(c.status),\n rawStatus: c.status,\n }))\n .filter((c) => c.status !== ServiceHealthStatus.Healthy);\n\n return {\n status: affected.length > 0 ? ServiceHealthStatus.Degraded : overall,\n rawIndicator: indicator ?? undefined,\n degradedOrDownComponents: affected.length > 0 ? affected : undefined,\n };\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError')\n return errResult('Request timed out');\n return errResult(e instanceof Error ? e.message : 'Unknown error');\n }\n}\n\n// ---------------------------------------------------------------------------\n// Individual statuspage-backed checks\n// ---------------------------------------------------------------------------\n\nexport const checkAnthropicHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator('https://status.claude.com/api/v2/status.json');\n\nexport const checkGithubHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator('https://www.githubstatus.com/api/v2/status.json');\n\nexport const checkNpmOverallHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator('https://status.npmjs.org/api/v2/status.json');\n\nexport const checkNpmComponentHealth = (): Promise<ComponentHealthResult> =>\n fetchStatuspageSummary('https://status.npmjs.org/api/v2/summary.json');\n\nexport const checkCloudflareOverallHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator(\n 'https://www.cloudflarestatus.com/api/v2/status.json',\n );\n\nexport const checkCloudflareComponentHealth =\n (): Promise<ComponentHealthResult> =>\n fetchStatuspageSummary(\n 'https://www.cloudflarestatus.com/api/v2/summary.json',\n );\n","import {\n ServiceHealthStatus,\n type BaseHealthResult,\n type ComponentHealthResult,\n type ComponentStatus,\n} from './types';\n\ninterface IncidentIoAffectedComponent {\n id: string;\n name: string;\n group_name?: string;\n current_status: string;\n}\n\ninterface IncidentIoIncident {\n id: string;\n name: string;\n status: string;\n current_worst_impact: string;\n affected_components: IncidentIoAffectedComponent[];\n}\n\ninterface IncidentIoSummary {\n ongoing_incidents: IncidentIoIncident[];\n in_progress_maintenances: unknown[];\n}\n\nfunction mapIncidentImpact(impact: string): ServiceHealthStatus {\n switch (impact) {\n case 'full_outage':\n return ServiceHealthStatus.Down;\n case 'partial_outage':\n case 'degraded_performance':\n return ServiceHealthStatus.Degraded;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction mapComponentStatus(status: string): ServiceHealthStatus {\n switch (status) {\n case 'operational':\n return ServiceHealthStatus.Healthy;\n case 'full_outage':\n return ServiceHealthStatus.Down;\n case 'partial_outage':\n case 'degraded_performance':\n return ServiceHealthStatus.Degraded;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction errResult(error: string): BaseHealthResult {\n return { status: ServiceHealthStatus.Degraded, error };\n}\n\nconst POSTHOG_STATUS_URL = 'https://www.posthogstatus.com/api/v1/summary';\n\nasync function fetchPosthogStatus(\n timeoutMs = 5000,\n): Promise<{ overall: BaseHealthResult; components: ComponentHealthResult }> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(POSTHOG_STATUS_URL, { signal: controller.signal });\n clearTimeout(tid);\n\n if (!res.ok) {\n const err = errResult(`HTTP ${res.status}`);\n return { overall: err, components: err };\n }\n\n const data = (await res.json()) as IncidentIoSummary;\n const incidents = data.ongoing_incidents ?? [];\n\n if (incidents.length === 0) {\n return {\n overall: { status: ServiceHealthStatus.Healthy },\n components: { status: ServiceHealthStatus.Healthy },\n };\n }\n\n let worstOverall = ServiceHealthStatus.Degraded;\n const affected: ComponentStatus[] = [];\n\n for (const incident of incidents) {\n const impact = mapIncidentImpact(incident.current_worst_impact);\n if (impact === ServiceHealthStatus.Down) {\n worstOverall = ServiceHealthStatus.Down;\n }\n\n for (const comp of incident.affected_components ?? []) {\n const compStatus = mapComponentStatus(comp.current_status);\n if (compStatus !== ServiceHealthStatus.Healthy) {\n affected.push({\n name: comp.group_name\n ? `${comp.group_name} — ${comp.name}`\n : comp.name,\n status: compStatus,\n rawStatus: comp.current_status,\n });\n }\n }\n }\n\n return {\n overall: { status: worstOverall },\n components: {\n status:\n affected.length > 0 ? ServiceHealthStatus.Degraded : worstOverall,\n degradedOrDownComponents: affected.length > 0 ? affected : undefined,\n },\n };\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError') {\n const err = errResult('Request timed out');\n return { overall: err, components: err };\n }\n const err = errResult(e instanceof Error ? e.message : 'Unknown error');\n return { overall: err, components: err };\n }\n}\n\nlet _cache: Promise<{\n overall: BaseHealthResult;\n components: ComponentHealthResult;\n}> | null = null;\n\nfunction getPosthogHealth() {\n if (!_cache) _cache = fetchPosthogStatus();\n return _cache;\n}\n\nexport function resetPosthogHealthCache(): void {\n _cache = null;\n}\n\nexport const checkPosthogOverallHealth = async (): Promise<BaseHealthResult> =>\n (await getPosthogHealth()).overall;\n\nexport const checkPosthogComponentHealth =\n async (): Promise<ComponentHealthResult> =>\n (await getPosthogHealth()).components;\n","import { REMOTE_SKILLS_BASE_URL } from '@lib/constants';\nimport { logToFile } from '@utils/debug';\nimport { ServiceHealthStatus, type BaseHealthResult } from './types';\n\n// ---------------------------------------------------------------------------\n// Direct endpoint health checks\n//\n// These ping PostHog-owned services directly (no Statuspage intermediary).\n// A non-expected HTTP status or any network error is treated as Down.\n//\n// LLM Gateway – FastAPI service\n// Source: posthog/services/llm-gateway/src/llm_gateway/api/health.py\n// GET /_liveness → 200 {\"status\":\"alive\"}\n//\n// MCP – Cloudflare Worker\n// Source: posthog/services/mcp/src/index.ts\n// GET / → 302 to posthog.com docs. The redirect proves the worker is up.\n// ---------------------------------------------------------------------------\n\nfunction downResult(error: string): BaseHealthResult {\n return { status: ServiceHealthStatus.Down, error };\n}\n\nasync function fetchEndpointHealth(\n url: string,\n timeoutMs = 5000,\n isExpectedStatus: (status: number) => boolean = (s) => s === 200,\n redirect: 'follow' | 'manual' | 'error' = 'follow',\n): Promise<BaseHealthResult> {\n const result = await (async (): Promise<BaseHealthResult> => {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, {\n signal: controller.signal,\n redirect,\n });\n clearTimeout(tid);\n\n if (isExpectedStatus(res.status)) {\n return {\n status: ServiceHealthStatus.Healthy,\n rawIndicator: `HTTP ${res.status}`,\n };\n }\n return downResult(`HTTP ${res.status}`);\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError')\n return downResult(`Request timed out after ${timeoutMs}ms`);\n return downResult(e instanceof Error ? e.message : 'Unknown error');\n }\n })();\n\n logToFile(\n `[health-checks] GET ${url} -> ${result.status}` +\n `${result.rawIndicator ? ` (${result.rawIndicator})` : ''}` +\n `${result.error ? ` (${result.error})` : ''}`,\n );\n return result;\n}\n\nexport const checkLlmGatewayHealth = (): Promise<BaseHealthResult> =>\n fetchEndpointHealth('https://gateway.us.posthog.com/_liveness');\n\nexport const checkMcpHealth = (): Promise<BaseHealthResult> =>\n fetchEndpointHealth(\n 'https://mcp.posthog.com/',\n 5000,\n // 2xx-3xx counts as up (redirect to docs)\n (s) => s >= 200 && s < 400,\n 'manual',\n );\n\nexport const checkGithubReleasesHealth = (): Promise<BaseHealthResult> =>\n fetchEndpointHealth(`${REMOTE_SKILLS_BASE_URL}/skill-menu.json`);\n","import {\n ServiceHealthStatus,\n type AllServicesHealth,\n type BaseHealthResult,\n type ComponentHealthResult,\n type HealthCheckKey,\n} from './types';\nimport {\n checkAnthropicHealth,\n checkGithubHealth,\n checkNpmOverallHealth,\n checkNpmComponentHealth,\n checkCloudflareOverallHealth,\n checkCloudflareComponentHealth,\n} from './statuspage';\nimport {\n checkPosthogOverallHealth,\n checkPosthogComponentHealth,\n} from './incidentio';\nimport {\n checkLlmGatewayHealth,\n checkMcpHealth,\n checkGithubReleasesHealth,\n} from './endpoints';\nimport { logToFile } from '@utils/debug';\n\n// ---------------------------------------------------------------------------\n// Service labels (used in human-readable reason strings)\n// ---------------------------------------------------------------------------\n\nexport const SERVICE_LABELS: Record<HealthCheckKey, string> = {\n anthropic: 'Anthropic',\n posthogOverall: 'PostHog',\n posthogComponents: 'PostHog (components)',\n github: 'GitHub',\n npmOverall: 'npm',\n npmComponents: 'npm (components)',\n cloudflareOverall: 'Cloudflare',\n cloudflareComponents: 'Cloudflare (components)',\n llmGateway: 'LLM Gateway',\n mcp: 'MCP',\n githubReleases: 'GitHub Releases',\n};\n\n// ---------------------------------------------------------------------------\n// Readiness config\n// ---------------------------------------------------------------------------\n\nexport interface WizardReadinessConfig {\n /** Services where status=Down blocks the run (readiness=No). */\n downBlocksRun: HealthCheckKey[];\n /** Services where status=Degraded (or worse) blocks the run (readiness=No). */\n degradedBlocksRun?: HealthCheckKey[];\n}\n\n/**\n * See README section \"Health checks\" for the full rationale.\n * Adjust these arrays to change what blocks a wizard run.\n */\nexport const DEFAULT_WIZARD_READINESS_CONFIG: WizardReadinessConfig = {\n downBlocksRun: [\n 'anthropic',\n 'npmOverall',\n 'llmGateway',\n 'mcp',\n 'githubReleases',\n ],\n degradedBlocksRun: ['anthropic'],\n};\n\n/**\n * Reduced readiness config for --signup provisioning flows.\n *\n * Provisioning only needs PostHog and the LLM Gateway - it doesn't\n * use Anthropic directly, npm, GitHub Releases, or MCP.\n */\nexport const SIGNUP_WIZARD_READINESS_CONFIG: WizardReadinessConfig = {\n downBlocksRun: ['posthogOverall', 'llmGateway'],\n};\n\n// ---------------------------------------------------------------------------\n// Aggregate check\n// ---------------------------------------------------------------------------\n\nexport async function checkAllExternalServices(): Promise<AllServicesHealth> {\n const [\n anthropic,\n posthogOverall,\n posthogComponents,\n github,\n npmOverall,\n npmComponents,\n cloudflareOverall,\n cloudflareComponents,\n llmGateway,\n mcp,\n githubReleases,\n ] = await Promise.all([\n checkAnthropicHealth(),\n checkPosthogOverallHealth(),\n checkPosthogComponentHealth(),\n checkGithubHealth(),\n checkNpmOverallHealth(),\n checkNpmComponentHealth(),\n checkCloudflareOverallHealth(),\n checkCloudflareComponentHealth(),\n checkLlmGatewayHealth(),\n checkMcpHealth(),\n checkGithubReleasesHealth(),\n ]);\n\n return {\n anthropic,\n posthogOverall,\n posthogComponents,\n github,\n npmOverall,\n npmComponents,\n cloudflareOverall,\n cloudflareComponents,\n llmGateway,\n mcp,\n githubReleases,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Wizard readiness evaluation\n// ---------------------------------------------------------------------------\n\nexport enum WizardReadiness {\n Yes = 'yes',\n No = 'no',\n YesWithWarnings = 'yes_with_warnings',\n}\n\nexport interface WizardReadinessResult {\n decision: WizardReadiness;\n health: AllServicesHealth;\n reasons: string[];\n}\n\nfunction describeResult(label: string, h: BaseHealthResult): string {\n const parts = [`${label}: ${h.status}`];\n if (h.rawIndicator) parts.push(`indicator=${h.rawIndicator}`);\n if (h.error) parts.push(h.error);\n return parts.join(' — ');\n}\n\nconst MAX_COMPONENT_NAMES = 8;\n\nfunction describeComponents(label: string, h: ComponentHealthResult): string {\n const affected = h.degradedOrDownComponents;\n if (!affected || affected.length === 0)\n return `${label} components: all operational`;\n const shown = affected\n .slice(0, MAX_COMPONENT_NAMES)\n .map((c) => `${c.name} (${c.status})`);\n const suffix =\n affected.length > MAX_COMPONENT_NAMES\n ? `, +${affected.length - MAX_COMPONENT_NAMES} more`\n : '';\n return `${label} components impacted: ${shown.join(', ')}${suffix}`;\n}\n\nconst READINESS_TIMEOUT_MS = 10_000;\n\nexport async function evaluateWizardReadiness(\n config: WizardReadinessConfig = DEFAULT_WIZARD_READINESS_CONFIG,\n): Promise<WizardReadinessResult> {\n try {\n const health = await Promise.race([\n checkAllExternalServices(),\n new Promise<AllServicesHealth>((resolve) =>\n setTimeout(\n () => resolve(allUnknown('Health check timed out')),\n READINESS_TIMEOUT_MS,\n ),\n ),\n ]);\n\n const reasons: string[] = [];\n\n for (const key of Object.keys(health) as HealthCheckKey[]) {\n const result = health[key];\n const label = SERVICE_LABELS[key];\n\n reasons.push(describeResult(label, result));\n\n if ('degradedOrDownComponents' in result) {\n reasons.push(describeComponents(label, result));\n }\n }\n\n const blockingKeys = getBlockingServiceKeys(health, config);\n if (blockingKeys.length > 0) {\n const blockingDetails = blockingKeys.map((key) => {\n const h = health[key];\n return `${key} (${h.status}${h.error ? ` — ${h.error}` : ''})`;\n });\n logToFile(`[health-checks] blocked by: ${blockingDetails.join(', ')}`);\n return { decision: WizardReadiness.No, health, reasons };\n }\n\n const hasWarnings = Object.values(health).some(\n (h) => h.status !== ServiceHealthStatus.Healthy,\n );\n\n if (hasWarnings) {\n return { decision: WizardReadiness.YesWithWarnings, health, reasons };\n }\n\n return { decision: WizardReadiness.Yes, health, reasons };\n } catch (err) {\n logToFile(\n `[health-checks] error: ${err instanceof Error ? err.message : err}`,\n );\n // Health checks must never block the wizard run\n return {\n decision: WizardReadiness.Yes,\n health: allUnknown('Unexpected error'),\n reasons: ['Health check failed unexpectedly — proceeding anyway'],\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Blocking service detection\n// ---------------------------------------------------------------------------\n\n/** Keys that are component-level detail, not top-level services. */\nconst COMPONENT_KEYS: HealthCheckKey[] = [\n 'posthogComponents',\n 'npmComponents',\n 'cloudflareComponents',\n];\n\n/**\n * Get the keys of services that would block a wizard run per the given config.\n */\nexport function getBlockingServiceKeys(\n health: AllServicesHealth,\n config: WizardReadinessConfig = DEFAULT_WIZARD_READINESS_CONFIG,\n): HealthCheckKey[] {\n return (Object.keys(health) as HealthCheckKey[]).filter((key) => {\n if (COMPONENT_KEYS.includes(key)) return false;\n const result = health[key];\n if (\n config.downBlocksRun.includes(key) &&\n result.status === ServiceHealthStatus.Down\n ) {\n return true;\n }\n if (\n (config.degradedBlocksRun ?? []).includes(key) &&\n result.status !== ServiceHealthStatus.Healthy\n ) {\n return true;\n }\n return false;\n });\n}\n\n/** Build an AllServicesHealth where every service is Degraded with the given error. */\nfunction allUnknown(error: string): AllServicesHealth {\n const base: BaseHealthResult = {\n status: ServiceHealthStatus.Degraded,\n error,\n };\n return {\n anthropic: base,\n posthogOverall: base,\n posthogComponents: { ...base },\n github: base,\n npmOverall: base,\n npmComponents: { ...base },\n cloudflareOverall: base,\n cloudflareComponents: { ...base },\n llmGateway: base,\n mcp: base,\n githubReleases: base,\n };\n}\n","/* eslint-disable no-console */\n/**\n * LoggingUI — Logging-only implementation for CI mode.\n * No prompts, no TUI, no interactivity. Just console output.\n */\n\nimport {\n TaskStatus,\n type WizardUI,\n type SpinnerHandle,\n type AuthErrorDetail,\n} from './wizard-ui';\nimport type { SettingsConflict } from '@lib/agent/claude-settings';\nimport type { ApiUser } from '@lib/api';\nimport {\n type WizardReadinessResult,\n getBlockingServiceKeys,\n SERVICE_LABELS,\n} from '@lib/health-checks/readiness';\nimport type {\n AskAnswers,\n OutroData,\n PendingQuestion,\n} from '@lib/wizard-session';\n\nexport class LoggingUI implements WizardUI {\n intro(message: string): void {\n console.log(`┌ ${message}`);\n }\n\n outro(message: string): void {\n console.log(`└ ${message}`);\n }\n\n outroError(data: OutroData): void {\n console.log(`✖ ${data.message ?? 'Wizard aborted'}`);\n if (data.body) console.log(`│ ${data.body}`);\n if (data.docsUrl) console.log(`│ Docs: ${data.docsUrl}`);\n }\n\n waitForOutroDismissed(): Promise<void> {\n return Promise.resolve();\n }\n\n cancel(message: string): void {\n console.log(`■ ${message}`);\n }\n\n log = {\n info(message: string): void {\n console.log(`│ ${message}`);\n },\n warn(message: string): void {\n console.log(`▲ ${message}`);\n },\n error(message: string): void {\n console.log(`✖ ${message}`);\n },\n success(message: string): void {\n console.log(`✔ ${message}`);\n },\n step(message: string): void {\n console.log(`◇ ${message}`);\n },\n };\n\n note(message: string): void {\n console.log(`│ ${message}`);\n }\n\n spinner(): SpinnerHandle {\n return {\n start(message?: string) {\n if (message) console.log(`◌ ${message}`);\n },\n stop(message?: string) {\n if (message) console.log(`● ${message}`);\n },\n message(msg?: string) {\n if (msg) console.log(`◌ ${msg}`);\n },\n };\n }\n\n pushStatus(message: string): void {\n console.log(`◇ ${message}`);\n }\n\n setDetectedFramework(label: string): void {\n console.log(`✔ Framework: ${label}`);\n }\n\n onEnterScreen(_screen: string, _fn: () => void): void {\n // No screen transitions in CI\n }\n\n setLoginUrl(url: string | null): void {\n if (url) {\n console.log(\n `│ If the browser didn't open automatically, use this link:`,\n );\n console.log(`│ ${url}`);\n }\n }\n\n setAuthorizeUrl(_url: string | null): void {\n // Manual-paste modal is TUI-only; CI/non-interactive runs don't use it.\n }\n\n showBlockingOutage(result: WizardReadinessResult): Promise<void> {\n console.log(`▲ Service health issues detected — blocking outage.`);\n const blockingKeys = getBlockingServiceKeys(result.health);\n if (blockingKeys.length > 0) {\n console.log(`│`);\n console.log(`│ Blocking services:`);\n for (const key of blockingKeys) {\n const status = result.health[key].status;\n const error = result.health[key].error;\n const label = SERVICE_LABELS[key];\n const detail = error ? ` — ${error}` : '';\n console.log(`│ ✖ ${label}: ${status}${detail}`);\n }\n console.log(`│`);\n }\n for (const reason of result.reasons) {\n console.log(`│ ${reason}`);\n }\n console.log(`│ The wizard cannot start while these services are down.`);\n return Promise.resolve();\n }\n\n setReadinessWarnings(result: WizardReadinessResult): void {\n console.log(`▲ Service health warnings detected.`);\n for (const reason of result.reasons) {\n console.log(`│ ${reason}`);\n }\n }\n\n showPortConflict(_processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void> {\n return Promise.resolve();\n }\n\n waitForManualAuthCode(): Promise<string> {\n // No interactive prompt in CI/logging mode — never resolves. CI bypasses\n // OAuth entirely, so this is only here to satisfy the interface.\n return new Promise<string>(() => {\n /* intentionally never resolves */\n });\n }\n\n showSettingsOverride(\n _conflicts: SettingsConflict[],\n _backupAndFix: () => boolean,\n ): Promise<void> {\n return Promise.resolve();\n }\n\n requestQuestion(_question: PendingQuestion): Promise<AskAnswers> {\n return Promise.reject(\n new Error(\n 'wizard_ask is not available in CI / non-interactive mode. ' +\n 'Re-run the wizard without --ci to answer interactively.',\n ),\n );\n }\n\n showAuthError(detail?: AuthErrorDetail): void {\n console.log(`✖ Authentication failed (401)`);\n if (detail?.hasSettingsConflict) {\n console.log(\n `│ Claude Code auth is conflicting with the wizard. Please try again after logging out:`,\n );\n console.log(`│ claude auth logout`);\n } else {\n console.log(\n `│ The PostHog LLM Gateway rejected the API key. Common causes:`,\n );\n console.log(\n `│ - Wrong key type: pass a personal API key (phx_xxx). pha_ is an OAuth access token, phc_ is a project key.`,\n );\n console.log(\n `│ - Missing scope: the personal API key needs the \"llm_gateway:read\" scope.`,\n );\n console.log(`│ - Expired or revoked key.`);\n console.log(\n `│ - Region mismatch: --region must match the region the key was issued in (us vs eu).`,\n );\n }\n if (detail?.logFilePath) {\n console.log(`│ Verbose log: ${detail.logFilePath}`);\n }\n }\n\n startRun(): void {\n // No-op in CI mode\n }\n\n setCredentials(_credentials: {\n accessToken: string;\n projectApiKey: string;\n host: string;\n projectId: number;\n }): void {\n // No-op in CI mode — credentials are handled directly\n }\n\n setRoleAtOrganization(_role: string | null): void {\n // No-op in CI mode — there's no TUI to render role-tailored prompts\n }\n\n setApiUser(_user: ApiUser | null): void {\n // No-op in CI mode — there's no TUI to read account context from\n // the session.\n }\n\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void {\n const completed = todos.filter(\n (t) => t.status === TaskStatus.Completed,\n ).length;\n const inProgress = todos.find((t) => t.status === TaskStatus.InProgress);\n if (inProgress) {\n console.log(\n `◌ [${completed}/${todos.length}] ${\n inProgress.activeForm || inProgress.content\n }`,\n );\n }\n }\n\n setEventPlan(_events: Array<{ name: string; description: string }>): void {\n // No-op in CI mode\n }\n\n setDashboardUrl(_url: string): void {\n // No-op in CI mode\n }\n\n setNotebookUrl(_url: string): void {\n // No-op in CI mode\n }\n\n setOutroData(_data: import('@lib/wizard-session').OutroData): void {\n // No-op in CI mode\n }\n\n setFrameworkContext(_key: string, _value: unknown): void {\n // No-op in CI mode\n }\n}\n","/**\n * UI singleton — provides getUI() and setUI() for the wizard.\n * Default: LoggingUI. Swap to InkUI at startup for TUI mode.\n */\n\nimport type { WizardUI } from './wizard-ui';\nimport { LoggingUI } from './logging-ui';\n\nlet currentUI: WizardUI = new LoggingUI();\n\nexport function getUI(): WizardUI {\n return currentUI;\n}\n\nexport function setUI(ui: WizardUI): void {\n currentUI = ui;\n}\n\nexport type { WizardUI, SpinnerHandle } from './wizard-ui';\n","import { tmpdir } from 'node:os';\nimport { join, sep } from 'node:path';\n\n// /tmp is stable and discoverable on macOS/Linux; Windows needs os.tmpdir()\nconst TMP = process.platform === 'win32' ? tmpdir() : '/tmp';\n\nexport const WIZARD_LOG_FILE = join(TMP, 'posthog-wizard.log');\nexport const WIZARD_BENCHMARK_FILE = join(TMP, 'posthog-wizard-benchmark.json');\nexport const WIZARD_YARA_REPORT_FILE = join(\n TMP,\n 'posthog-wizard-yara-report.json',\n);\n/** Temp path for a skill download zip. */\nexport function skillTmpPath(skillId: string): string {\n return join(TMP, `posthog-skill-${skillId}.zip`);\n}\n\n/**\n * Strip an absolute installDir prefix off a project file path so the UI\n * renders `index.js:12` instead of `/Users/.../index.js:12`. Defends\n * against false matches like `/Users/foo` ⊂ `/Users/foobar/x.js` by\n * normalizing to a trailing path separator before the prefix check.\n */\nexport function relativeToInstallDir(file: string, installDir: string): string {\n const prefix = installDir.endsWith(sep) ? installDir : installDir + sep;\n return file.startsWith(prefix) ? file.slice(prefix.length) : file;\n}\n","import { appendFileSync } from 'fs';\nimport path from 'path';\nimport { inspect } from 'node:util';\nimport { getUI } from '@ui';\nimport { runtimeEnv } from '@env';\nimport { WIZARD_LOG_FILE } from './paths';\n\nlet logFilePath = WIZARD_LOG_FILE;\nlet fileLoggingEnabled = true;\nlet consoleLoggingEnabled = false;\n\nfunction stringify(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value instanceof Error) return value.stack ?? String(value);\n try {\n // JSON.stringify throws on cycles and skips some values — fall back to\n // inspect so a crash log line is never dropped.\n return JSON.stringify(value, null, 2) ?? inspect(value, { depth: 3 });\n } catch {\n return inspect(value, { depth: 3 });\n }\n}\n\nfunction renderLine(args: readonly unknown[]): string {\n return args.map(stringify).join(' ');\n}\n\nexport function getLogFilePath(): string {\n return logFilePath;\n}\n\nexport function configureLogFile(opts: {\n path?: string;\n enabled?: boolean;\n}): void {\n if (opts.path !== undefined) logFilePath = opts.path;\n if (opts.enabled !== undefined) fileLoggingEnabled = opts.enabled;\n}\n\nexport function configureLogFileFromEnvironment(): void {\n const dir = runtimeEnv('POSTHOG_WIZARD_LOG_DIR');\n if (dir) {\n configureLogFile({ path: path.join(dir, 'posthog-wizard.log') });\n }\n}\n\nexport function initLogFile(): void {\n if (!fileLoggingEnabled) return;\n try {\n const divider = '='.repeat(60);\n appendFileSync(\n logFilePath,\n `\\n${divider}\\nPostHog Wizard Run: ${new Date().toISOString()}\\n${divider}\\n`,\n );\n } catch {\n // Logging must never crash the wizard.\n }\n}\n\nexport function logToFile(...args: unknown[]): void {\n if (!fileLoggingEnabled) return;\n try {\n const ts = new Date().toISOString();\n appendFileSync(logFilePath, `[${ts}] ${renderLine(args)}\\n`);\n } catch {\n // Logging must never crash the wizard.\n }\n}\n\nexport function debug(...args: unknown[]): void {\n if (!consoleLoggingEnabled) return;\n getUI().log.info(renderLine(args));\n}\n\nexport function enableDebugLogs(): void {\n consoleLoggingEnabled = true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,WAAA;;AA0Cb,SAAgB,WAAW,KAAwC;AACjE,QAAO,QAAQ,IAAI;;;;AC/DrB,MAAa,UAAU;;;;;;;;;ACUvB,IAAY,cAAL,yBAAA,aAAA;AAEL,aAAA,YAAA;AACA,aAAA,UAAA;AACA,aAAA,SAAA;AACA,aAAA,iBAAA;AACA,aAAA,mBAAA;AACA,aAAA,oBAAA;AACA,aAAA,iBAAA;AACA,aAAA,aAAA;AACA,aAAA,WAAA;AACA,aAAA,YAAA;AACA,aAAA,WAAA;AACA,aAAA,aAAA;AACA,aAAA,aAAA;AACA,aAAA,eAAA;AACA,aAAA,WAAA;AACA,aAAA,aAAA;AACA,aAAA,WAAA;AAGA,aAAA,YAAA;AACA,aAAA,UAAA;AACA,aAAA,oBAAA;AACA,aAAA,oBAAA;;KACD;AAkBD,MAAa,mBAET;AACJ,MAAa,aAAa;AAC1B,MAAa,mBAAmB;AA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KAAK,YAAY,KAAA,EAAW,sBAAqB,KAAK;;AAG5D,SAAgB,kCAAwC;CACtD,MAAM,MAAM,WAAW,yBAAyB;AAChD,KAAI,IACF,kBAAiB,EAAE,MAAM,KAAK,KAAK,KAAK,qBAAqB,EAAE,CAAC;;AAIpE,SAAgB,cAAoB;AAClC,KAAI,CAAC,mBAAoB;AACzB,KAAI;EACF,MAAM,UAAU,IAAI,OAAO,GAAG;AAC9B,iBACE,aACA,KAAK,QAAQ,yCAAwB,IAAI,MAAM,EAAC,aAAa,CAAC,IAAI,QAAQ,IAC3E;SACK;;AAKV,SAAgB,UAAU,GAAG,MAAuB;AAClD,KAAI,CAAC,mBAAoB;AACzB,KAAI;EACF,MAAM,sBAAK,IAAI,MAAM,EAAC,aAAa;AACnC,iBAAe,aAAa,IAAI,GAAG,IAAI,WAAW,KAAK,CAAC,IAAI;SACtD;;AAKV,SAAgB,MAAM,GAAG,MAAuB;AAC9C,KAAI,CAAC,sBAAuB;AAC5B,QAAO,CAAC,IAAI,KAAK,WAAW,KAAK,CAAC;;AAGpC,SAAgB,kBAAwB;AACtC,yBAAwB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"playground-DCVaVeVD.js","names":["path","MOCK_TASKS","getMigrationContentBlocks"],"sources":["../src/ui/tui/playground/demos/WelcomeDemo.tsx","../src/ui/tui/playground/demos/LayoutDemo.tsx","../src/ui/tui/playground/demos/InputDemo.tsx","../src/ui/tui/playground/demos/ProgressDemo.tsx","../src/ui/tui/playground/demos/LogDemo.tsx","../src/ui/tui/playground/demos/RunScreenDemo.tsx","../src/ui/tui/playground/demos/HealthCheckDemo.tsx","../src/ui/tui/playground/demos/DoctorReportDemo.tsx","../src/ui/tui/playground/demos/ModalDemo.tsx","../src/ui/tui/playground/demos/McpDemo.tsx","../src/ui/tui/playground/demos/McpSuggestedPromptsDemo.tsx","../src/ui/tui/playground/demos/KeyboardHintsDemo.tsx","../src/ui/tui/playground/demos/AuditChecksDemo.tsx","../src/ui/tui/playground/demos/LearnDeckDemo.tsx","../src/ui/tui/playground/demos/EndScreensDemo.tsx","../src/ui/tui/playground/PlaygroundApp.tsx","../src/ui/tui/playground/start-playground.ts","../src/commands/basic-integration/playground.ts"],"sourcesContent":["/**\n * WelcomeDemo — Splash screen. Press enter to push the tabbed view.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport type { WizardStore } from '@ui/tui/store';\nimport { Colors, Icons } from '@ui/tui/styles';\n\ninterface WelcomeDemoProps {\n store: WizardStore;\n}\n\nexport const WelcomeDemo = ({ store }: WelcomeDemoProps) => {\n useInput((_input, key) => {\n if (key.return) {\n store.completeSetup();\n }\n });\n\n return (\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n justifyContent=\"center\"\n alignItems=\"center\"\n >\n <Text bold color={Colors.accent}>\n {Icons.diamond} PostHog Setup Wizard layout primitives playground\n </Text>\n <Box height={1} />\n <Text>Layout primitives for the PostHog Setup Wizard TUI.</Text>\n <Text dimColor>\n CardLayout, SplitView, TabContainer, ProgressList, and more.\n </Text>\n <Box height={1} />\n <Text color={Colors.primary}>\n Press enter to continue {Icons.triangleRight}\n </Text>\n </Box>\n );\n};\n","/**\n * LayoutDemo — Demonstrates CardLayout + SplitView.\n * Cycles alignment enums with keyboard shortcuts.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useState } from 'react';\nimport { CardLayout, SplitView } from '@ui/tui/primitives/index';\nimport { HAlign, VAlign, Colors } from '@ui/tui/styles';\n\nconst hAligns = [HAlign.Left, HAlign.Center, HAlign.Right];\nconst vAligns = [VAlign.Top, VAlign.Center, VAlign.Bottom];\nconst hLabels = ['Left', 'Center', 'Right'];\nconst vLabels = ['Top', 'Center', 'Bottom'];\n\nexport const LayoutDemo = () => {\n const [hIdx, setHIdx] = useState(0);\n const [vIdx, setVIdx] = useState(0);\n\n useInput((input) => {\n if (input === 'h') setHIdx((i) => (i + 1) % hAligns.length);\n if (input === 'v') setVIdx((i) => (i + 1) % vAligns.length);\n });\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n Layout Demo\n </Text>\n <Text dimColor>\n Press [h] to cycle hAlign ({hLabels[hIdx]}), [v] to cycle vAlign (\n {vLabels[vIdx]})\n </Text>\n <Box height={1} />\n <SplitView\n left={\n <CardLayout hAlign={hAligns[hIdx]} vAlign={vAligns[vIdx]}>\n <Box borderStyle=\"single\" borderColor={Colors.primary} paddingX={1}>\n <Text color={Colors.primary}>Left Pane</Text>\n </Box>\n </CardLayout>\n }\n right={\n <CardLayout hAlign={HAlign.Center} vAlign={VAlign.Center}>\n <Box borderStyle=\"single\" borderColor={Colors.accent} paddingX={1}>\n <Text color={Colors.accent}>Right Pane</Text>\n </Box>\n </CardLayout>\n }\n />\n </Box>\n );\n};\n","/**\n * InputDemo — Demonstrates PickerMenu (single + multi) and ConfirmationInput.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState } from 'react';\nimport { PickerMenu, ConfirmationInput } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nenum DemoStep {\n Single = 'single',\n Multi = 'multi',\n Confirm = 'confirm',\n Done = 'done',\n}\n\nexport const InputDemo = () => {\n const [step, setStep] = useState<DemoStep>(DemoStep.Single);\n const [results, setResults] = useState<string[]>([]);\n\n if (step === DemoStep.Single) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Single Select\n </Text>\n <Box height={1} />\n <PickerMenu\n message=\"Pick a color\"\n options={[\n { label: 'Red', value: 'red', hint: 'warm' },\n { label: 'Blue', value: 'blue', hint: 'cool' },\n { label: 'Green', value: 'green', hint: 'natural' },\n ]}\n onSelect={(value) => {\n setResults((prev) => [...prev, `Single: ${value}`]);\n setStep(DemoStep.Multi);\n }}\n />\n </Box>\n );\n }\n\n if (step === DemoStep.Multi) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Multi Select\n </Text>\n <Box height={1} />\n <PickerMenu\n message=\"Pick toppings\"\n mode=\"multi\"\n options={[\n { label: 'Cheese', value: 'cheese' },\n { label: 'Pepperoni', value: 'pepperoni' },\n { label: 'Mushrooms', value: 'mushrooms' },\n { label: 'Onions', value: 'onions' },\n ]}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n setResults((prev) => [...prev, `Multi: ${arr.join(', ')}`]);\n setStep(DemoStep.Confirm);\n }}\n />\n </Box>\n );\n }\n\n if (step === DemoStep.Confirm) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Confirmation\n </Text>\n <Box height={1} />\n <ConfirmationInput\n message=\"Are you satisfied with your choices?\"\n onConfirm={() => {\n setResults((prev) => [...prev, 'Confirmed: Yes']);\n setStep(DemoStep.Done);\n }}\n onCancel={() => {\n setResults((prev) => [...prev, 'Confirmed: No']);\n setStep(DemoStep.Done);\n }}\n />\n </Box>\n );\n }\n\n // done\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Results\n </Text>\n <Box height={1} />\n {results.map((r, i) => (\n <Text key={i} color={Colors.success}>\n {'\\u2714'} {r}\n </Text>\n ))}\n <Box height={1} />\n <Text dimColor>Switch away from this tab and back to restart.</Text>\n </Box>\n );\n};\n","/**\n * ProgressDemo — Demonstrates ProgressList + LoadingBox.\n * Auto-animates task progression through states.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useEffect } from 'react';\nimport { ProgressList, LoadingBox } from '@ui/tui/primitives/index';\nimport type { ProgressItem } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nconst INITIAL_ITEMS: ProgressItem[] = [\n {\n label: 'Detect framework',\n activeForm: 'Detecting framework',\n status: 'pending',\n },\n {\n label: 'Install dependencies',\n activeForm: 'Installing dependencies',\n status: 'pending',\n },\n {\n label: 'Configure PostHog',\n activeForm: 'Configuring PostHog',\n status: 'pending',\n },\n {\n label: 'Add analytics provider',\n activeForm: 'Adding analytics provider',\n status: 'pending',\n },\n { label: 'Verify setup', activeForm: 'Verifying setup', status: 'pending' },\n];\n\nexport const ProgressDemo = () => {\n const [items, setItems] = useState<ProgressItem[]>(INITIAL_ITEMS);\n const [tick, setTick] = useState(0);\n\n useEffect(() => {\n const timer = setInterval(() => {\n setTick((t) => t + 1);\n }, 1500);\n return () => clearInterval(timer);\n }, []);\n\n useEffect(() => {\n // Cycle: each tick advances the \"active\" task\n const total = INITIAL_ITEMS.length;\n // After all tasks complete, restart\n const cycle = tick % (total + 2); // +2 for a pause at the end\n\n setItems(\n INITIAL_ITEMS.map((item, i) => {\n if (i < cycle) return { ...item, status: 'completed' as const };\n if (i === cycle) return { ...item, status: 'in_progress' as const };\n return { ...item, status: 'pending' as const };\n }),\n );\n }, [tick]);\n\n const allDone = items.every((i) => i.status === 'completed');\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n Progress Demo\n </Text>\n <Text dimColor>Tasks auto-advance every 1.5s (cycles continuously)</Text>\n <Box height={1} />\n <ProgressList items={items} title=\"Setup in progress:\" />\n <Box height={1} />\n {!allDone && <LoadingBox message=\"Working...\" />}\n {allDone && (\n <Text color={Colors.success} bold>\n {'\\u2714'} All tasks complete! Restarting...\n </Text>\n )}\n </Box>\n );\n};\n","/**\n * LogDemo — Demonstrates LogViewer.\n * Writes demo log lines to a temp file, then tails it.\n */\n\nimport { Box, Text } from 'ink';\nimport { useEffect, useState } from 'react';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { LogViewer } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nconst DEMO_LOG_PATH = path.join(os.tmpdir(), 'posthog-playground.log');\n\nconst LOG_MESSAGES = [\n '[info] Playground started',\n '[info] Initializing demo components...',\n '[debug] Loading primitives barrel export',\n '[info] ScreenContainer mounted',\n '[info] TabContainer initialized with 6 tabs',\n '[debug] LayoutDemo: hAlign=Left, vAlign=Top',\n '[info] NavigationDemo: screenStack depth = 1',\n '[warn] TabDemo: arrow key conflict with outer container',\n '[info] InputDemo: waiting for user selection',\n '[info] ProgressDemo: tick 0, cycling tasks',\n '[debug] LogViewer: watching file for changes',\n '[info] All demos loaded successfully',\n];\n\nexport const LogDemo = () => {\n const [ready, setReady] = useState(false);\n\n useEffect(() => {\n // Write initial log content\n fs.writeFileSync(DEMO_LOG_PATH, LOG_MESSAGES.join('\\n') + '\\n');\n setReady(true);\n\n // Append lines periodically\n let lineNum = LOG_MESSAGES.length;\n const timer = setInterval(() => {\n lineNum++;\n const msg = `[info] Demo log line #${lineNum} — ${new Date().toISOString()}\\n`;\n fs.appendFileSync(DEMO_LOG_PATH, msg);\n }, 2000);\n\n return () => {\n clearInterval(timer);\n try {\n fs.unlinkSync(DEMO_LOG_PATH);\n } catch {\n // ignore\n }\n };\n }, []);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n Log Demo\n </Text>\n <Text dimColor>Tailing {DEMO_LOG_PATH} (new line every 2s)</Text>\n <Box height={1} />\n {ready && <LogViewer filePath={DEMO_LOG_PATH} height={15} />}\n </Box>\n );\n};\n","/**\n * RunScreenDemo — Renders the real RunScreen with a mock store.\n * Tasks auto-advance every 1.5s. Discovered features (Stripe, LLM)\n * are pre-populated so conditional tips appear.\n */\n\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\nimport { WizardStore, TaskStatus } from '@ui/tui/store';\nimport { DiscoveredFeature } from '@lib/wizard-session';\nimport {\n TabContainer,\n SplitView,\n ProgressList,\n LogViewer,\n EventPlanViewer,\n HNViewer,\n} from '@ui/tui/primitives/index';\nimport type { ProgressItem } from '@ui/tui/primitives/index';\nimport { LearnCard } from '@ui/tui/components/LearnCard';\nimport { TipsCard } from '@ui/tui/components/TipsCard';\nimport { getContentBlocks as getMigrationContentBlocks } from '@lib/programs/migration/content/index';\nimport { WIZARD_LOG_FILE } from '@utils/paths';\n\nconst MOCK_TASKS = [\n {\n label: 'Checking project structure and finding files for event tracking',\n activeForm: 'Checking project structure',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Verify PostHog dependencies',\n activeForm: 'Verifying PostHog dependencies',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Generate events plan (.posthog-events.json)',\n activeForm: 'Generating events plan',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Install posthog-js and posthog-node packages',\n activeForm: 'Installing packages',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Set up environment variables',\n activeForm: 'Setting up environment variables',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Create instrumentation-client.ts',\n activeForm: 'Creating instrumentation-client.ts',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Update next.config with rewrites',\n activeForm: 'Updating next.config',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Create posthog-server.ts',\n activeForm: 'Creating posthog-server.ts',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Add PostHog capture events to project files',\n activeForm: 'Adding capture events',\n status: TaskStatus.Pending,\n done: false,\n },\n];\n\nconst MOCK_EVENTS = [\n { name: 'page_viewed', description: 'Fires when a user views any page' },\n {\n name: 'button_clicked',\n description: 'Fires when the CTA button is clicked',\n },\n {\n name: 'form_submitted',\n description: 'Fires when the contact form is submitted',\n },\n {\n name: 'signup_started',\n description: 'Fires when a user begins the signup flow',\n },\n];\n\ninterface RunScreenDemoProps {\n store: WizardStore;\n}\n\nexport const RunScreenDemo = ({ store }: RunScreenDemoProps) => {\n const tickRef = useRef(0);\n const lastStatusRef = useRef('');\n\n // Seed the store with mock data on mount\n useEffect(() => {\n store.addDiscoveredFeature(DiscoveredFeature.Stripe);\n store.addDiscoveredFeature(DiscoveredFeature.LLM);\n store.setEventPlan(MOCK_EVENTS);\n store.pushStatus('Checking project structure.');\n lastStatusRef.current = 'Checking project structure.';\n\n // Set initial tasks\n const initial = MOCK_TASKS.map((t, i) =>\n i === 0 ? { ...t, status: TaskStatus.InProgress } : t,\n );\n store.setTasks(initial);\n }, []);\n\n // Auto-advance tasks every 1.5s\n useEffect(() => {\n const timer = setInterval(() => {\n tickRef.current += 1;\n const tick = tickRef.current;\n const total = MOCK_TASKS.length;\n const cycle = tick % (total + 3); // +3 for pause at end before restart\n\n const tasks = MOCK_TASKS.map((t, i) => {\n if (i < cycle)\n return { ...t, status: TaskStatus.Completed, done: true };\n if (i === cycle)\n return { ...t, status: TaskStatus.InProgress, done: false };\n return { ...t, status: TaskStatus.Pending, done: false };\n });\n\n store.setTasks(tasks);\n\n // Only push status when the message actually changes\n if (cycle < total) {\n const msg = MOCK_TASKS[cycle].activeForm + '...';\n if (msg !== lastStatusRef.current) {\n store.pushStatus(msg);\n lastStatusRef.current = msg;\n }\n }\n }, 1500);\n\n return () => clearInterval(timer);\n }, []);\n\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n const progressItems: ProgressItem[] = store.tasks.map((t) => ({\n label: t.label,\n activeForm: t.activeForm,\n status: t.status,\n }));\n\n const statuses =\n store.statusMessages.length > 0 ? store.statusMessages : undefined;\n\n const learnBlocks = getMigrationContentBlocks(store);\n\n const tabs = [\n {\n id: 'status',\n label: 'Status',\n component: (\n <SplitView\n left={\n store.learnCardComplete ? (\n <TipsCard store={store} />\n ) : (\n <LearnCard\n store={store}\n blocks={learnBlocks}\n onComplete={() => store.setLearnCardComplete()}\n />\n )\n }\n right={<ProgressList items={progressItems} title=\"Tasks\" />}\n />\n ),\n },\n ...(store.eventPlan.length > 0\n ? [\n {\n id: 'events',\n label: 'Event plan',\n component: <EventPlanViewer events={store.eventPlan} />,\n },\n ]\n : []),\n {\n id: 'logs',\n label: 'Tail logs',\n component: <LogViewer filePath={WIZARD_LOG_FILE} />,\n },\n {\n id: 'hn',\n label: 'HN',\n component: <HNViewer />,\n },\n ];\n\n return (\n <TabContainer\n tabs={tabs}\n statusMessage={statuses}\n expandableStatus\n store={store}\n />\n );\n};\n","/**\n * HealthCheckDemo — Playground demo for health check UI components.\n *\n * Shows the ModalOverlay with ServiceHealthList, cycling through states:\n * 1. Checking (spinner) — 2 seconds\n * 2. Blocking outage modal (Anthropic down, npm degraded)\n *\n * Renders components directly (not HealthCheckScreen) to avoid useInput\n * conflicts with TabContainer's key handling.\n */\n\nimport { useEffect, useState } from 'react';\nimport { Box, Text } from 'ink';\nimport { LoadingBox, ModalOverlay } from '@ui/tui/primitives/index';\nimport { Icons } from '@ui/tui/styles';\nimport { ServiceHealthList } from '@ui/tui/components/ServiceHealthList';\nimport { getBlockingServiceKeys } from '@lib/health-checks/readiness';\nimport { ServiceHealthStatus } from '@lib/health-checks/types';\nimport type { AllServicesHealth } from '@lib/health-checks/types';\n\nconst HEALTHY = { status: ServiceHealthStatus.Healthy } as const;\n\nconst MOCK_HEALTH: AllServicesHealth = {\n anthropic: { status: ServiceHealthStatus.Down, rawIndicator: 'major' },\n posthogOverall: HEALTHY,\n posthogComponents: { status: ServiceHealthStatus.Healthy },\n github: HEALTHY,\n npmOverall: {\n status: ServiceHealthStatus.Degraded,\n rawIndicator: 'minor',\n },\n npmComponents: {\n status: ServiceHealthStatus.Degraded,\n degradedOrDownComponents: [\n {\n name: 'Registry API',\n status: ServiceHealthStatus.Degraded,\n rawStatus: 'degraded_performance',\n },\n ],\n },\n cloudflareOverall: HEALTHY,\n cloudflareComponents: { status: ServiceHealthStatus.Healthy },\n llmGateway: HEALTHY,\n mcp: HEALTHY,\n githubReleases: HEALTHY,\n};\n\nexport const HealthCheckDemo = () => {\n const [showOutage, setShowOutage] = useState(false);\n\n useEffect(() => {\n const timer = setTimeout(() => setShowOutage(true), 2000);\n return () => clearTimeout(timer);\n }, []);\n\n if (!showOutage) {\n return (\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n alignItems=\"center\"\n justifyContent=\"center\"\n >\n <LoadingBox message=\"Checking service status...\" />\n </Box>\n );\n }\n\n const blockingKeys = getBlockingServiceKeys(MOCK_HEALTH);\n\n return (\n <ModalOverlay\n borderColor=\"red\"\n title={`${Icons.warning} Ongoing service disruptions`}\n width={72}\n footer={\n <Box marginLeft={2}>\n <Text dimColor>\n Continue [Enter] / Exit [Esc] (disabled in playground)\n </Text>\n </Box>\n }\n >\n <Box flexDirection=\"column\" marginBottom={1}>\n <Box marginBottom={1}>\n <Text>\n <Text color=\"red\">{Icons.squareFilled}</Text>\n <Text dimColor> Down </Text>\n <Text color=\"#DC9300\">{Icons.squareFilled}</Text>\n <Text dimColor> Degraded</Text>\n </Text>\n </Box>\n\n <ServiceHealthList\n health={MOCK_HEALTH}\n filterKeys={blockingKeys}\n showHealthy={false}\n />\n </Box>\n\n <Text dimColor>\n The wizard may not work reliably while services are affected.\n </Text>\n </ModalOverlay>\n );\n};\n","import { Box, Text } from 'ink';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { IssueTable } from '@ui/tui/screens/doctor/IssueTable';\nimport type { HealthIssue } from '@lib/programs/posthog-doctor/index';\n\nconst NOW = '2026-04-27T15:00:00Z';\n\nconst MOCK_ISSUES: HealthIssue[] = [\n mock('1', 'ingestion_lag', 'critical'),\n mock('2', 'ingestion_warning', 'critical'),\n mock('3', 'materialized_view_failure', 'critical'),\n mock('4', 'sdk_outdated', 'warning'),\n mock('5', 'no_pageleave_events', 'warning'),\n mock('6', 'scroll_depth', 'warning'),\n mock('7', 'web_vitals', 'warning'),\n mock('8', 'reverse_proxy', 'info'),\n mock('9', 'authorized_urls', 'info'),\n mock('10', 'unrecognised_kind_with_a_long_slug_that_should_truncate', 'info'),\n];\n\nfunction mock(\n id: string,\n kind: string,\n severity: HealthIssue['severity'],\n): HealthIssue {\n return {\n id,\n kind,\n severity,\n status: 'active',\n dismissed: false,\n created_at: NOW,\n updated_at: NOW,\n };\n}\n\nexport const DoctorReportDemo = () => {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n PostHog Doctor Report\n </Text>\n <Text dimColor>\n Project 12345 {Icons.bullet} https://us.i.posthog.com\n </Text>\n <Box marginTop={1}>\n <Text>\n {MOCK_ISSUES.length} active issues: 3 critical, 4 warning, 3 info\n </Text>\n </Box>\n <IssueTable issues={MOCK_ISSUES} />\n </Box>\n );\n};\n","/**\n * ModalDemo — Playground demo for the ModalOverlay primitive.\n *\n * Shows several modal variants: info, warning, error, and one with feedback text.\n */\n\nimport { Box, Text } from 'ink';\nimport { ModalOverlay } from '@ui/tui/primitives/index';\nimport { Icons } from '@ui/tui/styles';\n\nexport const ModalDemo = () => {\n return (\n <Box flexDirection=\"column\" gap={1} flexGrow={1}>\n <ModalOverlay borderColor=\"cyan\" title=\"Info Modal\" width={60}>\n <Text>A simple informational modal with default styling.</Text>\n </ModalOverlay>\n\n <ModalOverlay\n borderColor=\"#DC9300\"\n title={`${Icons.warning} Warning Modal`}\n width={60}\n feedback=\"Something needs your attention.\"\n >\n <Text>This modal includes a feedback message shown in yellow.</Text>\n </ModalOverlay>\n\n <ModalOverlay\n borderColor=\"red\"\n title={`${Icons.warning} Error Modal`}\n width={60}\n footer={\n <Box marginLeft={2}>\n <Text dimColor>\n Continue [Enter] / Exit [Esc] (disabled in playground)\n </Text>\n </Box>\n }\n >\n <Text>This modal has a footer section below a divider.</Text>\n </ModalOverlay>\n </Box>\n );\n};\n","/**\n * McpDemo — Playground demo for the MCP client selection screen.\n *\n * Uses a mock McpInstaller that simulates detecting three editors,\n * a short install delay, and a successful result.\n */\n\nimport { WizardStore } from '@ui/tui/store';\nimport { McpScreen } from '@ui/tui/screens/McpScreen';\nimport type {\n McpInstaller,\n McpClientInfo,\n} from '@ui/tui/services/mcp-installer';\n\nconst MOCK_CLIENTS: McpClientInfo[] = [\n { name: 'Claude Code', supportsPlugin: true },\n { name: 'Cursor', supportsPlugin: true },\n { name: 'VS Code', supportsPlugin: false },\n {\n name: 'Claude Desktop/Web',\n supportsPlugin: false,\n finish: {\n url: 'https://claude.ai/directory/connectors/posthog',\n instruction: 'Sign in and click \"Connect\" to finish.',\n },\n },\n];\n\nfunction createMockInstaller(): McpInstaller {\n return {\n async detectClients() {\n await new Promise((r) => setTimeout(r, 800));\n return MOCK_CLIENTS;\n },\n async install(clientNames) {\n await new Promise((r) => setTimeout(r, 1500));\n return clientNames;\n },\n async installPlugins(clientNames) {\n await new Promise((r) => setTimeout(r, 800));\n return clientNames.filter(\n (name) => MOCK_CLIENTS.find((c) => c.name === name)?.supportsPlugin,\n );\n },\n async remove() {\n await new Promise((r) => setTimeout(r, 1000));\n return MOCK_CLIENTS.map((c) => c.name);\n },\n };\n}\n\ninterface McpDemoProps {\n store: WizardStore;\n}\n\nexport const McpDemo = ({ store }: McpDemoProps) => {\n return (\n <McpScreen store={store} installer={createMockInstaller()} mode=\"install\" />\n );\n};\n","/**\n * McpSuggestedPromptsDemo — Playground demo for the post-MCP\n * suggested-prompts screen.\n *\n * Mounts the real McpSuggestedPromptsScreen with mock services so every\n * phase (Choose → Authenticating → Greeting → PromptPicker → Running →\n * FollowUp) can be previewed without touching the network. The Greeting\n * phase auto-advances; FollowUp re-enters Running when a follow-up is\n * picked, building a conversation tree up to MAX_PROMPT_RUNS deep.\n *\n * R cycle role (null → founder → product → ... → data → null)\n * F cycle framework (null → nextjs → vue → swift → django → null)\n * X remount the screen (useful after Exit)\n *\n * O OAuth outcome: success | error\n * L login delay: 0ms (skip UI) | 2000ms | 6000ms\n * S stream script: short-text | with-tools | mid-stream-error\n * C chunk delay: 50ms | 200ms | 800ms\n *\n * Tip: switch S to \"with-tools\" and the FollowUp picker after the run\n * will show context-aware suggestions based on the last tool (mock\n * tool names are MCP-prefixed and pass through the normalization in\n * getFollowUps).\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\nimport { McpSuggestedPromptsScreen } from '@ui/tui/screens/McpSuggestedPromptsScreen';\nimport { Colors } from '@ui/tui/styles';\nimport { Integration } from '@lib/constants';\nimport { McpOutcome } from '@lib/wizard-session';\nimport { TAILORED_ROLES } from '@lib/mcp-role-prompts';\nimport type {\n AgentChunk,\n McpSuggestedPromptsServices,\n} from '@ui/tui/services/mcp-suggested-prompts-services';\n\n// One Integration per framework family so cycling exercises every\n// override bucket in mcp-role-prompts.ts.\nconst FAMILY_INTEGRATIONS: Array<Integration | null> = [\n null,\n Integration.nextjs, // fullstack\n Integration.vue, // frontend-web\n Integration.swift, // mobile\n Integration.django, // backend\n];\n\nconst ROLE_CYCLE: Array<string | null> = [null, ...TAILORED_ROLES];\n\nconst LOGIN_DELAYS_MS = [0, 2000, 6000] as const;\nconst CHUNK_DELAYS_MS = [50, 200, 800] as const;\ntype LoginOutcome = 'success' | 'error';\ntype StreamScript = 'short-text' | 'with-tools' | 'mid-stream-error';\nconst LOGIN_OUTCOMES: LoginOutcome[] = ['success', 'error'];\nconst STREAM_SCRIPTS: StreamScript[] = [\n 'short-text',\n 'with-tools',\n 'mid-stream-error',\n];\n\nconst SCRIPTS: Record<StreamScript, AgentChunk[]> = {\n 'short-text': [\n { kind: 'text', text: 'Looking at your project…' },\n { kind: 'text', text: ' here is a quick read of the last 24 hours.' },\n {\n kind: 'text',\n text: ' You had 12,308 events from 2,144 distinct users.',\n },\n { kind: 'text', text: '\\n\\nNothing unusual stood out.' },\n { kind: 'done', sessionId: 'mock-session-aaa' },\n ],\n 'with-tools': [\n { kind: 'text', text: 'Looking up your project…' },\n {\n kind: 'tool-call',\n toolName: 'mcp__posthog-wizard__query-trends',\n detail: '{ event: \"signup\", interval: \"day\", window: \"7d\" }',\n },\n {\n kind: 'tool-result',\n toolName: 'mcp__posthog-wizard__query-trends',\n detail: '{ rows: 7, total: 482, change: +8.4% }',\n },\n {\n kind: 'text',\n text: '\\nSignups are up 8.4% week-over-week — 482 over the last 7 days.',\n },\n {\n kind: 'tool-call',\n toolName: 'mcp__posthog-wizard__create-insight',\n detail: '{ name: \"Weekly signups\", query: <trends>, save: true }',\n },\n {\n kind: 'tool-result',\n toolName: 'mcp__posthog-wizard__create-insight',\n detail:\n '{ id: \"ins_abc123\", url: \"https://app.posthog.com/i/ins_abc123\" }',\n },\n {\n kind: 'text',\n text: '\\nInsight saved as \"Weekly signups\" — pinned to your team dashboard.',\n },\n { kind: 'done', sessionId: 'mock-session-aaa' },\n ],\n 'mid-stream-error': [\n { kind: 'text', text: 'Looking at the most recent errors…' },\n {\n kind: 'tool-call',\n toolName: 'mcp__posthog-wizard__list-errors',\n detail: '{ window: \"7d\", limit: 5 }',\n },\n {\n kind: 'error',\n text: 'MCP server returned 503 — try again in a moment.',\n },\n ],\n};\n\ninterface MockConfig {\n role: string | null;\n loginOutcome: LoginOutcome;\n loginDelayMs: number;\n script: StreamScript;\n chunkDelayMs: number;\n slackConnected: boolean;\n}\n\ninterface McpSuggestedPromptsDemoProps {\n store: WizardStore;\n}\n\nconst delay = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Returns a McpSuggestedPromptsServices instance whose behavior is read\n * fresh from `configRef` on every call. Hotkey changes take effect on\n * the *next* invocation without remounting the screen.\n */\nfunction createMockServices(\n store: WizardStore,\n configRef: { current: MockConfig },\n): McpSuggestedPromptsServices {\n return {\n performLogin: async () => {\n const cfg = configRef.current;\n store.setLoginUrl('https://app.posthog.com/oauth/playground-mock');\n await delay(cfg.loginDelayMs);\n store.setLoginUrl(null);\n\n if (cfg.loginOutcome === 'error') {\n throw new Error('Mock OAuth rejected — exercising error path.');\n }\n\n return {\n credentials: {\n accessToken: 'phx_mock',\n projectApiKey: 'phc_mock',\n host: 'http://127.0.0.1:1',\n projectId: 1,\n },\n roleAtOrganization: cfg.role,\n user: {\n distinct_id: 'demo-distinct-id',\n uuid: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',\n id: 1,\n email: 'joe@demo.example.com',\n first_name: 'Joe',\n last_name: 'Demo',\n role_at_organization: cfg.role,\n team: {\n id: 1,\n uuid: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',\n organization: 'cccccccc-cccc-cccc-cccc-cccccccccccc',\n api_token: 'phc_mock',\n project_id: 1,\n name: 'Demo team',\n timezone: 'UTC',\n },\n organization: {\n id: 'cccccccc-cccc-cccc-cccc-cccccccccccc',\n name: 'Demo org',\n slug: 'demo-org',\n membership_level: 1,\n },\n organizations: [\n {\n id: 'cccccccc-cccc-cccc-cccc-cccccccccccc',\n name: 'Demo org',\n membership_level: 1,\n },\n ],\n },\n };\n },\n\n checkSlackConnected: () =>\n Promise.resolve(configRef.current.slackConnected),\n\n runPromptStreaming: ({ signal }) => mockStream(configRef, signal),\n };\n}\n\nasync function* mockStream(\n configRef: { current: MockConfig },\n signal: AbortSignal,\n): AsyncIterable<AgentChunk> {\n const cfg = configRef.current;\n const chunks = SCRIPTS[cfg.script];\n for (const chunk of chunks) {\n if (signal.aborted) return;\n await delay(cfg.chunkDelayMs);\n if (signal.aborted) return;\n yield chunk;\n }\n}\n\nexport const McpSuggestedPromptsDemo = ({\n store,\n}: McpSuggestedPromptsDemoProps) => {\n const [roleIdx, setRoleIdx] = useState(2); // 'product' — has overrides\n const [familyIdx, setFamilyIdx] = useState(1); // nextjs (fullstack)\n const [resetKey, setResetKey] = useState(0);\n const [loginOutcomeIdx, setLoginOutcomeIdx] = useState(0);\n const [loginDelayIdx, setLoginDelayIdx] = useState(1); // 2000ms default\n const [scriptIdx, setScriptIdx] = useState(1); // 'with-tools' default\n const [chunkDelayIdx, setChunkDelayIdx] = useState(1); // 200ms default\n const [slackConnected, setSlackConnected] = useState(false);\n\n const role = ROLE_CYCLE[roleIdx];\n const integration = FAMILY_INTEGRATIONS[familyIdx];\n const loginOutcome = LOGIN_OUTCOMES[loginOutcomeIdx];\n const loginDelayMs = LOGIN_DELAYS_MS[loginDelayIdx];\n const script = STREAM_SCRIPTS[scriptIdx];\n const chunkDelayMs = CHUNK_DELAYS_MS[chunkDelayIdx];\n\n // Ref-based config so hotkeys can update behavior without remounting.\n const configRef = useRef<MockConfig>({\n role,\n loginOutcome,\n loginDelayMs,\n script,\n chunkDelayMs,\n slackConnected,\n });\n configRef.current = {\n role,\n loginOutcome,\n loginDelayMs,\n script,\n chunkDelayMs,\n slackConnected,\n };\n\n // Stable services instance — reads from configRef each call.\n const services = useMemo(() => createMockServices(store, configRef), [store]);\n\n // Seed framework + a fake \"installed\" MCP state. setMcpComplete here\n // is harmless — production would have set it from the McpScreen step\n // before this screen mounts.\n useEffect(() => {\n store.setMcpComplete(McpOutcome.Installed, ['Claude Code']);\n store.setFrameworkConfig(integration ?? null, null);\n }, [store, integration]);\n\n useInput((input) => {\n if (input === 'R' || input === 'r') {\n setRoleIdx((i) => (i + 1) % ROLE_CYCLE.length);\n setResetKey((k) => k + 1);\n } else if (input === 'F' || input === 'f') {\n setFamilyIdx((i) => (i + 1) % FAMILY_INTEGRATIONS.length);\n setResetKey((k) => k + 1);\n } else if (input === 'X' || input === 'x') {\n store.setCredentials(null);\n store.setRoleAtOrganization(null);\n setResetKey((k) => k + 1);\n } else if (input === 'O' || input === 'o') {\n setLoginOutcomeIdx((i) => (i + 1) % LOGIN_OUTCOMES.length);\n } else if (input === 'L' || input === 'l') {\n setLoginDelayIdx((i) => (i + 1) % LOGIN_DELAYS_MS.length);\n } else if (input === 'S' || input === 's') {\n setScriptIdx((i) => (i + 1) % STREAM_SCRIPTS.length);\n } else if (input === 'C' || input === 'c') {\n setChunkDelayIdx((i) => (i + 1) % CHUNK_DELAYS_MS.length);\n } else if (input === 'K' || input === 'k') {\n setSlackConnected((v) => !v);\n }\n });\n\n const familyLabel = integration ?? 'unknown';\n\n return (\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <Text dimColor>\n R role · F framework · X reset · O oauth · L login-delay · S script · C\n chunk-delay · K slack-connected\n </Text>\n <Text dimColor>\n role={String(role)} · integration={familyLabel} · login={loginOutcome}/\n {loginDelayMs}ms · script={script}/{chunkDelayMs}ms · slack=\n {slackConnected ? 'connected' : 'not-connected'}\n </Text>\n <Box marginTop={1} flexDirection=\"column\" flexGrow={1}>\n <McpSuggestedPromptsScreen\n key={resetKey}\n store={store}\n services={services}\n />\n </Box>\n <Box marginTop={1}>\n <Text color={Colors.muted} dimColor>\n (mock services — no real OAuth, no real LLM. Press R/F to preview\n different prompt kits; O/L/S/C to flip mock outcomes.)\n </Text>\n </Box>\n </Box>\n );\n};\n","/**\n * KeyboardHintsDemo — Demonstrates the KeyboardHintsBar with all input types.\n *\n * Cycles through SinglePicker, MultiPicker, GroupedPicker, and Confirmation\n * so the user can see the hints bar update automatically for each component.\n * The bar appears at the bottom of the screen and stays visible, updating to\n * match the active component.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, type ReactNode } from 'react';\nimport {\n PickerMenu,\n GroupedPickerMenu,\n ConfirmationInput,\n} from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nenum DemoStep {\n SingleSelect = 'single',\n MultiSelect = 'multi',\n GroupedSelect = 'grouped',\n Confirmation = 'confirm',\n Done = 'done',\n}\n\nconst STEP_LABELS: Record<DemoStep, string> = {\n [DemoStep.SingleSelect]: 'Single Select — hints: ↑↓ navigate, enter select',\n [DemoStep.MultiSelect]:\n 'Multi Select — hints: ↑↓ navigate, space toggle, enter confirm',\n [DemoStep.GroupedSelect]:\n 'Grouped Select — hints: ↑↓ navigate, space toggle, a toggle all, enter confirm',\n [DemoStep.Confirmation]:\n 'Confirmation — hints: ←→ switch, enter confirm, esc cancel',\n [DemoStep.Done]: 'Done',\n};\n\nexport const KeyboardHintsDemo = () => {\n const [step, setStep] = useState<DemoStep>(DemoStep.SingleSelect);\n const [log, setLog] = useState<string[]>([]);\n\n const addLog = (msg: string) => setLog((prev) => [...prev.slice(-4), msg]);\n\n if (step === DemoStep.SingleSelect) {\n return (\n <Wrapper step={step} log={log}>\n <PickerMenu\n message=\"Pick a framework\"\n options={[\n { label: 'Next.js', value: 'next' },\n { label: 'React', value: 'react' },\n { label: 'Vue', value: 'vue' },\n { label: 'Svelte', value: 'svelte' },\n ]}\n columns={2}\n onSelect={(v) => {\n addLog(`Single: ${String(v)}`);\n setStep(DemoStep.MultiSelect);\n }}\n />\n </Wrapper>\n );\n }\n\n if (step === DemoStep.MultiSelect) {\n return (\n <Wrapper step={step} log={log}>\n <PickerMenu\n message=\"Pick features to enable\"\n mode=\"multi\"\n options={[\n { label: 'Analytics', value: 'analytics' },\n { label: 'Session Replay', value: 'replay' },\n { label: 'Feature Flags', value: 'flags' },\n { label: 'Surveys', value: 'surveys' },\n ]}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n addLog(`Multi: ${arr.join(', ')}`);\n setStep(DemoStep.GroupedSelect);\n }}\n />\n </Wrapper>\n );\n }\n\n if (step === DemoStep.GroupedSelect) {\n return (\n <Wrapper step={step} log={log}>\n <GroupedPickerMenu\n message=\"Select integrations\"\n groups={{\n Frontend: [\n { label: 'React SDK', value: 'react-sdk' },\n { label: 'Web Analytics', value: 'web-analytics' },\n ],\n Backend: [\n { label: 'Node SDK', value: 'node-sdk' },\n { label: 'Python SDK', value: 'python-sdk' },\n ],\n Tooling: [\n { label: 'MCP Server', value: 'mcp' },\n { label: 'CLI', value: 'cli' },\n ],\n }}\n onSelect={(values) => {\n addLog(`Grouped: ${values.join(', ')}`);\n setStep(DemoStep.Confirmation);\n }}\n />\n </Wrapper>\n );\n }\n\n if (step === DemoStep.Confirmation) {\n return (\n <Wrapper step={step} log={log}>\n <ConfirmationInput\n message=\"Apply these settings?\"\n onConfirm={() => {\n addLog('Confirmed!');\n setStep(DemoStep.Done);\n }}\n onCancel={() => {\n addLog('Cancelled');\n setStep(DemoStep.Done);\n }}\n />\n </Wrapper>\n );\n }\n\n return (\n <Wrapper step={step} log={log}>\n <Text dimColor>\n All steps complete. Switch away from this tab and back to restart.\n </Text>\n </Wrapper>\n );\n};\n\nconst Wrapper = ({\n step,\n log,\n children,\n}: {\n step: DemoStep;\n log: string[];\n children: ReactNode;\n}) => (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Keyboard Hints Demo\n </Text>\n <Text dimColor>{STEP_LABELS[step]}</Text>\n <Box height={1} />\n {children}\n {log.length > 0 && (\n <>\n <Box height={1} />\n <Text dimColor>Log:</Text>\n {log.map((entry, i) => (\n <Text key={i} color={Colors.muted}>\n {' '}\n {entry}\n </Text>\n ))}\n </>\n )}\n </Box>\n);\n","/**\n * AuditChecksDemo — renders the AuditChecksViewer against a mock ledger so\n * the scroll/expand/sort behavior can be verified in the playground without\n * running the actual audit agent.\n */\n\nimport { Box } from 'ink';\nimport type { AuditCheck } from '@lib/programs/audit/types';\nimport { AuditChecksViewer } from '@ui/tui/screens/audit/AuditChecksViewer/AuditChecksViewer';\n\nconst MOCK_CHECKS: AuditCheck[] = [\n {\n id: 'sdk-installed',\n area: 'Installation',\n label: 'PostHog SDK installed',\n status: 'pass',\n file: 'package.json',\n details: 'posthog-js@1.260.0 found in dependencies.',\n },\n {\n id: 'sdk-up-to-date',\n area: 'Installation',\n label: 'SDK version up to date',\n status: 'warning',\n details: 'installed 1.260.0, latest 1.372.6 — more than one minor behind.',\n },\n {\n id: 'init-correct',\n area: 'Installation',\n label: 'Initialization is correct',\n status: 'warning',\n file: 'index.js:12',\n details:\n 'Init runs at module load with no singleton guard; calling posthog.init() multiple times can cause duplicate events.',\n },\n {\n id: 'identify-stable-distinct-id',\n area: 'Identification',\n label: 'Stable distinct_id (not session UUID)',\n status: 'error',\n file: 'index.js:18',\n details:\n 'distinct_id is crypto.randomUUID() — a per-session ephemeral UUID that resets on every page load. Replace with an authenticated user id.',\n },\n {\n id: 'identify-not-late',\n area: 'Identification',\n label: 'identify() called before captures / flag evals',\n status: 'pass',\n file: 'index.js:18',\n details:\n 'posthog.identify() is called before any posthog.capture() calls in this module.',\n },\n {\n id: 'cross-runtime-distinct-id',\n area: 'Identification',\n label: 'Same distinct_id across client and server',\n status: 'pass',\n details: 'Single runtime — no cross-runtime check needed.',\n },\n {\n id: 'identify-reset-on-logout',\n area: 'Identification',\n label: 'reset() called on logout / account switch',\n status: 'error',\n file: 'auth.ts:44',\n details:\n 'signOut() clears app auth state but never calls posthog.reset(), so the next identify() on this device can merge into the prior user profile.',\n },\n {\n id: 'capture-event-names-static',\n area: 'Event Capture',\n label: 'Event names are static and consistent',\n status: 'pass',\n file: 'index.js:21',\n details:\n \"All posthog.capture() calls use static string literals ('pageview', 'cta_clicked'); no template literals or dynamic variables found.\",\n },\n {\n id: 'capture-uses-proxy',\n area: 'Event Capture',\n label: 'Captures route through a reverse proxy',\n status: 'warning',\n file: 'index.js:13',\n details:\n 'api_host is set to the default PostHog US ingest host (https://us.i.posthog.com) rather than a first-party reverse proxy — ad/tracking blockers can silently drop these events.',\n },\n {\n id: 'capture-growth-events',\n area: 'Event Capture',\n label: 'Key activation events captured',\n status: 'pending',\n },\n];\n\nexport const AuditChecksDemo = () => (\n <Box flexDirection=\"column\" flexGrow={1}>\n <AuditChecksViewer checks={MOCK_CHECKS} />\n </Box>\n);\n","/**\n * LearnDeckDemo — flip through every program's content deck one block at\n * a time so wording, pauses, and visual blocks can be reviewed without\n * waiting for the auto-advance timer.\n *\n * n / p step block (next / previous)\n * [ / ] switch deck\n * r replay current block (re-runs the reveal animation)\n *\n * Arrow keys are reserved for the playground's tab switcher, so this demo\n * uses letter keys.\n *\n * Decks are pulled from `PROGRAM_REGISTRY` so every program that ships a\n * deck is reviewable here. Migration also gets per-variant entries (one\n * per `--product=<id>` choice) so the variant composer in\n * `migration/content/index.tsx` can be exercised side-by-side with the\n * generic deck.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useMemo, useState } from 'react';\nimport {\n ContentSequencer,\n ProgressList,\n SplitView,\n TextRevealMode,\n} from '@ui/tui/primitives/index';\nimport type { ContentBlock, ProgressItem } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\nimport type { WizardStore } from '@ui/tui/store';\nimport { PROGRAM_REGISTRY } from '@lib/programs/program-registry';\nimport { AUDIT_AREA_SLIDES } from '@ui/tui/screens/audit/slides/index';\nimport { AUDIT_3000_AREA_SLIDES } from '@ui/tui/screens/audit-3000/slides/index';\nimport type { AreaSlide } from '@ui/tui/screens/audit/slides/shared';\n\ninterface Deck {\n id: string;\n label: string;\n blocks: ContentBlock[];\n}\n\n/**\n * Fake task list to fill the right-hand pane so the SplitView layout matches\n * what operators actually see during a real run. Mix of statuses so the\n * spinner glyph, the in-progress row, and completed rows all render.\n */\nconst MOCK_TASKS: ProgressItem[] = [\n {\n label: 'Confirm Statsig is in use',\n activeForm: 'Confirming Statsig is in use',\n status: 'completed',\n },\n {\n label: 'Install PostHog',\n activeForm: 'Installing PostHog',\n status: 'completed',\n },\n {\n label: 'Plan call site replacements',\n activeForm: 'Planning call site replacements',\n status: 'in_progress',\n },\n {\n label: 'Rewrite call sites',\n activeForm: 'Rewriting call sites',\n status: 'pending',\n },\n {\n label: 'Remove Statsig',\n activeForm: 'Removing Statsig',\n status: 'pending',\n },\n {\n label: 'Verify the project still builds',\n activeForm: 'Verifying the build',\n status: 'pending',\n },\n {\n label: 'Write migration report',\n activeForm: 'Writing migration report',\n status: 'pending',\n },\n];\n\ninterface LearnDeckDemoProps {\n store: WizardStore;\n}\n\nexport const LearnDeckDemo = ({ store }: LearnDeckDemoProps) => {\n const decks: Deck[] = useMemo(() => {\n const all: Deck[] = [];\n\n // Every program in the registry that ships a deck. Seed the store's\n // skillId from the program config so decks that template the skill\n // name (e.g. agent-skill's \"Running the <skill> skill...\") render the\n // real value instead of \"unknown\".\n for (const program of PROGRAM_REGISTRY) {\n if (!program.getContentBlocks) continue;\n const stub = program.skillId\n ? withSessionOverride(store, { skillId: program.skillId })\n : store;\n all.push({\n id: `program:${program.id}`,\n label: `${program.id} (${program.command ?? 'default'})${\n program.skillId ? ` · skill: ${program.skillId}` : ''\n }`,\n blocks: program.getContentBlocks(stub),\n });\n }\n\n // Audit + audit-3000 ship their own per-area slide model (not the\n // ContentBlock deck most programs use). Adapt each AreaSlide into a\n // flat ContentBlock list so the flipper can review them the same way.\n all.push({\n id: 'audit:area-slides',\n label: 'audit · area slides',\n blocks: areaSlidesToBlocks(AUDIT_AREA_SLIDES),\n });\n all.push({\n id: 'audit-3000:area-slides',\n label: 'audit-3000 · area slides',\n blocks: areaSlidesToBlocks(AUDIT_3000_AREA_SLIDES),\n });\n\n return all;\n }, [store]);\n\n const [deckIdx, setDeckIdx] = useState(0);\n const [blockIdx, setBlockIdx] = useState(0);\n const [replayKey, setReplayKey] = useState(0);\n\n const deck = decks[deckIdx];\n const block = deck.blocks[blockIdx];\n\n useInput((input) => {\n if (input === 'p') {\n setBlockIdx((i) => Math.max(0, i - 1));\n } else if (input === 'n') {\n setBlockIdx((i) => Math.min(deck.blocks.length - 1, i + 1));\n } else if (input === '[') {\n setDeckIdx((i) => (i - 1 + decks.length) % decks.length);\n setBlockIdx(0);\n } else if (input === ']') {\n setDeckIdx((i) => (i + 1) % decks.length);\n setBlockIdx(0);\n } else if (input === 'r') {\n setReplayKey((k) => k + 1);\n }\n });\n\n const pauseMs =\n typeof block === 'object' && 'pause' in block ? block.pause : '—';\n const blockKind = describeBlockKind(block);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <Text bold color={Colors.accent}>\n Learn deck flipper\n </Text>\n <Text dimColor>n/p step block · [ ] switch deck · r replay</Text>\n <Box height={1} />\n\n <Text>\n <Text bold>Deck:</Text> {deck.label}{' '}\n <Text dimColor>\n ({deckIdx + 1}/{decks.length})\n </Text>\n </Text>\n <Text>\n <Text bold>Block:</Text> {blockIdx + 1}/{deck.blocks.length}{' '}\n <Text dimColor>\n · kind: {blockKind} · pause: {String(pauseMs)}ms\n </Text>\n </Text>\n <Box height={1} />\n\n <Box flexGrow={1}>\n <SplitView\n left={\n <ContentSequencer\n key={`${deck.id}-${blockIdx}-${replayKey}`}\n blocks={deck.blocks.slice(0, blockIdx + 1)}\n mode={TextRevealMode.SentenceBySentence}\n startDelay={0}\n initialBlockIdx={blockIdx}\n />\n }\n right={<ProgressList items={MOCK_TASKS} title=\"Tasks\" />}\n />\n </Box>\n </Box>\n );\n};\n\n/**\n * Build a store proxy that exposes an overridden `session` while keeping\n * every prototype method (e.g. `setStatusExpanded`) and atom reference\n * intact. A plain `{...store, session: ...}` spread would drop the\n * prototype, so anything that called a store method on the result would\n * crash at render time.\n */\nfunction withSessionOverride(\n store: WizardStore,\n patch: Partial<WizardStore['session']>,\n): WizardStore {\n const stub = Object.create(Object.getPrototypeOf(store)) as WizardStore;\n Object.assign(stub, store);\n Object.defineProperty(stub, 'session', {\n value: { ...store.session, ...patch },\n writable: false,\n configurable: true,\n });\n return stub;\n}\n\n/**\n * Adapter: turn each audit AreaSlide into a sequence of ContentBlocks so it\n * fits the flipper's renderer. One block per intro paragraph, one for the\n * visual when present. Each slide is preceded by a heading block naming the\n * area so flipping between areas is obvious.\n */\nfunction areaSlidesToBlocks(slides: AreaSlide[]): ContentBlock[] {\n const out: ContentBlock[] = [];\n for (const slide of slides) {\n out.push({\n content: (\n <Text bold color={Colors.accent}>\n {slide.area}\n </Text>\n ),\n pause: 3000,\n });\n for (const paragraph of slide.intro) {\n out.push({ content: paragraph, pause: 5000 });\n }\n if (slide.visual) {\n out.push({\n content: slide.visual,\n pause: 8000,\n persist: true,\n });\n }\n out.push({ type: 'clear', pause: 1000 });\n }\n return out;\n}\n\nfunction describeBlockKind(block: ContentBlock): string {\n if (typeof block === 'string') return 'string';\n if (typeof block === 'object' && block !== null) {\n if ('type' in block && block.type === 'clear') return 'clear';\n if ('type' in block && block.type === 'lines') return 'lines';\n if ('content' in block) {\n return typeof block.content === 'string' ? 'text' : 'jsx';\n }\n }\n return 'unknown';\n}\n","/**\n * EndScreensDemo — Playground demo for the screens shown at the end of\n * a wizard run.\n *\n * Mounts the real SlackConnectScreen and OutroScreen against the shared\n * playground store so every variant can be previewed without a run:\n *\n * V switch view (slack-connect → outro)\n * K toggle Slack state (connected ↔ not connected) — simulates the\n * poll flipping the screen when the user finishes the browser OAuth\n * O cycle outro kind (success → error → cancel)\n *\n * The playground credentials are re-pointed at a localhost dead-end\n * while this demo is mounted, so SlackConnectScreen's poll fails fast\n * without real network traffic; `K` drives `session.slackConnected`\n * directly, which is the same store key the poll writes.\n *\n * KeepSkillsScreen is intentionally absent — it reads the install dir's\n * .claude/skills/ from disk and calls process.exit() when none are\n * found, which would kill the playground.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useEffect, useState, useSyncExternalStore } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\nimport { SlackConnectScreen } from '@ui/tui/screens/SlackConnectScreen';\nimport { OutroScreen } from '@ui/tui/screens/OutroScreen';\nimport { Colors } from '@ui/tui/styles';\nimport { OutroKind, type OutroData } from '@lib/wizard-session';\n\nconst VIEWS = ['slack-connect', 'outro'] as const;\ntype View = (typeof VIEWS)[number];\n\nconst OUTRO_KINDS = [OutroKind.Success, OutroKind.Error, OutroKind.Cancel];\n\nconst OUTRO_FIXTURES: Record<OutroKind, OutroData> = {\n [OutroKind.Success]: {\n kind: OutroKind.Success,\n message: 'PostHog is set up!',\n changes: [\n 'Installed posthog-js and wired the provider',\n 'Added pageview + pageleave capture',\n 'Instrumented 4 product events',\n ],\n reportFile: 'posthog-setup-report.md',\n dashboardUrl: 'https://us.posthog.com/project/1/dashboard/42',\n notebookUrl: 'https://us.posthog.com/project/1/notebooks/demo',\n docsUrl: 'https://posthog.com/docs/libraries/next-js',\n },\n [OutroKind.Error]: {\n kind: OutroKind.Error,\n message: 'The agent hit an error',\n body: 'The integration step failed before any files were changed.\\nRe-run the wizard to try again.',\n docsUrl: 'https://posthog.com/docs/ai-engineering/ai-wizard',\n },\n [OutroKind.Cancel]: {\n kind: OutroKind.Cancel,\n message: 'Cancelled — no changes were made',\n },\n};\n\ninterface EndScreensDemoProps {\n store: WizardStore;\n}\n\nexport const EndScreensDemo = ({ store }: EndScreensDemoProps) => {\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n const [viewIdx, setViewIdx] = useState(0);\n const [outroKindIdx, setOutroKindIdx] = useState(0);\n\n const view: View = VIEWS[viewIdx];\n const outroKind = OUTRO_KINDS[outroKindIdx];\n\n // The playground pre-seeds fake credentials pointed at the real\n // PostHog host, which SlackConnectScreen's poll would hit. Swap the\n // host for a localhost dead-end while this demo is mounted (restore\n // on unmount — tab switches unmount). The credentials must stay\n // non-null: the router derives the active screen from session state,\n // and nulling them drops the playground out of the 'run' screen,\n // unmounting the tab bar and resetting it to the first tab.\n useEffect(() => {\n const previous = store.session.credentials;\n store.setCredentials({\n accessToken: 'playground',\n projectApiKey: 'playground',\n host: 'http://127.0.0.1:9',\n projectId: 0,\n });\n return () => {\n store.setCredentials(previous);\n };\n }, [store]);\n\n // Seed the outro fixture each screen reads. slackConnected starts\n // null (unknown) so the first paint shows the nudge variant, exactly\n // like a wizard run before the poll's first response.\n useEffect(() => {\n store.setOutroData(OUTRO_FIXTURES[outroKind]);\n }, [store, outroKind]);\n\n useInput((input) => {\n if (input === 'V' || input === 'v') {\n setViewIdx((i) => (i + 1) % VIEWS.length);\n } else if (input === 'K' || input === 'k') {\n store.setSlackConnected(store.session.slackConnected !== true);\n } else if (input === 'O' || input === 'o') {\n setOutroKindIdx((i) => (i + 1) % OUTRO_KINDS.length);\n }\n });\n\n const slackState =\n store.session.slackConnected === true ? 'connected' : 'not-connected';\n\n return (\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <Text dimColor>V view · K slack state · O outro kind</Text>\n <Text dimColor>\n view={view} · slack={slackState} · outro={outroKind}\n </Text>\n <Box marginTop={1} flexDirection=\"column\" flexGrow={1}>\n {view === 'slack-connect' ? (\n <SlackConnectScreen store={store} />\n ) : (\n <OutroScreen store={store} />\n )}\n </Box>\n <Box marginTop={1}>\n <Text color={Colors.muted} dimColor>\n (session-driven previews — the Slack poll points at a localhost\n dead-end; K flips the same store key the poll writes.)\n </Text>\n </Box>\n </Box>\n );\n};\n","/**\n * PlaygroundApp — Root component for the primitives playground.\n *\n * Two screens mirroring the real wizard flow:\n * intro → (press enter) → run (tabbed demo view)\n */\n\nimport { ScreenContainer, TabContainer } from '@ui/tui/primitives/index';\nimport type { WizardStore } from '@ui/tui/store';\nimport { WelcomeDemo } from './demos/WelcomeDemo.js';\nimport { LayoutDemo } from './demos/LayoutDemo.js';\nimport { InputDemo } from './demos/InputDemo.js';\nimport { ProgressDemo } from './demos/ProgressDemo.js';\nimport { LogDemo } from './demos/LogDemo.js';\nimport { RunScreenDemo } from './demos/RunScreenDemo.js';\nimport { HealthCheckDemo } from './demos/HealthCheckDemo.js';\nimport { DoctorReportDemo } from './demos/DoctorReportDemo.js';\nimport { ModalDemo } from './demos/ModalDemo.js';\nimport { McpDemo } from './demos/McpDemo.js';\nimport { McpSuggestedPromptsDemo } from './demos/McpSuggestedPromptsDemo.js';\nimport { KeyboardHintsDemo } from './demos/KeyboardHintsDemo.js';\nimport { AuditChecksDemo } from './demos/AuditChecksDemo.js';\nimport { LearnDeckDemo } from './demos/LearnDeckDemo.js';\nimport { EndScreensDemo } from './demos/EndScreensDemo.js';\n\ninterface PlaygroundAppProps {\n store: WizardStore;\n}\n\nexport const PlaygroundApp = ({ store }: PlaygroundAppProps) => {\n const tabs = [\n { id: 'layout', label: 'Layout', component: <LayoutDemo /> },\n { id: 'input', label: 'Input', component: <InputDemo /> },\n { id: 'progress', label: 'Progress', component: <ProgressDemo /> },\n { id: 'logs', label: 'Logs', component: <LogDemo /> },\n {\n id: 'run',\n label: 'RunScreen',\n component: <RunScreenDemo store={store} />,\n },\n {\n id: 'health',\n label: 'HealthCheck',\n component: <HealthCheckDemo />,\n },\n {\n id: 'doctor',\n label: 'Doctor',\n component: <DoctorReportDemo />,\n },\n {\n id: 'modal',\n label: 'Modal',\n component: <ModalDemo />,\n },\n {\n id: 'mcp',\n label: 'MCP',\n component: <McpDemo store={store} />,\n },\n {\n id: 'mcp-tutorial',\n label: 'MCP tutorial',\n component: <McpSuggestedPromptsDemo store={store} />,\n },\n {\n id: 'hints',\n label: 'KeyHints',\n component: <KeyboardHintsDemo />,\n },\n {\n id: 'audit-checks',\n label: 'Audit checks',\n component: <AuditChecksDemo />,\n },\n {\n id: 'learn-deck',\n label: 'Learn deck',\n component: <LearnDeckDemo store={store} />,\n },\n {\n id: 'end-screens',\n label: 'End screens',\n component: <EndScreensDemo store={store} />,\n },\n ];\n\n return (\n <ScreenContainer\n store={store}\n screens={{\n intro: <WelcomeDemo store={store} />,\n run: (\n <TabContainer\n tabs={tabs}\n statusMessage=\"Primitives Playground — use arrow keys to switch tabs\"\n />\n ),\n }}\n />\n );\n};\n","/**\n * start-playground.ts — Launches the TUI primitives playground.\n */\n\nimport { render } from 'ink';\nimport { createElement } from 'react';\nimport { WizardStore } from '@ui/tui/store';\nimport { PlaygroundApp } from './PlaygroundApp.js';\nimport { WizardReadiness } from '@lib/health-checks/readiness';\n\nexport function startPlayground(version: string): void {\n const store = new WizardStore();\n store.version = version;\n\n // Pre-fill session so the router skips health-check, auth, and setup,\n // landing on 'run' after the intro screen.\n // dismissOutage() guards against the onInit health-check async result\n // overwriting this with WizardReadiness.No before the user presses enter.\n store.setReadinessResult({\n decision: WizardReadiness.Yes,\n health: {} as never,\n reasons: [],\n });\n store.dismissOutage();\n store.setCredentials({\n accessToken: 'fake',\n projectApiKey: 'fake',\n host: 'https://app.posthog.com',\n projectId: 0,\n });\n\n const { unmount, waitUntilExit } = render(\n createElement(PlaygroundApp, { store }),\n );\n\n void waitUntilExit().then(() => {\n unmount();\n process.exit(0);\n });\n}\n","import { VERSION } from '@lib/version';\nimport { startPlayground } from '@ui/tui/playground/start-playground';\n\n/** Launch the TUI primitives playground. */\nexport function runPlayground(): void {\n startPlayground(VERSION);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,MAAa,eAAe,EAAE,YAA8B;AAC1D,WAAU,QAAQ,QAAQ;AACxB,MAAI,IAAI,OACN,OAAM,eAAe;GAEvB;AAEF,QACE,qBAAC,KAAD;EACE,eAAc;EACd,UAAU;EACV,gBAAe;EACf,YAAW;YAJb;GAME,qBAAC,MAAD;IAA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