@posthog/wizard 2.6.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -714,6 +714,11 @@ async function runAgent(agentConfig, prompt, options, spinner, config, middlewar
714
714
  ...process.env,
715
715
  // Prevent user's Anthropic API key from overriding the wizard's OAuth token
716
716
  ANTHROPIC_API_KEY: undefined,
717
+ // Defer MCP tool schemas to avoid bloating the system prompt.
718
+ // The posthog-wizard MCP exposes many query tools with large schemas;
719
+ // without deferral these consume ~113k tokens upfront, leaving
720
+ // almost no room in Sonnet's 200k context window.
721
+ ENABLE_TOOL_SEARCH: 'auto:0',
717
722
  ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(agentConfig.wizardMetadata ?? {}, agentConfig.wizardFlags ?? {}),
718
723
  },
719
724
  canUseTool: (toolName, input) => {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../../src/lib/agent-interface.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoJH,oEAcC;AAaD,8DAoCC;AAMD,gEAqBC;AAMD,sDAeC;AAgCD,wCA+CC;AAiBD,kDAOC;AA8GD,4CAwHC;AAKD,0CAmFC;AA2BD,4BAyYC;AA1kCD,gDAAwB;AACxB,uCAAyB;AACzB,8BAAkD;AAClD,0CAA+E;AAE/E,kDAA+C;AAC/C,2CAMqB;AACrB,qDAG0B;AAC1B,wDAI+B;AAC/B,4DAA8D;AAC9D,wCAAyD;AACzD,6CAA6C;AAC7C,iDAA4E;AAC5E,6CAGsB;AACtB,iDAAuD;AAGvD,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,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BACvC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBACrC,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,IAAA,iBAAS,EAAC,0BAA0B,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;gBACtD,oEAAoE;gBACpE,mDAAmD;gBACnD,IAAI,OAAO,CAAC,MAAM,IAAI,CAAC,qBAAqB,EAAE,CAAC;oBAC7C,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;wBACjC,IAAA,UAAK,GAAE,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC;wBACnC,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 * as fs from 'fs';\nimport { getUI, type SpinnerHandle } from '../ui';\nimport { debug, logToFile, initLogFile, getLogFilePath } from '../utils/debug';\nimport type { WizardOptions } from '../utils/types';\nimport { analytics } from '../utils/analytics';\nimport {\n WIZARD_REMARK_EVENT_NAME,\n POSTHOG_PROPERTY_HEADER_PREFIX,\n WIZARD_VARIANT_FLAG_KEY,\n WIZARD_VARIANTS,\n WIZARD_USER_AGENT,\n} from './constants';\nimport {\n type AdditionalFeature,\n ADDITIONAL_FEATURE_PROMPTS,\n} from './wizard-session';\nimport {\n registerCleanup,\n wizardAbort,\n WizardError,\n} from '../utils/wizard-abort';\nimport { createCustomHeaders } from '../utils/custom-headers';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls';\nimport { LINTING_TOOLS } from './safe-tools';\nimport { createWizardToolsServer, WIZARD_TOOL_NAMES } from './wizard-tools';\nimport {\n createPreToolUseYaraHooks,\n createPostToolUseYaraHooks,\n} from './yara-hooks';\nimport { getWizardCommandments } from './commandments';\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 /** YARA scanner detected a security violation */\n YARA_VIOLATION = 'WIZARD_YARA_VIOLATION',\n}\n\nconst BLOCKING_ENV_KEYS = [\n 'ANTHROPIC_API_KEY',\n 'ANTHROPIC_BASE_URL',\n 'ANTHROPIC_AUTH_TOKEN',\n];\nconst BLOCKING_SETTINGS_KEYS = ['apiKeyHelper'];\n\n/** Where a settings conflict was found. */\nexport type SettingsConflictSource = 'project' | 'managed';\n\n/** A single settings conflict detected during startup. */\nexport interface SettingsConflict {\n /** Where the conflict was found. */\n source: SettingsConflictSource;\n /** The blocking keys found (e.g. 'ANTHROPIC_BASE_URL', 'apiKeyHelper'). */\n keys: string[];\n /** Whether the wizard can back up / remove this file. Managed settings are read-only. */\n writable: boolean;\n}\n\n/**\n * Check a single settings file for blocking env keys and top-level settings keys.\n * Returns matched key names, or an empty array if none found.\n */\nfunction checkSettingsFile(filePath: string): string[] {\n try {\n const raw = fs.readFileSync(filePath, 'utf-8');\n const parsed = JSON.parse(raw);\n const matched: string[] = [];\n\n // Check env block for blocking env keys\n const envBlock = parsed?.env;\n if (envBlock && typeof envBlock === 'object') {\n matched.push(...BLOCKING_ENV_KEYS.filter((key) => key in envBlock));\n }\n\n // Check top-level settings keys\n matched.push(\n ...BLOCKING_SETTINGS_KEYS.filter(\n (key) => key in parsed && parsed[key] !== '' && parsed[key] != null,\n ),\n );\n\n return matched;\n } catch {\n // File doesn't exist or isn't valid JSON — skip\n return [];\n }\n}\n\n/**\n * Check if .claude/settings.json in the project directory contains env\n * overrides or apiKeyHelper that block the Wizard from accessing the PostHog LLM Gateway.\n * Returns the list of matched key names, or an empty array if none found.\n *\n * @deprecated Use {@link checkAllSettingsConflicts} for comprehensive detection.\n */\nexport function checkClaudeSettingsOverrides(\n workingDirectory: string,\n): string[] {\n const candidates = [\n path.join(workingDirectory, '.claude', 'settings.json'),\n path.join(workingDirectory, '.claude', 'settings'),\n ];\n\n for (const filePath of candidates) {\n const matched = checkSettingsFile(filePath);\n if (matched.length > 0) return matched;\n }\n\n return [];\n}\n\n/**\n * Managed settings path on macOS.\n * IT/MDM-deployed settings — readable by all users, writable only by root.\n */\nconst MANAGED_SETTINGS_PATH =\n '/Library/Application Support/ClaudeCode/managed-settings.json';\n\n/**\n * Check project and org-managed settings for blocking keys that conflict\n * with the wizard's proxy auth.\n */\nexport function checkAllSettingsConflicts(\n workingDirectory: string,\n): SettingsConflict[] {\n const conflicts: SettingsConflict[] = [];\n\n const sources: {\n source: SettingsConflictSource;\n paths: string[];\n writable: boolean;\n }[] = [\n {\n source: 'managed',\n paths: [MANAGED_SETTINGS_PATH],\n writable: false,\n },\n {\n source: 'project',\n paths: [\n path.join(workingDirectory, '.claude', 'settings.json'),\n path.join(workingDirectory, '.claude', 'settings'),\n ],\n writable: true,\n },\n ];\n\n for (const { source, paths, writable } of sources) {\n for (const filePath of paths) {\n const keys = checkSettingsFile(filePath);\n if (keys.length > 0) {\n conflicts.push({ source, keys, writable });\n break; // Only one conflict per source (settings.json vs settings fallback)\n }\n }\n }\n\n return conflicts;\n}\n\n/**\n * Copy .claude/settings.json to .wizard-backup (overwriting if it exists),\n * then remove the original so the SDK doesn't load the blocking overrides.\n */\nexport function backupAndFixClaudeSettings(workingDirectory: string): boolean {\n for (const name of ['settings.json', 'settings']) {\n const filePath = path.join(workingDirectory, '.claude', name);\n const backupPath = `${filePath}.wizard-backup`;\n analytics.wizardCapture('backedup-claude-settings');\n try {\n fs.copyFileSync(filePath, backupPath);\n fs.unlinkSync(filePath);\n registerCleanup(() => {\n try {\n restoreClaudeSettings(workingDirectory);\n } catch (error) {\n analytics.captureException(error);\n }\n });\n return true;\n } catch {\n // File doesn't exist — try next candidate\n }\n }\n return false;\n}\n\n/**\n * Restore .claude/settings.json from .wizard-backup.\n * Copies (not moves) so the backup is preserved.\n */\nexport function restoreClaudeSettings(workingDirectory: string): void {\n for (const name of ['settings.json', 'settings']) {\n const backup = path.join(\n workingDirectory,\n '.claude',\n `${name}.wizard-backup`,\n );\n try {\n fs.copyFileSync(backup, path.join(workingDirectory, '.claude', name));\n analytics.wizardCapture('restored-claude-settings');\n return;\n } catch (error) {\n analytics.captureException(error);\n }\n }\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 /** Base URL for the skills server (context-mill dev or GitHub releases) */\n skillsBaseUrl: string;\n /** Feature flag key -> variant (evaluated at start of run). */\n wizardFlags?: Record<string, string>;\n wizardMetadata?: Record<string, string>;\n};\n\n/**\n * Stop hook return type: either allow stop or block with a reason.\n */\nexport type StopHookResult =\n | Record<string, never>\n | { decision: 'block'; reason: string };\n\n/**\n * Create a stop hook callback that drains the additional feature queue,\n * then collects a remark, then allows stop.\n *\n * Three-phase logic using closure state:\n * Phase 1 — drain queue: block with each feature prompt in order\n * Phase 2 — collect remark (once): block with remark prompt\n * Phase 3 — allow stop: return {}\n */\nexport function createStopHook(\n featureQueue: readonly AdditionalFeature[],\n collectedText?: string[],\n): (input: { stop_hook_active: boolean }) => StopHookResult {\n let featureIndex = 0;\n let remarkRequested = false;\n\n return (input: { stop_hook_active: boolean }): StopHookResult => {\n logToFile('Stop hook triggered', {\n stop_hook_active: input.stop_hook_active,\n featureIndex,\n remarkRequested,\n queueLength: featureQueue.length,\n });\n\n // On API errors, allow stop immediately — blocking with remark/feature\n // prompts would just fail again. The auth error screen is shown separately.\n if (collectedText) {\n const text = collectedText.join('\\n');\n if (text.includes('API Error:')) {\n logToFile('Stop hook: API error detected, allowing immediate stop');\n return {};\n }\n }\n\n // Phase 1: drain feature queue\n if (featureIndex < featureQueue.length) {\n const feature = featureQueue[featureIndex++];\n const prompt = ADDITIONAL_FEATURE_PROMPTS[feature];\n logToFile(`Stop hook: injecting feature prompt for ${feature}`);\n return { decision: 'block', reason: prompt };\n }\n\n // Phase 2: collect remark (once)\n if (!remarkRequested) {\n remarkRequested = true;\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 // Phase 3: allow stop\n logToFile('Stop hook: allowing stop');\n return {};\n };\n}\n\n/**\n * Internal configuration object returned by initializeAgent\n */\ntype AgentRunConfig = {\n workingDirectory: string;\n mcpServers: McpServersConfig;\n model: string;\n wizardFlags?: Record<string, string>;\n wizardMetadata?: Record<string, string>;\n};\n\n/**\n * Select wizard metadata from WIZARD_VARIANTS using the variant feature flag.\n * If the flag is missing or the value is not in config, returns the \"base\" variant (VARIANT: \"base\").\n */\nexport function buildWizardMetadata(\n flags: Record<string, string> = {},\n): Record<string, string> {\n const variantKey = flags[WIZARD_VARIANT_FLAG_KEY];\n const variant =\n (variantKey && WIZARD_VARIANTS[variantKey]) ?? WIZARD_VARIANTS['base'];\n return { ...variant };\n}\n\n/**\n * Build env for the SDK subprocess: process.env plus ANTHROPIC_CUSTOM_HEADERS from wizard metadata/flags.\n */\nfunction buildAgentEnv(\n wizardMetadata: Record<string, string>,\n wizardFlags: Record<string, string>,\n): string {\n const headers = createCustomHeaders();\n for (const [key, value] of Object.entries(wizardMetadata)) {\n headers.add(\n key.startsWith(POSTHOG_PROPERTY_HEADER_PREFIX)\n ? key\n : `${POSTHOG_PROPERTY_HEADER_PREFIX}${key}`,\n value,\n );\n }\n for (const [flagKey, variant] of Object.entries(wizardFlags)) {\n if (!flagKey.toLowerCase().startsWith('wizard')) continue;\n headers.addFlag(flagKey, variant);\n }\n const encoded = headers.encode();\n logToFile('ANTHROPIC_CUSTOM_HEADERS', encoded);\n return encoded;\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 */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n// Re-export for backwards compatibility — canonical source is skill-install.ts\nexport { isSkillInstallCommand } from './skill-install';\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 */\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 // 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.wizardCapture('bash 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.wizardCapture('bash 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.wizardCapture('bash 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.wizardCapture('bash 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 getUI().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, skill loading)\n const wizardToolsServer = await createWizardToolsServer({\n workingDirectory: config.workingDirectory,\n detectPackageManager: config.detectPackageManager,\n skillsBaseUrl: config.skillsBaseUrl,\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 wizardFlags: config.wizardFlags,\n wizardMetadata: config.wizardMetadata,\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 getUI().log.step(`Verbose logs: ${getLogFilePath()}`);\n getUI().log.success(\"Agent initialized. Let's get cooking!\");\n return agentRunConfig;\n } catch (error) {\n getUI().log.error(\n `Failed to initialize agent: ${(error as Error).message}`,\n );\n logToFile('Agent initialization error:', error);\n debug('Agent initialization error:', error);\n throw error;\n }\n}\n\n/**\n * Check agent output for YARA scanner violations.\n * Used in both the success and catch paths of runAgent.\n */\nfunction checkYaraViolation(\n outputText: string,\n spinner: SpinnerHandle,\n): { error: AgentErrorType } | null {\n if (\n outputText.includes('[YARA CRITICAL]') ||\n outputText.includes('[YARA] Scanner error')\n ) {\n logToFile('Agent error: YARA_VIOLATION');\n spinner.stop('Security violation detected');\n return { error: AgentErrorType.YARA_VIOLATION };\n }\n return null;\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: SpinnerHandle,\n config?: {\n estimatedDurationMinutes?: number;\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n additionalFeatureQueue?: readonly AdditionalFeature[];\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 spinnerMessage = 'Customizing your PostHog setup...',\n successMessage = 'PostHog integration complete',\n errorMessage = 'Integration failed',\n } = config ?? {};\n\n const { query } = await getSDKModule();\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.wizardCapture('agent 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 // Event plan file watcher — cleaned up in finally block\n let eventPlanWatcher: fs.FSWatcher | undefined;\n let eventPlanInterval: ReturnType<typeof setInterval> | undefined;\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 sandbox: {\n enabled: true,\n allowUnsandboxedCommands: false,\n filesystem: {\n allowWrite: [\n '/' + agentConfig.workingDirectory,\n '/' + agentConfig.workingDirectory + '/**',\n '//tmp',\n '//tmp/**',\n '//private/tmp',\n '//private/tmp/**',\n // Package manager stores — allow writes so pnpm/npm can\n // install packages without breaking the user's existing setup\n '~/Library/pnpm/store/**', // pnpm global store (macOS)\n '~/.local/share/pnpm/store/**', // pnpm global store (Linux)\n '~/.pnpm-store/**', // pnpm alternate store\n '~/.npm/**', // npm cache\n '~/.yarn/**', // yarn classic cache\n '~/.yarn/berry/**', // yarn berry cache\n ],\n },\n network: {\n allowedDomains: [\n 'github.com',\n 'api.github.com',\n 'raw.githubusercontent.com',\n 'release-assets.githubusercontent.com',\n 'objects.githubusercontent.com',\n ],\n },\n },\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 ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(\n agentConfig.wizardMetadata ?? {},\n agentConfig.wizardFlags ?? {},\n ),\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 systemPrompt: {\n type: 'preset',\n preset: 'claude_code',\n // Append wizard-wide commandments rather than replacing\n // the preset so we keep default Claude Code behaviors.\n append: getWizardCommandments(),\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: drain additional feature queue, then collect remark, then allow stop\n hooks: {\n PreToolUse: createPreToolUseYaraHooks(),\n PostToolUse: createPostToolUseYaraHooks(),\n Stop: [\n {\n hooks: [\n createStopHook(\n config?.additionalFeatureQueue ?? [],\n collectedText,\n ),\n ],\n timeout: 30,\n },\n ],\n },\n },\n });\n\n // Watch for .posthog-events.json and feed into the store\n const eventPlanPath = path.join(\n agentConfig.workingDirectory,\n '.posthog-events.json',\n );\n const readEventPlan = () => {\n try {\n const content = fs.readFileSync(eventPlanPath, 'utf-8');\n const parsed = JSON.parse(content);\n if (Array.isArray(parsed)) {\n getUI().setEventPlan(\n parsed.map((e: Record<string, unknown>) => ({\n name: (e.name ?? e.event ?? '') as string,\n description: (e.description ?? '') as string,\n })),\n );\n }\n } catch {\n // File doesn't exist or isn't valid JSON yet\n }\n };\n\n try {\n eventPlanWatcher = fs.watch(eventPlanPath, () => readEventPlan());\n readEventPlan();\n } catch {\n // File doesn't exist yet — poll until it appears\n eventPlanInterval = setInterval(() => {\n try {\n fs.accessSync(eventPlanPath);\n readEventPlan();\n clearInterval(eventPlanInterval);\n eventPlanInterval = undefined;\n eventPlanWatcher = fs.watch(eventPlanPath, () => readEventPlan());\n } catch {\n // Still waiting\n }\n }, 1000);\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 // 401: show auth error screen and exit immediately\n if (\n message.type === 'assistant' &&\n collectedText.join('\\n').includes('API Error: 401')\n ) {\n signalDone!();\n spinner.stop('Authentication failed');\n logToFile('Agent error: 401, showing auth error screen');\n getUI().showAuthError();\n await wizardAbort({\n message: 'Authentication failed (401)',\n error: new WizardError('Authentication failed'),\n });\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 YARA scanner violations\n const yaraResult = checkYaraViolation(outputText, spinner);\n if (yaraResult) return yaraResult;\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 error before the exception was thrown\n const outputText = collectedText.join('\\n');\n\n // Check for YARA scanner violations\n const yaraResult = checkYaraViolation(outputText, spinner);\n if (yaraResult) return yaraResult;\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 getUI().log.error(`Error: ${(error as Error).message}`);\n logToFile('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n } finally {\n eventPlanWatcher?.close();\n if (eventPlanInterval) clearInterval(eventPlanInterval);\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: SpinnerHandle,\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 const statusText = statusMatch[1].trim();\n getUI().pushStatus(statusText);\n spinner.message(statusText);\n }\n }\n\n // Intercept TodoWrite tool_use blocks for task progression\n if (\n block.type === 'tool_use' &&\n block.name === 'TodoWrite' &&\n block.input?.todos &&\n Array.isArray(block.input.todos)\n ) {\n getUI().syncTodos(block.input.todos);\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 getUI().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 getUI().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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoJH,oEAcC;AAaD,8DAoCC;AAMD,gEAqBC;AAMD,sDAeC;AAgCD,wCA+CC;AAiBD,kDAOC;AA8GD,4CAwHC;AAKD,0CAmFC;AA2BD,4BA8YC;AA/kCD,gDAAwB;AACxB,uCAAyB;AACzB,8BAAkD;AAClD,0CAA+E;AAE/E,kDAA+C;AAC/C,2CAMqB;AACrB,qDAG0B;AAC1B,wDAI+B;AAC/B,4DAA8D;AAC9D,wCAAyD;AACzD,6CAA6C;AAC7C,iDAA4E;AAC5E,6CAGsB;AACtB,iDAAuD;AAGvD,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;IAChC,0CAA0C;IAC1C,SAAS,EAAE,aA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AU,GAAG,EAAE,CAAC,CAAC;wBACnC,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 * as fs from 'fs';\nimport { getUI, type SpinnerHandle } from '../ui';\nimport { debug, logToFile, initLogFile, getLogFilePath } from '../utils/debug';\nimport type { WizardOptions } from '../utils/types';\nimport { analytics } from '../utils/analytics';\nimport {\n WIZARD_REMARK_EVENT_NAME,\n POSTHOG_PROPERTY_HEADER_PREFIX,\n WIZARD_VARIANT_FLAG_KEY,\n WIZARD_VARIANTS,\n WIZARD_USER_AGENT,\n} from './constants';\nimport {\n type AdditionalFeature,\n ADDITIONAL_FEATURE_PROMPTS,\n} from './wizard-session';\nimport {\n registerCleanup,\n wizardAbort,\n WizardError,\n} from '../utils/wizard-abort';\nimport { createCustomHeaders } from '../utils/custom-headers';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls';\nimport { LINTING_TOOLS } from './safe-tools';\nimport { createWizardToolsServer, WIZARD_TOOL_NAMES } from './wizard-tools';\nimport {\n createPreToolUseYaraHooks,\n createPostToolUseYaraHooks,\n} from './yara-hooks';\nimport { getWizardCommandments } from './commandments';\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 /** YARA scanner detected a security violation */\n YARA_VIOLATION = 'WIZARD_YARA_VIOLATION',\n}\n\nconst BLOCKING_ENV_KEYS = [\n 'ANTHROPIC_API_KEY',\n 'ANTHROPIC_BASE_URL',\n 'ANTHROPIC_AUTH_TOKEN',\n];\nconst BLOCKING_SETTINGS_KEYS = ['apiKeyHelper'];\n\n/** Where a settings conflict was found. */\nexport type SettingsConflictSource = 'project' | 'managed';\n\n/** A single settings conflict detected during startup. */\nexport interface SettingsConflict {\n /** Where the conflict was found. */\n source: SettingsConflictSource;\n /** The blocking keys found (e.g. 'ANTHROPIC_BASE_URL', 'apiKeyHelper'). */\n keys: string[];\n /** Whether the wizard can back up / remove this file. Managed settings are read-only. */\n writable: boolean;\n}\n\n/**\n * Check a single settings file for blocking env keys and top-level settings keys.\n * Returns matched key names, or an empty array if none found.\n */\nfunction checkSettingsFile(filePath: string): string[] {\n try {\n const raw = fs.readFileSync(filePath, 'utf-8');\n const parsed = JSON.parse(raw);\n const matched: string[] = [];\n\n // Check env block for blocking env keys\n const envBlock = parsed?.env;\n if (envBlock && typeof envBlock === 'object') {\n matched.push(...BLOCKING_ENV_KEYS.filter((key) => key in envBlock));\n }\n\n // Check top-level settings keys\n matched.push(\n ...BLOCKING_SETTINGS_KEYS.filter(\n (key) => key in parsed && parsed[key] !== '' && parsed[key] != null,\n ),\n );\n\n return matched;\n } catch {\n // File doesn't exist or isn't valid JSON — skip\n return [];\n }\n}\n\n/**\n * Check if .claude/settings.json in the project directory contains env\n * overrides or apiKeyHelper that block the Wizard from accessing the PostHog LLM Gateway.\n * Returns the list of matched key names, or an empty array if none found.\n *\n * @deprecated Use {@link checkAllSettingsConflicts} for comprehensive detection.\n */\nexport function checkClaudeSettingsOverrides(\n workingDirectory: string,\n): string[] {\n const candidates = [\n path.join(workingDirectory, '.claude', 'settings.json'),\n path.join(workingDirectory, '.claude', 'settings'),\n ];\n\n for (const filePath of candidates) {\n const matched = checkSettingsFile(filePath);\n if (matched.length > 0) return matched;\n }\n\n return [];\n}\n\n/**\n * Managed settings path on macOS.\n * IT/MDM-deployed settings — readable by all users, writable only by root.\n */\nconst MANAGED_SETTINGS_PATH =\n '/Library/Application Support/ClaudeCode/managed-settings.json';\n\n/**\n * Check project and org-managed settings for blocking keys that conflict\n * with the wizard's proxy auth.\n */\nexport function checkAllSettingsConflicts(\n workingDirectory: string,\n): SettingsConflict[] {\n const conflicts: SettingsConflict[] = [];\n\n const sources: {\n source: SettingsConflictSource;\n paths: string[];\n writable: boolean;\n }[] = [\n {\n source: 'managed',\n paths: [MANAGED_SETTINGS_PATH],\n writable: false,\n },\n {\n source: 'project',\n paths: [\n path.join(workingDirectory, '.claude', 'settings.json'),\n path.join(workingDirectory, '.claude', 'settings'),\n ],\n writable: true,\n },\n ];\n\n for (const { source, paths, writable } of sources) {\n for (const filePath of paths) {\n const keys = checkSettingsFile(filePath);\n if (keys.length > 0) {\n conflicts.push({ source, keys, writable });\n break; // Only one conflict per source (settings.json vs settings fallback)\n }\n }\n }\n\n return conflicts;\n}\n\n/**\n * Copy .claude/settings.json to .wizard-backup (overwriting if it exists),\n * then remove the original so the SDK doesn't load the blocking overrides.\n */\nexport function backupAndFixClaudeSettings(workingDirectory: string): boolean {\n for (const name of ['settings.json', 'settings']) {\n const filePath = path.join(workingDirectory, '.claude', name);\n const backupPath = `${filePath}.wizard-backup`;\n analytics.wizardCapture('backedup-claude-settings');\n try {\n fs.copyFileSync(filePath, backupPath);\n fs.unlinkSync(filePath);\n registerCleanup(() => {\n try {\n restoreClaudeSettings(workingDirectory);\n } catch (error) {\n analytics.captureException(error);\n }\n });\n return true;\n } catch {\n // File doesn't exist — try next candidate\n }\n }\n return false;\n}\n\n/**\n * Restore .claude/settings.json from .wizard-backup.\n * Copies (not moves) so the backup is preserved.\n */\nexport function restoreClaudeSettings(workingDirectory: string): void {\n for (const name of ['settings.json', 'settings']) {\n const backup = path.join(\n workingDirectory,\n '.claude',\n `${name}.wizard-backup`,\n );\n try {\n fs.copyFileSync(backup, path.join(workingDirectory, '.claude', name));\n analytics.wizardCapture('restored-claude-settings');\n return;\n } catch (error) {\n analytics.captureException(error);\n }\n }\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 /** Base URL for the skills server (context-mill dev or GitHub releases) */\n skillsBaseUrl: string;\n /** Feature flag key -> variant (evaluated at start of run). */\n wizardFlags?: Record<string, string>;\n wizardMetadata?: Record<string, string>;\n};\n\n/**\n * Stop hook return type: either allow stop or block with a reason.\n */\nexport type StopHookResult =\n | Record<string, never>\n | { decision: 'block'; reason: string };\n\n/**\n * Create a stop hook callback that drains the additional feature queue,\n * then collects a remark, then allows stop.\n *\n * Three-phase logic using closure state:\n * Phase 1 — drain queue: block with each feature prompt in order\n * Phase 2 — collect remark (once): block with remark prompt\n * Phase 3 — allow stop: return {}\n */\nexport function createStopHook(\n featureQueue: readonly AdditionalFeature[],\n collectedText?: string[],\n): (input: { stop_hook_active: boolean }) => StopHookResult {\n let featureIndex = 0;\n let remarkRequested = false;\n\n return (input: { stop_hook_active: boolean }): StopHookResult => {\n logToFile('Stop hook triggered', {\n stop_hook_active: input.stop_hook_active,\n featureIndex,\n remarkRequested,\n queueLength: featureQueue.length,\n });\n\n // On API errors, allow stop immediately — blocking with remark/feature\n // prompts would just fail again. The auth error screen is shown separately.\n if (collectedText) {\n const text = collectedText.join('\\n');\n if (text.includes('API Error:')) {\n logToFile('Stop hook: API error detected, allowing immediate stop');\n return {};\n }\n }\n\n // Phase 1: drain feature queue\n if (featureIndex < featureQueue.length) {\n const feature = featureQueue[featureIndex++];\n const prompt = ADDITIONAL_FEATURE_PROMPTS[feature];\n logToFile(`Stop hook: injecting feature prompt for ${feature}`);\n return { decision: 'block', reason: prompt };\n }\n\n // Phase 2: collect remark (once)\n if (!remarkRequested) {\n remarkRequested = true;\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 // Phase 3: allow stop\n logToFile('Stop hook: allowing stop');\n return {};\n };\n}\n\n/**\n * Internal configuration object returned by initializeAgent\n */\ntype AgentRunConfig = {\n workingDirectory: string;\n mcpServers: McpServersConfig;\n model: string;\n wizardFlags?: Record<string, string>;\n wizardMetadata?: Record<string, string>;\n};\n\n/**\n * Select wizard metadata from WIZARD_VARIANTS using the variant feature flag.\n * If the flag is missing or the value is not in config, returns the \"base\" variant (VARIANT: \"base\").\n */\nexport function buildWizardMetadata(\n flags: Record<string, string> = {},\n): Record<string, string> {\n const variantKey = flags[WIZARD_VARIANT_FLAG_KEY];\n const variant =\n (variantKey && WIZARD_VARIANTS[variantKey]) ?? WIZARD_VARIANTS['base'];\n return { ...variant };\n}\n\n/**\n * Build env for the SDK subprocess: process.env plus ANTHROPIC_CUSTOM_HEADERS from wizard metadata/flags.\n */\nfunction buildAgentEnv(\n wizardMetadata: Record<string, string>,\n wizardFlags: Record<string, string>,\n): string {\n const headers = createCustomHeaders();\n for (const [key, value] of Object.entries(wizardMetadata)) {\n headers.add(\n key.startsWith(POSTHOG_PROPERTY_HEADER_PREFIX)\n ? key\n : `${POSTHOG_PROPERTY_HEADER_PREFIX}${key}`,\n value,\n );\n }\n for (const [flagKey, variant] of Object.entries(wizardFlags)) {\n if (!flagKey.toLowerCase().startsWith('wizard')) continue;\n headers.addFlag(flagKey, variant);\n }\n const encoded = headers.encode();\n logToFile('ANTHROPIC_CUSTOM_HEADERS', encoded);\n return encoded;\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 */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n// Re-export for backwards compatibility — canonical source is skill-install.ts\nexport { isSkillInstallCommand } from './skill-install';\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 */\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 // 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.wizardCapture('bash 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.wizardCapture('bash 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.wizardCapture('bash 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.wizardCapture('bash 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 getUI().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, skill loading)\n const wizardToolsServer = await createWizardToolsServer({\n workingDirectory: config.workingDirectory,\n detectPackageManager: config.detectPackageManager,\n skillsBaseUrl: config.skillsBaseUrl,\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 wizardFlags: config.wizardFlags,\n wizardMetadata: config.wizardMetadata,\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 getUI().log.step(`Verbose logs: ${getLogFilePath()}`);\n getUI().log.success(\"Agent initialized. Let's get cooking!\");\n return agentRunConfig;\n } catch (error) {\n getUI().log.error(\n `Failed to initialize agent: ${(error as Error).message}`,\n );\n logToFile('Agent initialization error:', error);\n debug('Agent initialization error:', error);\n throw error;\n }\n}\n\n/**\n * Check agent output for YARA scanner violations.\n * Used in both the success and catch paths of runAgent.\n */\nfunction checkYaraViolation(\n outputText: string,\n spinner: SpinnerHandle,\n): { error: AgentErrorType } | null {\n if (\n outputText.includes('[YARA CRITICAL]') ||\n outputText.includes('[YARA] Scanner error')\n ) {\n logToFile('Agent error: YARA_VIOLATION');\n spinner.stop('Security violation detected');\n return { error: AgentErrorType.YARA_VIOLATION };\n }\n return null;\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: SpinnerHandle,\n config?: {\n estimatedDurationMinutes?: number;\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n additionalFeatureQueue?: readonly AdditionalFeature[];\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 spinnerMessage = 'Customizing your PostHog setup...',\n successMessage = 'PostHog integration complete',\n errorMessage = 'Integration failed',\n } = config ?? {};\n\n const { query } = await getSDKModule();\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.wizardCapture('agent 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 // Event plan file watcher — cleaned up in finally block\n let eventPlanWatcher: fs.FSWatcher | undefined;\n let eventPlanInterval: ReturnType<typeof setInterval> | undefined;\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 sandbox: {\n enabled: true,\n allowUnsandboxedCommands: false,\n filesystem: {\n allowWrite: [\n '/' + agentConfig.workingDirectory,\n '/' + agentConfig.workingDirectory + '/**',\n '//tmp',\n '//tmp/**',\n '//private/tmp',\n '//private/tmp/**',\n // Package manager stores — allow writes so pnpm/npm can\n // install packages without breaking the user's existing setup\n '~/Library/pnpm/store/**', // pnpm global store (macOS)\n '~/.local/share/pnpm/store/**', // pnpm global store (Linux)\n '~/.pnpm-store/**', // pnpm alternate store\n '~/.npm/**', // npm cache\n '~/.yarn/**', // yarn classic cache\n '~/.yarn/berry/**', // yarn berry cache\n ],\n },\n network: {\n allowedDomains: [\n 'github.com',\n 'api.github.com',\n 'raw.githubusercontent.com',\n 'release-assets.githubusercontent.com',\n 'objects.githubusercontent.com',\n ],\n },\n },\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 // Defer MCP tool schemas to avoid bloating the system prompt.\n // The posthog-wizard MCP exposes many query tools with large schemas;\n // without deferral these consume ~113k tokens upfront, leaving\n // almost no room in Sonnet's 200k context window.\n ENABLE_TOOL_SEARCH: 'auto:0',\n ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(\n agentConfig.wizardMetadata ?? {},\n agentConfig.wizardFlags ?? {},\n ),\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 systemPrompt: {\n type: 'preset',\n preset: 'claude_code',\n // Append wizard-wide commandments rather than replacing\n // the preset so we keep default Claude Code behaviors.\n append: getWizardCommandments(),\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: drain additional feature queue, then collect remark, then allow stop\n hooks: {\n PreToolUse: createPreToolUseYaraHooks(),\n PostToolUse: createPostToolUseYaraHooks(),\n Stop: [\n {\n hooks: [\n createStopHook(\n config?.additionalFeatureQueue ?? [],\n collectedText,\n ),\n ],\n timeout: 30,\n },\n ],\n },\n },\n });\n\n // Watch for .posthog-events.json and feed into the store\n const eventPlanPath = path.join(\n agentConfig.workingDirectory,\n '.posthog-events.json',\n );\n const readEventPlan = () => {\n try {\n const content = fs.readFileSync(eventPlanPath, 'utf-8');\n const parsed = JSON.parse(content);\n if (Array.isArray(parsed)) {\n getUI().setEventPlan(\n parsed.map((e: Record<string, unknown>) => ({\n name: (e.name ?? e.event ?? '') as string,\n description: (e.description ?? '') as string,\n })),\n );\n }\n } catch {\n // File doesn't exist or isn't valid JSON yet\n }\n };\n\n try {\n eventPlanWatcher = fs.watch(eventPlanPath, () => readEventPlan());\n readEventPlan();\n } catch {\n // File doesn't exist yet — poll until it appears\n eventPlanInterval = setInterval(() => {\n try {\n fs.accessSync(eventPlanPath);\n readEventPlan();\n clearInterval(eventPlanInterval);\n eventPlanInterval = undefined;\n eventPlanWatcher = fs.watch(eventPlanPath, () => readEventPlan());\n } catch {\n // Still waiting\n }\n }, 1000);\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 // 401: show auth error screen and exit immediately\n if (\n message.type === 'assistant' &&\n collectedText.join('\\n').includes('API Error: 401')\n ) {\n signalDone!();\n spinner.stop('Authentication failed');\n logToFile('Agent error: 401, showing auth error screen');\n getUI().showAuthError();\n await wizardAbort({\n message: 'Authentication failed (401)',\n error: new WizardError('Authentication failed'),\n });\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 YARA scanner violations\n const yaraResult = checkYaraViolation(outputText, spinner);\n if (yaraResult) return yaraResult;\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 error before the exception was thrown\n const outputText = collectedText.join('\\n');\n\n // Check for YARA scanner violations\n const yaraResult = checkYaraViolation(outputText, spinner);\n if (yaraResult) return yaraResult;\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 getUI().log.error(`Error: ${(error as Error).message}`);\n logToFile('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n } finally {\n eventPlanWatcher?.close();\n if (eventPlanInterval) clearInterval(eventPlanInterval);\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: SpinnerHandle,\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 const statusText = statusMatch[1].trim();\n getUI().pushStatus(statusText);\n spinner.message(statusText);\n }\n }\n\n // Intercept TodoWrite tool_use blocks for task progression\n if (\n block.type === 'tool_use' &&\n block.name === 'TodoWrite' &&\n block.input?.todos &&\n Array.isArray(block.input.todos)\n ) {\n getUI().syncTodos(block.input.todos);\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 getUI().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 getUI().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"]}
@@ -53,7 +53,7 @@ export declare const WIZARD_VARIANT_FLAG_KEY = "wizard-variant";
53
53
  /** Variant key -> metadata for wizard run (VARIANT flag selects which entry to use). */
54
54
  export declare const WIZARD_VARIANTS: Record<string, Record<string, string>>;
55
55
  /** User-Agent for wizard HTTP requests and MCP server identification. */
56
- export declare const WIZARD_USER_AGENT = "posthog/wizard; version: 2.6.0";
56
+ export declare const WIZARD_USER_AGENT = "posthog/wizard; version: 2.6.1";
57
57
  /** Header prefix for PostHog properties (e.g. X-POSTHOG-PROPERTY-VARIANT). */
58
58
  export declare const POSTHOG_PROPERTY_HEADER_PREFIX = "X-POSTHOG-PROPERTY-";
59
59
  /** Header prefix for PostHog feature flags. */
@@ -1 +1 @@
1
- export declare const VERSION = "2.6.0";
1
+ export declare const VERSION = "2.6.1";
@@ -2,5 +2,5 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  // Auto-generated by scripts/generate-version.js — do not edit
5
- exports.VERSION = '2.6.0';
5
+ exports.VERSION = '2.6.1';
6
6
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,8DAA8D;AACjD,QAAA,OAAO,GAAG,OAAO,CAAC","sourcesContent":["// Auto-generated by scripts/generate-version.js — do not edit\nexport const VERSION = '2.6.0';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,8DAA8D;AACjD,QAAA,OAAO,GAAG,OAAO,CAAC","sourcesContent":["// Auto-generated by scripts/generate-version.js — do not edit\nexport const VERSION = '2.6.1';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/wizard",
3
- "version": "2.6.0",
3
+ "version": "2.6.1",
4
4
  "homepage": "https://github.com/PostHog/wizard",
5
5
  "repository": "https://github.com/PostHog/wizard",
6
6
  "description": "The PostHog wizard helps you to configure your project",