@posthog/wizard 1.31.1 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/README.md +2 -1
  2. package/dist/bin.js +14 -1
  3. package/dist/bin.js.map +1 -1
  4. package/dist/src/__tests__/run.test.js +5 -5
  5. package/dist/src/__tests__/run.test.js.map +1 -1
  6. package/dist/src/android/android-wizard-agent.d.ts +6 -0
  7. package/dist/src/android/android-wizard-agent.js +140 -0
  8. package/dist/src/android/android-wizard-agent.js.map +1 -0
  9. package/dist/src/android/utils.d.ts +11 -0
  10. package/dist/src/android/utils.js +97 -0
  11. package/dist/src/android/utils.js.map +1 -0
  12. package/dist/src/angular/angular-wizard-agent.d.ts +4 -0
  13. package/dist/src/angular/angular-wizard-agent.js +67 -0
  14. package/dist/src/angular/angular-wizard-agent.js.map +1 -0
  15. package/dist/src/angular/utils.d.ts +4 -0
  16. package/dist/src/angular/utils.js +9 -0
  17. package/dist/src/angular/utils.js.map +1 -0
  18. package/dist/src/astro/astro-wizard-agent.d.ts +7 -0
  19. package/dist/src/astro/astro-wizard-agent.js +102 -0
  20. package/dist/src/astro/astro-wizard-agent.js.map +1 -0
  21. package/dist/src/astro/utils.d.ts +17 -0
  22. package/dist/src/astro/utils.js +163 -0
  23. package/dist/src/astro/utils.js.map +1 -0
  24. package/dist/src/django/django-wizard-agent.d.ts +8 -5
  25. package/dist/src/django/django-wizard-agent.js +62 -51
  26. package/dist/src/django/django-wizard-agent.js.map +1 -1
  27. package/dist/src/django/utils.d.ts +1 -1
  28. package/dist/src/django/utils.js +3 -22
  29. package/dist/src/django/utils.js.map +1 -1
  30. package/dist/src/fastapi/fastapi-wizard-agent.d.ts +7 -0
  31. package/dist/src/fastapi/fastapi-wizard-agent.js +217 -0
  32. package/dist/src/fastapi/fastapi-wizard-agent.js.map +1 -0
  33. package/dist/src/fastapi/utils.d.ts +26 -0
  34. package/dist/src/fastapi/utils.js +258 -0
  35. package/dist/src/fastapi/utils.js.map +1 -0
  36. package/dist/src/flask/flask-wizard-agent.d.ts +8 -5
  37. package/dist/src/flask/flask-wizard-agent.js +67 -51
  38. package/dist/src/flask/flask-wizard-agent.js.map +1 -1
  39. package/dist/src/flask/utils.d.ts +1 -1
  40. package/dist/src/flask/utils.js +3 -22
  41. package/dist/src/flask/utils.js.map +1 -1
  42. package/dist/src/laravel/laravel-wizard-agent.d.ts +10 -5
  43. package/dist/src/laravel/laravel-wizard-agent.js +50 -53
  44. package/dist/src/laravel/laravel-wizard-agent.js.map +1 -1
  45. package/dist/src/laravel/utils.d.ts +1 -1
  46. package/dist/src/laravel/utils.js +3 -22
  47. package/dist/src/laravel/utils.js.map +1 -1
  48. package/dist/src/lib/__tests__/agent-interface.test.js +1 -0
  49. package/dist/src/lib/__tests__/agent-interface.test.js.map +1 -1
  50. package/dist/src/lib/agent-interface.d.ts +4 -1
  51. package/dist/src/lib/agent-interface.js +36 -3
  52. package/dist/src/lib/agent-interface.js.map +1 -1
  53. package/dist/src/lib/agent-runner.js +69 -6
  54. package/dist/src/lib/agent-runner.js.map +1 -1
  55. package/dist/src/lib/api.d.ts +4 -4
  56. package/dist/src/lib/constants.d.ts +15 -14
  57. package/dist/src/lib/constants.js +17 -40
  58. package/dist/src/lib/constants.js.map +1 -1
  59. package/dist/src/lib/env-file-tools.d.ts +11 -0
  60. package/dist/src/lib/env-file-tools.js +154 -0
  61. package/dist/src/lib/env-file-tools.js.map +1 -0
  62. package/dist/src/lib/framework-config.d.ts +34 -16
  63. package/dist/src/lib/framework-config.js.map +1 -1
  64. package/dist/src/lib/registry.d.ts +3 -0
  65. package/dist/src/lib/registry.js +41 -0
  66. package/dist/src/lib/registry.js.map +1 -0
  67. package/dist/src/nextjs/nextjs-wizard-agent.d.ts +7 -5
  68. package/dist/src/nextjs/nextjs-wizard-agent.js +16 -79
  69. package/dist/src/nextjs/nextjs-wizard-agent.js.map +1 -1
  70. package/dist/src/nextjs/utils.d.ts +1 -1
  71. package/dist/src/nextjs/utils.js +3 -22
  72. package/dist/src/nextjs/utils.js.map +1 -1
  73. package/dist/src/nuxt/nuxt-wizard-agent.d.ts +6 -0
  74. package/dist/src/nuxt/nuxt-wizard-agent.js +77 -0
  75. package/dist/src/nuxt/nuxt-wizard-agent.js.map +1 -0
  76. package/dist/src/python/python-wizard-agent.d.ts +7 -0
  77. package/dist/src/python/python-wizard-agent.js +269 -0
  78. package/dist/src/python/python-wizard-agent.js.map +1 -0
  79. package/dist/src/python/utils.d.ts +28 -0
  80. package/dist/src/python/utils.js +147 -0
  81. package/dist/src/python/utils.js.map +1 -0
  82. package/dist/src/react-native/react-native-wizard-agent.d.ts +7 -0
  83. package/dist/src/react-native/react-native-wizard-agent.js +91 -0
  84. package/dist/src/react-native/react-native-wizard-agent.js.map +1 -0
  85. package/dist/src/react-native/utils.d.ts +8 -0
  86. package/dist/src/react-native/utils.js +31 -0
  87. package/dist/src/react-native/utils.js.map +1 -0
  88. package/dist/src/react-router/react-router-wizard-agent.d.ts +7 -5
  89. package/dist/src/react-router/react-router-wizard-agent.js +18 -80
  90. package/dist/src/react-router/react-router-wizard-agent.js.map +1 -1
  91. package/dist/src/react-router/utils.d.ts +1 -1
  92. package/dist/src/react-router/utils.js +3 -21
  93. package/dist/src/react-router/utils.js.map +1 -1
  94. package/dist/src/run.d.ts +1 -0
  95. package/dist/src/run.js +28 -76
  96. package/dist/src/run.js.map +1 -1
  97. package/dist/src/steps/add-mcp-server-to-clients/clients/claude-code.d.ts +6 -6
  98. package/dist/src/steps/add-mcp-server-to-clients/clients/claude.d.ts +6 -6
  99. package/dist/src/steps/add-mcp-server-to-clients/clients/codex.d.ts +6 -6
  100. package/dist/src/steps/add-mcp-server-to-clients/clients/cursor.d.ts +6 -6
  101. package/dist/src/steps/add-mcp-server-to-clients/clients/visual-studio-code.d.ts +6 -6
  102. package/dist/src/steps/add-mcp-server-to-clients/clients/zed.d.ts +6 -6
  103. package/dist/src/steps/add-mcp-server-to-clients/defaults.d.ts +6 -6
  104. package/dist/src/svelte/svelte-wizard-agent.d.ts +4 -0
  105. package/dist/src/svelte/svelte-wizard-agent.js +60 -0
  106. package/dist/src/svelte/svelte-wizard-agent.js.map +1 -0
  107. package/dist/src/swift/swift-wizard-agent.d.ts +7 -0
  108. package/dist/src/swift/swift-wizard-agent.js +141 -0
  109. package/dist/src/swift/swift-wizard-agent.js.map +1 -0
  110. package/dist/src/swift/utils.d.ts +8 -0
  111. package/dist/src/swift/utils.js +105 -0
  112. package/dist/src/swift/utils.js.map +1 -0
  113. package/dist/src/tanstack-router/tanstack-router-wizard-agent.d.ts +7 -0
  114. package/dist/src/tanstack-router/tanstack-router-wizard-agent.js +93 -0
  115. package/dist/src/tanstack-router/tanstack-router-wizard-agent.js.map +1 -0
  116. package/dist/src/tanstack-router/utils.d.ts +17 -0
  117. package/dist/src/tanstack-router/utils.js +192 -0
  118. package/dist/src/tanstack-router/utils.js.map +1 -0
  119. package/dist/src/tanstack-start/tanstack-start-wizard-agent.d.ts +4 -0
  120. package/dist/src/tanstack-start/tanstack-start-wizard-agent.js +66 -0
  121. package/dist/src/tanstack-start/tanstack-start-wizard-agent.js.map +1 -0
  122. package/dist/src/tanstack-start/utils.d.ts +4 -0
  123. package/dist/src/tanstack-start/utils.js +9 -0
  124. package/dist/src/tanstack-start/utils.js.map +1 -0
  125. package/dist/src/utils/__tests__/semver.test.d.ts +1 -0
  126. package/dist/src/utils/__tests__/semver.test.js +117 -0
  127. package/dist/src/utils/__tests__/semver.test.js.map +1 -0
  128. package/dist/src/utils/clack-utils.js +3 -5
  129. package/dist/src/utils/clack-utils.js.map +1 -1
  130. package/dist/src/utils/debug.d.ts +2 -0
  131. package/dist/src/utils/debug.js +17 -5
  132. package/dist/src/utils/debug.js.map +1 -1
  133. package/dist/src/utils/file-utils.d.ts +1 -31
  134. package/dist/src/utils/file-utils.js +0 -163
  135. package/dist/src/utils/file-utils.js.map +1 -1
  136. package/dist/src/utils/semver.d.ts +16 -0
  137. package/dist/src/utils/semver.js +37 -0
  138. package/dist/src/utils/semver.js.map +1 -1
  139. package/dist/src/utils/types.d.ts +4 -0
  140. package/dist/src/utils/types.js.map +1 -1
  141. package/dist/src/vue/vue-wizard-agent.d.ts +4 -0
  142. package/dist/src/vue/vue-wizard-agent.js +64 -0
  143. package/dist/src/vue/vue-wizard-agent.js.map +1 -0
  144. package/package.json +1 -1
  145. package/dist/src/astro/astro-wizard.d.ts +0 -2
  146. package/dist/src/astro/astro-wizard.js +0 -89
  147. package/dist/src/astro/astro-wizard.js.map +0 -1
  148. package/dist/src/astro/docs.d.ts +0 -4
  149. package/dist/src/astro/docs.js +0 -101
  150. package/dist/src/astro/docs.js.map +0 -1
  151. package/dist/src/lib/config.d.ts +0 -104
  152. package/dist/src/lib/config.js +0 -368
  153. package/dist/src/lib/config.js.map +0 -1
  154. package/dist/src/lib/messages.d.ts +0 -16
  155. package/dist/src/lib/messages.js +0 -66
  156. package/dist/src/lib/messages.js.map +0 -1
  157. package/dist/src/lib/prompts.d.ts +0 -16
  158. package/dist/src/lib/prompts.js +0 -83
  159. package/dist/src/lib/prompts.js.map +0 -1
  160. package/dist/src/react/docs.d.ts +0 -4
  161. package/dist/src/react/docs.js +0 -49
  162. package/dist/src/react/docs.js.map +0 -1
  163. package/dist/src/react/react-wizard.d.ts +0 -2
  164. package/dist/src/react/react-wizard.js +0 -121
  165. package/dist/src/react/react-wizard.js.map +0 -1
  166. package/dist/src/react-native/docs.d.ts +0 -5
  167. package/dist/src/react-native/docs.js +0 -31
  168. package/dist/src/react-native/docs.js.map +0 -1
  169. package/dist/src/react-native/react-native-wizard.d.ts +0 -2
  170. package/dist/src/react-native/react-native-wizard.js +0 -128
  171. package/dist/src/react-native/react-native-wizard.js.map +0 -1
  172. package/dist/src/svelte/docs.d.ts +0 -3
  173. package/dist/src/svelte/docs.js +0 -111
  174. package/dist/src/svelte/docs.js.map +0 -1
  175. package/dist/src/svelte/svelte-wizard.d.ts +0 -2
  176. package/dist/src/svelte/svelte-wizard.js +0 -121
  177. package/dist/src/svelte/svelte-wizard.js.map +0 -1
  178. package/dist/src/utils/errors.d.ts +0 -3
  179. package/dist/src/utils/errors.js +0 -11
  180. package/dist/src/utils/errors.js.map +0 -1
  181. package/dist/src/utils/query.d.ts +0 -11
  182. package/dist/src/utils/query.js +0 -115
  183. package/dist/src/utils/query.js.map +0 -1
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
@@ -12,16 +45,41 @@ const clack_1 = __importDefault(require("../utils/clack"));
12
45
  const agent_interface_1 = require("./agent-interface");
13
46
  const urls_1 = require("../utils/urls");
14
47
  const chalk_1 = __importDefault(require("chalk"));
48
+ const semver = __importStar(require("semver"));
15
49
  const steps_1 = require("../steps");
16
50
  const anthropic_status_1 = require("../utils/anthropic-status");
51
+ const debug_1 = require("../utils/debug");
17
52
  /**
18
53
  * Universal agent-powered wizard runner.
19
54
  * Handles the complete flow for any framework using PostHog MCP integration.
20
55
  */
21
56
  async function runAgentWizard(config, options) {
57
+ if (options.debug) {
58
+ (0, debug_1.enableDebugLogs)();
59
+ }
60
+ // Version check
61
+ if (config.detection.minimumVersion && config.detection.getInstalledVersion) {
62
+ const version = await config.detection.getInstalledVersion(options);
63
+ if (version) {
64
+ const coerced = semver.coerce(version);
65
+ if (coerced && semver.lt(coerced, config.detection.minimumVersion)) {
66
+ const docsUrl = config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl;
67
+ clack_1.default.log.warn(`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.`);
68
+ clack_1.default.log.info(`Setup ${config.metadata.name} manually: ${chalk_1.default.cyan(docsUrl)}`);
69
+ clack_1.default.outro('PostHog wizard will see you next time!');
70
+ return;
71
+ }
72
+ }
73
+ }
22
74
  // Setup phase
23
75
  (0, clack_utils_1.printWelcome)({ wizardName: (0, framework_config_1.getWelcomeMessage)(config.metadata.name) });
24
- clack_1.default.log.info(`🧙 The wizard has chosen you to try the next-generation agent integration for ${config.metadata.name}.\n\nStand by for the good stuff, and let the robot minders know how it goes:\n\nwizard@posthog.com`);
76
+ if (config.metadata.beta) {
77
+ clack_1.default.log.info(`${chalk_1.default.yellow('[BETA]')} The ${config.metadata.name} wizard is in beta. Questions or feedback? Email ${chalk_1.default.cyan('wizard@posthog.com')}`);
78
+ }
79
+ if (config.metadata.preRunNotice) {
80
+ clack_1.default.log.warn(config.metadata.preRunNotice);
81
+ }
82
+ clack_1.default.log.info(`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.`);
25
83
  const aiConsent = await (0, clack_utils_1.askForAIConsent)(options);
26
84
  if (!aiConsent) {
27
85
  await (0, clack_utils_1.abort)(`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}`, 0);
@@ -89,11 +147,12 @@ async function runAgentWizard(config, options) {
89
147
  (cloudRegion === 'eu'
90
148
  ? 'https://mcp-eu.posthog.com/mcp'
91
149
  : 'https://mcp.posthog.com/mcp');
92
- const agent = (0, agent_interface_1.initializeAgent)({
150
+ const agent = await (0, agent_interface_1.initializeAgent)({
93
151
  workingDirectory: options.installDir,
94
152
  posthogMcpUrl: mcpUrl,
95
153
  posthogApiKey: accessToken,
96
154
  posthogApiHost: host,
155
+ additionalMcpServers: config.metadata.additionalMcpServers,
97
156
  }, options);
98
157
  const agentResult = await (0, agent_interface_1.runAgent)(agent, integrationPrompt, options, spinner, {
99
158
  estimatedDurationMinutes: config.ui.estimatedDurationMinutes,
@@ -232,9 +291,10 @@ Project context:
232
291
 
233
292
  Instructions (follow these steps IN ORDER - do not skip or reorder):
234
293
 
235
- STEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool.
294
+ STEP 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: ${agent_interface_1.AgentSignals.ERROR_MCP_MISSING} Could not access the PostHog MCP server and halt.
295
+
236
296
  Review the skill descriptions and choose the one that best matches this project's framework and configuration.
237
- If no suitable skill is found, or you cannot access the MCP server, emit: ${agent_interface_1.AgentSignals.ERROR_RESOURCE_MISSING} Could not find a suitable skill for this project.
297
+ If no suitable skill is found, or you cannot access the MCP server, you emit: ${agent_interface_1.AgentSignals.ERROR_RESOURCE_MISSING} Could not find a suitable skill for this project.
238
298
 
239
299
  STEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).
240
300
  The resource returns a shell command to install the skill.
@@ -247,9 +307,12 @@ STEP 4: Load the installed skill's SKILL.md file to understand what references a
247
307
 
248
308
  STEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like "1.0-", "1.1-", "1.2-"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.
249
309
 
250
- STEP 6: Set up environment variables for PostHog in a .env file with the API key and host provided above, using the appropriate naming convention for ${config.metadata.name}. Make sure to use these environment variables in the code files you create instead of hardcoding the API key and host.
310
+ STEP 6: Set up environment variables for PostHog using the env-file-tools MCP server (this runs locally secret values never leave the machine):
311
+ - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).
312
+ - Use set_env_values to create or update the PostHog API key and host, using the appropriate naming convention for ${config.metadata.name}. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.
313
+ - Reference these environment variables in the code files you create instead of hardcoding the API key and host.
251
314
 
252
- Important: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager. Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation.
315
+ Important: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager (excluding the contents of node_modules). Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.
253
316
 
254
317
  `;
255
318
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../src/lib/agent-runner.ts"],"names":[],"mappings":";;;;;AAsCA,wCA6QC;AAnTD,yDAI4B;AAE5B,sDAU8B;AAC9B,kDAA+C;AAC/C,2CAA4D;AAC5D,2DAAmC;AACnC,uDAK2B;AAC3B,wCAAsD;AACtD,kDAA0B;AAC1B,oCAGkB;AAClB,gEAA2E;AAE3E;;;GAGG;AACI,KAAK,U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;;;;;;;;;;;;wJAcC,MAAM,CAAC,QAAQ,CAAC,IAClB;;;;CAID,CAAC;AACF,CAAC","sourcesContent":["import {\n getWelcomeMessage,\n SPINNER_MESSAGE,\n type FrameworkConfig,\n} from './framework-config';\nimport type { WizardOptions } from '../utils/types';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n isUsingTypeScript,\n printWelcome,\n askForCloudRegion,\n} from '../utils/clack-utils';\nimport { 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 {\n addMCPServerToClientsStep,\n uploadEnvironmentVariablesStep,\n} from '../steps';\nimport { checkAnthropicStatusWithPrompt } from '../utils/anthropic-status';\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 // Setup phase\n printWelcome({ wizardName: getWelcomeMessage(config.metadata.name) });\n\n clack.log.info(\n `🧙 The wizard has chosen you to try the next-generation agent integration for ${config.metadata.name}.\\n\\nStand by for the good stuff, and let the robot minders know how it goes:\\n\\nwizard@posthog.com`,\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: any = 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 = initializeAgent(\n {\n workingDirectory: options.installDir,\n posthogMcpUrl: mcpUrl,\n posthogApiKey: accessToken,\n posthogApiHost: host,\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, any>,\n): string {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- Framework: ${config.metadata.name} ${context.frameworkVersion}\n- TypeScript: ${context.typescript ? 'Yes' : 'No'}\n- PostHog API Key: ${context.projectApiKey}\n- PostHog Host: ${context.host}${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool.\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, emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).\n The resource returns a shell command to install the skill.\n\nSTEP 3: Run the installation command using Bash:\n - Execute the EXACT command returned by the resource (do not modify it)\n - This will download and extract the skill to .claude/skills/{skill-id}/\n\nSTEP 4: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.\n\nSTEP 6: Set up environment variables for PostHog in a .env file with the API key and host provided above, using the appropriate naming convention for ${\n config.metadata.name\n }. Make sure to use these environment variables in the code files you create instead of hardcoding the API key and host.\n\nImportant: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager. Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation.\n\n`;\n}\n"]}
1
+ {"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../src/lib/agent-runner.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,wCAoTC;AA7VD,yDAI4B;AAE5B,sDAU8B;AAE9B,kDAA+C;AAC/C,2CAA4D;AAC5D,2DAAmC;AACnC,uDAK2B;AAC3B,wCAAsD;AACtD,kDAA0B;AAC1B,+CAAiC;AACjC,oCAGkB;AAClB,gEAA2E;AAC3E,0CAAiD;AAEjD;;;GAGG;AACI,KAAK,UAAU,cAAc,CAClC,MAAuB,EACvB,OAAsB;IAEtB,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QAClB,IAAA,uBAAe,GAAE,CAAC;IACpB,CAAC;IAED,gBAAgB;IAChB,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,IAAI,MAAM,CAAC,SAAS,CAAC,mBAAmB,EAAE,CAAC;QAC5E,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QACpE,IAAI,OAAO,EAAE,CAAC;YACZ,MAAM,OAAO,GAAG,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,CAA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,EACvB,OAKC,EACD,gBAAyC;IAEzC,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,yBAAyB;QAC9D,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,CAAC;QAC5D,CAAC,CAAC,EAAE,CAAC;IAEP,MAAM,iBAAiB,GACrB,eAAe,CAAC,MAAM,GAAG,CAAC;QACxB,CAAC,CAAC,IAAI,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC;IAET,OAAO,kGACL,MAAM,CAAC,QAAQ,CAAC,IAClB;;;eAGa,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,OAAO,CAAC,gBAAgB;gBAC/C,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;qBAC5B,OAAO,CAAC,aAAa;kBACxB,OAAO,CAAC,IAAI,GAAG,iBAAiB;;;;0KAK9C,8BAAY,CAAC,iBACf;;;mFAIG,8BAAY,CAAC,sBACf;;;;;;;;;;;;;;;wHAgBE,MAAM,CAAC,QAAQ,CAAC,IAClB;;;;;CAKF,CAAC;AACF,CAAC","sourcesContent":["import {\n getWelcomeMessage,\n SPINNER_MESSAGE,\n type FrameworkConfig,\n} from './framework-config';\nimport type { WizardOptions } from '../utils/types';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n isUsingTypeScript,\n printWelcome,\n askForCloudRegion,\n} from '../utils/clack-utils';\nimport type { PackageDotJson } from '../utils/package-json';\nimport { analytics } from '../utils/analytics';\nimport { WIZARD_INTERACTION_EVENT_NAME } from './constants';\nimport clack from '../utils/clack';\nimport {\n initializeAgent,\n runAgent,\n AgentSignals,\n AgentErrorType,\n} from './agent-interface';\nimport { getCloudUrlFromRegion } from '../utils/urls';\nimport chalk from 'chalk';\nimport * as semver from 'semver';\nimport {\n addMCPServerToClientsStep,\n uploadEnvironmentVariablesStep,\n} from '../steps';\nimport { checkAnthropicStatusWithPrompt } from '../utils/anthropic-status';\nimport { enableDebugLogs } from '../utils/debug';\n\n/**\n * Universal agent-powered wizard runner.\n * Handles the complete flow for any framework using PostHog MCP integration.\n */\nexport async function runAgentWizard(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<void> {\n if (options.debug) {\n enableDebugLogs();\n }\n\n // Version check\n if (config.detection.minimumVersion && config.detection.getInstalledVersion) {\n const version = await config.detection.getInstalledVersion(options);\n if (version) {\n const coerced = semver.coerce(version);\n if (coerced && semver.lt(coerced, config.detection.minimumVersion)) {\n const docsUrl =\n config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl;\n clack.log.warn(\n `Sorry: the wizard can't help you with ${config.metadata.name} ${version}. Upgrade to ${config.metadata.name} ${config.detection.minimumVersion} or later, or check out the manual setup guide.`,\n );\n clack.log.info(\n `Setup ${config.metadata.name} manually: ${chalk.cyan(docsUrl)}`,\n );\n clack.outro('PostHog wizard will see you next time!');\n return;\n }\n }\n }\n\n // Setup phase\n printWelcome({ wizardName: getWelcomeMessage(config.metadata.name) });\n\n if (config.metadata.beta) {\n clack.log.info(\n `${chalk.yellow('[BETA]')} The ${\n config.metadata.name\n } wizard is in beta. Questions or feedback? Email ${chalk.cyan(\n 'wizard@posthog.com',\n )}`,\n );\n }\n\n if (config.metadata.preRunNotice) {\n clack.log.warn(config.metadata.preRunNotice);\n }\n\n clack.log.info(\n `We're about to read your project using our LLM gateway.\\n\\n.env* file contents will not leave your machine.\\n\\nOther files will be read and edited to provide a fully-custom PostHog integration.`,\n );\n\n const aiConsent = await askForAIConsent(options);\n if (!aiConsent) {\n await abort(\n `This wizard uses an LLM agent to intelligently modify your project. Please view the docs to set up ${config.metadata.name} manually instead: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n // Check Anthropic/Claude service status before proceeding\n const statusOk = await checkAnthropicStatusWithPrompt({ ci: options.ci });\n if (!statusOk) {\n await abort(\n `Please try again later, or set up ${config.metadata.name} manually: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n const typeScriptDetected = isUsingTypeScript(options);\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n // Framework detection and version\n // Only check package.json for Node.js/JavaScript frameworks\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let packageJson: PackageDotJson | null = null;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n packageJson = await getPackageDotJson(options);\n await ensurePackageIsInstalled(\n packageJson,\n config.detection.packageName,\n config.detection.packageDisplayName,\n );\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n // For non-Node frameworks (e.g., Django), version is handled differently\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Set analytics tags for framework version\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'started agent integration',\n integration: config.metadata.integration,\n });\n\n // Get PostHog credentials\n const { projectApiKey, host, accessToken } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n // Gather framework-specific context (e.g., Next.js router, React Native platform)\n const frameworkContext = config.metadata.gatherContext\n ? await config.metadata.gatherContext(options)\n : {};\n\n // Set analytics tags from framework context\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n // Build integration prompt\n const integrationPrompt = buildIntegrationPrompt(\n config,\n {\n frameworkVersion: frameworkVersion || 'latest',\n typescript: typeScriptDetected,\n projectApiKey,\n host,\n },\n frameworkContext,\n );\n\n // Initialize and run agent\n const spinner = clack.spinner();\n\n // Determine MCP URL: CLI flag > env var > production default\n // Use EU subdomain for EU users to work around Claude Code's OAuth bug\n // See: https://github.com/anthropics/claude-code/issues/2267\n const mcpUrl = options.localMcp\n ? 'http://localhost:8787/mcp'\n : process.env.MCP_URL ||\n (cloudRegion === 'eu'\n ? 'https://mcp-eu.posthog.com/mcp'\n : 'https://mcp.posthog.com/mcp');\n\n const agent = await initializeAgent(\n {\n workingDirectory: options.installDir,\n posthogMcpUrl: mcpUrl,\n posthogApiKey: accessToken,\n posthogApiHost: host,\n additionalMcpServers: config.metadata.additionalMcpServers,\n },\n options,\n );\n\n const agentResult = await runAgent(\n agent,\n integrationPrompt,\n options,\n spinner,\n {\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n errorMessage: 'Integration failed',\n },\n );\n\n // Handle error cases detected in agent output\n if (agentResult.error === AgentErrorType.MCP_MISSING) {\n analytics.captureException(\n new Error('Agent could not access PostHog MCP server'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.MCP_MISSING,\n signal: AgentSignals.ERROR_MCP_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('❌ Could not access the PostHog MCP server')}\n\nThe wizard was unable to connect to the PostHog MCP server.\nThis could be due to a network issue or a configuration problem.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (agentResult.error === AgentErrorType.RESOURCE_MISSING) {\n analytics.captureException(\n new Error('Agent could not access setup resource'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.RESOURCE_MISSING,\n signal: AgentSignals.ERROR_RESOURCE_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('❌ Could not access the setup resource')}\n\nThe wizard could not access the setup resource. This may indicate a version mismatch or a temporary service issue.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (\n agentResult.error === AgentErrorType.RATE_LIMIT ||\n agentResult.error === AgentErrorType.API_ERROR\n ) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'api error',\n integration: config.metadata.integration,\n error_type: agentResult.error,\n error_message: agentResult.message,\n });\n\n analytics.captureException(new Error(`API error: ${agentResult.message}`), {\n integration: config.metadata.integration,\n error_type: agentResult.error,\n });\n\n const errorMessage = `\n${chalk.red('❌ API Error')}\n\n${chalk.yellow(agentResult.message || 'Unknown error')}\n\nPlease report this error to: ${chalk.cyan('wizard@posthog.com')}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n // Build environment variables from OAuth credentials\n const envVars = config.environment.getEnvVars(projectApiKey, host);\n\n // Upload environment variables to hosting providers (if configured)\n let uploadedEnvVars: string[] = [];\n if (config.environment.uploadToHosting) {\n uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {\n integration: config.metadata.integration,\n options,\n });\n }\n\n // Add MCP server to clients\n await addMCPServerToClientsStep({\n cloudRegion,\n integration: config.metadata.integration,\n ci: options.ci,\n });\n\n // Build outro message\n const continueUrl = options.signup\n ? `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`\n : undefined;\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? `Added environment variables to .env file`\n : '',\n uploadedEnvVars.length > 0\n ? `Uploaded environment variables to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const nextSteps = [\n ...config.ui.getOutroNextSteps(frameworkContext),\n uploadedEnvVars.length === 0 && config.environment.uploadToHosting\n ? `Upload your Project API key to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const outroMessage = `\n${chalk.green('Successfully installed PostHog!')}\n\n${chalk.cyan('What the agent did:')}\n${changes.map((change) => `• ${change}`).join('\\n')}\n\n${chalk.yellow('Next steps:')}\n${nextSteps.map((step) => `• ${step}`).join('\\n')}\n\nLearn more: ${chalk.cyan(config.metadata.docsUrl)}\n${continueUrl ? `\\nContinue onboarding: ${chalk.cyan(continueUrl)}\\n` : ``}\n${chalk.dim(\n 'Note: This wizard uses an LLM agent to analyze and modify your project. Please review the changes made.',\n)}\n\n${chalk.dim(`How did this work for you? Drop us a line: wizard@posthog.com`)}`;\n\n clack.outro(outroMessage);\n\n await analytics.shutdown('success');\n}\n\n/**\n * Build the integration prompt for the agent.\n * Uses shared base prompt with optional framework-specific addendum.\n */\nfunction buildIntegrationPrompt(\n config: FrameworkConfig,\n context: {\n frameworkVersion: string;\n typescript: boolean;\n projectApiKey: string;\n host: string;\n },\n frameworkContext: Record<string, unknown>,\n): string {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- Framework: ${config.metadata.name} ${context.frameworkVersion}\n- TypeScript: ${context.typescript ? 'Yes' : 'No'}\n- PostHog API Key: ${context.projectApiKey}\n- PostHog Host: ${context.host}${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool. If this tool is not available or you cannot access the MCP server, you must emit: ${\n AgentSignals.ERROR_MCP_MISSING\n } Could not access the PostHog MCP server and halt.\n\n Review the skill descriptions and choose the one that best matches this project's framework and configuration.\n If no suitable skill is found, or you cannot access the MCP server, you emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).\n The resource returns a shell command to install the skill.\n\nSTEP 3: Run the installation command using Bash:\n - Execute the EXACT command returned by the resource (do not modify it)\n - This will download and extract the skill to .claude/skills/{skill-id}/\n\nSTEP 4: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.\n\nSTEP 6: Set up environment variables for PostHog using the env-file-tools MCP server (this runs locally — secret values never leave the machine):\n - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).\n - Use set_env_values to create or update the PostHog API key and host, using the appropriate naming convention for ${\n config.metadata.name\n }. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.\n - Reference these environment variables in the code files you create instead of hardcoding the API key and host.\n\nImportant: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager (excluding the contents of node_modules). Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.\n\n`;\n}\n"]}
@@ -57,17 +57,17 @@ export declare const ApiProjectSchema: z.ZodObject<{
57
57
  api_token: z.ZodString;
58
58
  name: z.ZodString;
59
59
  }, "strip", z.ZodTypeAny, {
60
+ uuid: string;
61
+ name: string;
60
62
  id: number;
61
63
  organization: string;
62
- uuid: string;
63
64
  api_token: string;
64
- name: string;
65
65
  }, {
66
+ uuid: string;
67
+ name: string;
66
68
  id: number;
67
69
  organization: string;
68
- uuid: string;
69
70
  api_token: string;
70
- name: string;
71
71
  }>;
72
72
  export type ApiUser = z.infer<typeof ApiUserSchema>;
73
73
  export type ApiProject = z.infer<typeof ApiProjectSchema>;
@@ -1,23 +1,25 @@
1
+ /**
2
+ * Detection order matters: put framework-specific integrations BEFORE basic language fallbacks
3
+ */
1
4
  export declare enum Integration {
2
5
  nextjs = "nextjs",
3
- react = "react",
4
- svelte = "svelte",
6
+ nuxt = "nuxt",
7
+ vue = "vue",
8
+ reactRouter = "react-router",
9
+ tanstackStart = "tanstack-start",
10
+ tanstackRouter = "tanstack-router",
5
11
  reactNative = "react-native",
12
+ angular = "angular",
6
13
  astro = "astro",
7
- reactRouter = "react-router",
8
14
  django = "django",
9
15
  flask = "flask",
10
- laravel = "laravel"
11
- }
12
- export declare enum FeatureFlagDefinition {
13
- ReactRouter = "wizard-react-router"
16
+ fastapi = "fastapi",
17
+ laravel = "laravel",
18
+ sveltekit = "sveltekit",
19
+ swift = "swift",
20
+ android = "android",
21
+ python = "python"
14
22
  }
15
- export declare function getIntegrationDescription(type: string): string;
16
- type IntegrationChoice = {
17
- name: string;
18
- value: string;
19
- };
20
- export declare function getIntegrationChoices(): IntegrationChoice[];
21
23
  export interface Args {
22
24
  debug: boolean;
23
25
  integration: Integration;
@@ -37,4 +39,3 @@ export declare const POSTHOG_DEV_CLIENT_ID = "DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqd
37
39
  export declare const OAUTH_PORT = 8239;
38
40
  export declare const WIZARD_INTERACTION_EVENT_NAME = "wizard interaction";
39
41
  export declare const WIZARD_REMARK_EVENT_NAME = "wizard remark";
40
- export {};
@@ -1,54 +1,31 @@
1
1
  "use strict";
2
2
  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.FeatureFlagDefinition = exports.Integration = void 0;
4
- exports.getIntegrationDescription = getIntegrationDescription;
5
- exports.getIntegrationChoices = getIntegrationChoices;
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;
4
+ /**
5
+ * Detection order matters: put framework-specific integrations BEFORE basic language fallbacks
6
+ */
6
7
  var Integration;
7
8
  (function (Integration) {
9
+ // Frameworks
8
10
  Integration["nextjs"] = "nextjs";
9
- Integration["react"] = "react";
10
- Integration["svelte"] = "svelte";
11
+ Integration["nuxt"] = "nuxt";
12
+ Integration["vue"] = "vue";
13
+ Integration["reactRouter"] = "react-router";
14
+ Integration["tanstackStart"] = "tanstack-start";
15
+ Integration["tanstackRouter"] = "tanstack-router";
11
16
  Integration["reactNative"] = "react-native";
17
+ Integration["angular"] = "angular";
12
18
  Integration["astro"] = "astro";
13
- Integration["reactRouter"] = "react-router";
14
19
  Integration["django"] = "django";
15
20
  Integration["flask"] = "flask";
21
+ Integration["fastapi"] = "fastapi";
16
22
  Integration["laravel"] = "laravel";
23
+ Integration["sveltekit"] = "sveltekit";
24
+ Integration["swift"] = "swift";
25
+ Integration["android"] = "android";
26
+ // Language fallbacks
27
+ Integration["python"] = "python";
17
28
  })(Integration || (exports.Integration = Integration = {}));
18
- var FeatureFlagDefinition;
19
- (function (FeatureFlagDefinition) {
20
- FeatureFlagDefinition["ReactRouter"] = "wizard-react-router";
21
- })(FeatureFlagDefinition || (exports.FeatureFlagDefinition = FeatureFlagDefinition = {}));
22
- function getIntegrationDescription(type) {
23
- switch (type) {
24
- case Integration.nextjs:
25
- return 'Next.js';
26
- case Integration.react:
27
- return 'React';
28
- case Integration.reactNative:
29
- return 'React Native';
30
- case Integration.svelte:
31
- return 'Svelte';
32
- case Integration.astro:
33
- return 'Astro';
34
- case Integration.reactRouter:
35
- return 'React Router';
36
- case Integration.django:
37
- return 'Django';
38
- case Integration.flask:
39
- return 'Flask';
40
- case Integration.laravel:
41
- return 'Laravel';
42
- default:
43
- throw new Error(`Unknown integration ${type}`);
44
- }
45
- }
46
- function getIntegrationChoices() {
47
- return Object.keys(Integration).map((type) => ({
48
- name: getIntegrationDescription(type),
49
- value: type,
50
- }));
51
- }
52
29
  exports.IS_DEV = ['test', 'development'].includes(process.env.NODE_ENV ?? '');
53
30
  exports.DEBUG = false;
54
31
  exports.DEFAULT_URL = exports.IS_DEV
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAgBA,8DAuBC;AAOD,sDAKC;AAnDD,IAAY,WAUX;AAVD,WAAY,WAAW;IACrB,gCAAiB,CAAA;IACjB,8BAAe,CAAA;IACf,gCAAiB,CAAA;IACjB,2CAA4B,CAAA;IAC5B,8BAAe,CAAA;IACf,2CAA4B,CAAA;IAC5B,gCAAiB,CAAA;IACjB,8BAAe,CAAA;IACf,kCAAmB,CAAA;AACrB,CAAC,EAVW,WAAW,2BAAX,WAAW,QAUtB;AAED,IAAY,qBAEX;AAFD,WAAY,qBAAqB;IAC/B,4DAAmC,CAAA;AACrC,CAAC,EAFW,qBAAqB,qCAArB,qBAAqB,QAEhC;AAED,SAAgB,yBAAyB,CAAC,IAAY;IACpD,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,WAAW,CAAC,MAAM;YACrB,OAAO,SAAS,CAAC;QACnB,KAAK,WAAW,CAAC,KAAK;YACpB,OAAO,OAAO,CAAC;QACjB,KAAK,WAAW,CAAC,WAAW;YAC1B,OAAO,cAAc,CAAC;QACxB,KAAK,WAAW,CAAC,MAAM;YACrB,OAAO,QAAQ,CAAC;QAClB,KAAK,WAAW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G,0CAA0C,CAAC;AACnE,QAAA,UAAU,GAAG,IAAI,CAAC;AAElB,QAAA,6BAA6B,GAAG,oBAAoB,CAAC;AACrD,QAAA,wBAAwB,GAAG,eAAe,CAAC","sourcesContent":["export enum Integration {\n nextjs = 'nextjs',\n react = 'react',\n svelte = 'svelte',\n reactNative = 'react-native',\n astro = 'astro',\n reactRouter = 'react-router',\n django = 'django',\n flask = 'flask',\n laravel = 'laravel',\n}\n\nexport enum FeatureFlagDefinition {\n ReactRouter = 'wizard-react-router',\n}\n\nexport function getIntegrationDescription(type: string): string {\n switch (type) {\n case Integration.nextjs:\n return 'Next.js';\n case Integration.react:\n return 'React';\n case Integration.reactNative:\n return 'React Native';\n case Integration.svelte:\n return 'Svelte';\n case Integration.astro:\n return 'Astro';\n case Integration.reactRouter:\n return 'React Router';\n case Integration.django:\n return 'Django';\n case Integration.flask:\n return 'Flask';\n case Integration.laravel:\n return 'Laravel';\n default:\n throw new Error(`Unknown integration ${type}`);\n }\n}\n\ntype IntegrationChoice = {\n name: string;\n value: string;\n};\n\nexport function getIntegrationChoices(): IntegrationChoice[] {\n return Object.keys(Integration).map((type: string) => ({\n name: getIntegrationDescription(type),\n value: type,\n }));\n}\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"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,IAAY,WAqBX;AArBD,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;IAEnB,qBAAqB;IACrB,gCAAiB,CAAA;AACnB,CAAC,EArBW,WAAW,2BAAX,WAAW,QAqBtB;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","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\n // Language fallbacks\n python = 'python',\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"]}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * In-process MCP server that reads/writes .env files locally.
3
+ * Secret values never leave the machine.
4
+ */
5
+ /**
6
+ * Create an in-process MCP server with env file tools.
7
+ * Must be called asynchronously because the SDK is an ESM module loaded via dynamic import.
8
+ */
9
+ export declare function createEnvFileServer(workingDirectory: string): Promise<any>;
10
+ /** Tool names exposed by the env file server, for use in allowedTools */
11
+ export declare const ENV_FILE_TOOL_NAMES: string[];
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ /**
3
+ * In-process MCP server that reads/writes .env files locally.
4
+ * Secret values never leave the machine.
5
+ */
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ENV_FILE_TOOL_NAMES = void 0;
11
+ exports.createEnvFileServer = createEnvFileServer;
12
+ const path_1 = __importDefault(require("path"));
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const zod_1 = require("zod");
15
+ const debug_1 = require("../utils/debug");
16
+ // Dynamic import cache for ESM module (same pattern as agent-interface.ts)
17
+ let _sdkModule = null;
18
+ async function getSDKModule() {
19
+ if (!_sdkModule) {
20
+ _sdkModule = await import('@anthropic-ai/claude-agent-sdk');
21
+ }
22
+ return _sdkModule;
23
+ }
24
+ /**
25
+ * Resolve filePath relative to workingDirectory, rejecting path traversal.
26
+ */
27
+ function resolveEnvPath(workingDirectory, filePath) {
28
+ const resolved = path_1.default.resolve(workingDirectory, filePath);
29
+ if (!resolved.startsWith(workingDirectory + path_1.default.sep) &&
30
+ resolved !== workingDirectory) {
31
+ throw new Error(`Path traversal rejected: "${filePath}" resolves outside working directory`);
32
+ }
33
+ return resolved;
34
+ }
35
+ /**
36
+ * Ensure the given env file basename is covered by .gitignore in the working directory.
37
+ * Creates .gitignore if it doesn't exist; appends the entry if missing.
38
+ */
39
+ function ensureGitignoreCoverage(workingDirectory, envFileName) {
40
+ const gitignorePath = path_1.default.join(workingDirectory, '.gitignore');
41
+ if (fs_1.default.existsSync(gitignorePath)) {
42
+ const content = fs_1.default.readFileSync(gitignorePath, 'utf8');
43
+ // Check if the file (or a glob covering it) is already listed
44
+ if (content.split('\n').some((line) => line.trim() === envFileName)) {
45
+ return;
46
+ }
47
+ const newContent = content.endsWith('\n')
48
+ ? `${content}${envFileName}\n`
49
+ : `${content}\n${envFileName}\n`;
50
+ fs_1.default.writeFileSync(gitignorePath, newContent, 'utf8');
51
+ }
52
+ else {
53
+ fs_1.default.writeFileSync(gitignorePath, `${envFileName}\n`, 'utf8');
54
+ }
55
+ }
56
+ /**
57
+ * Create an in-process MCP server with env file tools.
58
+ * Must be called asynchronously because the SDK is an ESM module loaded via dynamic import.
59
+ */
60
+ async function createEnvFileServer(workingDirectory) {
61
+ const sdk = await getSDKModule();
62
+ const { tool, createSdkMcpServer } = sdk;
63
+ const checkEnvKeys = tool('check_env_keys', 'Check which environment variable keys are present or missing in a .env file. Never reveals values.', {
64
+ filePath: zod_1.z
65
+ .string()
66
+ .describe('Path to the .env file, relative to the project root'),
67
+ keys: zod_1.z
68
+ .array(zod_1.z.string())
69
+ .describe('Environment variable key names to check'),
70
+ }, (args) => {
71
+ const resolved = resolveEnvPath(workingDirectory, args.filePath);
72
+ (0, debug_1.logToFile)(`check_env_keys: ${resolved}, keys: ${args.keys.join(', ')}`);
73
+ const existingKeys = new Set();
74
+ if (fs_1.default.existsSync(resolved)) {
75
+ const content = fs_1.default.readFileSync(resolved, 'utf8');
76
+ for (const line of content.split('\n')) {
77
+ const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/);
78
+ if (match) {
79
+ existingKeys.add(match[1]);
80
+ }
81
+ }
82
+ }
83
+ const results = {};
84
+ for (const key of args.keys) {
85
+ results[key] = existingKeys.has(key) ? 'present' : 'missing';
86
+ }
87
+ return {
88
+ content: [
89
+ { type: 'text', text: JSON.stringify(results, null, 2) },
90
+ ],
91
+ };
92
+ });
93
+ const setEnvValues = tool('set_env_values', 'Create or update environment variable keys in a .env file. Creates the file if it does not exist. Ensures .gitignore coverage.', {
94
+ filePath: zod_1.z
95
+ .string()
96
+ .describe('Path to the .env file, relative to the project root'),
97
+ values: zod_1.z
98
+ .record(zod_1.z.string(), zod_1.z.string())
99
+ .describe('Key-value pairs to set'),
100
+ }, (args) => {
101
+ const resolved = resolveEnvPath(workingDirectory, args.filePath);
102
+ (0, debug_1.logToFile)(`set_env_values: ${resolved}, keys: ${Object.keys(args.values).join(', ')}`);
103
+ let content = '';
104
+ if (fs_1.default.existsSync(resolved)) {
105
+ content = fs_1.default.readFileSync(resolved, 'utf8');
106
+ }
107
+ const updatedKeys = new Set();
108
+ for (const [key, value] of Object.entries(args.values)) {
109
+ const regex = new RegExp(`^(\\s*${key}\\s*=).*$`, 'm');
110
+ if (regex.test(content)) {
111
+ content = content.replace(regex, `$1${value}`);
112
+ updatedKeys.add(key);
113
+ }
114
+ }
115
+ // Append keys that weren't already in the file
116
+ const newKeys = Object.entries(args.values).filter(([key]) => !updatedKeys.has(key));
117
+ if (newKeys.length > 0) {
118
+ if (content.length > 0 && !content.endsWith('\n')) {
119
+ content += '\n';
120
+ }
121
+ for (const [key, value] of newKeys) {
122
+ content += `${key}=${value}\n`;
123
+ }
124
+ }
125
+ // Ensure parent directory exists
126
+ const dir = path_1.default.dirname(resolved);
127
+ if (!fs_1.default.existsSync(dir)) {
128
+ fs_1.default.mkdirSync(dir, { recursive: true });
129
+ }
130
+ fs_1.default.writeFileSync(resolved, content, 'utf8');
131
+ // Ensure .gitignore coverage for this env file
132
+ const envFileName = path_1.default.basename(resolved);
133
+ ensureGitignoreCoverage(workingDirectory, envFileName);
134
+ return {
135
+ content: [
136
+ {
137
+ type: 'text',
138
+ text: `Updated ${Object.keys(args.values).length} key(s) in ${args.filePath}`,
139
+ },
140
+ ],
141
+ };
142
+ });
143
+ return createSdkMcpServer({
144
+ name: 'env-file-tools',
145
+ version: '1.0.0',
146
+ tools: [checkEnvKeys, setEnvValues],
147
+ });
148
+ }
149
+ /** Tool names exposed by the env file server, for use in allowedTools */
150
+ exports.ENV_FILE_TOOL_NAMES = [
151
+ 'env-file-tools:check_env_keys',
152
+ 'env-file-tools:set_env_values',
153
+ ];
154
+ //# sourceMappingURL=env-file-tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-file-tools.js","sourceRoot":"","sources":["../../../src/lib/env-file-tools.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AA6DH,kDAwHC;AAnLD,gDAAwB;AACxB,4CAAoB;AACpB,6BAAwB;AACxB,0CAA2C;AAE3C,2EAA2E;AAC3E,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;;GAEG;AACH,SAAS,cAAc,CAAC,gBAAwB,EAAE,QAAgB;IAChE,MAAM,QAAQ,GAAG,cAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,QAAQ,CAAC,CAAC;IAC1D,IACE,CAAC,QAAQ,CAAC,UAAU,CAAC,gBAAgB,GAAG,cAAI,CAAC,GAA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ACJ,CAAC,CACF,CAAC;IAEF,OAAO,kBAAkB,CAAC;QACxB,IAAI,EAAE,gBAAgB;QACtB,OAAO,EAAE,OAAO;QAChB,KAAK,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC;KACpC,CAAC,CAAC;AACL,CAAC;AAED,yEAAyE;AAC5D,QAAA,mBAAmB,GAAG;IACjC,+BAA+B;IAC/B,+BAA+B;CAChC,CAAC","sourcesContent":["/**\n * In-process MCP server that reads/writes .env files locally.\n * Secret values never leave the machine.\n */\n\nimport path from 'path';\nimport fs from 'fs';\nimport { z } from 'zod';\nimport { logToFile } from '../utils/debug';\n\n// Dynamic import cache for ESM module (same pattern as agent-interface.ts)\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 * Resolve filePath relative to workingDirectory, rejecting path traversal.\n */\nfunction resolveEnvPath(workingDirectory: string, filePath: string): string {\n const resolved = path.resolve(workingDirectory, filePath);\n if (\n !resolved.startsWith(workingDirectory + path.sep) &&\n resolved !== workingDirectory\n ) {\n throw new Error(\n `Path traversal rejected: \"${filePath}\" resolves outside working directory`,\n );\n }\n return resolved;\n}\n\n/**\n * Ensure the given env file basename is covered by .gitignore in the working directory.\n * Creates .gitignore if it doesn't exist; appends the entry if missing.\n */\nfunction ensureGitignoreCoverage(\n workingDirectory: string,\n envFileName: string,\n): void {\n const gitignorePath = path.join(workingDirectory, '.gitignore');\n\n if (fs.existsSync(gitignorePath)) {\n const content = fs.readFileSync(gitignorePath, 'utf8');\n // Check if the file (or a glob covering it) is already listed\n if (content.split('\\n').some((line) => line.trim() === envFileName)) {\n return;\n }\n const newContent = content.endsWith('\\n')\n ? `${content}${envFileName}\\n`\n : `${content}\\n${envFileName}\\n`;\n fs.writeFileSync(gitignorePath, newContent, 'utf8');\n } else {\n fs.writeFileSync(gitignorePath, `${envFileName}\\n`, 'utf8');\n }\n}\n\n/**\n * Create an in-process MCP server with env file tools.\n * Must be called asynchronously because the SDK is an ESM module loaded via dynamic import.\n */\nexport async function createEnvFileServer(workingDirectory: string) {\n const sdk = await getSDKModule();\n const { tool, createSdkMcpServer } = sdk;\n\n const checkEnvKeys = tool(\n 'check_env_keys',\n 'Check which environment variable keys are present or missing in a .env file. Never reveals values.',\n {\n filePath: z\n .string()\n .describe('Path to the .env file, relative to the project root'),\n keys: z\n .array(z.string())\n .describe('Environment variable key names to check'),\n },\n (args: { filePath: string; keys: string[] }) => {\n const resolved = resolveEnvPath(workingDirectory, args.filePath);\n logToFile(`check_env_keys: ${resolved}, keys: ${args.keys.join(', ')}`);\n\n const existingKeys: Set<string> = new Set();\n if (fs.existsSync(resolved)) {\n const content = fs.readFileSync(resolved, 'utf8');\n for (const line of content.split('\\n')) {\n const match = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=/);\n if (match) {\n existingKeys.add(match[1]);\n }\n }\n }\n\n const results: Record<string, 'present' | 'missing'> = {};\n for (const key of args.keys) {\n results[key] = existingKeys.has(key) ? 'present' : 'missing';\n }\n\n return {\n content: [\n { type: 'text' as const, text: JSON.stringify(results, null, 2) },\n ],\n };\n },\n );\n\n const setEnvValues = tool(\n 'set_env_values',\n 'Create or update environment variable keys in a .env file. Creates the file if it does not exist. Ensures .gitignore coverage.',\n {\n filePath: z\n .string()\n .describe('Path to the .env file, relative to the project root'),\n values: z\n .record(z.string(), z.string())\n .describe('Key-value pairs to set'),\n },\n (args: { filePath: string; values: Record<string, string> }) => {\n const resolved = resolveEnvPath(workingDirectory, args.filePath);\n logToFile(\n `set_env_values: ${resolved}, keys: ${Object.keys(args.values).join(\n ', ',\n )}`,\n );\n\n let content = '';\n if (fs.existsSync(resolved)) {\n content = fs.readFileSync(resolved, 'utf8');\n }\n\n const updatedKeys = new Set<string>();\n\n for (const [key, value] of Object.entries(args.values)) {\n const regex = new RegExp(`^(\\\\s*${key}\\\\s*=).*$`, 'm');\n if (regex.test(content)) {\n content = content.replace(regex, `$1${value}`);\n updatedKeys.add(key);\n }\n }\n\n // Append keys that weren't already in the file\n const newKeys = Object.entries(args.values).filter(\n ([key]) => !updatedKeys.has(key),\n );\n if (newKeys.length > 0) {\n if (content.length > 0 && !content.endsWith('\\n')) {\n content += '\\n';\n }\n for (const [key, value] of newKeys) {\n content += `${key}=${value}\\n`;\n }\n }\n\n // Ensure parent directory exists\n const dir = path.dirname(resolved);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n fs.writeFileSync(resolved, content, 'utf8');\n\n // Ensure .gitignore coverage for this env file\n const envFileName = path.basename(resolved);\n ensureGitignoreCoverage(workingDirectory, envFileName);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `Updated ${Object.keys(args.values).length} key(s) in ${\n args.filePath\n }`,\n },\n ],\n };\n },\n );\n\n return createSdkMcpServer({\n name: 'env-file-tools',\n version: '1.0.0',\n tools: [checkEnvKeys, setEnvValues],\n });\n}\n\n/** Tool names exposed by the env file server, for use in allowedTools */\nexport const ENV_FILE_TOOL_NAMES = [\n 'env-file-tools:check_env_keys',\n 'env-file-tools:set_env_values',\n];\n"]}