@posthog/wizard 1.32.1 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/src/android/android-wizard-agent.js +2 -0
  2. package/dist/src/android/android-wizard-agent.js.map +1 -1
  3. package/dist/src/angular/angular-wizard-agent.js +2 -1
  4. package/dist/src/angular/angular-wizard-agent.js.map +1 -1
  5. package/dist/src/astro/astro-wizard-agent.js +2 -1
  6. package/dist/src/astro/astro-wizard-agent.js.map +1 -1
  7. package/dist/src/django/django-wizard-agent.js +4 -1
  8. package/dist/src/django/django-wizard-agent.js.map +1 -1
  9. package/dist/src/fastapi/fastapi-wizard-agent.js +4 -1
  10. package/dist/src/fastapi/fastapi-wizard-agent.js.map +1 -1
  11. package/dist/src/flask/flask-wizard-agent.js +4 -1
  12. package/dist/src/flask/flask-wizard-agent.js.map +1 -1
  13. package/dist/src/laravel/laravel-wizard-agent.js +2 -0
  14. package/dist/src/laravel/laravel-wizard-agent.js.map +1 -1
  15. package/dist/src/lib/__tests__/package-manager-detection.test.d.ts +1 -0
  16. package/dist/src/lib/__tests__/package-manager-detection.test.js +195 -0
  17. package/dist/src/lib/__tests__/package-manager-detection.test.js.map +1 -0
  18. package/dist/src/lib/__tests__/wizard-tools.test.d.ts +1 -0
  19. package/dist/src/lib/__tests__/wizard-tools.test.js +200 -0
  20. package/dist/src/lib/__tests__/wizard-tools.test.js.map +1 -0
  21. package/dist/src/lib/agent-interface.d.ts +2 -0
  22. package/dist/src/lib/agent-interface.js +12 -9
  23. package/dist/src/lib/agent-interface.js.map +1 -1
  24. package/dist/src/lib/agent-runner.js +7 -4
  25. package/dist/src/lib/agent-runner.js.map +1 -1
  26. package/dist/src/lib/framework-config.d.ts +15 -2
  27. package/dist/src/lib/framework-config.js +8 -1
  28. package/dist/src/lib/framework-config.js.map +1 -1
  29. package/dist/src/lib/package-manager-detection.d.ts +36 -0
  30. package/dist/src/lib/package-manager-detection.js +166 -0
  31. package/dist/src/lib/package-manager-detection.js.map +1 -0
  32. package/dist/src/lib/wizard-tools.d.ts +40 -0
  33. package/dist/src/lib/{env-file-tools.js → wizard-tools.js} +95 -46
  34. package/dist/src/lib/wizard-tools.js.map +1 -0
  35. package/dist/src/nextjs/nextjs-wizard-agent.js +2 -1
  36. package/dist/src/nextjs/nextjs-wizard-agent.js.map +1 -1
  37. package/dist/src/nuxt/nuxt-wizard-agent.js +2 -1
  38. package/dist/src/nuxt/nuxt-wizard-agent.js.map +1 -1
  39. package/dist/src/python/python-wizard-agent.js +4 -1
  40. package/dist/src/python/python-wizard-agent.js.map +1 -1
  41. package/dist/src/react-native/react-native-wizard-agent.js +2 -1
  42. package/dist/src/react-native/react-native-wizard-agent.js.map +1 -1
  43. package/dist/src/react-router/react-router-wizard-agent.js +2 -1
  44. package/dist/src/react-router/react-router-wizard-agent.js.map +1 -1
  45. package/dist/src/run.js +13 -3
  46. package/dist/src/run.js.map +1 -1
  47. package/dist/src/svelte/svelte-wizard-agent.js +2 -1
  48. package/dist/src/svelte/svelte-wizard-agent.js.map +1 -1
  49. package/dist/src/swift/swift-wizard-agent.js +2 -0
  50. package/dist/src/swift/swift-wizard-agent.js.map +1 -1
  51. package/dist/src/tanstack-router/tanstack-router-wizard-agent.js +2 -1
  52. package/dist/src/tanstack-router/tanstack-router-wizard-agent.js.map +1 -1
  53. package/dist/src/tanstack-start/tanstack-start-wizard-agent.js +2 -1
  54. package/dist/src/tanstack-start/tanstack-start-wizard-agent.js.map +1 -1
  55. package/dist/src/vue/vue-wizard-agent.js +2 -1
  56. package/dist/src/vue/vue-wizard-agent.js.map +1 -1
  57. package/package.json +1 -1
  58. package/dist/src/lib/env-file-tools.d.ts +0 -11
  59. package/dist/src/lib/env-file-tools.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../../src/lib/agent-interface.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AAyLH,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MAAM,EAAE,CAAC;gBAC/B,IAAA,iBAAS,EAAC,2BAA2B,EAAE;oBACrC,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM;oBAC5B,UAAU,EAAE,OAAO,CAAC,WAAW;iBAChC,CAAC,CAAC;YACL,CAAC;YACD,MAAM;QACR,CAAC;QAED;YACE,wCAAwC;YACxC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;gBAClB,IAAA,aAAK,EAAC,2BAA2B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,MAAM;IACV,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared agent interface for PostHog wizards\n * Uses Claude Agent SDK directly with PostHog LLM gateway\n */\n\nimport path from 'path';\nimport clack from '../utils/clack';\nimport { debug, logToFile, initLogFile, LOG_FILE_PATH } from '../utils/debug';\nimport type { WizardOptions } from '../utils/types';\nimport { analytics } from '../utils/analytics';\nimport {\n WIZARD_INTERACTION_EVENT_NAME,\n WIZARD_REMARK_EVENT_NAME,\n} from './constants';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls';\nimport { LINTING_TOOLS } from './safe-tools';\nimport { createEnvFileServer, ENV_FILE_TOOL_NAMES } from './env-file-tools';\n\n// Dynamic import cache for ESM module\nlet _sdkModule: any = null;\nasync function getSDKModule(): Promise<any> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\n/**\n * Get the path to the bundled Claude Code CLI from the SDK package.\n * This ensures we use the SDK's bundled version rather than the user's installed Claude Code.\n */\nfunction getClaudeCodeExecutablePath(): string {\n // require.resolve finds the package's main entry, then we get cli.js from same dir\n const sdkPackagePath = require.resolve('@anthropic-ai/claude-agent-sdk');\n return path.join(path.dirname(sdkPackagePath), 'cli.js');\n}\n\n// Using `any` because typed imports from ESM modules require import attributes\n// syntax which prettier cannot parse. See PR discussion for details.\ntype SDKMessage = any;\ntype McpServersConfig = any;\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the PostHog MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** Agent could not access the PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n}\n\nexport type AgentConfig = {\n workingDirectory: string;\n posthogMcpUrl: string;\n posthogApiKey: string;\n posthogApiHost: string;\n additionalMcpServers?: Record<string, { url: string }>;\n};\n\n/**\n * Internal configuration object returned by initializeAgent\n */\ntype AgentRunConfig = {\n workingDirectory: string;\n mcpServers: McpServersConfig;\n model: string;\n};\n\n/**\n * Package managers that can be used to run commands.\n */\nconst PACKAGE_MANAGERS = [\n // JavaScript\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n 'npx',\n // Python\n 'pip',\n 'pip3',\n 'poetry',\n 'pipenv',\n 'uv',\n];\n\n/**\n * Safe scripts/commands that can be run with any package manager.\n * Uses startsWith matching, so 'build' matches 'build', 'build:prod', etc.\n * Note: Linting tools are in LINTING_TOOLS and checked separately.\n */\nconst SAFE_SCRIPTS = [\n // Package installation\n 'install',\n 'add',\n 'ci',\n // Build\n 'build',\n // Type checking (various naming conventions)\n 'tsc',\n 'typecheck',\n 'type-check',\n 'check-types',\n 'types',\n // Linting/formatting script names (actual tools are in LINTING_TOOLS)\n 'lint',\n 'format',\n];\n\n/**\n * Dangerous shell operators that could allow command injection.\n * Note: We handle `2>&1` and `| tail/head` separately as safe patterns.\n * Note: `&&` is allowed for specific safe patterns like skill installation.\n */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n/**\n * Check if command is a PostHog skill installation from MCP.\n * We control the MCP server, so we only need to verify:\n * 1. It installs to .claude/skills/\n * 2. It downloads from our GitHub releases or localhost (dev)\n */\nfunction isSkillInstallCommand(command: string): boolean {\n if (!command.startsWith('mkdir -p .claude/skills/')) return false;\n\n const urlMatch = command.match(/curl -sL ['\"]([^'\"]+)['\"]/);\n if (!urlMatch) return false;\n\n const url = urlMatch[1];\n return (\n url.startsWith('https://github.com/PostHog/examples/releases/') ||\n /^http:\\/\\/localhost:\\d+\\//.test(url)\n );\n}\n\n/**\n * Check if command is an allowed package manager command.\n * Matches: <pkg-manager> [run|exec] <safe-script> [args...]\n */\nfunction matchesAllowedPrefix(command: string): boolean {\n const parts = command.split(/\\s+/);\n if (parts.length === 0 || !PACKAGE_MANAGERS.includes(parts[0])) {\n return false;\n }\n\n // Skip 'run' or 'exec' if present\n let scriptIndex = 1;\n if (parts[scriptIndex] === 'run' || parts[scriptIndex] === 'exec') {\n scriptIndex++;\n }\n\n // Get the script/command portion (may include args)\n const scriptPart = parts.slice(scriptIndex).join(' ');\n\n // Check if script starts with any safe script name or linting tool\n return (\n SAFE_SCRIPTS.some((safe) => scriptPart.startsWith(safe)) ||\n LINTING_TOOLS.some((tool) => scriptPart.startsWith(tool))\n );\n}\n\n/**\n * Permission hook that allows only safe commands.\n * - Package manager install commands\n * - Build/typecheck/lint commands for verification\n * - Piping to tail/head for output limiting is allowed\n * - Stderr redirection (2>&1) is allowed\n * - PostHog skill installation commands from MCP\n */\nexport function wizardCanUseTool(\n toolName: string,\n input: Record<string, unknown>,\n):\n | { behavior: 'allow'; updatedInput: Record<string, unknown> }\n | { behavior: 'deny'; message: string } {\n // Block direct reads/writes of .env files — use env-file-tools MCP instead\n if (toolName === 'Read' || toolName === 'Write' || toolName === 'Edit') {\n const filePath = typeof input.file_path === 'string' ? input.file_path : '';\n const basename = path.basename(filePath);\n if (basename.startsWith('.env')) {\n logToFile(`Denying ${toolName} on env file: ${filePath}`);\n return {\n behavior: 'deny',\n message: `Direct ${toolName} of ${basename} is not allowed. Use the env-file-tools MCP server (check_env_keys / set_env_values) to read or modify environment variables.`,\n };\n }\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Block Grep when it directly targets a .env file.\n // Note: ripgrep skips dotfiles (like .env*) by default during directory traversal,\n // so broad searches like `Grep { path: \".\" }` are already safe.\n if (toolName === 'Grep') {\n const grepPath = typeof input.path === 'string' ? input.path : '';\n if (grepPath && path.basename(grepPath).startsWith('.env')) {\n logToFile(`Denying Grep on env file: ${grepPath}`);\n return {\n behavior: 'deny',\n message: `Grep on ${path.basename(\n grepPath,\n )} is not allowed. Use the env-file-tools MCP server (check_env_keys) to check environment variables.`,\n };\n }\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Allow all other non-Bash tools\n if (toolName !== 'Bash') {\n return { behavior: 'allow', updatedInput: input };\n }\n\n const command = (\n typeof input.command === 'string' ? input.command : ''\n ).trim();\n\n // Check for PostHog skill installation command (before dangerous operator check)\n // These commands use && chaining but are generated by MCP with a strict format\n if (isSkillInstallCommand(command)) {\n logToFile(`Allowing skill installation command: ${command}`);\n debug(`Allowing skill installation command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Block definitely dangerous operators: ; ` $ ( )\n if (DANGEROUS_OPERATORS.test(command)) {\n logToFile(`Denying bash command with dangerous operators: ${command}`);\n debug(`Denying bash command with dangerous operators: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'dangerous operators',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Shell operators like ; \\` $ ( ) are not permitted.`,\n };\n }\n\n // Normalize: remove safe stderr redirection (2>&1, 2>&2, etc.)\n const normalized = command.replace(/\\s*\\d*>&\\d+\\s*/g, ' ').trim();\n\n // Check for pipe to tail/head (safe output limiting)\n const pipeMatch = normalized.match(/^(.+?)\\s*\\|\\s*(tail|head)(\\s+\\S+)*\\s*$/);\n if (pipeMatch) {\n const baseCommand = pipeMatch[1].trim();\n\n // Block if base command has pipes or & (multiple chaining)\n if (/[|&]/.test(baseCommand)) {\n logToFile(`Denying bash command with multiple pipes: ${command}`);\n debug(`Denying bash command with multiple pipes: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'multiple pipes',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only single pipe to tail/head is permitted.`,\n };\n }\n\n if (matchesAllowedPrefix(baseCommand)) {\n logToFile(`Allowing bash command with output limiter: ${command}`);\n debug(`Allowing bash command with output limiter: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n }\n\n // Block remaining pipes and & (not covered by tail/head case above)\n if (/[|&]/.test(normalized)) {\n logToFile(`Denying bash command with pipe/&: ${command}`);\n debug(`Denying bash command with pipe/&: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'disallowed pipe',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Pipes are only permitted with tail/head for output limiting.`,\n };\n }\n\n // Check if command starts with any allowed prefix (package manager commands)\n if (matchesAllowedPrefix(normalized)) {\n logToFile(`Allowing bash command: ${command}`);\n debug(`Allowing bash command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n logToFile(`Denying bash command: ${command}`);\n debug(`Denying bash command: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'not in allowlist',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only install, build, typecheck, lint, and formatting commands are permitted.`,\n };\n}\n\n/**\n * Initialize agent configuration for the LLM gateway\n */\nexport async function initializeAgent(\n config: AgentConfig,\n options: WizardOptions,\n): Promise<AgentRunConfig> {\n // Initialize log file for this run\n initLogFile();\n logToFile('Agent initialization starting');\n logToFile('Install directory:', options.installDir);\n\n clack.log.step('Initializing Claude agent...');\n\n try {\n // Configure LLM gateway environment variables (inherited by SDK subprocess)\n const gatewayUrl = getLlmGatewayUrlFromHost(config.posthogApiHost);\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = config.posthogApiKey;\n // Use CLAUDE_CODE_OAUTH_TOKEN to override any stored /login credentials\n process.env.CLAUDE_CODE_OAUTH_TOKEN = config.posthogApiKey;\n // Disable experimental betas (like input_examples) that the LLM gateway doesn't support\n process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = 'true';\n\n logToFile('Configured LLM gateway:', gatewayUrl);\n\n // Configure MCP server with PostHog authentication\n const mcpServers: McpServersConfig = {\n 'posthog-wizard': {\n type: 'http',\n url: config.posthogMcpUrl,\n headers: {\n Authorization: `Bearer ${config.posthogApiKey}`,\n },\n },\n ...Object.fromEntries(\n Object.entries(config.additionalMcpServers ?? {}).map(\n ([name, { url }]) => [name, { type: 'http', url }],\n ),\n ),\n };\n\n // Add in-process env file tools (secret values never leave the machine)\n const envFileServer = await createEnvFileServer(config.workingDirectory);\n mcpServers['env-file-tools'] = envFileServer;\n\n const agentRunConfig: AgentRunConfig = {\n workingDirectory: config.workingDirectory,\n mcpServers,\n model: 'claude-opus-4-5-20251101',\n };\n\n logToFile('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n\n if (options.debug) {\n debug('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n }\n\n clack.log.step(`Verbose logs: ${LOG_FILE_PATH}`);\n clack.log.success(\"Agent initialized. Let's get cooking!\");\n return agentRunConfig;\n } catch (error) {\n clack.log.error(`Failed to initialize agent: ${(error as Error).message}`);\n logToFile('Agent initialization error:', error);\n debug('Agent initialization error:', error);\n throw error;\n }\n}\n\n/**\n * Execute an agent with the provided prompt and options\n * Handles the full lifecycle: spinner, execution, error handling\n *\n * @returns An object containing any error detected in the agent's output\n */\nexport async function runAgent(\n agentConfig: AgentRunConfig,\n prompt: string,\n options: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n config?: {\n estimatedDurationMinutes?: number;\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n },\n): Promise<{ error?: AgentErrorType; message?: string }> {\n const {\n estimatedDurationMinutes = 8,\n spinnerMessage = 'Customizing your PostHog setup...',\n successMessage = 'PostHog integration complete',\n errorMessage = 'Integration failed',\n } = config ?? {};\n\n const { query } = await getSDKModule();\n\n clack.log.step(\n `This whole process should take about ${estimatedDurationMinutes} minutes including error checking and fixes.\\n\\nGrab some coffee!`,\n );\n\n spinner.start(spinnerMessage);\n\n const cliPath = getClaudeCodeExecutablePath();\n logToFile('Starting agent run');\n logToFile('Claude Code executable:', cliPath);\n logToFile('Prompt:', prompt);\n\n const startTime = Date.now();\n const collectedText: string[] = [];\n // Track if we received a successful result (before any cleanup errors)\n let receivedSuccessResult = false;\n\n // Workaround for SDK bug: stdin closes before canUseTool responses can be sent.\n // The fix is to use an async generator for the prompt that stays open until\n // the result is received, keeping the stdin stream alive for permission responses.\n // See: https://github.com/anthropics/claude-code/issues/4775\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n let signalDone: () => void;\n const resultReceived = new Promise<void>((resolve) => {\n signalDone = resolve;\n });\n\n const createPromptStream = async function* () {\n yield {\n type: 'user',\n session_id: '',\n message: { role: 'user', content: prompt },\n parent_tool_use_id: null,\n };\n await resultReceived;\n };\n\n // Helper to handle successful completion (used in normal path and race condition recovery)\n const completeWithSuccess = (\n suppressedError?: Error,\n ): { error?: AgentErrorType; message?: string } => {\n const durationMs = Date.now() - startTime;\n const durationSeconds = Math.round(durationMs / 1000);\n\n if (suppressedError) {\n logToFile(\n `Ignoring post-completion error, agent completed successfully in ${durationSeconds}s`,\n );\n logToFile('Suppressed error:', suppressedError.message);\n } else {\n logToFile(`Agent run completed in ${durationSeconds}s`);\n }\n\n // Extract and capture the agent's reflection on the run\n const outputText = collectedText.join('\\n');\n const remarkRegex = new RegExp(\n `${AgentSignals.WIZARD_REMARK.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)(?:\\\\n|$)`,\n 's',\n );\n const remarkMatch = outputText.match(remarkRegex);\n if (remarkMatch && remarkMatch[1]) {\n const remark = remarkMatch[1].trim();\n if (remark) {\n analytics.capture(WIZARD_REMARK_EVENT_NAME, { remark });\n }\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'agent integration completed',\n duration_ms: durationMs,\n duration_seconds: durationSeconds,\n });\n spinner.stop(successMessage);\n return {};\n };\n\n try {\n // Tools needed for the wizard:\n // - File operations: Read, Write, Edit\n // - Search: Glob, Grep\n // - Commands: Bash (with restrictions via canUseTool)\n // - MCP discovery: ListMcpResourcesTool (to find available skills)\n // - Skills: Skill (to load installed PostHog skills)\n // MCP tools (PostHog) come from mcpServers, not allowedTools\n const allowedTools = [\n 'Read',\n 'Write',\n 'Edit',\n 'Glob',\n 'Grep',\n 'Bash',\n 'ListMcpResourcesTool',\n 'Skill',\n ...ENV_FILE_TOOL_NAMES,\n ];\n\n const response = query({\n prompt: createPromptStream(),\n options: {\n model: agentConfig.model,\n cwd: agentConfig.workingDirectory,\n permissionMode: 'acceptEdits',\n mcpServers: agentConfig.mcpServers,\n // Load skills from project's .claude/skills/ directory\n settingSources: ['project'],\n // Explicitly enable required tools including Skill\n allowedTools,\n env: {\n ...process.env,\n // Prevent user's Anthropic API key from overriding the wizard's OAuth token\n ANTHROPIC_API_KEY: undefined,\n },\n canUseTool: (toolName: string, input: unknown) => {\n logToFile('canUseTool called:', { toolName, input });\n const result = wizardCanUseTool(\n toolName,\n input as Record<string, unknown>,\n );\n logToFile('canUseTool result:', result);\n return Promise.resolve(result);\n },\n tools: { type: 'preset', preset: 'claude_code' },\n // Capture stderr from CLI subprocess for debugging\n stderr: (data: string) => {\n logToFile('CLI stderr:', data);\n if (options.debug) {\n debug('CLI stderr:', data);\n }\n },\n // Stop hook to have the agent reflect on its run\n hooks: {\n Stop: [\n {\n hooks: [\n (input: { stop_hook_active: boolean }) => {\n logToFile('Stop hook triggered', {\n stop_hook_active: input.stop_hook_active,\n });\n\n // Only ask for reflection on first stop (not after reflection is provided)\n if (input.stop_hook_active) {\n logToFile('Stop hook: allowing stop (already reflected)');\n return {}; // Allow stopping\n }\n\n logToFile('Stop hook: requesting reflection');\n return {\n decision: 'block',\n reason: `Before concluding, provide a brief remark about what information or guidance would have been useful to have in the integration prompt or documentation for this run. Specifically cite anything that would have prevented tool failures, erroneous edits, or other wasted turns. Format your response exactly as: ${AgentSignals.WIZARD_REMARK} Your remark here`,\n };\n },\n ],\n timeout: 30,\n },\n ],\n },\n },\n });\n\n // Process the async generator\n for await (const message of response) {\n // Pass receivedSuccessResult so handleSDKMessage can suppress user-facing error\n // output for post-success cleanup errors while still logging them to file\n handleSDKMessage(\n message,\n options,\n spinner,\n collectedText,\n receivedSuccessResult,\n );\n\n // Signal completion when result received\n if (message.type === 'result') {\n // Track successful results before any potential cleanup errors\n // The SDK may emit a second error result during cleanup due to a race condition\n if (message.subtype === 'success' && !message.is_error) {\n receivedSuccessResult = true;\n }\n signalDone!();\n }\n }\n\n const outputText = collectedText.join('\\n');\n\n // Check for error markers in the agent's output\n if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {\n logToFile('Agent error: MCP_MISSING');\n spinner.stop('Agent could not access PostHog MCP');\n return { error: AgentErrorType.MCP_MISSING };\n }\n\n if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {\n logToFile('Agent error: RESOURCE_MISSING');\n spinner.stop('Agent could not access setup resource');\n return { error: AgentErrorType.RESOURCE_MISSING };\n }\n\n // Check for API errors (rate limits, etc.)\n // Extract just the API error line(s), not the entire output\n const apiErrorMatch = outputText.match(/API Error: [^\\n]+/g);\n const apiErrorMessage = apiErrorMatch\n ? apiErrorMatch.join('\\n')\n : 'Unknown API error';\n\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error: RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: apiErrorMessage };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error: API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: apiErrorMessage };\n }\n\n return completeWithSuccess();\n } catch (error) {\n // Signal done to unblock the async generator\n signalDone!();\n\n // If we already received a successful result, the error is from SDK cleanup\n // This happens due to a race condition: the SDK tries to send a cleanup command\n // after the prompt stream closes, but streaming mode is still active.\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n if (receivedSuccessResult) {\n return completeWithSuccess(error as Error);\n }\n\n // Check if we collected an API error before the exception was thrown\n const outputText = collectedText.join('\\n');\n\n // Extract just the API error line(s), not the entire output\n const apiErrorMatch = outputText.match(/API Error: [^\\n]+/g);\n const apiErrorMessage = apiErrorMatch\n ? apiErrorMatch.join('\\n')\n : 'Unknown API error';\n\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error (caught): RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: apiErrorMessage };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error (caught): API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: apiErrorMessage };\n }\n\n // No API error found, re-throw the original exception\n spinner.stop(errorMessage);\n clack.log.error(`Error: ${(error as Error).message}`);\n logToFile('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n }\n}\n\n/**\n * Handle SDK messages and provide user feedback\n *\n * @param receivedSuccessResult - If true, suppress user-facing error output for cleanup errors\n * while still logging to file. The SDK may emit a second error\n * result after success due to cleanup race conditions.\n */\nfunction handleSDKMessage(\n message: SDKMessage,\n options: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n collectedText: string[],\n receivedSuccessResult = false,\n): void {\n logToFile(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));\n\n if (options.debug) {\n debug(`SDK Message type: ${message.type}`);\n }\n\n switch (message.type) {\n case 'assistant': {\n // Extract text content from assistant messages\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n collectedText.push(block.text);\n\n // Check for [STATUS] markers\n const statusRegex = new RegExp(\n `^.*${AgentSignals.STATUS.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)$`,\n 'm',\n );\n const statusMatch = block.text.match(statusRegex);\n if (statusMatch) {\n spinner.stop(statusMatch[1].trim());\n spinner.start('Integrating PostHog...');\n }\n }\n }\n }\n break;\n }\n\n case 'result': {\n // Check is_error flag - can be true even when subtype is 'success'\n if (message.is_error) {\n logToFile('Agent result with error:', message.result);\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n // Only show errors to user if we haven't already succeeded.\n // Post-success errors are SDK cleanup noise (telemetry failures, streaming\n // mode race conditions). Full message already logged above via JSON dump.\n if (message.errors && !receivedSuccessResult) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n } else if (message.subtype === 'success') {\n logToFile('Agent completed successfully');\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n } else {\n logToFile('Agent result with error:', message.result);\n // Error result - only show to user if we haven't already succeeded.\n // Full message already logged above via JSON dump.\n if (message.errors && !receivedSuccessResult) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n }\n break;\n }\n\n case 'system': {\n if (message.subtype === 'init') {\n logToFile('Agent session initialized', {\n model: message.model,\n tools: message.tools?.length,\n mcpServers: message.mcp_servers,\n });\n }\n break;\n }\n\n default:\n // Log other message types for debugging\n if (options.debug) {\n debug(`Unhandled message type: ${message.type}`);\n }\n break;\n }\n}\n"]}
1
+ {"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../../src/lib/agent-interface.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AA2LH,4CAoIC;AAKD,0CA6EC;AAQD,4BAwRC;AA/qBD,gDAAwB;AACxB,2DAAmC;AACnC,0CAA8E;AAE9E,kDAA+C;AAC/C,2CAGqB;AACrB,wCAAyD;AACzD,6CAA6C;AAC7C,iDAA4E;AAG5E,sCAAsC;AACtC,IAAI,UAAU,GAAQ,IAAI,CAAC;AAC3B,KAAK,UAAU,YAAY;IACzB,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,UAAU,GAAG,MAAM,MAAM,CAAC,gCAAgC,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,SAAS,2BAA2B;IAClC,mFAAmF;IACnF,MAAM,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,gCAAgC,CAAC,CAAC;IACzE,OAAO,cAAI,CAAC,IAAI,CAAC,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC3D,CAAC;AAOY,QAAA,YAAY,GAAG;IAC1B,iEAAiE;IACjE,MAAM,EAAE,UAAU;IAClB,yEAAyE;IACzE,iBAAiB,EAAE,qBAAqB;IACxC,qEAAqE;IACrE,sBAAsB,EAAE,0BAA0B;IAClD,oEAAoE;IACpE,aAAa,EAAE,iBAAiB;CACxB,CAAC;AAIX;;;GAGG;AACH,IAAY,cASX;AATD,WAAY,cAAc;IACxB,oDAAoD;IACpD,oDAAkC,CAAA;IAClC,gDAAg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,mDAAmD;gBACnD,IAAI,OAAO,CAAC,MAAM,IAAI,CAAC,qBAAqB,EAAE,CAAC;oBAC7C,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;wBACjC,eAAK,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC;wBACjC,IAAA,iBAAS,EAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;oBAC3B,CAAC;gBACH,CAAC;YACH,CAAC;YACD,MAAM;QACR,CAAC;QAED,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,IAAI,OAAO,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;gBAC/B,IAAA,iBAAS,EAAC,2BAA2B,EAAE;oBACrC,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM;oBAC5B,UAAU,EAAE,OAAO,CAAC,WAAW;iBAChC,CAAC,CAAC;YACL,CAAC;YACD,MAAM;QACR,CAAC;QAED;YACE,wCAAwC;YACxC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;gBAClB,IAAA,aAAK,EAAC,2BAA2B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,MAAM;IACV,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared agent interface for PostHog wizards\n * Uses Claude Agent SDK directly with PostHog LLM gateway\n */\n\nimport path from 'path';\nimport clack from '../utils/clack';\nimport { debug, logToFile, initLogFile, LOG_FILE_PATH } from '../utils/debug';\nimport type { WizardOptions } from '../utils/types';\nimport { analytics } from '../utils/analytics';\nimport {\n WIZARD_INTERACTION_EVENT_NAME,\n WIZARD_REMARK_EVENT_NAME,\n} from './constants';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls';\nimport { LINTING_TOOLS } from './safe-tools';\nimport { createWizardToolsServer, WIZARD_TOOL_NAMES } from './wizard-tools';\nimport type { PackageManagerDetector } from './package-manager-detection';\n\n// Dynamic import cache for ESM module\nlet _sdkModule: any = null;\nasync function getSDKModule(): Promise<any> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\n/**\n * Get the path to the bundled Claude Code CLI from the SDK package.\n * This ensures we use the SDK's bundled version rather than the user's installed Claude Code.\n */\nfunction getClaudeCodeExecutablePath(): string {\n // require.resolve finds the package's main entry, then we get cli.js from same dir\n const sdkPackagePath = require.resolve('@anthropic-ai/claude-agent-sdk');\n return path.join(path.dirname(sdkPackagePath), 'cli.js');\n}\n\n// Using `any` because typed imports from ESM modules require import attributes\n// syntax which prettier cannot parse. See PR discussion for details.\ntype SDKMessage = any;\ntype McpServersConfig = any;\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the PostHog MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** Agent could not access the PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n}\n\nexport type AgentConfig = {\n workingDirectory: string;\n posthogMcpUrl: string;\n posthogApiKey: string;\n posthogApiHost: string;\n additionalMcpServers?: Record<string, { url: string }>;\n detectPackageManager: PackageManagerDetector;\n};\n\n/**\n * Internal configuration object returned by initializeAgent\n */\ntype AgentRunConfig = {\n workingDirectory: string;\n mcpServers: McpServersConfig;\n model: string;\n};\n\n/**\n * Package managers that can be used to run commands.\n */\nconst PACKAGE_MANAGERS = [\n // JavaScript\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n 'npx',\n // Python\n 'pip',\n 'pip3',\n 'poetry',\n 'pipenv',\n 'uv',\n];\n\n/**\n * Safe scripts/commands that can be run with any package manager.\n * Uses startsWith matching, so 'build' matches 'build', 'build:prod', etc.\n * Note: Linting tools are in LINTING_TOOLS and checked separately.\n */\nconst SAFE_SCRIPTS = [\n // Package installation\n 'install',\n 'add',\n 'ci',\n // Build\n 'build',\n // Type checking (various naming conventions)\n 'tsc',\n 'typecheck',\n 'type-check',\n 'check-types',\n 'types',\n // Linting/formatting script names (actual tools are in LINTING_TOOLS)\n 'lint',\n 'format',\n];\n\n/**\n * Dangerous shell operators that could allow command injection.\n * Note: We handle `2>&1` and `| tail/head` separately as safe patterns.\n * Note: `&&` is allowed for specific safe patterns like skill installation.\n */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n/**\n * Check if command is a PostHog skill installation from MCP.\n * We control the MCP server, so we only need to verify:\n * 1. It installs to .claude/skills/\n * 2. It downloads from our GitHub releases or localhost (dev)\n */\nfunction isSkillInstallCommand(command: string): boolean {\n if (!command.startsWith('mkdir -p .claude/skills/')) return false;\n\n const urlMatch = command.match(/curl -sL ['\"]([^'\"]+)['\"]/);\n if (!urlMatch) return false;\n\n const url = urlMatch[1];\n return (\n url.startsWith('https://github.com/PostHog/examples/releases/') ||\n /^http:\\/\\/localhost:\\d+\\//.test(url)\n );\n}\n\n/**\n * Check if command is an allowed package manager command.\n * Matches: <pkg-manager> [run|exec] <safe-script> [args...]\n */\nfunction matchesAllowedPrefix(command: string): boolean {\n const parts = command.split(/\\s+/);\n if (parts.length === 0 || !PACKAGE_MANAGERS.includes(parts[0])) {\n return false;\n }\n\n // Skip 'run' or 'exec' if present\n let scriptIndex = 1;\n if (parts[scriptIndex] === 'run' || parts[scriptIndex] === 'exec') {\n scriptIndex++;\n }\n\n // Get the script/command portion (may include args)\n const scriptPart = parts.slice(scriptIndex).join(' ');\n\n // Check if script starts with any safe script name or linting tool\n return (\n SAFE_SCRIPTS.some((safe) => scriptPart.startsWith(safe)) ||\n LINTING_TOOLS.some((tool) => scriptPart.startsWith(tool))\n );\n}\n\n/**\n * Permission hook that allows only safe commands.\n * - Package manager install commands\n * - Build/typecheck/lint commands for verification\n * - Piping to tail/head for output limiting is allowed\n * - Stderr redirection (2>&1) is allowed\n * - PostHog skill installation commands from MCP\n */\nexport function wizardCanUseTool(\n toolName: string,\n input: Record<string, unknown>,\n):\n | { behavior: 'allow'; updatedInput: Record<string, unknown> }\n | { behavior: 'deny'; message: string } {\n // Block direct reads/writes of .env files — use wizard-tools MCP instead\n if (toolName === 'Read' || toolName === 'Write' || toolName === 'Edit') {\n const filePath = typeof input.file_path === 'string' ? input.file_path : '';\n const basename = path.basename(filePath);\n if (basename.startsWith('.env')) {\n logToFile(`Denying ${toolName} on env file: ${filePath}`);\n return {\n behavior: 'deny',\n message: `Direct ${toolName} of ${basename} is not allowed. Use the wizard-tools MCP server (check_env_keys / set_env_values) to read or modify environment variables.`,\n };\n }\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Block Grep when it directly targets a .env file.\n // Note: ripgrep skips dotfiles (like .env*) by default during directory traversal,\n // so broad searches like `Grep { path: \".\" }` are already safe.\n if (toolName === 'Grep') {\n const grepPath = typeof input.path === 'string' ? input.path : '';\n if (grepPath && path.basename(grepPath).startsWith('.env')) {\n logToFile(`Denying Grep on env file: ${grepPath}`);\n return {\n behavior: 'deny',\n message: `Grep on ${path.basename(\n grepPath,\n )} is not allowed. Use the wizard-tools MCP server (check_env_keys) to check environment variables.`,\n };\n }\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Allow all other non-Bash tools\n if (toolName !== 'Bash') {\n return { behavior: 'allow', updatedInput: input };\n }\n\n const command = (\n typeof input.command === 'string' ? input.command : ''\n ).trim();\n\n // Check for PostHog skill installation command (before dangerous operator check)\n // These commands use && chaining but are generated by MCP with a strict format\n if (isSkillInstallCommand(command)) {\n logToFile(`Allowing skill installation command: ${command}`);\n debug(`Allowing skill installation command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Block definitely dangerous operators: ; ` $ ( )\n if (DANGEROUS_OPERATORS.test(command)) {\n logToFile(`Denying bash command with dangerous operators: ${command}`);\n debug(`Denying bash command with dangerous operators: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'dangerous operators',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Shell operators like ; \\` $ ( ) are not permitted.`,\n };\n }\n\n // Normalize: remove safe stderr redirection (2>&1, 2>&2, etc.)\n const normalized = command.replace(/\\s*\\d*>&\\d+\\s*/g, ' ').trim();\n\n // Check for pipe to tail/head (safe output limiting)\n const pipeMatch = normalized.match(/^(.+?)\\s*\\|\\s*(tail|head)(\\s+\\S+)*\\s*$/);\n if (pipeMatch) {\n const baseCommand = pipeMatch[1].trim();\n\n // Block if base command has pipes or & (multiple chaining)\n if (/[|&]/.test(baseCommand)) {\n logToFile(`Denying bash command with multiple pipes: ${command}`);\n debug(`Denying bash command with multiple pipes: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'multiple pipes',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only single pipe to tail/head is permitted.`,\n };\n }\n\n if (matchesAllowedPrefix(baseCommand)) {\n logToFile(`Allowing bash command with output limiter: ${command}`);\n debug(`Allowing bash command with output limiter: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n }\n\n // Block remaining pipes and & (not covered by tail/head case above)\n if (/[|&]/.test(normalized)) {\n logToFile(`Denying bash command with pipe/&: ${command}`);\n debug(`Denying bash command with pipe/&: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'disallowed pipe',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Pipes are only permitted with tail/head for output limiting.`,\n };\n }\n\n // Check if command starts with any allowed prefix (package manager commands)\n if (matchesAllowedPrefix(normalized)) {\n logToFile(`Allowing bash command: ${command}`);\n debug(`Allowing bash command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n logToFile(`Denying bash command: ${command}`);\n debug(`Denying bash command: ${command}`);\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'not in allowlist',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only install, build, typecheck, lint, and formatting commands are permitted.`,\n };\n}\n\n/**\n * Initialize agent configuration for the LLM gateway\n */\nexport async function initializeAgent(\n config: AgentConfig,\n options: WizardOptions,\n): Promise<AgentRunConfig> {\n // Initialize log file for this run\n initLogFile();\n logToFile('Agent initialization starting');\n logToFile('Install directory:', options.installDir);\n\n clack.log.step('Initializing Claude agent...');\n\n try {\n // Configure LLM gateway environment variables (inherited by SDK subprocess)\n const gatewayUrl = getLlmGatewayUrlFromHost(config.posthogApiHost);\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = config.posthogApiKey;\n // Use CLAUDE_CODE_OAUTH_TOKEN to override any stored /login credentials\n process.env.CLAUDE_CODE_OAUTH_TOKEN = config.posthogApiKey;\n // Disable experimental betas (like input_examples) that the LLM gateway doesn't support\n process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = 'true';\n\n logToFile('Configured LLM gateway:', gatewayUrl);\n\n // Configure MCP server with PostHog authentication\n const mcpServers: McpServersConfig = {\n 'posthog-wizard': {\n type: 'http',\n url: config.posthogMcpUrl,\n headers: {\n Authorization: `Bearer ${config.posthogApiKey}`,\n },\n },\n ...Object.fromEntries(\n Object.entries(config.additionalMcpServers ?? {}).map(\n ([name, { url }]) => [name, { type: 'http', url }],\n ),\n ),\n };\n\n // Add in-process wizard tools (env files, package manager detection)\n const wizardToolsServer = await createWizardToolsServer({\n workingDirectory: config.workingDirectory,\n detectPackageManager: config.detectPackageManager,\n });\n mcpServers['wizard-tools'] = wizardToolsServer;\n\n const agentRunConfig: AgentRunConfig = {\n workingDirectory: config.workingDirectory,\n mcpServers,\n model: 'anthropic/claude-sonnet-4-6',\n };\n\n logToFile('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n\n if (options.debug) {\n debug('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n }\n\n clack.log.step(`Verbose logs: ${LOG_FILE_PATH}`);\n clack.log.success(\"Agent initialized. Let's get cooking!\");\n return agentRunConfig;\n } catch (error) {\n clack.log.error(`Failed to initialize agent: ${(error as Error).message}`);\n logToFile('Agent initialization error:', error);\n debug('Agent initialization error:', error);\n throw error;\n }\n}\n\n/**\n * Execute an agent with the provided prompt and options\n * Handles the full lifecycle: spinner, execution, error handling\n *\n * @returns An object containing any error detected in the agent's output\n */\nexport async function runAgent(\n agentConfig: AgentRunConfig,\n prompt: string,\n options: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n config?: {\n estimatedDurationMinutes?: number;\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n },\n): Promise<{ error?: AgentErrorType; message?: string }> {\n const {\n estimatedDurationMinutes = 8,\n spinnerMessage = 'Customizing your PostHog setup...',\n successMessage = 'PostHog integration complete',\n errorMessage = 'Integration failed',\n } = config ?? {};\n\n const { query } = await getSDKModule();\n\n clack.log.step(\n `This whole process should take about ${estimatedDurationMinutes} minutes including error checking and fixes.\\n\\nGrab some coffee!`,\n );\n\n spinner.start(spinnerMessage);\n\n const cliPath = getClaudeCodeExecutablePath();\n logToFile('Starting agent run');\n logToFile('Claude Code executable:', cliPath);\n logToFile('Prompt:', prompt);\n\n const startTime = Date.now();\n const collectedText: string[] = [];\n // Track if we received a successful result (before any cleanup errors)\n let receivedSuccessResult = false;\n\n // Workaround for SDK bug: stdin closes before canUseTool responses can be sent.\n // The fix is to use an async generator for the prompt that stays open until\n // the result is received, keeping the stdin stream alive for permission responses.\n // See: https://github.com/anthropics/claude-code/issues/4775\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n let signalDone: () => void;\n const resultReceived = new Promise<void>((resolve) => {\n signalDone = resolve;\n });\n\n const createPromptStream = async function* () {\n yield {\n type: 'user',\n session_id: '',\n message: { role: 'user', content: prompt },\n parent_tool_use_id: null,\n };\n await resultReceived;\n };\n\n // Helper to handle successful completion (used in normal path and race condition recovery)\n const completeWithSuccess = (\n suppressedError?: Error,\n ): { error?: AgentErrorType; message?: string } => {\n const durationMs = Date.now() - startTime;\n const durationSeconds = Math.round(durationMs / 1000);\n\n if (suppressedError) {\n logToFile(\n `Ignoring post-completion error, agent completed successfully in ${durationSeconds}s`,\n );\n logToFile('Suppressed error:', suppressedError.message);\n } else {\n logToFile(`Agent run completed in ${durationSeconds}s`);\n }\n\n // Extract and capture the agent's reflection on the run\n const outputText = collectedText.join('\\n');\n const remarkRegex = new RegExp(\n `${AgentSignals.WIZARD_REMARK.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)(?:\\\\n|$)`,\n 's',\n );\n const remarkMatch = outputText.match(remarkRegex);\n if (remarkMatch && remarkMatch[1]) {\n const remark = remarkMatch[1].trim();\n if (remark) {\n analytics.capture(WIZARD_REMARK_EVENT_NAME, { remark });\n }\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'agent integration completed',\n duration_ms: durationMs,\n duration_seconds: durationSeconds,\n });\n spinner.stop(successMessage);\n return {};\n };\n\n try {\n // Tools needed for the wizard:\n // - File operations: Read, Write, Edit\n // - Search: Glob, Grep\n // - Commands: Bash (with restrictions via canUseTool)\n // - MCP discovery: ListMcpResourcesTool (to find available skills)\n // - Skills: Skill (to load installed PostHog skills)\n // MCP tools (PostHog) come from mcpServers, not allowedTools\n const allowedTools = [\n 'Read',\n 'Write',\n 'Edit',\n 'Glob',\n 'Grep',\n 'Bash',\n 'ListMcpResourcesTool',\n 'Skill',\n ...WIZARD_TOOL_NAMES,\n ];\n\n const response = query({\n prompt: createPromptStream(),\n options: {\n model: agentConfig.model,\n cwd: agentConfig.workingDirectory,\n permissionMode: 'acceptEdits',\n mcpServers: agentConfig.mcpServers,\n // Load skills from project's .claude/skills/ directory\n settingSources: ['project'],\n // Explicitly enable required tools including Skill\n allowedTools,\n env: {\n ...process.env,\n // Prevent user's Anthropic API key from overriding the wizard's OAuth token\n ANTHROPIC_API_KEY: undefined,\n },\n canUseTool: (toolName: string, input: unknown) => {\n logToFile('canUseTool called:', { toolName, input });\n const result = wizardCanUseTool(\n toolName,\n input as Record<string, unknown>,\n );\n logToFile('canUseTool result:', result);\n return Promise.resolve(result);\n },\n tools: { type: 'preset', preset: 'claude_code' },\n // Capture stderr from CLI subprocess for debugging\n stderr: (data: string) => {\n logToFile('CLI stderr:', data);\n if (options.debug) {\n debug('CLI stderr:', data);\n }\n },\n // Stop hook to have the agent reflect on its run\n hooks: {\n Stop: [\n {\n hooks: [\n (input: { stop_hook_active: boolean }) => {\n logToFile('Stop hook triggered', {\n stop_hook_active: input.stop_hook_active,\n });\n\n // Only ask for reflection on first stop (not after reflection is provided)\n if (input.stop_hook_active) {\n logToFile('Stop hook: allowing stop (already reflected)');\n return {}; // Allow stopping\n }\n\n logToFile('Stop hook: requesting reflection');\n return {\n decision: 'block',\n reason: `Before concluding, provide a brief remark about what information or guidance would have been useful to have in the integration prompt or documentation for this run. Specifically cite anything that would have prevented tool failures, erroneous edits, or other wasted turns. Format your response exactly as: ${AgentSignals.WIZARD_REMARK} Your remark here`,\n };\n },\n ],\n timeout: 30,\n },\n ],\n },\n },\n });\n\n // Process the async generator\n for await (const message of response) {\n // Pass receivedSuccessResult so handleSDKMessage can suppress user-facing error\n // output for post-success cleanup errors while still logging them to file\n handleSDKMessage(\n message,\n options,\n spinner,\n collectedText,\n receivedSuccessResult,\n );\n\n // Signal completion when result received\n if (message.type === 'result') {\n // Track successful results before any potential cleanup errors\n // The SDK may emit a second error result during cleanup due to a race condition\n if (message.subtype === 'success' && !message.is_error) {\n receivedSuccessResult = true;\n }\n signalDone!();\n }\n }\n\n const outputText = collectedText.join('\\n');\n\n // Check for error markers in the agent's output\n if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {\n logToFile('Agent error: MCP_MISSING');\n spinner.stop('Agent could not access PostHog MCP');\n return { error: AgentErrorType.MCP_MISSING };\n }\n\n if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {\n logToFile('Agent error: RESOURCE_MISSING');\n spinner.stop('Agent could not access setup resource');\n return { error: AgentErrorType.RESOURCE_MISSING };\n }\n\n // Check for API errors (rate limits, etc.)\n // Extract just the API error line(s), not the entire output\n const apiErrorMatch = outputText.match(/API Error: [^\\n]+/g);\n const apiErrorMessage = apiErrorMatch\n ? apiErrorMatch.join('\\n')\n : 'Unknown API error';\n\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error: RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: apiErrorMessage };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error: API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: apiErrorMessage };\n }\n\n return completeWithSuccess();\n } catch (error) {\n // Signal done to unblock the async generator\n signalDone!();\n\n // If we already received a successful result, the error is from SDK cleanup\n // This happens due to a race condition: the SDK tries to send a cleanup command\n // after the prompt stream closes, but streaming mode is still active.\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n if (receivedSuccessResult) {\n return completeWithSuccess(error as Error);\n }\n\n // Check if we collected an API error before the exception was thrown\n const outputText = collectedText.join('\\n');\n\n // Extract just the API error line(s), not the entire output\n const apiErrorMatch = outputText.match(/API Error: [^\\n]+/g);\n const apiErrorMessage = apiErrorMatch\n ? apiErrorMatch.join('\\n')\n : 'Unknown API error';\n\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error (caught): RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: apiErrorMessage };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error (caught): API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: apiErrorMessage };\n }\n\n // No API error found, re-throw the original exception\n spinner.stop(errorMessage);\n clack.log.error(`Error: ${(error as Error).message}`);\n logToFile('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n }\n}\n\n/**\n * Handle SDK messages and provide user feedback\n *\n * @param receivedSuccessResult - If true, suppress user-facing error output for cleanup errors\n * while still logging to file. The SDK may emit a second error\n * result after success due to cleanup race conditions.\n */\nfunction handleSDKMessage(\n message: SDKMessage,\n options: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n collectedText: string[],\n receivedSuccessResult = false,\n): void {\n logToFile(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));\n\n if (options.debug) {\n debug(`SDK Message type: ${message.type}`);\n }\n\n switch (message.type) {\n case 'assistant': {\n // Extract text content from assistant messages\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n collectedText.push(block.text);\n\n // Check for [STATUS] markers\n const statusRegex = new RegExp(\n `^.*${AgentSignals.STATUS.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)$`,\n 'm',\n );\n const statusMatch = block.text.match(statusRegex);\n if (statusMatch) {\n spinner.stop(statusMatch[1].trim());\n spinner.start('Integrating PostHog...');\n }\n }\n }\n }\n break;\n }\n\n case 'result': {\n // Check is_error flag - can be true even when subtype is 'success'\n if (message.is_error) {\n logToFile('Agent result with error:', message.result);\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n // Only show errors to user if we haven't already succeeded.\n // Post-success errors are SDK cleanup noise (telemetry failures, streaming\n // mode race conditions). Full message already logged above via JSON dump.\n if (message.errors && !receivedSuccessResult) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n } else if (message.subtype === 'success') {\n logToFile('Agent completed successfully');\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n } else {\n logToFile('Agent result with error:', message.result);\n // Error result - only show to user if we haven't already succeeded.\n // Full message already logged above via JSON dump.\n if (message.errors && !receivedSuccessResult) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n }\n break;\n }\n\n case 'system': {\n if (message.subtype === 'init') {\n logToFile('Agent session initialized', {\n model: message.model,\n tools: message.tools?.length,\n mcpServers: message.mcp_servers,\n });\n }\n break;\n }\n\n default:\n // Log other message types for debugging\n if (options.debug) {\n debug(`Unhandled message type: ${message.type}`);\n }\n break;\n }\n}\n"]}
@@ -153,6 +153,7 @@ async function runAgentWizard(config, options) {
153
153
  posthogApiKey: accessToken,
154
154
  posthogApiHost: host,
155
155
  additionalMcpServers: config.metadata.additionalMcpServers,
156
+ detectPackageManager: config.detection.detectPackageManager,
156
157
  }, options);
157
158
  const agentResult = await (0, agent_interface_1.runAgent)(agent, integrationPrompt, options, spinner, {
158
159
  estimatedDurationMinutes: config.ui.estimatedDurationMinutes,
@@ -287,7 +288,9 @@ Project context:
287
288
  - Framework: ${config.metadata.name} ${context.frameworkVersion}
288
289
  - TypeScript: ${context.typescript ? 'Yes' : 'No'}
289
290
  - PostHog API Key: ${context.projectApiKey}
290
- - PostHog Host: ${context.host}${additionalContext}
291
+ - PostHog Host: ${context.host}
292
+ - Project type: ${config.prompts.projectTypeDetection}
293
+ - Package installation: ${config.prompts.packageInstallation ?? framework_config_1.DEFAULT_PACKAGE_INSTALLATION}${additionalContext}
291
294
 
292
295
  Instructions (follow these steps IN ORDER - do not skip or reorder):
293
296
 
@@ -305,14 +308,14 @@ STEP 3: Run the installation command using Bash:
305
308
 
306
309
  STEP 4: Load the installed skill's SKILL.md file to understand what references are available.
307
310
 
308
- STEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like "1.0-", "1.1-", "1.2-"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.
311
+ STEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like "1.0-", "1.1-", "1.2-"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next. Never directly write PostHog keys directly to code files; always use environment variables.
309
312
 
310
- STEP 6: Set up environment variables for PostHog using the env-file-tools MCP server (this runs locally — secret values never leave the machine):
313
+ STEP 6: Set up environment variables for PostHog using the wizard-tools MCP server (this runs locally — secret values never leave the machine):
311
314
  - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).
312
315
  - Use set_env_values to create or update the PostHog API key and host, using the appropriate naming convention for ${config.metadata.name}. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.
313
316
  - Reference these environment variables in the code files you create instead of hardcoding the API key and host.
314
317
 
315
- Important: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager (excluding the contents of node_modules). Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.
318
+ Important: Use the detect_package_manager tool (from the wizard-tools MCP server) to determine which package manager the project uses. Do not manually search for lockfiles or config files. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.
316
319
 
317
320
  `;
318
321
  }
@@ -1 +1 @@
1
- {"version":3,"file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,CAAC,CAAC,EAAE,CAAC;IAEP,MAAM,iBAAiB,GACrB,eAAe,CAAC,MAAM,GAAG,CAAC;QACxB,CAAC,CAAC,IAAI,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC;IAET,OAAO,kGACL,MAAM,CAAC,QAAQ,CAAC,IAClB;;;eAGa,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,OAAO,CAAC,gBAAgB;gBAC/C,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;qBAC5B,OAAO,CAAC,aAAa;kBACxB,OAAO,CAAC,IAAI,GAAG,iBAAiB;;;;0KAK9C,8BAAY,CAAC,iBACf;;;mFAIG,8BAAY,CAAC,sBACf;;;;;;;;;;;;;;;wHAgBE,MAAM,CAAC,QAAQ,CAAC,IAClB;;;;;CAKF,CAAC;AACF,CAAC","sourcesContent":["import {\n getWelcomeMessage,\n SPINNER_MESSAGE,\n type FrameworkConfig,\n} from './framework-config';\nimport type { WizardOptions } from '../utils/types';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n isUsingTypeScript,\n printWelcome,\n askForCloudRegion,\n} from '../utils/clack-utils';\nimport type { PackageDotJson } from '../utils/package-json';\nimport { analytics } from '../utils/analytics';\nimport { WIZARD_INTERACTION_EVENT_NAME } from './constants';\nimport clack from '../utils/clack';\nimport {\n initializeAgent,\n runAgent,\n AgentSignals,\n AgentErrorType,\n} from './agent-interface';\nimport { getCloudUrlFromRegion } from '../utils/urls';\nimport chalk from 'chalk';\nimport * as semver from 'semver';\nimport {\n addMCPServerToClientsStep,\n uploadEnvironmentVariablesStep,\n} from '../steps';\nimport { checkAnthropicStatusWithPrompt } from '../utils/anthropic-status';\nimport { enableDebugLogs } from '../utils/debug';\n\n/**\n * Universal agent-powered wizard runner.\n * Handles the complete flow for any framework using PostHog MCP integration.\n */\nexport async function runAgentWizard(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<void> {\n if (options.debug) {\n enableDebugLogs();\n }\n\n // Version check\n if (config.detection.minimumVersion && config.detection.getInstalledVersion) {\n const version = await config.detection.getInstalledVersion(options);\n if (version) {\n const coerced = semver.coerce(version);\n if (coerced && semver.lt(coerced, config.detection.minimumVersion)) {\n const docsUrl =\n config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl;\n clack.log.warn(\n `Sorry: the wizard can't help you with ${config.metadata.name} ${version}. Upgrade to ${config.metadata.name} ${config.detection.minimumVersion} or later, or check out the manual setup guide.`,\n );\n clack.log.info(\n `Setup ${config.metadata.name} manually: ${chalk.cyan(docsUrl)}`,\n );\n clack.outro('PostHog wizard will see you next time!');\n return;\n }\n }\n }\n\n // Setup phase\n printWelcome({ wizardName: getWelcomeMessage(config.metadata.name) });\n\n if (config.metadata.beta) {\n clack.log.info(\n `${chalk.yellow('[BETA]')} The ${\n config.metadata.name\n } wizard is in beta. Questions or feedback? Email ${chalk.cyan(\n 'wizard@posthog.com',\n )}`,\n );\n }\n\n if (config.metadata.preRunNotice) {\n clack.log.warn(config.metadata.preRunNotice);\n }\n\n clack.log.info(\n `We're about to read your project using our LLM gateway.\\n\\n.env* file contents will not leave your machine.\\n\\nOther files will be read and edited to provide a fully-custom PostHog integration.`,\n );\n\n const aiConsent = await askForAIConsent(options);\n if (!aiConsent) {\n await abort(\n `This wizard uses an LLM agent to intelligently modify your project. Please view the docs to set up ${config.metadata.name} manually instead: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n // Check Anthropic/Claude service status before proceeding\n const statusOk = await checkAnthropicStatusWithPrompt({ ci: options.ci });\n if (!statusOk) {\n await abort(\n `Please try again later, or set up ${config.metadata.name} manually: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n const typeScriptDetected = isUsingTypeScript(options);\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n // Framework detection and version\n // Only check package.json for Node.js/JavaScript frameworks\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let packageJson: PackageDotJson | null = null;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n packageJson = await getPackageDotJson(options);\n await ensurePackageIsInstalled(\n packageJson,\n config.detection.packageName,\n config.detection.packageDisplayName,\n );\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n // For non-Node frameworks (e.g., Django), version is handled differently\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Set analytics tags for framework version\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'started agent integration',\n integration: config.metadata.integration,\n });\n\n // Get PostHog credentials\n const { projectApiKey, host, accessToken } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n // Gather framework-specific context (e.g., Next.js router, React Native platform)\n const frameworkContext = config.metadata.gatherContext\n ? await config.metadata.gatherContext(options)\n : {};\n\n // Set analytics tags from framework context\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n // Build integration prompt\n const integrationPrompt = buildIntegrationPrompt(\n config,\n {\n frameworkVersion: frameworkVersion || 'latest',\n typescript: typeScriptDetected,\n projectApiKey,\n host,\n },\n frameworkContext,\n );\n\n // Initialize and run agent\n const spinner = clack.spinner();\n\n // Determine MCP URL: CLI flag > env var > production default\n // Use EU subdomain for EU users to work around Claude Code's OAuth bug\n // See: https://github.com/anthropics/claude-code/issues/2267\n const mcpUrl = options.localMcp\n ? 'http://localhost:8787/mcp'\n : process.env.MCP_URL ||\n (cloudRegion === 'eu'\n ? 'https://mcp-eu.posthog.com/mcp'\n : 'https://mcp.posthog.com/mcp');\n\n const agent = await initializeAgent(\n {\n workingDirectory: options.installDir,\n posthogMcpUrl: mcpUrl,\n posthogApiKey: accessToken,\n posthogApiHost: host,\n additionalMcpServers: config.metadata.additionalMcpServers,\n },\n options,\n );\n\n const agentResult = await runAgent(\n agent,\n integrationPrompt,\n options,\n spinner,\n {\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n errorMessage: 'Integration failed',\n },\n );\n\n // Handle error cases detected in agent output\n if (agentResult.error === AgentErrorType.MCP_MISSING) {\n analytics.captureException(\n new Error('Agent could not access PostHog MCP server'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.MCP_MISSING,\n signal: AgentSignals.ERROR_MCP_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('❌ Could not access the PostHog MCP server')}\n\nThe wizard was unable to connect to the PostHog MCP server.\nThis could be due to a network issue or a configuration problem.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (agentResult.error === AgentErrorType.RESOURCE_MISSING) {\n analytics.captureException(\n new Error('Agent could not access setup resource'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.RESOURCE_MISSING,\n signal: AgentSignals.ERROR_RESOURCE_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('❌ Could not access the setup resource')}\n\nThe wizard could not access the setup resource. This may indicate a version mismatch or a temporary service issue.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (\n agentResult.error === AgentErrorType.RATE_LIMIT ||\n agentResult.error === AgentErrorType.API_ERROR\n ) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'api error',\n integration: config.metadata.integration,\n error_type: agentResult.error,\n error_message: agentResult.message,\n });\n\n analytics.captureException(new Error(`API error: ${agentResult.message}`), {\n integration: config.metadata.integration,\n error_type: agentResult.error,\n });\n\n const errorMessage = `\n${chalk.red('❌ API Error')}\n\n${chalk.yellow(agentResult.message || 'Unknown error')}\n\nPlease report this error to: ${chalk.cyan('wizard@posthog.com')}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n // Build environment variables from OAuth credentials\n const envVars = config.environment.getEnvVars(projectApiKey, host);\n\n // Upload environment variables to hosting providers (if configured)\n let uploadedEnvVars: string[] = [];\n if (config.environment.uploadToHosting) {\n uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {\n integration: config.metadata.integration,\n options,\n });\n }\n\n // Add MCP server to clients\n await addMCPServerToClientsStep({\n cloudRegion,\n integration: config.metadata.integration,\n ci: options.ci,\n });\n\n // Build outro message\n const continueUrl = options.signup\n ? `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`\n : undefined;\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? `Added environment variables to .env file`\n : '',\n uploadedEnvVars.length > 0\n ? `Uploaded environment variables to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const nextSteps = [\n ...config.ui.getOutroNextSteps(frameworkContext),\n uploadedEnvVars.length === 0 && config.environment.uploadToHosting\n ? `Upload your Project API key to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const outroMessage = `\n${chalk.green('Successfully installed PostHog!')}\n\n${chalk.cyan('What the agent did:')}\n${changes.map((change) => `• ${change}`).join('\\n')}\n\n${chalk.yellow('Next steps:')}\n${nextSteps.map((step) => `• ${step}`).join('\\n')}\n\nLearn more: ${chalk.cyan(config.metadata.docsUrl)}\n${continueUrl ? `\\nContinue onboarding: ${chalk.cyan(continueUrl)}\\n` : ``}\n${chalk.dim(\n 'Note: This wizard uses an LLM agent to analyze and modify your project. Please review the changes made.',\n)}\n\n${chalk.dim(`How did this work for you? Drop us a line: wizard@posthog.com`)}`;\n\n clack.outro(outroMessage);\n\n await analytics.shutdown('success');\n}\n\n/**\n * Build the integration prompt for the agent.\n * Uses shared base prompt with optional framework-specific addendum.\n */\nfunction buildIntegrationPrompt(\n config: FrameworkConfig,\n context: {\n frameworkVersion: string;\n typescript: boolean;\n projectApiKey: string;\n host: string;\n },\n frameworkContext: Record<string, unknown>,\n): string {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- Framework: ${config.metadata.name} ${context.frameworkVersion}\n- TypeScript: ${context.typescript ? 'Yes' : 'No'}\n- PostHog API Key: ${context.projectApiKey}\n- PostHog Host: ${context.host}${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool. If this tool is not available or you cannot access the MCP server, you must emit: ${\n AgentSignals.ERROR_MCP_MISSING\n } Could not access the PostHog MCP server and halt.\n\n Review the skill descriptions and choose the one that best matches this project's framework and configuration.\n If no suitable skill is found, or you cannot access the MCP server, you emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).\n The resource returns a shell command to install the skill.\n\nSTEP 3: Run the installation command using Bash:\n - Execute the EXACT command returned by the resource (do not modify it)\n - This will download and extract the skill to .claude/skills/{skill-id}/\n\nSTEP 4: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.\n\nSTEP 6: Set up environment variables for PostHog using the env-file-tools MCP server (this runs locally — secret values never leave the machine):\n - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).\n - Use set_env_values to create or update the PostHog API key and host, using the appropriate naming convention for ${\n config.metadata.name\n }. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.\n - Reference these environment variables in the code files you create instead of hardcoding the API key and host.\n\nImportant: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager (excluding the contents of node_modules). Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.\n\n`;\n}\n"]}
1
+ {"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../src/lib/agent-runner.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,wCAqTC;AA/VD,yDAK4B;AAE5B,sDAU8B;AAE9B,kDAA+C;AAC/C,2CAA4D;AAC5D,2DAAmC;AACnC,uDAK2B;AAC3B,wCAAsD;AACtD,kDAA0B;AAC1B,+CAAiC;AACjC,oCAGkB;AAClB,gEAA2E;AAC3E,0CAAiD;AAEjD;;;GAGG;AACI,KAAK,UAAU,cAAc,CAClC,MAAuB,EACvB,OAAsB;IAEtB,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QAClB,IAAA,uBAAe,GAAE,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,IAAI,MAAM,CAAC,SAAS,CAAC,mBAAmB,EAAE,CAAC;QAC5E,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QACpE,IAAI,OAAO,EAAE,CAAC;YACZ,MAAM,OAAO,GAAG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AAC,sBACf;;;;;;;;;;;;;;;wHAgBE,MAAM,CAAC,QAAQ,CAAC,IAClB;;;;;CAKF,CAAC;AACF,CAAC","sourcesContent":["import {\n DEFAULT_PACKAGE_INSTALLATION,\n getWelcomeMessage,\n SPINNER_MESSAGE,\n type FrameworkConfig,\n} from './framework-config';\nimport type { WizardOptions } from '../utils/types';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n isUsingTypeScript,\n printWelcome,\n askForCloudRegion,\n} from '../utils/clack-utils';\nimport type { PackageDotJson } from '../utils/package-json';\nimport { analytics } from '../utils/analytics';\nimport { WIZARD_INTERACTION_EVENT_NAME } from './constants';\nimport clack from '../utils/clack';\nimport {\n initializeAgent,\n runAgent,\n AgentSignals,\n AgentErrorType,\n} from './agent-interface';\nimport { getCloudUrlFromRegion } from '../utils/urls';\nimport chalk from 'chalk';\nimport * as semver from 'semver';\nimport {\n addMCPServerToClientsStep,\n uploadEnvironmentVariablesStep,\n} from '../steps';\nimport { checkAnthropicStatusWithPrompt } from '../utils/anthropic-status';\nimport { enableDebugLogs } from '../utils/debug';\n\n/**\n * Universal agent-powered wizard runner.\n * Handles the complete flow for any framework using PostHog MCP integration.\n */\nexport async function runAgentWizard(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<void> {\n if (options.debug) {\n enableDebugLogs();\n }\n\n // Version check\n if (config.detection.minimumVersion && config.detection.getInstalledVersion) {\n const version = await config.detection.getInstalledVersion(options);\n if (version) {\n const coerced = semver.coerce(version);\n if (coerced && semver.lt(coerced, config.detection.minimumVersion)) {\n const docsUrl =\n config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl;\n clack.log.warn(\n `Sorry: the wizard can't help you with ${config.metadata.name} ${version}. Upgrade to ${config.metadata.name} ${config.detection.minimumVersion} or later, or check out the manual setup guide.`,\n );\n clack.log.info(\n `Setup ${config.metadata.name} manually: ${chalk.cyan(docsUrl)}`,\n );\n clack.outro('PostHog wizard will see you next time!');\n return;\n }\n }\n }\n\n // Setup phase\n printWelcome({ wizardName: getWelcomeMessage(config.metadata.name) });\n\n if (config.metadata.beta) {\n clack.log.info(\n `${chalk.yellow('[BETA]')} The ${\n config.metadata.name\n } wizard is in beta. Questions or feedback? Email ${chalk.cyan(\n 'wizard@posthog.com',\n )}`,\n );\n }\n\n if (config.metadata.preRunNotice) {\n clack.log.warn(config.metadata.preRunNotice);\n }\n\n clack.log.info(\n `We're about to read your project using our LLM gateway.\\n\\n.env* file contents will not leave your machine.\\n\\nOther files will be read and edited to provide a fully-custom PostHog integration.`,\n );\n\n const aiConsent = await askForAIConsent(options);\n if (!aiConsent) {\n await abort(\n `This wizard uses an LLM agent to intelligently modify your project. Please view the docs to set up ${config.metadata.name} manually instead: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n // Check Anthropic/Claude service status before proceeding\n const statusOk = await checkAnthropicStatusWithPrompt({ ci: options.ci });\n if (!statusOk) {\n await abort(\n `Please try again later, or set up ${config.metadata.name} manually: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n const typeScriptDetected = isUsingTypeScript(options);\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n // Framework detection and version\n // Only check package.json for Node.js/JavaScript frameworks\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let packageJson: PackageDotJson | null = null;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n packageJson = await getPackageDotJson(options);\n await ensurePackageIsInstalled(\n packageJson,\n config.detection.packageName,\n config.detection.packageDisplayName,\n );\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n // For non-Node frameworks (e.g., Django), version is handled differently\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Set analytics tags for framework version\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'started agent integration',\n integration: config.metadata.integration,\n });\n\n // Get PostHog credentials\n const { projectApiKey, host, accessToken } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n // Gather framework-specific context (e.g., Next.js router, React Native platform)\n const frameworkContext = config.metadata.gatherContext\n ? await config.metadata.gatherContext(options)\n : {};\n\n // Set analytics tags from framework context\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n // Build integration prompt\n const integrationPrompt = buildIntegrationPrompt(\n config,\n {\n frameworkVersion: frameworkVersion || 'latest',\n typescript: typeScriptDetected,\n projectApiKey,\n host,\n },\n frameworkContext,\n );\n\n // Initialize and run agent\n const spinner = clack.spinner();\n\n // Determine MCP URL: CLI flag > env var > production default\n // Use EU subdomain for EU users to work around Claude Code's OAuth bug\n // See: https://github.com/anthropics/claude-code/issues/2267\n const mcpUrl = options.localMcp\n ? 'http://localhost:8787/mcp'\n : process.env.MCP_URL ||\n (cloudRegion === 'eu'\n ? 'https://mcp-eu.posthog.com/mcp'\n : 'https://mcp.posthog.com/mcp');\n\n const agent = await initializeAgent(\n {\n workingDirectory: options.installDir,\n posthogMcpUrl: mcpUrl,\n posthogApiKey: accessToken,\n posthogApiHost: host,\n additionalMcpServers: config.metadata.additionalMcpServers,\n detectPackageManager: config.detection.detectPackageManager,\n },\n options,\n );\n\n const agentResult = await runAgent(\n agent,\n integrationPrompt,\n options,\n spinner,\n {\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n errorMessage: 'Integration failed',\n },\n );\n\n // Handle error cases detected in agent output\n if (agentResult.error === AgentErrorType.MCP_MISSING) {\n analytics.captureException(\n new Error('Agent could not access PostHog MCP server'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.MCP_MISSING,\n signal: AgentSignals.ERROR_MCP_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('❌ Could not access the PostHog MCP server')}\n\nThe wizard was unable to connect to the PostHog MCP server.\nThis could be due to a network issue or a configuration problem.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (agentResult.error === AgentErrorType.RESOURCE_MISSING) {\n analytics.captureException(\n new Error('Agent could not access setup resource'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.RESOURCE_MISSING,\n signal: AgentSignals.ERROR_RESOURCE_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('❌ Could not access the setup resource')}\n\nThe wizard could not access the setup resource. This may indicate a version mismatch or a temporary service issue.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (\n agentResult.error === AgentErrorType.RATE_LIMIT ||\n agentResult.error === AgentErrorType.API_ERROR\n ) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'api error',\n integration: config.metadata.integration,\n error_type: agentResult.error,\n error_message: agentResult.message,\n });\n\n analytics.captureException(new Error(`API error: ${agentResult.message}`), {\n integration: config.metadata.integration,\n error_type: agentResult.error,\n });\n\n const errorMessage = `\n${chalk.red('❌ API Error')}\n\n${chalk.yellow(agentResult.message || 'Unknown error')}\n\nPlease report this error to: ${chalk.cyan('wizard@posthog.com')}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n // Build environment variables from OAuth credentials\n const envVars = config.environment.getEnvVars(projectApiKey, host);\n\n // Upload environment variables to hosting providers (if configured)\n let uploadedEnvVars: string[] = [];\n if (config.environment.uploadToHosting) {\n uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {\n integration: config.metadata.integration,\n options,\n });\n }\n\n // Add MCP server to clients\n await addMCPServerToClientsStep({\n cloudRegion,\n integration: config.metadata.integration,\n ci: options.ci,\n });\n\n // Build outro message\n const continueUrl = options.signup\n ? `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`\n : undefined;\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? `Added environment variables to .env file`\n : '',\n uploadedEnvVars.length > 0\n ? `Uploaded environment variables to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const nextSteps = [\n ...config.ui.getOutroNextSteps(frameworkContext),\n uploadedEnvVars.length === 0 && config.environment.uploadToHosting\n ? `Upload your Project API key to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const outroMessage = `\n${chalk.green('Successfully installed PostHog!')}\n\n${chalk.cyan('What the agent did:')}\n${changes.map((change) => `• ${change}`).join('\\n')}\n\n${chalk.yellow('Next steps:')}\n${nextSteps.map((step) => `• ${step}`).join('\\n')}\n\nLearn more: ${chalk.cyan(config.metadata.docsUrl)}\n${continueUrl ? `\\nContinue onboarding: ${chalk.cyan(continueUrl)}\\n` : ``}\n${chalk.dim(\n 'Note: This wizard uses an LLM agent to analyze and modify your project. Please review the changes made.',\n)}\n\n${chalk.dim(`How did this work for you? Drop us a line: wizard@posthog.com`)}`;\n\n clack.outro(outroMessage);\n\n await analytics.shutdown('success');\n}\n\n/**\n * Build the integration prompt for the agent.\n * Uses shared base prompt with optional framework-specific addendum.\n */\nfunction buildIntegrationPrompt(\n config: FrameworkConfig,\n context: {\n frameworkVersion: string;\n typescript: boolean;\n projectApiKey: string;\n host: string;\n },\n frameworkContext: Record<string, unknown>,\n): string {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- Framework: ${config.metadata.name} ${context.frameworkVersion}\n- TypeScript: ${context.typescript ? 'Yes' : 'No'}\n- PostHog API Key: ${context.projectApiKey}\n- PostHog Host: ${context.host}\n- Project type: ${config.prompts.projectTypeDetection}\n- Package installation: ${\n config.prompts.packageInstallation ?? DEFAULT_PACKAGE_INSTALLATION\n }${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool. If this tool is not available or you cannot access the MCP server, you must emit: ${\n AgentSignals.ERROR_MCP_MISSING\n } Could not access the PostHog MCP server and halt.\n\n Review the skill descriptions and choose the one that best matches this project's framework and configuration.\n If no suitable skill is found, or you cannot access the MCP server, you emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).\n The resource returns a shell command to install the skill.\n\nSTEP 3: Run the installation command using Bash:\n - Execute the EXACT command returned by the resource (do not modify it)\n - This will download and extract the skill to .claude/skills/{skill-id}/\n\nSTEP 4: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next. Never directly write PostHog keys directly to code files; always use environment variables.\n\nSTEP 6: Set up environment variables for PostHog using the wizard-tools MCP server (this runs locally — secret values never leave the machine):\n - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).\n - Use set_env_values to create or update the PostHog API key and host, using the appropriate naming convention for ${\n config.metadata.name\n }. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.\n - Reference these environment variables in the code files you create instead of hardcoding the API key and host.\n\nImportant: Use the detect_package_manager tool (from the wizard-tools MCP server) to determine which package manager the project uses. Do not manually search for lockfiles or config files. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.\n\n`;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { Integration } from './constants';
2
2
  import type { WizardOptions } from '../utils/types';
3
+ import type { PackageManagerDetector } from './package-manager-detection';
3
4
  /**
4
5
  * Configuration interface for framework-specific agent integrations.
5
6
  * Each framework exports a FrameworkConfig that the universal runner uses.
@@ -70,6 +71,8 @@ export interface FrameworkDetection {
70
71
  getInstalledVersion?: (options: WizardOptions) => Promise<string | undefined>;
71
72
  /** Detect whether this framework is present in the project. */
72
73
  detect: (options: Pick<WizardOptions, 'installDir'>) => Promise<boolean>;
74
+ /** Detect the project's package manager(s). Used by the in-process MCP tool. */
75
+ detectPackageManager: PackageManagerDetector;
73
76
  }
74
77
  /**
75
78
  * Environment variable configuration
@@ -92,6 +95,13 @@ export interface AnalyticsConfig<TContext extends Record<string, unknown> = Reco
92
95
  /** Optional: Additional event properties */
93
96
  getEventProperties?: (context: TContext) => Record<string, string>;
94
97
  }
98
+ /**
99
+ * Default package installation instruction used when frameworks don't
100
+ * provide their own. Frameworks with specific needs (e.g., Swift SPM,
101
+ * Composer) override this in their config.
102
+ */
103
+ export declare const DEFAULT_PACKAGE_INSTALLATION = "Use the detect_package_manager tool to determine the package manager. Do not manually edit package.json; the package manager handles it automatically.";
104
+ export declare const PYTHON_PACKAGE_INSTALLATION = "Use the detect_package_manager tool to determine the package manager. If the detected tool manages dependencies directly (e.g. uv add, poetry add), use it \u2014 it will update the manifest automatically. If using pip, you must also add the dependency to requirements.txt or the appropriate manifest file.";
95
105
  /**
96
106
  * Prompt configuration
97
107
  */
@@ -104,14 +114,17 @@ export interface PromptConfig<TContext extends Record<string, unknown> = Record<
104
114
  getAdditionalContextLines?: (context: TContext) => string[];
105
115
  /**
106
116
  * How to detect the project type for this framework.
117
+ * Included in the agent prompt as project context.
107
118
  * e.g., "Look for package.json and lockfiles" or "Look for requirements.txt and manage.py"
108
119
  */
109
120
  projectTypeDetection: string;
110
121
  /**
111
122
  * How to install packages for this framework.
112
- * e.g., "Use npm/yarn/pnpm based on lockfile" or "Use pip/poetry based on config files"
123
+ * Included in the agent prompt as project context.
124
+ * Defaults to DEFAULT_PACKAGE_INSTALLATION. Only override if the framework
125
+ * has specific installation guidance (e.g., Swift SPM, Composer).
113
126
  */
114
- packageInstallation: string;
127
+ packageInstallation?: string;
115
128
  }
116
129
  /**
117
130
  * UI messaging configuration
@@ -1,7 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SPINNER_MESSAGE = void 0;
3
+ exports.SPINNER_MESSAGE = exports.PYTHON_PACKAGE_INSTALLATION = exports.DEFAULT_PACKAGE_INSTALLATION = void 0;
4
4
  exports.getWelcomeMessage = getWelcomeMessage;
5
+ /**
6
+ * Default package installation instruction used when frameworks don't
7
+ * provide their own. Frameworks with specific needs (e.g., Swift SPM,
8
+ * Composer) override this in their config.
9
+ */
10
+ exports.DEFAULT_PACKAGE_INSTALLATION = 'Use the detect_package_manager tool to determine the package manager. Do not manually edit package.json; the package manager handles it automatically.';
11
+ exports.PYTHON_PACKAGE_INSTALLATION = 'Use the detect_package_manager tool to determine the package manager. If the detected tool manages dependencies directly (e.g. uv add, poetry add), use it — it will update the manifest automatically. If using pip, you must also add the dependency to requirements.txt or the appropriate manifest file.';
5
12
  /**
6
13
  * Generate welcome message from framework name
7
14
  */
@@ -1 +1 @@
1
- {"version":3,"file":"framework-config.js","sourceRoot":"","sources":["../../../src/lib/framework-config.ts"],"names":[],"mappings":";;;AAwKA,8CAEC;AALD;;GAEG;AACH,SAAgB,iBAAiB,CAAC,aAAqB;IACrD,OAAO,WAAW,aAAa,yBAAyB,CAAC;AAC3D,CAAC;AAED;;GAEG;AACU,QAAA,eAAe,GAC1B,mEAAmE,CAAC","sourcesContent":["import type { Integration } from './constants';\nimport type { WizardOptions } from '../utils/types';\n\n/**\n * Configuration interface for framework-specific agent integrations.\n * Each framework exports a FrameworkConfig that the universal runner uses.\n *\n * The TContext generic represents the framework-specific context gathered\n * before the agent runs (e.g., router type for Next.js, project type for Django).\n * The runner threads this opaquely — all framework-specific logic stays inside the config.\n */\nexport interface FrameworkConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n metadata: FrameworkMetadata<TContext>;\n detection: FrameworkDetection;\n environment: EnvironmentConfig;\n analytics: AnalyticsConfig<TContext>;\n prompts: PromptConfig<TContext>;\n ui: UIConfig<TContext>;\n}\n\n/**\n * Basic framework information and documentation\n */\nexport interface FrameworkMetadata<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Display name (e.g., \"Next.js\", \"React\") */\n name: string;\n\n /** Integration type from constants */\n integration: Integration;\n\n /** URL to framework-specific PostHog docs */\n docsUrl: string;\n\n /**\n * Optional URL to docs for users with unsupported framework versions.\n * If not provided, defaults to docsUrl.\n */\n unsupportedVersionDocsUrl?: string;\n\n /** If true, shows a beta notice before running the wizard. */\n beta?: boolean;\n\n /** Optional notice shown before the agent runs (e.g., \"Close Xcode before proceeding\"). */\n preRunNotice?: string;\n\n /**\n * Optional function to gather framework-specific context before agent runs.\n * For Next.js: detects router type\n * For React Native: detects Expo vs bare\n */\n gatherContext?: (options: WizardOptions) => Promise<TContext>;\n\n /** Optional additional MCP servers for this framework (e.g., Svelte MCP). */\n additionalMcpServers?: Record<string, { url: string }>;\n}\n\n/**\n * Framework detection and version handling\n */\nexport interface FrameworkDetection {\n /** Package name to check in package.json (e.g., \"next\", \"react\") */\n packageName: string;\n\n /** Human-readable name for error messages (e.g., \"Next.js\") */\n packageDisplayName: string;\n\n /** Extract version from package.json */\n getVersion: (packageJson: unknown) => string | undefined;\n\n /** Optional: Convert version to analytics bucket (e.g., \"15.x\") */\n getVersionBucket?: (version: string) => string;\n\n /**\n * Whether this framework uses package.json (Node.js/JavaScript).\n * If false, skips package.json checks (for Python, Go, etc.)\n * Defaults to true if not specified.\n */\n usesPackageJson?: boolean;\n\n /** Minimum supported version. If set, runner checks before proceeding. */\n minimumVersion?: string;\n\n /** Get the currently installed version. Called by runner for version check. */\n getInstalledVersion?: (options: WizardOptions) => Promise<string | undefined>;\n\n /** Detect whether this framework is present in the project. */\n detect: (options: Pick<WizardOptions, 'installDir'>) => Promise<boolean>;\n}\n\n/**\n * Environment variable configuration\n */\nexport interface EnvironmentConfig {\n /** Whether to upload env vars to hosting providers post-agent */\n uploadToHosting: boolean;\n\n /**\n * Build the environment variables object for this framework.\n * Returns the exact variable names and values to upload to hosting providers.\n */\n getEnvVars: (apiKey: string, host: string) => Record<string, string>;\n}\n\n/**\n * Analytics configuration\n */\nexport interface AnalyticsConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Generate tags from context (e.g., { 'nextjs-version': '15.x', 'router': 'app' }) */\n getTags: (context: TContext) => Record<string, string>;\n\n /** Optional: Additional event properties */\n getEventProperties?: (context: TContext) => Record<string, string>;\n}\n\n/**\n * Prompt configuration\n */\nexport interface PromptConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /**\n * Optional: Additional context lines to append to base prompt\n * For Next.js: \"- Router: app\"\n * For React Native: \"- Platform: Expo\"\n */\n getAdditionalContextLines?: (context: TContext) => string[];\n\n /**\n * How to detect the project type for this framework.\n * e.g., \"Look for package.json and lockfiles\" or \"Look for requirements.txt and manage.py\"\n */\n projectTypeDetection: string;\n\n /**\n * How to install packages for this framework.\n * e.g., \"Use npm/yarn/pnpm based on lockfile\" or \"Use pip/poetry based on config files\"\n */\n packageInstallation: string;\n}\n\n/**\n * UI messaging configuration\n */\nexport interface UIConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Success message when agent completes */\n successMessage: string;\n\n /** Estimated time for agent to complete (in minutes) */\n estimatedDurationMinutes: number;\n\n /** Generate \"What the agent did\" bullets from context */\n getOutroChanges: (context: TContext) => string[];\n\n /** Generate \"Next steps\" bullets from context */\n getOutroNextSteps: (context: TContext) => string[];\n}\n\n/**\n * Generate welcome message from framework name\n */\nexport function getWelcomeMessage(frameworkName: string): string {\n return `PostHog ${frameworkName} wizard (agent-powered)`;\n}\n\n/**\n * Shared spinner message for all frameworks\n */\nexport const SPINNER_MESSAGE =\n 'Writing your PostHog setup with events, error capture and more...';\n"]}
1
+ {"version":3,"file":"framework-config.js","sourceRoot":"","sources":["../../../src/lib/framework-config.ts"],"names":[],"mappings":";;;AA0LA,8CAEC;AAhED;;;;GAIG;AACU,QAAA,4BAA4B,GACvC,wJAAwJ,CAAC;AAE9I,QAAA,2BAA2B,GACtC,8SAA8S,CAAC;AAkDjT;;GAEG;AACH,SAAgB,iBAAiB,CAAC,aAAqB;IACrD,OAAO,WAAW,aAAa,yBAAyB,CAAC;AAC3D,CAAC;AAED;;GAEG;AACU,QAAA,eAAe,GAC1B,mEAAmE,CAAC","sourcesContent":["import type { Integration } from './constants';\nimport type { WizardOptions } from '../utils/types';\nimport type { PackageManagerDetector } from './package-manager-detection';\n\n/**\n * Configuration interface for framework-specific agent integrations.\n * Each framework exports a FrameworkConfig that the universal runner uses.\n *\n * The TContext generic represents the framework-specific context gathered\n * before the agent runs (e.g., router type for Next.js, project type for Django).\n * The runner threads this opaquely — all framework-specific logic stays inside the config.\n */\nexport interface FrameworkConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n metadata: FrameworkMetadata<TContext>;\n detection: FrameworkDetection;\n environment: EnvironmentConfig;\n analytics: AnalyticsConfig<TContext>;\n prompts: PromptConfig<TContext>;\n ui: UIConfig<TContext>;\n}\n\n/**\n * Basic framework information and documentation\n */\nexport interface FrameworkMetadata<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Display name (e.g., \"Next.js\", \"React\") */\n name: string;\n\n /** Integration type from constants */\n integration: Integration;\n\n /** URL to framework-specific PostHog docs */\n docsUrl: string;\n\n /**\n * Optional URL to docs for users with unsupported framework versions.\n * If not provided, defaults to docsUrl.\n */\n unsupportedVersionDocsUrl?: string;\n\n /** If true, shows a beta notice before running the wizard. */\n beta?: boolean;\n\n /** Optional notice shown before the agent runs (e.g., \"Close Xcode before proceeding\"). */\n preRunNotice?: string;\n\n /**\n * Optional function to gather framework-specific context before agent runs.\n * For Next.js: detects router type\n * For React Native: detects Expo vs bare\n */\n gatherContext?: (options: WizardOptions) => Promise<TContext>;\n\n /** Optional additional MCP servers for this framework (e.g., Svelte MCP). */\n additionalMcpServers?: Record<string, { url: string }>;\n}\n\n/**\n * Framework detection and version handling\n */\nexport interface FrameworkDetection {\n /** Package name to check in package.json (e.g., \"next\", \"react\") */\n packageName: string;\n\n /** Human-readable name for error messages (e.g., \"Next.js\") */\n packageDisplayName: string;\n\n /** Extract version from package.json */\n getVersion: (packageJson: unknown) => string | undefined;\n\n /** Optional: Convert version to analytics bucket (e.g., \"15.x\") */\n getVersionBucket?: (version: string) => string;\n\n /**\n * Whether this framework uses package.json (Node.js/JavaScript).\n * If false, skips package.json checks (for Python, Go, etc.)\n * Defaults to true if not specified.\n */\n usesPackageJson?: boolean;\n\n /** Minimum supported version. If set, runner checks before proceeding. */\n minimumVersion?: string;\n\n /** Get the currently installed version. Called by runner for version check. */\n getInstalledVersion?: (options: WizardOptions) => Promise<string | undefined>;\n\n /** Detect whether this framework is present in the project. */\n detect: (options: Pick<WizardOptions, 'installDir'>) => Promise<boolean>;\n\n /** Detect the project's package manager(s). Used by the in-process MCP tool. */\n detectPackageManager: PackageManagerDetector;\n}\n\n/**\n * Environment variable configuration\n */\nexport interface EnvironmentConfig {\n /** Whether to upload env vars to hosting providers post-agent */\n uploadToHosting: boolean;\n\n /**\n * Build the environment variables object for this framework.\n * Returns the exact variable names and values to upload to hosting providers.\n */\n getEnvVars: (apiKey: string, host: string) => Record<string, string>;\n}\n\n/**\n * Analytics configuration\n */\nexport interface AnalyticsConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Generate tags from context (e.g., { 'nextjs-version': '15.x', 'router': 'app' }) */\n getTags: (context: TContext) => Record<string, string>;\n\n /** Optional: Additional event properties */\n getEventProperties?: (context: TContext) => Record<string, string>;\n}\n\n/**\n * Default package installation instruction used when frameworks don't\n * provide their own. Frameworks with specific needs (e.g., Swift SPM,\n * Composer) override this in their config.\n */\nexport const DEFAULT_PACKAGE_INSTALLATION =\n 'Use the detect_package_manager tool to determine the package manager. Do not manually edit package.json; the package manager handles it automatically.';\n\nexport const PYTHON_PACKAGE_INSTALLATION =\n 'Use the detect_package_manager tool to determine the package manager. If the detected tool manages dependencies directly (e.g. uv add, poetry add), use it — it will update the manifest automatically. If using pip, you must also add the dependency to requirements.txt or the appropriate manifest file.';\n\n/**\n * Prompt configuration\n */\nexport interface PromptConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /**\n * Optional: Additional context lines to append to base prompt\n * For Next.js: \"- Router: app\"\n * For React Native: \"- Platform: Expo\"\n */\n getAdditionalContextLines?: (context: TContext) => string[];\n\n /**\n * How to detect the project type for this framework.\n * Included in the agent prompt as project context.\n * e.g., \"Look for package.json and lockfiles\" or \"Look for requirements.txt and manage.py\"\n */\n projectTypeDetection: string;\n\n /**\n * How to install packages for this framework.\n * Included in the agent prompt as project context.\n * Defaults to DEFAULT_PACKAGE_INSTALLATION. Only override if the framework\n * has specific installation guidance (e.g., Swift SPM, Composer).\n */\n packageInstallation?: string;\n}\n\n/**\n * UI messaging configuration\n */\nexport interface UIConfig<\n TContext extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Success message when agent completes */\n successMessage: string;\n\n /** Estimated time for agent to complete (in minutes) */\n estimatedDurationMinutes: number;\n\n /** Generate \"What the agent did\" bullets from context */\n getOutroChanges: (context: TContext) => string[];\n\n /** Generate \"Next steps\" bullets from context */\n getOutroNextSteps: (context: TContext) => string[];\n}\n\n/**\n * Generate welcome message from framework name\n */\nexport function getWelcomeMessage(frameworkName: string): string {\n return `PostHog ${frameworkName} wizard (agent-powered)`;\n}\n\n/**\n * Shared spinner message for all frameworks\n */\nexport const SPINNER_MESSAGE =\n 'Writing your PostHog setup with events, error capture and more...';\n"]}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Cross-ecosystem package manager detection.
3
+ *
4
+ * Provides a common interface (PackageManagerDetector) that each FrameworkConfig
5
+ * implements, plus shared helpers for Node.js, Python, PHP, and Swift ecosystems.
6
+ * The MCP tool in wizard-tools.ts delegates to whatever detector the
7
+ * current framework supplies.
8
+ */
9
+ /** Structured package manager info the agent can act on */
10
+ export interface DetectedPackageManager {
11
+ name: string;
12
+ label: string;
13
+ installCommand: string;
14
+ runCommand?: string;
15
+ }
16
+ /** Result returned by every detector */
17
+ export interface PackageManagerInfo {
18
+ detected: DetectedPackageManager[];
19
+ primary: DetectedPackageManager | null;
20
+ recommendation: string;
21
+ }
22
+ /** Signature each framework implements */
23
+ export type PackageManagerDetector = (installDir: string) => Promise<PackageManagerInfo>;
24
+ /**
25
+ * Detect Node.js package managers via lockfiles.
26
+ * Wraps the existing detectAllPackageManagers() from utils/package-manager.ts.
27
+ */
28
+ export declare function detectNodePackageManagers(installDir: string): Promise<PackageManagerInfo>;
29
+ /**
30
+ * Detect Python package managers via lockfiles and config files.
31
+ * Wraps the existing detectPackageManager() from python/utils.ts.
32
+ */
33
+ export declare function detectPythonPackageManagers(installDir: string): Promise<PackageManagerInfo>;
34
+ export declare function composerPackageManager(): Promise<PackageManagerInfo>;
35
+ export declare function swiftPackageManager(): Promise<PackageManagerInfo>;
36
+ export declare function gradlePackageManager(): Promise<PackageManagerInfo>;