@posthog/wizard 2.0.2 → 2.1.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 (50) hide show
  1. package/dist/bin.js +22 -4
  2. package/dist/bin.js.map +1 -1
  3. package/dist/src/__tests__/cli.test.js +50 -3
  4. package/dist/src/__tests__/cli.test.js.map +1 -1
  5. package/dist/src/__tests__/package-json.test.d.ts +1 -0
  6. package/dist/src/__tests__/package-json.test.js +173 -0
  7. package/dist/src/__tests__/package-json.test.js.map +1 -0
  8. package/dist/src/lib/__tests__/agent-interface.test.js +1 -0
  9. package/dist/src/lib/__tests__/agent-interface.test.js.map +1 -1
  10. package/dist/src/lib/__tests__/yara-hooks.test.d.ts +1 -0
  11. package/dist/src/lib/__tests__/yara-hooks.test.js +432 -0
  12. package/dist/src/lib/__tests__/yara-hooks.test.js.map +1 -0
  13. package/dist/src/lib/__tests__/yara-scanner.test.d.ts +1 -0
  14. package/dist/src/lib/__tests__/yara-scanner.test.js +613 -0
  15. package/dist/src/lib/__tests__/yara-scanner.test.js.map +1 -0
  16. package/dist/src/lib/agent-interface.d.ts +4 -2
  17. package/dist/src/lib/agent-interface.js +40 -26
  18. package/dist/src/lib/agent-interface.js.map +1 -1
  19. package/dist/src/lib/agent-runner.js +34 -1
  20. package/dist/src/lib/agent-runner.js.map +1 -1
  21. package/dist/src/lib/commandments.js +1 -0
  22. package/dist/src/lib/commandments.js.map +1 -1
  23. package/dist/src/lib/constants.d.ts +4 -3
  24. package/dist/src/lib/constants.js +3 -2
  25. package/dist/src/lib/constants.js.map +1 -1
  26. package/dist/src/lib/skill-install.d.ts +10 -0
  27. package/dist/src/lib/skill-install.js +23 -0
  28. package/dist/src/lib/skill-install.js.map +1 -0
  29. package/dist/src/lib/version.d.ts +1 -1
  30. package/dist/src/lib/version.js +1 -1
  31. package/dist/src/lib/version.js.map +1 -1
  32. package/dist/src/lib/wizard-session.d.ts +2 -0
  33. package/dist/src/lib/wizard-session.js +1 -0
  34. package/dist/src/lib/wizard-session.js.map +1 -1
  35. package/dist/src/lib/yara-hooks.d.ts +44 -0
  36. package/dist/src/lib/yara-hooks.js +377 -0
  37. package/dist/src/lib/yara-hooks.js.map +1 -0
  38. package/dist/src/lib/yara-scanner.d.ts +61 -0
  39. package/dist/src/lib/yara-scanner.js +328 -0
  40. package/dist/src/lib/yara-scanner.js.map +1 -0
  41. package/dist/src/run.d.ts +3 -0
  42. package/dist/src/run.js +10 -0
  43. package/dist/src/run.js.map +1 -1
  44. package/dist/src/steps/add-mcp-server-to-clients/index.d.ts +2 -1
  45. package/dist/src/steps/add-mcp-server-to-clients/index.js +1 -1
  46. package/dist/src/steps/add-mcp-server-to-clients/index.js.map +1 -1
  47. package/dist/src/utils/rules/universal.md +12 -0
  48. package/dist/src/utils/types.d.ts +9 -0
  49. package/dist/src/utils/types.js.map +1 -1
  50. package/package.json +1 -1
@@ -0,0 +1,328 @@
1
+ "use strict";
2
+ /**
3
+ * YARA content scanner for the PostHog wizard.
4
+ *
5
+ * This file is the single source of truth for all wizard YARA rules.
6
+ *
7
+ * Scans tool inputs (pre-execution) and outputs (post-execution) for
8
+ * security violations including PII leakage, hardcoded secrets,
9
+ * prompt injection, and secret exfiltration.
10
+ *
11
+ * We use YARA-style regex rules rather than the real YARA C library to
12
+ * avoid native binary dependencies in an npx-distributed npm package.
13
+ *
14
+ * This is Layer 2 (L2) in the wizard's defense-in-depth model,
15
+ * complementing the prompt-based commandments (L0) and the
16
+ * canUseTool() allowlist (L1).
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.RULES = void 0;
20
+ exports.scan = scan;
21
+ exports.scanSkillDirectory = scanSkillDirectory;
22
+ // ─── Rule Definitions ────────────────────────────────────────────
23
+ //
24
+ // Patterns are compiled once at module load time for performance.
25
+ // Design spec: policies/yara/RULES.md
26
+ const POST_WRITE_EDIT = [
27
+ { phase: 'PostToolUse', tool: 'Write' },
28
+ { phase: 'PostToolUse', tool: 'Edit' },
29
+ ];
30
+ const POST_READ_GREP = [
31
+ { phase: 'PostToolUse', tool: 'Read' },
32
+ { phase: 'PostToolUse', tool: 'Grep' },
33
+ ];
34
+ const PRE_BASH = [
35
+ { phase: 'PreToolUse', tool: 'Bash' },
36
+ ];
37
+ // ── §1 PostHog API Violations ────────────────────────────────────
38
+ const pii_in_capture_call = {
39
+ name: 'pii_in_capture_call',
40
+ description: "Detects PII fields passed to posthog.capture() — violates 'NEVER send PII in capture()' commandment",
41
+ severity: 'high',
42
+ category: 'posthog_pii',
43
+ appliesTo: POST_WRITE_EDIT,
44
+ patterns: [
45
+ // Direct PII field names in capture properties
46
+ /\.capture\s*\([^)]{0,200}email/i,
47
+ /\.capture\s*\([^)]{0,200}phone/i,
48
+ /\.capture\s*\([^)]{0,200}full[_\s]?name/i,
49
+ /\.capture\s*\([^)]{0,200}first[_\s]?name/i,
50
+ /\.capture\s*\([^)]{0,200}last[_\s]?name/i,
51
+ /\.capture\s*\([^)]{0,200}(street|mailing|home|billing)[_\s]?address/i,
52
+ /\.capture\s*\([^)]{0,200}(ssn|social[_\s]?security)/i,
53
+ /\.capture\s*\([^)]{0,200}(date[_\s]?of[_\s]?birth|dob|birthday)/i,
54
+ /\.capture\s*\([^)]{0,200}\$ip/,
55
+ // identify() allows email/phone/name (standard PostHog user properties),
56
+ // but highly sensitive PII is still blocked in identify().
57
+ /\.identify\s*\([^)]{0,200}(ssn|social[_\s]?security)/i,
58
+ /\.identify\s*\([^)]{0,200}(card[_\s]?number|cvv|credit[_\s]?card)/i,
59
+ /\.identify\s*\([^)]{0,200}(date[_\s]?of[_\s]?birth|dob|birthday)/i,
60
+ /\.identify\s*\([^)]{0,200}(street|mailing|home|billing)[_\s]?address/i,
61
+ // PII in $set properties via capture (bound to same object)
62
+ /\$set[^}]{0,200}email/i,
63
+ /\$set[^}]{0,200}phone/i,
64
+ ],
65
+ };
66
+ const hardcoded_posthog_key = {
67
+ name: 'hardcoded_posthog_key',
68
+ description: "Detects hardcoded PostHog API keys in source — violates 'use environment variables' commandment",
69
+ severity: 'high',
70
+ category: 'posthog_hardcoded_key',
71
+ appliesTo: POST_WRITE_EDIT,
72
+ patterns: [
73
+ // PostHog project API key (phc_ prefix, 20+ alphanumeric chars)
74
+ /phc_[a-zA-Z0-9]{20,}/,
75
+ // PostHog personal API key (phx_ prefix)
76
+ /phx_[a-zA-Z0-9]{20,}/,
77
+ // Hardcoded key assignment patterns
78
+ /apiKey\s*[:=]\s*['"][a-zA-Z0-9_]{20,}['"]/,
79
+ /api_key\s*[:=]\s*['"][a-zA-Z0-9_]{20,}['"]/,
80
+ /POSTHOG_KEY\s*[:=]\s*['"][a-zA-Z0-9_]{20,}['"]/,
81
+ ],
82
+ };
83
+ const autocapture_disabled = {
84
+ name: 'autocapture_disabled',
85
+ description: "Detects agent disabling autocapture — violates 'don't disable autocapture' commandment",
86
+ severity: 'medium',
87
+ category: 'posthog_autocapture',
88
+ appliesTo: POST_WRITE_EDIT,
89
+ patterns: [
90
+ /autocapture\s*:\s*false/,
91
+ /autocapture\s*:\s*'false'/,
92
+ /autocapture\s*:\s*"false"/,
93
+ /autocapture\s*=\s*False/,
94
+ /disable_autocapture\s*[:=]\s*(true|True|1)/,
95
+ ],
96
+ };
97
+ // ── §1b Additional PostHog config rules ──────────────────────────
98
+ const hardcoded_posthog_host = {
99
+ name: 'hardcoded_posthog_host',
100
+ description: 'Detects hardcoded PostHog host URLs in source — should use environment variables',
101
+ severity: 'high',
102
+ category: 'posthog_hardcoded_key',
103
+ appliesTo: POST_WRITE_EDIT,
104
+ patterns: [/['"]https:\/\/(us|eu)\.i\.posthog\.com['"]/],
105
+ };
106
+ const session_recording_disabled = {
107
+ name: 'session_recording_disabled',
108
+ description: 'Detects agent disabling session recording',
109
+ severity: 'medium',
110
+ category: 'posthog_config',
111
+ appliesTo: POST_WRITE_EDIT,
112
+ patterns: [
113
+ /disable_session_recording\s*:\s*true/i,
114
+ /disable_session_recording\s*=\s*True/,
115
+ ],
116
+ };
117
+ const opt_out_capturing = {
118
+ name: 'opt_out_capturing',
119
+ description: 'Detects agent opting out of PostHog capturing entirely',
120
+ severity: 'medium',
121
+ category: 'posthog_config',
122
+ appliesTo: POST_WRITE_EDIT,
123
+ patterns: [
124
+ // Match opt_out_capturing as a config property (in init options), not as a method call.
125
+ // posthog.opt_out_capturing() is a legitimate GDPR-required API.
126
+ /opt_out_capturing\s*[:=]\s*(true|True|1)/i,
127
+ /opted_out\s*[:=]\s*(true|True|1)/i,
128
+ ],
129
+ };
130
+ // ── §2 Prompt Injection ──────────────────────────────────────────
131
+ const prompt_injection_wizard_override = {
132
+ name: 'prompt_injection_wizard_override',
133
+ description: 'Detects classic prompt injection attempting to override agent instructions',
134
+ severity: 'critical',
135
+ category: 'prompt_injection',
136
+ appliesTo: POST_READ_GREP,
137
+ patterns: [
138
+ // Direct instruction override — classic injection patterns
139
+ /ignore previous instructions/i,
140
+ /disregard all/i,
141
+ /forget your instructions/i,
142
+ /override your rules/i,
143
+ // Role manipulation
144
+ /act as a different/i,
145
+ /new instructions:/i,
146
+ ],
147
+ };
148
+ const prompt_injection_wizard_specific = {
149
+ name: 'prompt_injection_wizard_specific',
150
+ description: 'Detects wizard-specific manipulation or tool abuse attempts in project files',
151
+ severity: 'medium',
152
+ category: 'prompt_injection',
153
+ appliesTo: POST_READ_GREP,
154
+ patterns: [
155
+ // Wizard-specific manipulation
156
+ /skip posthog/i,
157
+ /do not install posthog/i,
158
+ /remove posthog/i,
159
+ /uninstall posthog/i,
160
+ /delete the posthog/i,
161
+ // Tool abuse via file content
162
+ /run the following command/i,
163
+ /execute this shell command/i,
164
+ // Role hijacking — require "you are now a" to avoid false positives
165
+ // on legitimate phrases like "you are now ready to..."
166
+ /you are now a\s/i,
167
+ ],
168
+ };
169
+ const prompt_injection_base64 = {
170
+ name: 'prompt_injection_base64',
171
+ description: 'Detects suspicious base64-encoded blocks in file content that may contain obfuscated prompt injection',
172
+ severity: 'critical',
173
+ category: 'prompt_injection',
174
+ appliesTo: POST_READ_GREP,
175
+ patterns: [
176
+ // Long base64 strings (100+ chars) in comments or string literals
177
+ // that aren't typical data URIs or legitimate base64 content
178
+ /(?:\/\/|#|\/\*)\s*[A-Za-z0-9+/]{100,}={0,2}/,
179
+ ],
180
+ };
181
+ // ── §3 Secret Exfiltration ───────────────────────────────────────
182
+ const secret_exfiltration_via_command = {
183
+ name: 'secret_exfiltration_via_command',
184
+ description: 'Detects shell commands attempting to exfiltrate secrets or credentials',
185
+ severity: 'critical',
186
+ category: 'exfiltration',
187
+ appliesTo: PRE_BASH,
188
+ patterns: [
189
+ // curl/wget with environment variable secrets
190
+ /curl\s+.*\$\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i,
191
+ /wget\s+.*\$\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i,
192
+ // Piping sensitive content to network tools
193
+ /(\$\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD)|\.env|credentials)\S*.*\|\s*curl/i,
194
+ /(\$\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD)|\.env|credentials)\S*.*\|\s*wget/i,
195
+ /\|\s*nc\s/,
196
+ /\|\s*netcat\s/,
197
+ // Base64 encoding piped to network
198
+ /base64.*\|\s*(curl|wget|nc\s)/i,
199
+ // Reading .env and sending
200
+ /cat\s+.*\.env.*\|\s*(curl|wget)/,
201
+ // PostHog key exfiltration specifically
202
+ /curl.*phc_[a-zA-Z0-9]/,
203
+ /wget.*phc_[a-zA-Z0-9]/,
204
+ ],
205
+ };
206
+ // ── §4 Filesystem Safety ─────────────────────────────────────────
207
+ const destructive_rm = {
208
+ name: 'destructive_rm',
209
+ description: 'Detects rm -rf or rm -r commands that could mass-delete files',
210
+ severity: 'critical',
211
+ category: 'filesystem_safety',
212
+ appliesTo: PRE_BASH,
213
+ patterns: [
214
+ // Combined flags: rm -rf, rm -fr, rm -rfi, etc.
215
+ /\brm\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\b/,
216
+ // Separated flags: rm -r -f, rm -f -r (with optional other flags)
217
+ /\brm\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*r[a-zA-Z]*\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*f\b/,
218
+ /\brm\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*f[a-zA-Z]*\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*r\b/,
219
+ ],
220
+ };
221
+ const git_force_push = {
222
+ name: 'git_force_push',
223
+ description: 'Detects git push --force which can overwrite remote history',
224
+ severity: 'critical',
225
+ category: 'filesystem_safety',
226
+ appliesTo: PRE_BASH,
227
+ patterns: [/git\s+push\s+.*--force/, /git\s+push\s+.*-f\b/],
228
+ };
229
+ const git_reset_hard = {
230
+ name: 'git_reset_hard',
231
+ description: 'Detects git reset --hard which discards all uncommitted changes',
232
+ severity: 'critical',
233
+ category: 'filesystem_safety',
234
+ appliesTo: PRE_BASH,
235
+ patterns: [/git\s+reset\s+--hard/],
236
+ };
237
+ // ── §5 Supply Chain ──────────────────────────────────────────────
238
+ const wrong_posthog_package = {
239
+ name: 'wrong_posthog_package',
240
+ description: 'Detects installing the wrong PostHog npm package — should be posthog-js or posthog-node',
241
+ severity: 'high',
242
+ category: 'supply_chain',
243
+ appliesTo: PRE_BASH,
244
+ patterns: [
245
+ // Match "npm install posthog" but not "posthog-js", "posthog-node", etc.
246
+ /npm\s+install\s+(?:--save\s+|--save-dev\s+|-[SD]\s+)*posthog(?!\s*-)/,
247
+ /pnpm\s+(?:add|install)\s+(?:--save\s+|--save-dev\s+|-[SD]\s+)*posthog(?!\s*-)/,
248
+ /yarn\s+add\s+(?:--dev\s+|-D\s+)*posthog(?!\s*-)/,
249
+ /bun\s+(?:add|install)\s+(?:--dev\s+|-[dD]\s+)*posthog(?!\s*-)/,
250
+ ],
251
+ };
252
+ const npm_install_global = {
253
+ name: 'npm_install_global',
254
+ description: 'Detects global npm installs — should never install packages globally',
255
+ severity: 'high',
256
+ category: 'supply_chain',
257
+ appliesTo: PRE_BASH,
258
+ patterns: [/npm\s+install\s+-g\b/, /npm\s+install\s+--global\b/],
259
+ };
260
+ // ─── Rule Registry ───────────────────────────────────────────────
261
+ exports.RULES = [
262
+ // §1 PostHog API violations
263
+ pii_in_capture_call,
264
+ hardcoded_posthog_key,
265
+ autocapture_disabled,
266
+ hardcoded_posthog_host,
267
+ session_recording_disabled,
268
+ opt_out_capturing,
269
+ // §2 Prompt injection
270
+ prompt_injection_wizard_override,
271
+ prompt_injection_wizard_specific,
272
+ prompt_injection_base64,
273
+ // §3 Secret exfiltration
274
+ secret_exfiltration_via_command,
275
+ // §4 Filesystem safety
276
+ destructive_rm,
277
+ git_force_push,
278
+ git_reset_hard,
279
+ // §5 Supply chain
280
+ wrong_posthog_package,
281
+ npm_install_global,
282
+ ];
283
+ // ─── Scan Engine ─────────────────────────────────────────────────
284
+ /** Maximum content length to scan (100 KB). Inputs beyond this are truncated. */
285
+ const MAX_SCAN_LENGTH = 100_000;
286
+ /**
287
+ * Scan content against rules applicable to a given hook phase and tool.
288
+ * Returns all matching rules (one match per rule, first pattern wins).
289
+ */
290
+ function scan(content, phase, tool) {
291
+ // Cap input length to prevent pathological regex performance
292
+ const scanContent = content.length > MAX_SCAN_LENGTH
293
+ ? content.slice(0, MAX_SCAN_LENGTH)
294
+ : content;
295
+ const applicableRules = exports.RULES.filter((r) => r.appliesTo.some((a) => a.phase === phase && a.tool === tool));
296
+ const matches = [];
297
+ for (const rule of applicableRules) {
298
+ for (const pattern of rule.patterns) {
299
+ const match = pattern.exec(scanContent);
300
+ if (match) {
301
+ matches.push({
302
+ rule,
303
+ matchedText: match[0],
304
+ offset: match.index,
305
+ });
306
+ break; // One match per rule is sufficient
307
+ }
308
+ }
309
+ }
310
+ return matches.length > 0 ? { matched: true, matches } : { matched: false };
311
+ }
312
+ /**
313
+ * Scan all files in a skill directory for prompt injection.
314
+ * Used for context-mill scanning after skill installation.
315
+ */
316
+ function scanSkillDirectory(files) {
317
+ const allMatches = [];
318
+ for (const file of files) {
319
+ const result = scan(file.content, 'PostToolUse', 'Read');
320
+ if (result.matched) {
321
+ allMatches.push(...result.matches);
322
+ }
323
+ }
324
+ return allMatches.length > 0
325
+ ? { matched: true, matches: allMatches }
326
+ : { matched: false };
327
+ }
328
+ //# sourceMappingURL=yara-scanner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yara-scanner.js","sourceRoot":"","sources":["../../../src/lib/yara-scanner.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AA+VH,oBA8BC;AAMD,gDAaC;AArWD,oEAAoE;AACpE,EAAE;AACF,kEAAkE;AAClE,sCAAsC;AAEtC,MAAM,eAAe,GAAkD;IACrE,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE;IACvC,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,EAAE;CACvC,CAAC;AAEF,MAAM,cAAc,GAAkD;IACpE,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,EAAE;IACtC,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,EAAE;CACvC,CAAC;AAEF,MAAM,QAAQ,GAAkD;IAC9D,EAAE,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE;CACtC,CAAC;AAEF,oEAAoE;AAEpE,MAAM,mBAAmB,GAAa;IACpC,IAAI,EAAE,qBAAqB;IAC3B,WAAW,EACT,qGAAqG;IACvG,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,aAAa;IACvB,SAAS,EAAE,eAAe;IAC1B,QAAQ,EAAE;QACR,+CAA+C;QAC/C,iCAAiC;QACjC,iCAAiC;QACjC,0CAA0C;QAC1C,2CAA2C;QAC3C,0CAA0C;QAC1C,sEAAsE;QACtE,sDAAsD;QACtD,kEAAkE;QAClE,+BAA+B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K,MAAM,IAAI,IAAI,eAAe,EAAE,CAAC;QACnC,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACpC,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YACxC,IAAI,KAAK,EAAE,CAAC;gBACV,OAAO,CAAC,IAAI,CAAC;oBACX,IAAI;oBACJ,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;oBACrB,MAAM,EAAE,KAAK,CAAC,KAAK;iBACpB,CAAC,CAAC;gBACH,MAAM,CAAC,mCAAmC;YAC5C,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9E,CAAC;AAED;;;GAGG;AACH,SAAgB,kBAAkB,CAChC,KAA+C;IAE/C,MAAM,UAAU,GAAgB,EAAE,CAAC;IACnC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE,MAAM,CAAC,CAAC;QACzD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;YACnB,UAAU,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC,MAAM,GAAG,CAAC;QAC1B,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE;QACxC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AACzB,CAAC","sourcesContent":["/**\n * YARA content scanner for the PostHog wizard.\n *\n * This file is the single source of truth for all wizard YARA rules.\n *\n * Scans tool inputs (pre-execution) and outputs (post-execution) for\n * security violations including PII leakage, hardcoded secrets,\n * prompt injection, and secret exfiltration.\n *\n * We use YARA-style regex rules rather than the real YARA C library to\n * avoid native binary dependencies in an npx-distributed npm package.\n *\n * This is Layer 2 (L2) in the wizard's defense-in-depth model,\n * complementing the prompt-based commandments (L0) and the\n * canUseTool() allowlist (L1).\n */\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type YaraSeverity = 'critical' | 'high' | 'medium' | 'low';\n\nexport type YaraCategory =\n | 'posthog_pii'\n | 'posthog_hardcoded_key'\n | 'posthog_autocapture'\n | 'posthog_config'\n | 'prompt_injection'\n | 'exfiltration'\n | 'filesystem_safety'\n | 'supply_chain';\n\nexport type HookPhase = 'PreToolUse' | 'PostToolUse';\nexport type ToolTarget = 'Bash' | 'Write' | 'Edit' | 'Read' | 'Grep';\n\nexport interface YaraRule {\n /** Rule name matching the .yar file (e.g. 'pii_in_capture_call') */\n name: string;\n description: string;\n severity: YaraSeverity;\n category: YaraCategory;\n /** Which hook+tool combinations this rule applies to */\n appliesTo: Array<{ phase: HookPhase; tool: ToolTarget }>;\n /** Compiled regex patterns — any match triggers the rule */\n patterns: RegExp[];\n}\n\nexport interface YaraMatch {\n rule: YaraRule;\n /** The matched substring */\n matchedText: string;\n /** Byte offset in the scanned content */\n offset: number;\n}\n\nexport type ScanResult =\n | { matched: false }\n | { matched: true; matches: YaraMatch[] };\n\n// ─── Rule Definitions ────────────────────────────────────────────\n//\n// Patterns are compiled once at module load time for performance.\n// Design spec: policies/yara/RULES.md\n\nconst POST_WRITE_EDIT: Array<{ phase: HookPhase; tool: ToolTarget }> = [\n { phase: 'PostToolUse', tool: 'Write' },\n { phase: 'PostToolUse', tool: 'Edit' },\n];\n\nconst POST_READ_GREP: Array<{ phase: HookPhase; tool: ToolTarget }> = [\n { phase: 'PostToolUse', tool: 'Read' },\n { phase: 'PostToolUse', tool: 'Grep' },\n];\n\nconst PRE_BASH: Array<{ phase: HookPhase; tool: ToolTarget }> = [\n { phase: 'PreToolUse', tool: 'Bash' },\n];\n\n// ── §1 PostHog API Violations ────────────────────────────────────\n\nconst pii_in_capture_call: YaraRule = {\n name: 'pii_in_capture_call',\n description:\n \"Detects PII fields passed to posthog.capture() — violates 'NEVER send PII in capture()' commandment\",\n severity: 'high',\n category: 'posthog_pii',\n appliesTo: POST_WRITE_EDIT,\n patterns: [\n // Direct PII field names in capture properties\n /\\.capture\\s*\\([^)]{0,200}email/i,\n /\\.capture\\s*\\([^)]{0,200}phone/i,\n /\\.capture\\s*\\([^)]{0,200}full[_\\s]?name/i,\n /\\.capture\\s*\\([^)]{0,200}first[_\\s]?name/i,\n /\\.capture\\s*\\([^)]{0,200}last[_\\s]?name/i,\n /\\.capture\\s*\\([^)]{0,200}(street|mailing|home|billing)[_\\s]?address/i,\n /\\.capture\\s*\\([^)]{0,200}(ssn|social[_\\s]?security)/i,\n /\\.capture\\s*\\([^)]{0,200}(date[_\\s]?of[_\\s]?birth|dob|birthday)/i,\n /\\.capture\\s*\\([^)]{0,200}\\$ip/,\n // identify() allows email/phone/name (standard PostHog user properties),\n // but highly sensitive PII is still blocked in identify().\n /\\.identify\\s*\\([^)]{0,200}(ssn|social[_\\s]?security)/i,\n /\\.identify\\s*\\([^)]{0,200}(card[_\\s]?number|cvv|credit[_\\s]?card)/i,\n /\\.identify\\s*\\([^)]{0,200}(date[_\\s]?of[_\\s]?birth|dob|birthday)/i,\n /\\.identify\\s*\\([^)]{0,200}(street|mailing|home|billing)[_\\s]?address/i,\n // PII in $set properties via capture (bound to same object)\n /\\$set[^}]{0,200}email/i,\n /\\$set[^}]{0,200}phone/i,\n ],\n};\n\nconst hardcoded_posthog_key: YaraRule = {\n name: 'hardcoded_posthog_key',\n description:\n \"Detects hardcoded PostHog API keys in source — violates 'use environment variables' commandment\",\n severity: 'high',\n category: 'posthog_hardcoded_key',\n appliesTo: POST_WRITE_EDIT,\n patterns: [\n // PostHog project API key (phc_ prefix, 20+ alphanumeric chars)\n /phc_[a-zA-Z0-9]{20,}/,\n // PostHog personal API key (phx_ prefix)\n /phx_[a-zA-Z0-9]{20,}/,\n // Hardcoded key assignment patterns\n /apiKey\\s*[:=]\\s*['\"][a-zA-Z0-9_]{20,}['\"]/,\n /api_key\\s*[:=]\\s*['\"][a-zA-Z0-9_]{20,}['\"]/,\n /POSTHOG_KEY\\s*[:=]\\s*['\"][a-zA-Z0-9_]{20,}['\"]/,\n ],\n};\n\nconst autocapture_disabled: YaraRule = {\n name: 'autocapture_disabled',\n description:\n \"Detects agent disabling autocapture — violates 'don't disable autocapture' commandment\",\n severity: 'medium',\n category: 'posthog_autocapture',\n appliesTo: POST_WRITE_EDIT,\n patterns: [\n /autocapture\\s*:\\s*false/,\n /autocapture\\s*:\\s*'false'/,\n /autocapture\\s*:\\s*\"false\"/,\n /autocapture\\s*=\\s*False/,\n /disable_autocapture\\s*[:=]\\s*(true|True|1)/,\n ],\n};\n\n// ── §1b Additional PostHog config rules ──────────────────────────\n\nconst hardcoded_posthog_host: YaraRule = {\n name: 'hardcoded_posthog_host',\n description:\n 'Detects hardcoded PostHog host URLs in source — should use environment variables',\n severity: 'high',\n category: 'posthog_hardcoded_key',\n appliesTo: POST_WRITE_EDIT,\n patterns: [/['\"]https:\\/\\/(us|eu)\\.i\\.posthog\\.com['\"]/],\n};\n\nconst session_recording_disabled: YaraRule = {\n name: 'session_recording_disabled',\n description: 'Detects agent disabling session recording',\n severity: 'medium',\n category: 'posthog_config',\n appliesTo: POST_WRITE_EDIT,\n patterns: [\n /disable_session_recording\\s*:\\s*true/i,\n /disable_session_recording\\s*=\\s*True/,\n ],\n};\n\nconst opt_out_capturing: YaraRule = {\n name: 'opt_out_capturing',\n description: 'Detects agent opting out of PostHog capturing entirely',\n severity: 'medium',\n category: 'posthog_config',\n appliesTo: POST_WRITE_EDIT,\n patterns: [\n // Match opt_out_capturing as a config property (in init options), not as a method call.\n // posthog.opt_out_capturing() is a legitimate GDPR-required API.\n /opt_out_capturing\\s*[:=]\\s*(true|True|1)/i,\n /opted_out\\s*[:=]\\s*(true|True|1)/i,\n ],\n};\n\n// ── §2 Prompt Injection ──────────────────────────────────────────\n\nconst prompt_injection_wizard_override: YaraRule = {\n name: 'prompt_injection_wizard_override',\n description:\n 'Detects classic prompt injection attempting to override agent instructions',\n severity: 'critical',\n category: 'prompt_injection',\n appliesTo: POST_READ_GREP,\n patterns: [\n // Direct instruction override — classic injection patterns\n /ignore previous instructions/i,\n /disregard all/i,\n /forget your instructions/i,\n /override your rules/i,\n // Role manipulation\n /act as a different/i,\n /new instructions:/i,\n ],\n};\n\nconst prompt_injection_wizard_specific: YaraRule = {\n name: 'prompt_injection_wizard_specific',\n description:\n 'Detects wizard-specific manipulation or tool abuse attempts in project files',\n severity: 'medium',\n category: 'prompt_injection',\n appliesTo: POST_READ_GREP,\n patterns: [\n // Wizard-specific manipulation\n /skip posthog/i,\n /do not install posthog/i,\n /remove posthog/i,\n /uninstall posthog/i,\n /delete the posthog/i,\n // Tool abuse via file content\n /run the following command/i,\n /execute this shell command/i,\n // Role hijacking — require \"you are now a\" to avoid false positives\n // on legitimate phrases like \"you are now ready to...\"\n /you are now a\\s/i,\n ],\n};\n\nconst prompt_injection_base64: YaraRule = {\n name: 'prompt_injection_base64',\n description:\n 'Detects suspicious base64-encoded blocks in file content that may contain obfuscated prompt injection',\n severity: 'critical',\n category: 'prompt_injection',\n appliesTo: POST_READ_GREP,\n patterns: [\n // Long base64 strings (100+ chars) in comments or string literals\n // that aren't typical data URIs or legitimate base64 content\n /(?:\\/\\/|#|\\/\\*)\\s*[A-Za-z0-9+/]{100,}={0,2}/,\n ],\n};\n\n// ── §3 Secret Exfiltration ───────────────────────────────────────\n\nconst secret_exfiltration_via_command: YaraRule = {\n name: 'secret_exfiltration_via_command',\n description:\n 'Detects shell commands attempting to exfiltrate secrets or credentials',\n severity: 'critical',\n category: 'exfiltration',\n appliesTo: PRE_BASH,\n patterns: [\n // curl/wget with environment variable secrets\n /curl\\s+.*\\$\\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i,\n /wget\\s+.*\\$\\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/i,\n // Piping sensitive content to network tools\n /(\\$\\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD)|\\.env|credentials)\\S*.*\\|\\s*curl/i,\n /(\\$\\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD)|\\.env|credentials)\\S*.*\\|\\s*wget/i,\n /\\|\\s*nc\\s/,\n /\\|\\s*netcat\\s/,\n // Base64 encoding piped to network\n /base64.*\\|\\s*(curl|wget|nc\\s)/i,\n // Reading .env and sending\n /cat\\s+.*\\.env.*\\|\\s*(curl|wget)/,\n // PostHog key exfiltration specifically\n /curl.*phc_[a-zA-Z0-9]/,\n /wget.*phc_[a-zA-Z0-9]/,\n ],\n};\n\n// ── §4 Filesystem Safety ─────────────────────────────────────────\n\nconst destructive_rm: YaraRule = {\n name: 'destructive_rm',\n description: 'Detects rm -rf or rm -r commands that could mass-delete files',\n severity: 'critical',\n category: 'filesystem_safety',\n appliesTo: PRE_BASH,\n patterns: [\n // Combined flags: rm -rf, rm -fr, rm -rfi, etc.\n /\\brm\\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\\b/,\n // Separated flags: rm -r -f, rm -f -r (with optional other flags)\n /\\brm\\s+(-[a-zA-Z]*\\s+)*-[a-zA-Z]*r[a-zA-Z]*\\s+(-[a-zA-Z]*\\s+)*-[a-zA-Z]*f\\b/,\n /\\brm\\s+(-[a-zA-Z]*\\s+)*-[a-zA-Z]*f[a-zA-Z]*\\s+(-[a-zA-Z]*\\s+)*-[a-zA-Z]*r\\b/,\n ],\n};\n\nconst git_force_push: YaraRule = {\n name: 'git_force_push',\n description: 'Detects git push --force which can overwrite remote history',\n severity: 'critical',\n category: 'filesystem_safety',\n appliesTo: PRE_BASH,\n patterns: [/git\\s+push\\s+.*--force/, /git\\s+push\\s+.*-f\\b/],\n};\n\nconst git_reset_hard: YaraRule = {\n name: 'git_reset_hard',\n description:\n 'Detects git reset --hard which discards all uncommitted changes',\n severity: 'critical',\n category: 'filesystem_safety',\n appliesTo: PRE_BASH,\n patterns: [/git\\s+reset\\s+--hard/],\n};\n\n// ── §5 Supply Chain ──────────────────────────────────────────────\n\nconst wrong_posthog_package: YaraRule = {\n name: 'wrong_posthog_package',\n description:\n 'Detects installing the wrong PostHog npm package — should be posthog-js or posthog-node',\n severity: 'high',\n category: 'supply_chain',\n appliesTo: PRE_BASH,\n patterns: [\n // Match \"npm install posthog\" but not \"posthog-js\", \"posthog-node\", etc.\n /npm\\s+install\\s+(?:--save\\s+|--save-dev\\s+|-[SD]\\s+)*posthog(?!\\s*-)/,\n /pnpm\\s+(?:add|install)\\s+(?:--save\\s+|--save-dev\\s+|-[SD]\\s+)*posthog(?!\\s*-)/,\n /yarn\\s+add\\s+(?:--dev\\s+|-D\\s+)*posthog(?!\\s*-)/,\n /bun\\s+(?:add|install)\\s+(?:--dev\\s+|-[dD]\\s+)*posthog(?!\\s*-)/,\n ],\n};\n\nconst npm_install_global: YaraRule = {\n name: 'npm_install_global',\n description:\n 'Detects global npm installs — should never install packages globally',\n severity: 'high',\n category: 'supply_chain',\n appliesTo: PRE_BASH,\n patterns: [/npm\\s+install\\s+-g\\b/, /npm\\s+install\\s+--global\\b/],\n};\n\n// ─── Rule Registry ───────────────────────────────────────────────\n\nexport const RULES: YaraRule[] = [\n // §1 PostHog API violations\n pii_in_capture_call,\n hardcoded_posthog_key,\n autocapture_disabled,\n hardcoded_posthog_host,\n session_recording_disabled,\n opt_out_capturing,\n // §2 Prompt injection\n prompt_injection_wizard_override,\n prompt_injection_wizard_specific,\n prompt_injection_base64,\n // §3 Secret exfiltration\n secret_exfiltration_via_command,\n // §4 Filesystem safety\n destructive_rm,\n git_force_push,\n git_reset_hard,\n // §5 Supply chain\n wrong_posthog_package,\n npm_install_global,\n];\n\n// ─── Scan Engine ─────────────────────────────────────────────────\n\n/** Maximum content length to scan (100 KB). Inputs beyond this are truncated. */\nconst MAX_SCAN_LENGTH = 100_000;\n\n/**\n * Scan content against rules applicable to a given hook phase and tool.\n * Returns all matching rules (one match per rule, first pattern wins).\n */\nexport function scan(\n content: string,\n phase: HookPhase,\n tool: ToolTarget,\n): ScanResult {\n // Cap input length to prevent pathological regex performance\n const scanContent =\n content.length > MAX_SCAN_LENGTH\n ? content.slice(0, MAX_SCAN_LENGTH)\n : content;\n const applicableRules = RULES.filter((r) =>\n r.appliesTo.some((a) => a.phase === phase && a.tool === tool),\n );\n\n const matches: YaraMatch[] = [];\n for (const rule of applicableRules) {\n for (const pattern of rule.patterns) {\n const match = pattern.exec(scanContent);\n if (match) {\n matches.push({\n rule,\n matchedText: match[0],\n offset: match.index,\n });\n break; // One match per rule is sufficient\n }\n }\n }\n\n return matches.length > 0 ? { matched: true, matches } : { matched: false };\n}\n\n/**\n * Scan all files in a skill directory for prompt injection.\n * Used for context-mill scanning after skill installation.\n */\nexport function scanSkillDirectory(\n files: Array<{ path: string; content: string }>,\n): ScanResult {\n const allMatches: YaraMatch[] = [];\n for (const file of files) {\n const result = scan(file.content, 'PostToolUse', 'Read');\n if (result.matched) {\n allMatches.push(...result.matches);\n }\n }\n return allMatches.length > 0\n ? { matched: true, matches: allMatches }\n : { matched: false };\n}\n"]}
package/dist/src/run.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { type WizardSession } from './lib/wizard-session';
2
+ import type { CloudRegion } from './utils/types';
2
3
  import { Integration } from './lib/constants';
3
4
  type Args = {
4
5
  integration?: Integration;
5
6
  debug?: boolean;
6
7
  forceInstall?: boolean;
7
8
  installDir?: string;
9
+ region?: CloudRegion;
8
10
  default?: boolean;
9
11
  signup?: boolean;
10
12
  localMcp?: boolean;
@@ -13,6 +15,7 @@ type Args = {
13
15
  projectId?: string;
14
16
  menu?: boolean;
15
17
  benchmark?: boolean;
18
+ yaraReport?: boolean;
16
19
  };
17
20
  export declare function runWizard(argv: Args, session?: WizardSession): Promise<void>;
18
21
  export declare function detectIntegration(installDir: string): Promise<Integration | undefined>;
package/dist/src/run.js CHANGED
@@ -47,6 +47,7 @@ async function runWizard(argv, session) {
47
47
  menu: finalArgs.menu,
48
48
  integration: finalArgs.integration,
49
49
  benchmark: finalArgs.benchmark,
50
+ yaraReport: finalArgs.yaraReport,
50
51
  projectId: finalArgs.projectId,
51
52
  });
52
53
  }
@@ -75,6 +76,7 @@ async function runWizard(argv, session) {
75
76
  ci: session.ci,
76
77
  menu: session.menu,
77
78
  benchmark: session.benchmark,
79
+ yaraReport: session.yaraReport,
78
80
  });
79
81
  for (const [key, value] of Object.entries(context)) {
80
82
  if (!(key in session.frameworkContext)) {
@@ -125,8 +127,16 @@ async function detectAndResolveIntegration(session) {
125
127
  const detectedIntegration = await detectIntegration(session.installDir);
126
128
  if (detectedIntegration) {
127
129
  (0, ui_1.getUI)().setDetectedFramework(registry_1.FRAMEWORK_REGISTRY[detectedIntegration].metadata.name);
130
+ analytics_1.analytics.capture(constants_1.WIZARD_INTERACTION_EVENT_NAME, {
131
+ action: 'wizard_framework_detected',
132
+ integration: detectedIntegration,
133
+ framework_name: registry_1.FRAMEWORK_REGISTRY[detectedIntegration].metadata.name,
134
+ });
128
135
  return detectedIntegration;
129
136
  }
137
+ analytics_1.analytics.capture(constants_1.WIZARD_INTERACTION_EVENT_NAME, {
138
+ action: 'wizard_framework_detection_failed',
139
+ });
130
140
  (0, ui_1.getUI)().log.info("I couldn't detect your framework. Please choose one to get started.");
131
141
  }
132
142
  // Fallback: in TUI mode the IntroScreen would handle this,
@@ -1 +1 @@
1
- {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;;;AA8BA,8BAiGC;AAED,8CAmBC;AApJD,yDAAwE;AAExE,+CAAoE;AACpE,qDAAsD;AACtD,6BAA6B;AAC7B,gDAAwB;AACxB,6CAAoD;AACpD,iDAA8C;AAC9C,qDAAoD;AACpD,mCAAsC;AACtC,yCAA0C;AAC1C,u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AO,CAAC,IAAI,CAAC;gBAClC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC;gBACvC,IAAI,OAAO,CAAQ,CAAC,OAAO,EAAE,EAAE,CAC7B,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,gCAAoB,CAAC,CACvD;aACF,CAAC,CAAC;YACH,IAAI,QAAQ,EAAE,CAAC;gBACb,OAAO,WAAW,CAAC;YACrB,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,yCAAyC;QAC3C,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,2BAA2B,CACxC,OAAsB;IAEtB,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;QAClB,MAAM,mBAAmB,GAAG,MAAM,iBAAiB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAExE,IAAI,mBAAmB,EAAE,CAAC;YACxB,IAAA,UAAK,GAAE,CAAC,oBAAoB,CAC1B,6BAAkB,CAAC,mBAAmB,CAAC,CAAC,QAAQ,CAAC,IAAI,CACtD,CAAC;YACF,OAAO,mBAAmB,CAAC;QAC7B,CAAC;QAED,IAAA,UAAK,GAAE,CAAC,GAAG,CAAC,IAAI,CACd,qEAAqE,CACtE,CAAC;IACJ,CAAC;IAED,2DAA2D;IAC3D,gEAAgE;IAChE,OAAO,IAAA,0BAAW,EAAC;QACjB,OAAO,EACL,yFAAyF;KAC5F,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { type WizardSession, buildSession } from './lib/wizard-session';\n\nimport { Integration, DETECTION_TIMEOUT_MS } from './lib/constants';\nimport { readEnvironment } from './utils/environment';\nimport { getUI } from './ui';\nimport path from 'path';\nimport { FRAMEWORK_REGISTRY } from './lib/registry';\nimport { analytics } from './utils/analytics';\nimport { runAgentWizard } from './lib/agent-runner';\nimport { EventEmitter } from 'events';\nimport { logToFile } from './utils/debug';\nimport { wizardAbort } from './utils/wizard-abort';\n\nEventEmitter.defaultMaxListeners = 50;\n\ntype Args = {\n integration?: Integration;\n debug?: boolean;\n forceInstall?: boolean;\n installDir?: string;\n default?: boolean;\n signup?: boolean;\n localMcp?: boolean;\n ci?: boolean;\n apiKey?: string;\n projectId?: string;\n menu?: boolean;\n benchmark?: boolean;\n};\n\nexport async function runWizard(argv: Args, session?: WizardSession) {\n const finalArgs = {\n ...argv,\n ...readEnvironment(),\n };\n\n let resolvedInstallDir: string;\n if (finalArgs.installDir) {\n if (path.isAbsolute(finalArgs.installDir)) {\n resolvedInstallDir = finalArgs.installDir;\n } else {\n resolvedInstallDir = path.join(process.cwd(), finalArgs.installDir);\n }\n } else {\n resolvedInstallDir = process.cwd();\n }\n\n // Build session if not provided (CI mode passes one pre-built)\n if (!session) {\n session = buildSession({\n debug: finalArgs.debug,\n forceInstall: finalArgs.forceInstall,\n installDir: resolvedInstallDir,\n ci: finalArgs.ci,\n signup: finalArgs.signup,\n localMcp: finalArgs.localMcp,\n apiKey: finalArgs.apiKey,\n menu: finalArgs.menu,\n integration: finalArgs.integration,\n benchmark: finalArgs.benchmark,\n projectId: finalArgs.projectId,\n });\n }\n\n session.installDir = resolvedInstallDir;\n\n getUI().intro(`Welcome to the PostHog setup wizard`);\n\n if (session.ci) {\n getUI().log.info('Running in CI mode');\n }\n\n const integration =\n session.integration ?? (await detectAndResolveIntegration(session));\n\n session.integration = integration;\n analytics.setTag('integration', integration);\n\n const config = FRAMEWORK_REGISTRY[integration];\n session.frameworkConfig = config;\n\n // Run gatherContext if the framework has it and it hasn't already run\n // (bin.ts runs it early so IntroScreen can show the friendly label)\n const contextAlreadyGathered =\n Object.keys(session.frameworkContext).length > 0;\n if (config.metadata.gatherContext && !contextAlreadyGathered) {\n try {\n const context = await config.metadata.gatherContext({\n installDir: session.installDir,\n debug: session.debug,\n forceInstall: session.forceInstall,\n default: false,\n signup: session.signup,\n localMcp: session.localMcp,\n ci: session.ci,\n menu: session.menu,\n benchmark: session.benchmark,\n });\n for (const [key, value] of Object.entries(context)) {\n if (!(key in session.frameworkContext)) {\n session.frameworkContext[key] = value;\n }\n }\n } catch {\n // Detection failed — SetupScreen or agent will handle it\n }\n }\n\n try {\n await runAgentWizard(config, session);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack =\n error instanceof Error && error.stack ? error.stack : undefined;\n\n logToFile(`[Wizard run.ts] ERROR MESSAGE: ${errorMessage} `);\n if (errorStack) {\n logToFile(`[Wizard run.ts] ERROR STACK: ${errorStack}`);\n }\n\n const debugInfo = session.debug && errorStack ? `\\n\\n${errorStack}` : '';\n\n await wizardAbort({\n message: `Something went wrong: ${errorMessage}\\n\\nYou can read the documentation at ${config.metadata.docsUrl} to set up PostHog manually.${debugInfo}`,\n error: error as Error,\n });\n }\n}\n\nexport async function detectIntegration(\n installDir: string,\n): Promise<Integration | undefined> {\n for (const integration of Object.values(Integration)) {\n const config = FRAMEWORK_REGISTRY[integration];\n try {\n const detected = await Promise.race([\n config.detection.detect({ installDir }),\n new Promise<false>((resolve) =>\n setTimeout(() => resolve(false), DETECTION_TIMEOUT_MS),\n ),\n ]);\n if (detected) {\n return integration;\n }\n } catch {\n // Skip frameworks whose detection throws\n }\n }\n}\n\nasync function detectAndResolveIntegration(\n session: WizardSession,\n): Promise<Integration> {\n if (!session.menu) {\n const detectedIntegration = await detectIntegration(session.installDir);\n\n if (detectedIntegration) {\n getUI().setDetectedFramework(\n FRAMEWORK_REGISTRY[detectedIntegration].metadata.name,\n );\n return detectedIntegration;\n }\n\n getUI().log.info(\n \"I couldn't detect your framework. Please choose one to get started.\",\n );\n }\n\n // Fallback: in TUI mode the IntroScreen would handle this,\n // but for CI mode or when detection fails, abort with guidance.\n return wizardAbort({\n message:\n 'Could not auto-detect your framework. Please specify --integration on the command line.',\n });\n}\n"]}
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;;;AAsCA,8BAmGC;AAED,8CAmBC;AA9JD,yDAAwE;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AC;QACH,IAAA,UAAK,GAAE,CAAC,GAAG,CAAC,IAAI,CACd,qEAAqE,CACtE,CAAC;IACJ,CAAC;IAED,2DAA2D;IAC3D,gEAAgE;IAChE,OAAO,IAAA,0BAAW,EAAC;QACjB,OAAO,EACL,yFAAyF;KAC5F,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { type WizardSession, buildSession } from './lib/wizard-session';\n\nimport type { CloudRegion } from './utils/types';\n\nimport {\n Integration,\n DETECTION_TIMEOUT_MS,\n WIZARD_INTERACTION_EVENT_NAME,\n} from './lib/constants';\nimport { readEnvironment } from './utils/environment';\nimport { getUI } from './ui';\nimport path from 'path';\nimport { FRAMEWORK_REGISTRY } from './lib/registry';\nimport { analytics } from './utils/analytics';\nimport { runAgentWizard } from './lib/agent-runner';\nimport { EventEmitter } from 'events';\nimport { logToFile } from './utils/debug';\nimport { wizardAbort } from './utils/wizard-abort';\n\nEventEmitter.defaultMaxListeners = 50;\n\ntype Args = {\n integration?: Integration;\n debug?: boolean;\n forceInstall?: boolean;\n installDir?: string;\n region?: CloudRegion;\n default?: boolean;\n signup?: boolean;\n localMcp?: boolean;\n ci?: boolean;\n apiKey?: string;\n projectId?: string;\n menu?: boolean;\n benchmark?: boolean;\n yaraReport?: boolean;\n};\n\nexport async function runWizard(argv: Args, session?: WizardSession) {\n const finalArgs = {\n ...argv,\n ...readEnvironment(),\n };\n\n let resolvedInstallDir: string;\n if (finalArgs.installDir) {\n if (path.isAbsolute(finalArgs.installDir)) {\n resolvedInstallDir = finalArgs.installDir;\n } else {\n resolvedInstallDir = path.join(process.cwd(), finalArgs.installDir);\n }\n } else {\n resolvedInstallDir = process.cwd();\n }\n\n // Build session if not provided (CI mode passes one pre-built)\n if (!session) {\n session = buildSession({\n debug: finalArgs.debug,\n forceInstall: finalArgs.forceInstall,\n installDir: resolvedInstallDir,\n ci: finalArgs.ci,\n signup: finalArgs.signup,\n localMcp: finalArgs.localMcp,\n apiKey: finalArgs.apiKey,\n menu: finalArgs.menu,\n integration: finalArgs.integration,\n benchmark: finalArgs.benchmark,\n yaraReport: finalArgs.yaraReport,\n projectId: finalArgs.projectId,\n });\n }\n\n session.installDir = resolvedInstallDir;\n\n getUI().intro(`Welcome to the PostHog setup wizard`);\n\n if (session.ci) {\n getUI().log.info('Running in CI mode');\n }\n\n const integration =\n session.integration ?? (await detectAndResolveIntegration(session));\n\n session.integration = integration;\n analytics.setTag('integration', integration);\n\n const config = FRAMEWORK_REGISTRY[integration];\n session.frameworkConfig = config;\n\n // Run gatherContext if the framework has it and it hasn't already run\n // (bin.ts runs it early so IntroScreen can show the friendly label)\n const contextAlreadyGathered =\n Object.keys(session.frameworkContext).length > 0;\n if (config.metadata.gatherContext && !contextAlreadyGathered) {\n try {\n const context = await config.metadata.gatherContext({\n installDir: session.installDir,\n debug: session.debug,\n forceInstall: session.forceInstall,\n default: false,\n signup: session.signup,\n localMcp: session.localMcp,\n ci: session.ci,\n menu: session.menu,\n benchmark: session.benchmark,\n yaraReport: session.yaraReport,\n });\n for (const [key, value] of Object.entries(context)) {\n if (!(key in session.frameworkContext)) {\n session.frameworkContext[key] = value;\n }\n }\n } catch {\n // Detection failed — SetupScreen or agent will handle it\n }\n }\n\n try {\n await runAgentWizard(config, session);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack =\n error instanceof Error && error.stack ? error.stack : undefined;\n\n logToFile(`[Wizard run.ts] ERROR MESSAGE: ${errorMessage} `);\n if (errorStack) {\n logToFile(`[Wizard run.ts] ERROR STACK: ${errorStack}`);\n }\n\n const debugInfo = session.debug && errorStack ? `\\n\\n${errorStack}` : '';\n\n await wizardAbort({\n message: `Something went wrong: ${errorMessage}\\n\\nYou can read the documentation at ${config.metadata.docsUrl} to set up PostHog manually.${debugInfo}`,\n error: error as Error,\n });\n }\n}\n\nexport async function detectIntegration(\n installDir: string,\n): Promise<Integration | undefined> {\n for (const integration of Object.values(Integration)) {\n const config = FRAMEWORK_REGISTRY[integration];\n try {\n const detected = await Promise.race([\n config.detection.detect({ installDir }),\n new Promise<false>((resolve) =>\n setTimeout(() => resolve(false), DETECTION_TIMEOUT_MS),\n ),\n ]);\n if (detected) {\n return integration;\n }\n } catch {\n // Skip frameworks whose detection throws\n }\n }\n}\n\nasync function detectAndResolveIntegration(\n session: WizardSession,\n): Promise<Integration> {\n if (!session.menu) {\n const detectedIntegration = await detectIntegration(session.installDir);\n\n if (detectedIntegration) {\n getUI().setDetectedFramework(\n FRAMEWORK_REGISTRY[detectedIntegration].metadata.name,\n );\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'wizard_framework_detected',\n integration: detectedIntegration,\n framework_name: FRAMEWORK_REGISTRY[detectedIntegration].metadata.name,\n });\n return detectedIntegration;\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'wizard_framework_detection_failed',\n });\n getUI().log.info(\n \"I couldn't detect your framework. Please choose one to get started.\",\n );\n }\n\n // Fallback: in TUI mode the IntroScreen would handle this,\n // but for CI mode or when detection fails, abort with guidance.\n return wizardAbort({\n message:\n 'Could not auto-detect your framework. Please specify --integration on the command line.',\n });\n}\n"]}
@@ -5,10 +5,11 @@ export declare const getSupportedClients: () => Promise<MCPClient[]>;
5
5
  * Add MCP server to clients. No prompts — pure orchestration.
6
6
  * Prompts are handled by McpScreen (TUI) or auto-accepted (CI).
7
7
  */
8
- export declare const addMCPServerToClientsStep: ({ integration, local, ci, }: {
8
+ export declare const addMCPServerToClientsStep: ({ integration, local, ci, cloudRegion: _cloudRegion, }: {
9
9
  integration?: Integration;
10
10
  local?: boolean;
11
11
  ci?: boolean;
12
+ cloudRegion?: import("../../utils/types").CloudRegion;
12
13
  }) => Promise<string[]>;
13
14
  export declare const removeMCPServerFromClientsStep: ({ integration, local, }: {
14
15
  integration?: Integration;
@@ -40,7 +40,7 @@ exports.getSupportedClients = getSupportedClients;
40
40
  * Add MCP server to clients. No prompts — pure orchestration.
41
41
  * Prompts are handled by McpScreen (TUI) or auto-accepted (CI).
42
42
  */
43
- const addMCPServerToClientsStep = async ({ integration, local = false, ci = false, }) => {
43
+ const addMCPServerToClientsStep = async ({ integration, local = false, ci = false, cloudRegion: _cloudRegion, }) => {
44
44
  const ui = (0, ui_1.getUI)();
45
45
  // CI mode: skip MCP installation entirely
46
46
  if (ci) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/steps/add-mcp-server-to-clients/index.ts"],"names":[],"mappings":";;;AACA,+CAA4C;AAC5C,qDAAkD;AAClD,iCAAiC;AAEjC,6CAAmD;AACnD,6CAAmD;AACnD,uDAA4D;AAC5D,qEAAsE;AACtE,uCAA0C;AAC1C,2CAAiD;AACjD,yCAAgD;AAChD,6CAA0C;AAEnC,MAAM,mBAAmB,GAAG,KAAK,IAA0B,EAAE;IAClE,MAAM,UAAU,GAAG;QACjB,IAAI,wBAAe,EAAE;QACrB,IAAI,wBAAe,EAAE;QACrB,IAAI,iCAAmB,EAAE;QACzB,IAAI,2CAAsB,EAAE;QAC5B,IAAI,eAAS,EAAE;QACf,IAAI,sBAAc,EAAE;KACrB,CAAC;IACF,MAAM,gBAAgB,GAAgB,EAAE,CAAC;IAEzC,IAAA,aAAK,EAAC,uCAAuC,CAAC,CAAC;IAC/C,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,WAAW,GAAG,MAAM,MAAM,CAAC,iBAAiB,EAAE,CAAC;QACrD,IAAA,aAAK,EAAC,GAAG,MAAM,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,iBAAiB,EAAE,CAAC,CAAC;QAC5E,IAAI,WAAW,EAAE,CAAC;YAChB,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IACD,IAAA,aAAK,EACH,SAAS,gBAAgB,CAAC,MAAM,yBAAyB,gBAAgB;SACtE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE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AE,CAAC;YAC1C,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,gBAAgB,CAAC;AAC1B,CAAC,CAAC;AAbW,QAAA,mBAAmB,uBAa9B;AAEK,MAAM,YAAY,GAAG,KAAK,EAC/B,OAAoB,EACpB,cAAuB,EACvB,gBAA2B,EAC3B,KAAe,EACA,EAAE;IACjB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,MAAM,CAAC,SAAS,CAAC,cAAc,EAAE,gBAAgB,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;AACH,CAAC,CAAC;AATW,QAAA,YAAY,gBASvB;AAEK,MAAM,eAAe,GAAG,KAAK,EAClC,OAAoB,EACpB,KAAe,EACA,EAAE;IACjB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;AACH,CAAC,CAAC;AAPW,QAAA,eAAe,mBAO1B","sourcesContent":["import type { Integration } from '../../lib/constants';\nimport { traceStep } from '../../telemetry';\nimport { analytics } from '../../utils/analytics';\nimport { getUI } from '../../ui';\nimport { MCPClient } from './MCPClient';\nimport { CursorMCPClient } from './clients/cursor';\nimport { ClaudeMCPClient } from './clients/claude';\nimport { ClaudeCodeMCPClient } from './clients/claude-code';\nimport { VisualStudioCodeClient } from './clients/visual-studio-code';\nimport { ZedClient } from './clients/zed';\nimport { CodexMCPClient } from './clients/codex';\nimport { ALL_FEATURE_VALUES } from './defaults';\nimport { debug } from '../../utils/debug';\n\nexport const getSupportedClients = async (): Promise<MCPClient[]> => {\n const allClients = [\n new CursorMCPClient(),\n new ClaudeMCPClient(),\n new ClaudeCodeMCPClient(),\n new VisualStudioCodeClient(),\n new ZedClient(),\n new CodexMCPClient(),\n ];\n const supportedClients: MCPClient[] = [];\n\n debug('Checking for supported MCP clients...');\n for (const client of allClients) {\n const isSupported = await client.isClientSupported();\n debug(`${client.name}: ${isSupported ? '✓ supported' : '✗ not supported'}`);\n if (isSupported) {\n supportedClients.push(client);\n }\n }\n debug(\n `Found ${supportedClients.length} supported client(s): ${supportedClients\n .map((c) => c.name)\n .join(', ')}`,\n );\n\n return supportedClients;\n};\n\n/**\n * Add MCP server to clients. No prompts — pure orchestration.\n * Prompts are handled by McpScreen (TUI) or auto-accepted (CI).\n */\nexport const addMCPServerToClientsStep = async ({\n integration,\n local = false,\n ci = false,\n}: {\n integration?: Integration;\n local?: boolean;\n ci?: boolean;\n}): Promise<string[]> => {\n const ui = getUI();\n\n // CI mode: skip MCP installation entirely\n if (ci) {\n ui.log.info('Skipping MCP installation (CI mode)');\n return [];\n }\n\n const supportedClients = await getSupportedClients();\n\n if (supportedClients.length === 0) {\n ui.log.info(\n 'No supported MCP clients detected. Skipping MCP installation.',\n );\n return [];\n }\n\n // Auto-install to all supported clients\n await traceStep('adding mcp servers', async () => {\n await addMCPServer(\n supportedClients,\n undefined,\n [...ALL_FEATURE_VALUES],\n local,\n );\n });\n\n ui.log.success(\n `Added the MCP server to:\n ${supportedClients.map((c) => `- ${c.name}`).join('\\n ')} `,\n );\n\n analytics.wizardCapture('mcp servers added', {\n clients: supportedClients.map((c) => c.name),\n integration,\n });\n\n return supportedClients.map((c) => c.name);\n};\n\nexport const removeMCPServerFromClientsStep = async ({\n integration,\n local = false,\n}: {\n integration?: Integration;\n local?: boolean;\n}): Promise<string[]> => {\n const installedClients = await getInstalledClients(local);\n if (installedClients.length === 0) {\n analytics.wizardCapture('mcp no servers to remove', {\n integration,\n });\n return [];\n }\n\n // Auto-remove from all installed clients\n const results = await traceStep('removing mcp servers', async () => {\n await removeMCPServer(installedClients, local);\n return installedClients.map((c) => c.name);\n });\n\n analytics.wizardCapture('mcp servers removed', {\n clients: results,\n integration,\n });\n\n return results;\n};\n\nexport const getInstalledClients = async (\n local?: boolean,\n): Promise<MCPClient[]> => {\n const clients = await getSupportedClients();\n const installedClients: MCPClient[] = [];\n\n for (const client of clients) {\n if (await client.isServerInstalled(local)) {\n installedClients.push(client);\n }\n }\n\n return installedClients;\n};\n\nexport const addMCPServer = async (\n clients: MCPClient[],\n personalApiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n): Promise<void> => {\n for (const client of clients) {\n await client.addServer(personalApiKey, selectedFeatures, local);\n }\n};\n\nexport const removeMCPServer = async (\n clients: MCPClient[],\n local?: boolean,\n): Promise<void> => {\n for (const client of clients) {\n await client.removeServer(local);\n }\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/steps/add-mcp-server-to-clients/index.ts"],"names":[],"mappings":";;;AACA,+CAA4C;AAC5C,qDAAkD;AAClD,iCAAiC;AAEjC,6CAAmD;AACnD,6CAAmD;AACnD,uDAA4D;AAC5D,qEAAsE;AACtE,uCAA0C;AAC1C,2CAAiD;AACjD,yCAAgD;AAChD,6CAA0C;AAEnC,MAAM,mBAAmB,GAAG,KAAK,IAA0B,EAAE;IAClE,MAAM,UAAU,GAAG;QACjB,IAAI,wBAAe,EAAE;QACrB,IAAI,wBAAe,EAAE;QACrB,IAAI,iCAAmB,EAAE;QACzB,IAAI,2CAAsB,EAAE;QAC5B,IAAI,eAAS,EAAE;QACf,IAAI,sBAAc,EAAE;KACrB,CAAC;IACF,MAAM,gBAAgB,GAAgB,EAAE,CAAC;IAEzC,IAAA,aAAK,EAAC,uCAAuC,CAAC,CAAC;IAC/C,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,WAAW,GAAG,MAAM,MAAM,CAAC,iBAAiB,EAAE,CAAC;QACrD,IAAA,aAAK,EAAC,GAAG,MAAM,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,iBAAiB,EAAE,CAAC,CAAC;QAC5E,IAAI,WAAW,EAAE,CAAC;YAChB,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAChC,CA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,MAAM,gBAAgB,GAAgB,EAAE,CAAC;IAEzC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,MAAM,MAAM,CAAC,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,gBAAgB,CAAC;AAC1B,CAAC,CAAC;AAbW,QAAA,mBAAmB,uBAa9B;AAEK,MAAM,YAAY,GAAG,KAAK,EAC/B,OAAoB,EACpB,cAAuB,EACvB,gBAA2B,EAC3B,KAAe,EACA,EAAE;IACjB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,MAAM,CAAC,SAAS,CAAC,cAAc,EAAE,gBAAgB,EAAE,KAAK,CAAC,CAAC;IAClE,CAAC;AACH,CAAC,CAAC;AATW,QAAA,YAAY,gBASvB;AAEK,MAAM,eAAe,GAAG,KAAK,EAClC,OAAoB,EACpB,KAAe,EACA,EAAE;IACjB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;AACH,CAAC,CAAC;AAPW,QAAA,eAAe,mBAO1B","sourcesContent":["import type { Integration } from '../../lib/constants';\nimport { traceStep } from '../../telemetry';\nimport { analytics } from '../../utils/analytics';\nimport { getUI } from '../../ui';\nimport { MCPClient } from './MCPClient';\nimport { CursorMCPClient } from './clients/cursor';\nimport { ClaudeMCPClient } from './clients/claude';\nimport { ClaudeCodeMCPClient } from './clients/claude-code';\nimport { VisualStudioCodeClient } from './clients/visual-studio-code';\nimport { ZedClient } from './clients/zed';\nimport { CodexMCPClient } from './clients/codex';\nimport { ALL_FEATURE_VALUES } from './defaults';\nimport { debug } from '../../utils/debug';\n\nexport const getSupportedClients = async (): Promise<MCPClient[]> => {\n const allClients = [\n new CursorMCPClient(),\n new ClaudeMCPClient(),\n new ClaudeCodeMCPClient(),\n new VisualStudioCodeClient(),\n new ZedClient(),\n new CodexMCPClient(),\n ];\n const supportedClients: MCPClient[] = [];\n\n debug('Checking for supported MCP clients...');\n for (const client of allClients) {\n const isSupported = await client.isClientSupported();\n debug(`${client.name}: ${isSupported ? '✓ supported' : '✗ not supported'}`);\n if (isSupported) {\n supportedClients.push(client);\n }\n }\n debug(\n `Found ${supportedClients.length} supported client(s): ${supportedClients\n .map((c) => c.name)\n .join(', ')}`,\n );\n\n return supportedClients;\n};\n\n/**\n * Add MCP server to clients. No prompts — pure orchestration.\n * Prompts are handled by McpScreen (TUI) or auto-accepted (CI).\n */\nexport const addMCPServerToClientsStep = async ({\n integration,\n local = false,\n ci = false,\n cloudRegion: _cloudRegion,\n}: {\n integration?: Integration;\n local?: boolean;\n ci?: boolean;\n cloudRegion?: import('../../utils/types').CloudRegion;\n}): Promise<string[]> => {\n const ui = getUI();\n\n // CI mode: skip MCP installation entirely\n if (ci) {\n ui.log.info('Skipping MCP installation (CI mode)');\n return [];\n }\n\n const supportedClients = await getSupportedClients();\n\n if (supportedClients.length === 0) {\n ui.log.info(\n 'No supported MCP clients detected. Skipping MCP installation.',\n );\n return [];\n }\n\n // Auto-install to all supported clients\n await traceStep('adding mcp servers', async () => {\n await addMCPServer(\n supportedClients,\n undefined,\n [...ALL_FEATURE_VALUES],\n local,\n );\n });\n\n ui.log.success(\n `Added the MCP server to:\n ${supportedClients.map((c) => `- ${c.name}`).join('\\n ')} `,\n );\n\n analytics.wizardCapture('mcp servers added', {\n clients: supportedClients.map((c) => c.name),\n integration,\n });\n\n return supportedClients.map((c) => c.name);\n};\n\nexport const removeMCPServerFromClientsStep = async ({\n integration,\n local = false,\n}: {\n integration?: Integration;\n local?: boolean;\n}): Promise<string[]> => {\n const installedClients = await getInstalledClients(local);\n if (installedClients.length === 0) {\n analytics.wizardCapture('mcp no servers to remove', {\n integration,\n });\n return [];\n }\n\n // Auto-remove from all installed clients\n const results = await traceStep('removing mcp servers', async () => {\n await removeMCPServer(installedClients, local);\n return installedClients.map((c) => c.name);\n });\n\n analytics.wizardCapture('mcp servers removed', {\n clients: results,\n integration,\n });\n\n return results;\n};\n\nexport const getInstalledClients = async (\n local?: boolean,\n): Promise<MCPClient[]> => {\n const clients = await getSupportedClients();\n const installedClients: MCPClient[] = [];\n\n for (const client of clients) {\n if (await client.isServerInstalled(local)) {\n installedClients.push(client);\n }\n }\n\n return installedClients;\n};\n\nexport const addMCPServer = async (\n clients: MCPClient[],\n personalApiKey?: string,\n selectedFeatures?: string[],\n local?: boolean,\n): Promise<void> => {\n for (const client of clients) {\n await client.addServer(personalApiKey, selectedFeatures, local);\n }\n};\n\nexport const removeMCPServer = async (\n clients: MCPClient[],\n local?: boolean,\n): Promise<void> => {\n for (const client of clients) {\n await client.removeServer(local);\n }\n};\n"]}
@@ -1,5 +1,17 @@
1
1
  Never hallucinate an API key. Instead, always use the API key populated in the .env file.
2
2
 
3
+ Never write API keys, access tokens, or other secrets directly into source code. Always reference environment variables instead, and rely on the wizard-tools MCP server (check_env_keys / set_env_values) to create or update .env files.
4
+
5
+ Always use the detect_package_manager tool from the wizard-tools MCP server to determine the package manager. Do not guess based on lockfiles or hard-code npm, yarn, pnpm, bun, pip, etc.
6
+
7
+ When installing packages, start the installation as a background task and then continue with other work. Do not block waiting for installs to finish unless explicitly instructed.
8
+
9
+ Before writing to any file, you MUST read that exact file immediately beforehand using the Read tool, even if you have already read it earlier in the run. This avoids tool failures and stale edits.
10
+
11
+ Prefer minimal, targeted edits that achieve the requested behavior while preserving existing structure and style. Avoid large refactors, broad reformatting, or unrelated changes unless explicitly requested.
12
+
13
+ Do not spawn subagents unless explicitly instructed to do so.
14
+
3
15
  # Feature flags
4
16
 
5
17
  A given feature flag should be used in as few places as possible. Do not increase the risk of undefined behavior by scattering the same feature flag across multiple areas of code. If the same feature flag needs to be introduced at multiple callsites, flag this for the developer to inspect carefully.
@@ -56,6 +56,15 @@ export type WizardOptions = {
56
56
  * and writes detailed usage data to /tmp/posthog-wizard-benchmark.json.
57
57
  */
58
58
  benchmark: boolean;
59
+ /**
60
+ * Cloud region for the PostHog instance (US or EU).
61
+ * When not provided, the user will be prompted to select one.
62
+ */
63
+ cloudRegion?: CloudRegion;
64
+ /**
65
+ * Whether to print a YARA scanner summary after the agent run.
66
+ */
67
+ yaraReport: boolean;
59
68
  };
60
69
  export interface Feature {
61
70
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/utils/types.ts"],"names":[],"mappings":"","sourcesContent":["export type PostHogProjectData = Record<string, unknown>;\n\nexport type PreselectedProject = {\n project: PostHogProjectData;\n authToken: string;\n};\n\nexport type WizardOptions = {\n /**\n * Whether to enable debug mode.\n */\n debug: boolean;\n\n /**\n * Whether to force install the SDK package to continue with the installation in case\n * any package manager checks are failing (e.g. peer dependency versions).\n *\n * Use with caution and only if you know what you're doing.\n *\n * Does not apply to all wizard flows (currently NPM only)\n */\n forceInstall: boolean;\n\n /**\n * The directory to run the wizard in.\n */\n installDir: string;\n\n /**\n * Whether to select the default option for all questions automatically.\n */\n default: boolean;\n\n /**\n * Whether to create a new PostHog account during setup.\n */\n signup: boolean;\n\n /**\n * Whether to use the local MCP server at http://localhost:8787/mcp\n */\n localMcp: boolean;\n\n /**\n * CI mode - non-interactive execution\n */\n ci: boolean;\n\n /**\n * Personal API key (phx_xxx) - used for LLM gateway auth, skips OAuth\n */\n apiKey?: string;\n\n /**\n * PostHog project ID. When set (e.g. in CI with --project-id), the wizard uses this project\n * instead of the default from the API key or OAuth.\n */\n projectId?: number;\n\n /**\n * Whether to show the menu for manual integration selection instead of auto-detecting.\n */\n menu: boolean;\n\n /**\n * Whether to run in benchmark mode with per-phase token tracking.\n * When enabled, the wizard runs each workflow phase as a separate agent call\n * and writes detailed usage data to /tmp/posthog-wizard-benchmark.json.\n */\n benchmark: boolean;\n};\n\nexport interface Feature {\n id: string;\n prompt: string;\n enabledHint?: string;\n disabledHint?: string;\n}\n\nexport type FileChange = {\n filePath: string;\n oldContent?: string;\n newContent: string;\n};\n\nexport type CloudRegion = 'us' | 'eu';\n\nexport type AIModel =\n | 'gpt-5-mini'\n | 'o4-mini'\n | 'gemini-2.5-flash'\n | 'gemini-2.5-pro';\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/utils/types.ts"],"names":[],"mappings":"","sourcesContent":["export type PostHogProjectData = Record<string, unknown>;\n\nexport type PreselectedProject = {\n project: PostHogProjectData;\n authToken: string;\n};\n\nexport type WizardOptions = {\n /**\n * Whether to enable debug mode.\n */\n debug: boolean;\n\n /**\n * Whether to force install the SDK package to continue with the installation in case\n * any package manager checks are failing (e.g. peer dependency versions).\n *\n * Use with caution and only if you know what you're doing.\n *\n * Does not apply to all wizard flows (currently NPM only)\n */\n forceInstall: boolean;\n\n /**\n * The directory to run the wizard in.\n */\n installDir: string;\n\n /**\n * Whether to select the default option for all questions automatically.\n */\n default: boolean;\n\n /**\n * Whether to create a new PostHog account during setup.\n */\n signup: boolean;\n\n /**\n * Whether to use the local MCP server at http://localhost:8787/mcp\n */\n localMcp: boolean;\n\n /**\n * CI mode - non-interactive execution\n */\n ci: boolean;\n\n /**\n * Personal API key (phx_xxx) - used for LLM gateway auth, skips OAuth\n */\n apiKey?: string;\n\n /**\n * PostHog project ID. When set (e.g. in CI with --project-id), the wizard uses this project\n * instead of the default from the API key or OAuth.\n */\n projectId?: number;\n\n /**\n * Whether to show the menu for manual integration selection instead of auto-detecting.\n */\n menu: boolean;\n\n /**\n * Whether to run in benchmark mode with per-phase token tracking.\n * When enabled, the wizard runs each workflow phase as a separate agent call\n * and writes detailed usage data to /tmp/posthog-wizard-benchmark.json.\n */\n benchmark: boolean;\n\n /**\n * Cloud region for the PostHog instance (US or EU).\n * When not provided, the user will be prompted to select one.\n */\n cloudRegion?: CloudRegion;\n\n /**\n * Whether to print a YARA scanner summary after the agent run.\n */\n yaraReport: boolean;\n};\n\nexport interface Feature {\n id: string;\n prompt: string;\n enabledHint?: string;\n disabledHint?: string;\n}\n\nexport type FileChange = {\n filePath: string;\n oldContent?: string;\n newContent: string;\n};\n\nexport type CloudRegion = 'us' | 'eu';\n\nexport type AIModel =\n | 'gpt-5-mini'\n | 'o4-mini'\n | 'gemini-2.5-flash'\n | 'gemini-2.5-pro';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/wizard",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
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",