@posthog/wizard 1.33.0 → 1.35.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.
- package/dist/bin.js +9 -0
- package/dist/bin.js.map +1 -1
- package/dist/src/javascript-node/javascript-node-wizard-agent.d.ts +4 -0
- package/dist/src/javascript-node/javascript-node-wizard-agent.js +61 -0
- package/dist/src/javascript-node/javascript-node-wizard-agent.js.map +1 -0
- package/dist/src/javascript-web/javascript-web-wizard-agent.d.ts +3 -0
- package/dist/src/javascript-web/javascript-web-wizard-agent.js +150 -0
- package/dist/src/javascript-web/javascript-web-wizard-agent.js.map +1 -0
- package/dist/src/javascript-web/utils.d.ts +23 -0
- package/dist/src/javascript-web/utils.js +99 -0
- package/dist/src/javascript-web/utils.js.map +1 -0
- package/dist/src/lib/__tests__/agent-interface.test.js +1 -0
- package/dist/src/lib/__tests__/agent-interface.test.js.map +1 -1
- package/dist/src/lib/agent-interface.d.ts +5 -0
- package/dist/src/lib/agent-interface.js +19 -2
- package/dist/src/lib/agent-interface.js.map +1 -1
- package/dist/src/lib/agent-runner.js +8 -4
- package/dist/src/lib/agent-runner.js.map +1 -1
- package/dist/src/lib/api.js +3 -0
- package/dist/src/lib/api.js.map +1 -1
- package/dist/src/lib/constants.d.ts +6 -1
- package/dist/src/lib/constants.js +15 -1
- package/dist/src/lib/constants.js.map +1 -1
- package/dist/src/lib/middleware/benchmark.d.ts +54 -0
- package/dist/src/lib/middleware/benchmark.js +49 -0
- package/dist/src/lib/middleware/benchmark.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/cache-tracker.d.ts +44 -0
- package/dist/src/lib/middleware/benchmarks/cache-tracker.js +81 -0
- package/dist/src/lib/middleware/benchmarks/cache-tracker.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/compaction-tracker.d.ts +29 -0
- package/dist/src/lib/middleware/benchmarks/compaction-tracker.js +60 -0
- package/dist/src/lib/middleware/benchmarks/compaction-tracker.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/context-size-tracker.d.ts +26 -0
- package/dist/src/lib/middleware/benchmarks/context-size-tracker.js +56 -0
- package/dist/src/lib/middleware/benchmarks/context-size-tracker.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/cost-tracker.d.ts +16 -0
- package/dist/src/lib/middleware/benchmarks/cost-tracker.js +76 -0
- package/dist/src/lib/middleware/benchmarks/cost-tracker.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/duration-tracker.d.ts +20 -0
- package/dist/src/lib/middleware/benchmarks/duration-tracker.js +40 -0
- package/dist/src/lib/middleware/benchmarks/duration-tracker.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/index.d.ts +9 -0
- package/dist/src/lib/middleware/benchmarks/index.js +60 -0
- package/dist/src/lib/middleware/benchmarks/index.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/json-writer.d.ts +15 -0
- package/dist/src/lib/middleware/benchmarks/json-writer.js +145 -0
- package/dist/src/lib/middleware/benchmarks/json-writer.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/summary.d.ts +9 -0
- package/dist/src/lib/middleware/benchmarks/summary.js +106 -0
- package/dist/src/lib/middleware/benchmarks/summary.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/token-tracker.d.ts +40 -0
- package/dist/src/lib/middleware/benchmarks/token-tracker.js +77 -0
- package/dist/src/lib/middleware/benchmarks/token-tracker.js.map +1 -0
- package/dist/src/lib/middleware/benchmarks/turn-counter.d.ts +34 -0
- package/dist/src/lib/middleware/benchmarks/turn-counter.js +59 -0
- package/dist/src/lib/middleware/benchmarks/turn-counter.js.map +1 -0
- package/dist/src/lib/middleware/config.d.ts +24 -0
- package/dist/src/lib/middleware/config.js +78 -0
- package/dist/src/lib/middleware/config.js.map +1 -0
- package/dist/src/lib/middleware/index.d.ts +11 -0
- package/dist/src/lib/middleware/index.js +18 -0
- package/dist/src/lib/middleware/index.js.map +1 -0
- package/dist/src/lib/middleware/phase-detector.d.ts +7 -0
- package/dist/src/lib/middleware/phase-detector.js +64 -0
- package/dist/src/lib/middleware/phase-detector.js.map +1 -0
- package/dist/src/lib/middleware/pipeline.d.ts +29 -0
- package/dist/src/lib/middleware/pipeline.js +82 -0
- package/dist/src/lib/middleware/pipeline.js.map +1 -0
- package/dist/src/lib/middleware/types.d.ts +40 -0
- package/dist/src/lib/middleware/types.js +9 -0
- package/dist/src/lib/middleware/types.js.map +1 -0
- package/dist/src/lib/package-manager-detection.d.ts +1 -0
- package/dist/src/lib/package-manager-detection.js +17 -0
- package/dist/src/lib/package-manager-detection.js.map +1 -1
- package/dist/src/lib/registry.js +8 -0
- package/dist/src/lib/registry.js.map +1 -1
- package/dist/src/python/python-wizard-agent.js +1 -78
- package/dist/src/python/python-wizard-agent.js.map +1 -1
- package/dist/src/rails/rails-wizard-agent.d.ts +8 -0
- package/dist/src/rails/rails-wizard-agent.js +90 -0
- package/dist/src/rails/rails-wizard-agent.js.map +1 -0
- package/dist/src/rails/utils.d.ts +37 -0
- package/dist/src/rails/utils.js +187 -0
- package/dist/src/rails/utils.js.map +1 -0
- package/dist/src/ruby/ruby-wizard-agent.d.ts +7 -0
- package/dist/src/ruby/ruby-wizard-agent.js +113 -0
- package/dist/src/ruby/ruby-wizard-agent.js.map +1 -0
- package/dist/src/ruby/utils.d.ts +25 -0
- package/dist/src/ruby/utils.js +158 -0
- package/dist/src/ruby/utils.js.map +1 -0
- package/dist/src/run.d.ts +2 -0
- package/dist/src/run.js +8 -0
- package/dist/src/run.js.map +1 -1
- package/dist/src/utils/clack-utils.d.ts +1 -1
- package/dist/src/utils/clack-utils.js +26 -7
- package/dist/src/utils/clack-utils.js.map +1 -1
- package/dist/src/utils/debug.d.ts +11 -3
- package/dist/src/utils/debug.js +25 -6
- package/dist/src/utils/debug.js.map +1 -1
- package/dist/src/utils/oauth.js +1 -0
- package/dist/src/utils/oauth.js.map +1 -1
- package/dist/src/utils/types.d.ts +11 -0
- package/dist/src/utils/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
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,gDAAgD;IAChD,8DAA4C,CAAA;IAC5C,8BAA8B;IAC9B,kDAAgC,CAAA;IAChC,wBAAwB;IACxB,gDAA8B,CAAA;AAChC,CAAC,EATW,cAAc,8BAAd,cAAc,QASzB;AAoBD;;GAEG;AACH,MAAM,gBAAgB,GAAG;IACvB,a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,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"]}
|
|
1
|
+
{"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../../src/lib/agent-interface.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AA8LH,4CAoIC;AAKD,0CA8EC;AAQD,4BAySC;AApsBD,gDAAwB;AACxB,2DAAmC;AACnC,0CAA+E;AAE/E,kDAA+C;AAC/C,2CAIqB;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,CA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ED,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, getLogFilePath } 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 WIZARD_USER_AGENT,\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 /** Signal prefix for benchmark logging */\n BENCHMARK: '[BENCHMARK]',\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 'User-Agent': WIZARD_USER_AGENT,\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: ${getLogFilePath()}`);\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 middleware?: {\n onMessage(message: any): void;\n finalize(resultMessage: any, totalDurationMs: number): any;\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 let lastResultMessage: any = null;\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 try {\n middleware?.finalize(lastResultMessage, durationMs);\n } catch (e) {\n logToFile(`${AgentSignals.BENCHMARK} Middleware finalize error:`, e);\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 try {\n middleware?.onMessage(message);\n } catch (e) {\n logToFile(`${AgentSignals.BENCHMARK} Middleware onMessage error:`, e);\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 lastResultMessage = message;\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"]}
|
|
@@ -49,6 +49,7 @@ const semver = __importStar(require("semver"));
|
|
|
49
49
|
const steps_1 = require("../steps");
|
|
50
50
|
const anthropic_status_1 = require("../utils/anthropic-status");
|
|
51
51
|
const debug_1 = require("../utils/debug");
|
|
52
|
+
const benchmark_1 = require("./middleware/benchmark");
|
|
52
53
|
/**
|
|
53
54
|
* Universal agent-powered wizard runner.
|
|
54
55
|
* Handles the complete flow for any framework using PostHog MCP integration.
|
|
@@ -116,7 +117,7 @@ async function runAgentWizard(config, options) {
|
|
|
116
117
|
integration: config.metadata.integration,
|
|
117
118
|
});
|
|
118
119
|
// Get PostHog credentials
|
|
119
|
-
const { projectApiKey, host, accessToken } = await (0, clack_utils_1.getOrAskForProjectData)({
|
|
120
|
+
const { projectApiKey, host, accessToken, projectId } = await (0, clack_utils_1.getOrAskForProjectData)({
|
|
120
121
|
...options,
|
|
121
122
|
cloudRegion,
|
|
122
123
|
});
|
|
@@ -129,12 +130,12 @@ async function runAgentWizard(config, options) {
|
|
|
129
130
|
Object.entries(contextTags).forEach(([key, value]) => {
|
|
130
131
|
analytics_1.analytics.setTag(key, value);
|
|
131
132
|
});
|
|
132
|
-
// Build integration prompt
|
|
133
133
|
const integrationPrompt = buildIntegrationPrompt(config, {
|
|
134
134
|
frameworkVersion: frameworkVersion || 'latest',
|
|
135
135
|
typescript: typeScriptDetected,
|
|
136
136
|
projectApiKey,
|
|
137
137
|
host,
|
|
138
|
+
projectId,
|
|
138
139
|
}, frameworkContext);
|
|
139
140
|
// Initialize and run agent
|
|
140
141
|
const spinner = clack_1.default.spinner();
|
|
@@ -155,12 +156,15 @@ async function runAgentWizard(config, options) {
|
|
|
155
156
|
additionalMcpServers: config.metadata.additionalMcpServers,
|
|
156
157
|
detectPackageManager: config.detection.detectPackageManager,
|
|
157
158
|
}, options);
|
|
159
|
+
const middleware = options.benchmark
|
|
160
|
+
? (0, benchmark_1.createBenchmarkPipeline)(spinner, options)
|
|
161
|
+
: undefined;
|
|
158
162
|
const agentResult = await (0, agent_interface_1.runAgent)(agent, integrationPrompt, options, spinner, {
|
|
159
163
|
estimatedDurationMinutes: config.ui.estimatedDurationMinutes,
|
|
160
164
|
spinnerMessage: framework_config_1.SPINNER_MESSAGE,
|
|
161
165
|
successMessage: config.ui.successMessage,
|
|
162
166
|
errorMessage: 'Integration failed',
|
|
163
|
-
});
|
|
167
|
+
}, middleware);
|
|
164
168
|
// Handle error cases detected in agent output
|
|
165
169
|
if (agentResult.error === agent_interface_1.AgentErrorType.MCP_MISSING) {
|
|
166
170
|
analytics_1.analytics.captureException(new Error('Agent could not access PostHog MCP server'), {
|
|
@@ -273,7 +277,6 @@ ${chalk_1.default.dim(`How did this work for you? Drop us a line: wizard@posthog
|
|
|
273
277
|
}
|
|
274
278
|
/**
|
|
275
279
|
* Build the integration prompt for the agent.
|
|
276
|
-
* Uses shared base prompt with optional framework-specific addendum.
|
|
277
280
|
*/
|
|
278
281
|
function buildIntegrationPrompt(config, context, frameworkContext) {
|
|
279
282
|
const additionalLines = config.prompts.getAdditionalContextLines
|
|
@@ -285,6 +288,7 @@ function buildIntegrationPrompt(config, context, frameworkContext) {
|
|
|
285
288
|
return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${config.metadata.name} project.
|
|
286
289
|
|
|
287
290
|
Project context:
|
|
291
|
+
- PostHog Project ID: ${context.projectId}
|
|
288
292
|
- Framework: ${config.metadata.name} ${context.frameworkVersion}
|
|
289
293
|
- TypeScript: ${context.typescript ? 'Yes' : 'No'}
|
|
290
294
|
- PostHog API Key: ${context.projectApiKey}
|
|
@@ -1 +1 @@
|
|
|
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,GAA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CAAC,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
|
+
{"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../src/lib/agent-runner.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,wCA2TC;AAtWD,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;AACjD,sDAAiE;AAEjE;;;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,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACvC,IAAI,OAAO,IAAI,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,EAAE,CAAC;gBACnE,MAAM,OAAO,GACX,MAAM,CAAC,QAAQ,CAAC,yBAAyB,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;gBACvE,eAAK,CAAC,GAAG,CAAC,IAAI,CACZ,yCAAyC,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,OAAO,gBAAgB,MAAM,CAAC,QAAQ,CAAC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import 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';\nimport { createBenchmarkPipeline } from './middleware/benchmark';\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, projectId } =\n 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 const integrationPrompt = buildIntegrationPrompt(\n config,\n {\n frameworkVersion: frameworkVersion || 'latest',\n typescript: typeScriptDetected,\n projectApiKey,\n host,\n projectId,\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 middleware = options.benchmark\n ? createBenchmarkPipeline(spinner, options)\n : undefined;\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 middleware,\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 */\nfunction buildIntegrationPrompt(\n config: FrameworkConfig,\n context: {\n frameworkVersion: string;\n typescript: boolean;\n projectApiKey: string;\n host: string;\n projectId: number;\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- PostHog Project ID: ${context.projectId}\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"]}
|
package/dist/src/lib/api.js
CHANGED
|
@@ -9,6 +9,7 @@ exports.fetchProjectData = fetchProjectData;
|
|
|
9
9
|
const axios_1 = __importDefault(require("axios"));
|
|
10
10
|
const zod_1 = require("zod");
|
|
11
11
|
const analytics_1 = require("../utils/analytics");
|
|
12
|
+
const constants_1 = require("./constants");
|
|
12
13
|
exports.ApiUserSchema = zod_1.z.object({
|
|
13
14
|
distinct_id: zod_1.z.string(),
|
|
14
15
|
organizations: zod_1.z.array(zod_1.z.object({
|
|
@@ -44,6 +45,7 @@ async function fetchUserData(accessToken, baseUrl) {
|
|
|
44
45
|
const response = await axios_1.default.get(`${baseUrl}/api/users/@me/`, {
|
|
45
46
|
headers: {
|
|
46
47
|
Authorization: `Bearer ${accessToken}`,
|
|
48
|
+
'User-Agent': constants_1.WIZARD_USER_AGENT,
|
|
47
49
|
},
|
|
48
50
|
});
|
|
49
51
|
return exports.ApiUserSchema.parse(response.data);
|
|
@@ -62,6 +64,7 @@ async function fetchProjectData(accessToken, projectId, baseUrl) {
|
|
|
62
64
|
const response = await axios_1.default.get(`${baseUrl}/api/projects/${projectId}/`, {
|
|
63
65
|
headers: {
|
|
64
66
|
Authorization: `Bearer ${accessToken}`,
|
|
67
|
+
'User-Agent': constants_1.WIZARD_USER_AGENT,
|
|
65
68
|
},
|
|
66
69
|
});
|
|
67
70
|
return exports.ApiProjectSchema.parse(response.data);
|
package/dist/src/lib/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../../src/lib/api.ts"],"names":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../../src/lib/api.ts"],"names":[],"mappings":";;;;;;AA2CA,sCAqBC;AAED,4CAuBC;AAzFD,kDAA0C;AAC1C,6BAAwB;AACxB,kDAA+C;AAC/C,2CAAgD;AAEnC,QAAA,aAAa,GAAG,OAAC,CAAC,MAAM,CAAC;IACp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MAAM,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC;QACjD,MAAM,QAAQ,GAAG,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC;QAExC,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,IAAI,QAAQ,CACjB,yCAAyC,SAAS,EAAE,EACpD,MAAM,EACN,QAAQ,CACT,CAAC;QACJ,CAAC;QAED,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,IAAI,QAAQ,CACjB,iCAAiC,SAAS,EAAE,EAC5C,MAAM,EACN,QAAQ,CACT,CAAC;QACJ,CAAC;QAED,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,IAAI,QAAQ,CACjB,sCAAsC,SAAS,EAAE,EACjD,MAAM,EACN,QAAQ,CACT,CAAC;QACJ,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,IAAI,aAAa,SAAS,EAAE,CAAC;QACnD,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,YAAY,OAAC,CAAC,QAAQ,EAAE,CAAC;QAChC,OAAO,IAAI,QAAQ,CAAC,2CAA2C,SAAS,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED,OAAO,IAAI,QAAQ,CACjB,oCAAoC,SAAS,KAC3C,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAC3C,EAAE,CACH,CAAC;AACJ,CAAC","sourcesContent":["import axios, { AxiosError } from 'axios';\nimport { z } from 'zod';\nimport { analytics } from '../utils/analytics';\nimport { WIZARD_USER_AGENT } from './constants';\n\nexport const ApiUserSchema = z.object({\n distinct_id: z.string(),\n organizations: z.array(\n z.object({\n id: z.string().uuid(),\n }),\n ),\n team: z.object({\n id: z.number(),\n organization: z.string().uuid(),\n }),\n organization: z.object({\n id: z.string().uuid(),\n }),\n});\n\nexport const ApiProjectSchema = z.object({\n id: z.number(),\n uuid: z.string().uuid(),\n organization: z.string().uuid(),\n api_token: z.string(),\n name: z.string(),\n});\n\nexport type ApiUser = z.infer<typeof ApiUserSchema>;\nexport type ApiProject = z.infer<typeof ApiProjectSchema>;\n\nclass ApiError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly endpoint?: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n\nexport async function fetchUserData(\n accessToken: string,\n baseUrl: string,\n): Promise<ApiUser> {\n try {\n const response = await axios.get(`${baseUrl}/api/users/@me/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n });\n\n return ApiUserSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch user data');\n analytics.captureException(apiError, {\n endpoint: '/api/users/@me/',\n baseUrl,\n });\n throw apiError;\n }\n}\n\nexport async function fetchProjectData(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n): Promise<ApiProject> {\n try {\n const response = await axios.get(`${baseUrl}/api/projects/${projectId}/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n });\n\n return ApiProjectSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch project data');\n analytics.captureException(apiError, {\n endpoint: `/api/projects/${projectId}/`,\n baseUrl,\n projectId,\n });\n throw apiError;\n }\n}\n\nfunction handleApiError(error: unknown, operation: string): ApiError {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<{ detail?: string }>;\n const status = axiosError.response?.status;\n const detail = axiosError.response?.data?.detail;\n const endpoint = axiosError.config?.url;\n\n if (status === 401) {\n return new ApiError(\n `Authentication failed while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 403) {\n return new ApiError(\n `Access denied while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 404) {\n return new ApiError(\n `Resource not found while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n const message = detail || `Failed to ${operation}`;\n return new ApiError(message, status, endpoint);\n }\n\n if (error instanceof z.ZodError) {\n return new ApiError(`Invalid response format while trying to ${operation}`);\n }\n\n return new ApiError(\n `Unexpected error while trying to ${operation}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n );\n}\n"]}
|
|
@@ -18,7 +18,11 @@ export declare enum Integration {
|
|
|
18
18
|
sveltekit = "sveltekit",
|
|
19
19
|
swift = "swift",
|
|
20
20
|
android = "android",
|
|
21
|
-
|
|
21
|
+
rails = "rails",
|
|
22
|
+
python = "python",
|
|
23
|
+
ruby = "ruby",
|
|
24
|
+
javascriptNode = "javascript_node",
|
|
25
|
+
javascript_web = "javascript_web"
|
|
22
26
|
}
|
|
23
27
|
export interface Args {
|
|
24
28
|
debug: boolean;
|
|
@@ -39,3 +43,4 @@ export declare const POSTHOG_DEV_CLIENT_ID = "DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqd
|
|
|
39
43
|
export declare const OAUTH_PORT = 8239;
|
|
40
44
|
export declare const WIZARD_INTERACTION_EVENT_NAME = "wizard interaction";
|
|
41
45
|
export declare const WIZARD_REMARK_EVENT_NAME = "wizard remark";
|
|
46
|
+
export declare const WIZARD_USER_AGENT: string;
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WIZARD_REMARK_EVENT_NAME = exports.WIZARD_INTERACTION_EVENT_NAME = exports.OAUTH_PORT = exports.POSTHOG_DEV_CLIENT_ID = exports.POSTHOG_EU_CLIENT_ID = exports.POSTHOG_US_CLIENT_ID = exports.DUMMY_PROJECT_API_KEY = exports.ANALYTICS_TEAM_TAG = exports.ANALYTICS_HOST_URL = exports.ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = exports.DEFAULT_HOST_URL = exports.ISSUES_URL = exports.DEFAULT_URL = exports.DEBUG = exports.IS_DEV = exports.Integration = void 0;
|
|
6
|
+
exports.WIZARD_USER_AGENT = exports.WIZARD_REMARK_EVENT_NAME = exports.WIZARD_INTERACTION_EVENT_NAME = exports.OAUTH_PORT = exports.POSTHOG_DEV_CLIENT_ID = exports.POSTHOG_EU_CLIENT_ID = exports.POSTHOG_US_CLIENT_ID = exports.DUMMY_PROJECT_API_KEY = exports.ANALYTICS_TEAM_TAG = exports.ANALYTICS_HOST_URL = exports.ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = exports.DEFAULT_HOST_URL = exports.ISSUES_URL = exports.DEFAULT_URL = exports.DEBUG = exports.IS_DEV = exports.Integration = void 0;
|
|
4
7
|
/**
|
|
5
8
|
* Detection order matters: put framework-specific integrations BEFORE basic language fallbacks
|
|
6
9
|
*/
|
|
@@ -23,8 +26,12 @@ var Integration;
|
|
|
23
26
|
Integration["sveltekit"] = "sveltekit";
|
|
24
27
|
Integration["swift"] = "swift";
|
|
25
28
|
Integration["android"] = "android";
|
|
29
|
+
Integration["rails"] = "rails";
|
|
26
30
|
// Language fallbacks
|
|
27
31
|
Integration["python"] = "python";
|
|
32
|
+
Integration["ruby"] = "ruby";
|
|
33
|
+
Integration["javascriptNode"] = "javascript_node";
|
|
34
|
+
Integration["javascript_web"] = "javascript_web";
|
|
28
35
|
})(Integration || (exports.Integration = Integration = {}));
|
|
29
36
|
exports.IS_DEV = ['test', 'development'].includes(process.env.NODE_ENV ?? '');
|
|
30
37
|
exports.DEBUG = false;
|
|
@@ -45,4 +52,11 @@ exports.POSTHOG_DEV_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ';
|
|
|
45
52
|
exports.OAUTH_PORT = 8239;
|
|
46
53
|
exports.WIZARD_INTERACTION_EVENT_NAME = 'wizard interaction';
|
|
47
54
|
exports.WIZARD_REMARK_EVENT_NAME = 'wizard remark';
|
|
55
|
+
/**
|
|
56
|
+
* User-Agent string for the wizard when making HTTP requests.
|
|
57
|
+
* Used for direct PostHog API calls and passed to the MCP server
|
|
58
|
+
* so it can identify requests originating from the wizard.
|
|
59
|
+
*/
|
|
60
|
+
const package_json_1 = __importDefault(require("../../package.json"));
|
|
61
|
+
exports.WIZARD_USER_AGENT = `posthog/wizard; version: ${package_json_1.default.version}`;
|
|
48
62
|
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;;;;AAAA;;GAEG;AACH,IAAY,WAyBX;AAzBD,WAAY,WAAW;IACrB,aAAa;IACb,gCAAiB,CAAA;IACjB,4BAAa,CAAA;IACb,0BAAW,CAAA;IACX,2CAA4B,CAAA;IAC5B,+CAAgC,CAAA;IAChC,iDAAkC,CAAA;IAClC,2CAA4B,CAAA;IAC5B,kCAAmB,CAAA;IACnB,8BAAe,CAAA;IACf,gCAAiB,CAAA;IACjB,8BAAe,CAAA;IACf,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;IACnB,sCAAuB,CAAA;IACvB,8BAAe,CAAA;IACf,kCAAmB,CAAA;IACnB,8BAAe,CAAA;IAEf,qBAAqB;IACrB,gCAAiB,CAAA;IACjB,4BAAa,CAAA;IACb,iDAAkC,CAAA;IAClC,gDAAiC,CAAA;AACnC,CAAC,EAzBW,WAAW,2BAAX,WAAW,QAyBtB;AAMY,QAAA,MAAM,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,QAAQ,CACpD,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAC3B,CAAC;AAEW,QAAA,KAAK,GAAG,KAAK,CAAC;AAEd,QAAA,WAAW,GAAG,cAAM;IAC/B,CAAC,CAAC,uBAAuB;IACzB,CAAC,CAAC,wBAAwB,CAAC;AAChB,QAAA,UAAU,GAAG,0CAA0C,CAAC;AACxD,QAAA,gBAAgB,GAAG,cAAM;IACpC,CAAC,CAAC,uBAAuB;IACzB,CAAC,CAAC,0BAA0B,CAAC;AAClB,QAAA,0CAA0C,GAAG,gBAAgB,CAAC;AAC9D,QAAA,kBAAkB,GAAG,gCAAgC,CAAC;AACtD,QAAA,kBAAkB,GAAG,iBAAiB,CAAC;AACvC,QAAA,qBAAqB,GAAG,gCAAgC,CAAC;AAEzD,QAAA,oBAAoB,GAAG,0CAA0C,CAAC;AAClE,QAAA,oBAAoB,GAAG,0CAA0C,CAAC;AAClE,QAAA,qBAAqB,GAAG,0CAA0C,CAAC;AACnE,QAAA,UAAU,GAAG,IAAI,CAAC;AAElB,QAAA,6BAA6B,GAAG,oBAAoB,CAAC;AACrD,QAAA,wBAAwB,GAAG,eAAe,CAAC;AAExD;;;;GAIG;AACH,sEAA6C;AAChC,QAAA,iBAAiB,GAAG,4BAA4B,sBAAW,CAAC,OAAO,EAAE,CAAC","sourcesContent":["/**\n * Detection order matters: put framework-specific integrations BEFORE basic language fallbacks\n */\nexport enum Integration {\n // Frameworks\n nextjs = 'nextjs',\n nuxt = 'nuxt',\n vue = 'vue',\n reactRouter = 'react-router',\n tanstackStart = 'tanstack-start',\n tanstackRouter = 'tanstack-router',\n reactNative = 'react-native',\n angular = 'angular',\n astro = 'astro',\n django = 'django',\n flask = 'flask',\n fastapi = 'fastapi',\n laravel = 'laravel',\n sveltekit = 'sveltekit',\n swift = 'swift',\n android = 'android',\n rails = 'rails',\n\n // Language fallbacks\n python = 'python',\n ruby = 'ruby',\n javascriptNode = 'javascript_node',\n javascript_web = 'javascript_web',\n}\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\nexport const IS_DEV = ['test', 'development'].includes(\n process.env.NODE_ENV ?? '',\n);\n\nexport const DEBUG = false;\n\nexport const DEFAULT_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.posthog.com';\nexport const ISSUES_URL = 'https://github.com/posthog/wizard/issues';\nexport const DEFAULT_HOST_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.i.posthog.com';\nexport const ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = 'sTMFPsFhdP1Ssg';\nexport const ANALYTICS_HOST_URL = 'https://internal-j.posthog.com';\nexport const ANALYTICS_TEAM_TAG = 'docs-and-wizard';\nexport const DUMMY_PROJECT_API_KEY = '_YOUR_POSTHOG_PROJECT_API_KEY_';\n\nexport const POSTHOG_US_CLIENT_ID = 'c4Rdw8DIxgtQfA80IiSnGKlNX8QN00cFWF00QQhM';\nexport const POSTHOG_EU_CLIENT_ID = 'bx2C5sZRN03TkdjraCcetvQFPGH6N2Y9vRLkcKEy';\nexport const POSTHOG_DEV_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ';\nexport const OAUTH_PORT = 8239;\n\nexport const WIZARD_INTERACTION_EVENT_NAME = 'wizard interaction';\nexport const WIZARD_REMARK_EVENT_NAME = 'wizard remark';\n\n/**\n * User-Agent string for the wizard when making HTTP requests.\n * Used for direct PostHog API calls and passed to the MCP server\n * so it can identify requests originating from the wizard.\n */\nimport packageJson from '../../package.json';\nexport const WIZARD_USER_AGENT = `posthog/wizard; version: ${packageJson.version}`;\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Benchmark tracking for wizard runs.
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* const pipeline = createBenchmarkPipeline(spinner, options);
|
|
6
|
+
* pipeline.onMessage(message);
|
|
7
|
+
* pipeline.finalize(resultMessage, durationMs);
|
|
8
|
+
*/
|
|
9
|
+
import clack from '../../utils/clack';
|
|
10
|
+
import { MiddlewarePipeline } from './pipeline';
|
|
11
|
+
import type { BenchmarkConfig } from './config';
|
|
12
|
+
import type { WizardOptions } from '../../utils/types';
|
|
13
|
+
export interface StepUsage {
|
|
14
|
+
name: string;
|
|
15
|
+
usage: {
|
|
16
|
+
input_tokens: number;
|
|
17
|
+
output_tokens: number;
|
|
18
|
+
cache_creation_input_tokens: number;
|
|
19
|
+
cache_read_input_tokens: number;
|
|
20
|
+
cache_creation?: {
|
|
21
|
+
ephemeral_5m_input_tokens: number;
|
|
22
|
+
ephemeral_1h_input_tokens: number;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
modelUsage: Record<string, unknown>;
|
|
26
|
+
totalCostUsd: number;
|
|
27
|
+
durationMs: number;
|
|
28
|
+
durationApiMs: number;
|
|
29
|
+
numTurns: number;
|
|
30
|
+
contextTokensIn?: number;
|
|
31
|
+
contextTokensOut?: number;
|
|
32
|
+
compactions?: number;
|
|
33
|
+
compactionPreTokens?: number[];
|
|
34
|
+
}
|
|
35
|
+
export interface BenchmarkData {
|
|
36
|
+
timestamp: string;
|
|
37
|
+
steps: StepUsage[];
|
|
38
|
+
totals: {
|
|
39
|
+
totalCostUsd: number;
|
|
40
|
+
durationMs: number;
|
|
41
|
+
inputTokens: number;
|
|
42
|
+
outputTokens: number;
|
|
43
|
+
numTurns: number;
|
|
44
|
+
totalCompactions: number;
|
|
45
|
+
totalCacheReadTokens: number;
|
|
46
|
+
totalCacheCreation5mTokens: number;
|
|
47
|
+
totalCacheCreation1hTokens: number;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Create a middleware pipeline configured for benchmarking.
|
|
52
|
+
* Loads .benchmark-config.json from the install dir, falls back to defaults.
|
|
53
|
+
*/
|
|
54
|
+
export declare function createBenchmarkPipeline(spinner: ReturnType<typeof clack.spinner>, options: WizardOptions, configOverride?: BenchmarkConfig): MiddlewarePipeline;
|