@posthog/wizard 2.79.0 → 2.79.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/PickerMenu-dG5DQCZA.js +758 -0
  2. package/dist/PickerMenu-dG5DQCZA.js.map +1 -0
  3. package/dist/{add-mcp-server-to-clients-amlJWW7W.js → add-mcp-server-to-clients-DIaTRWMY.js} +7 -18
  4. package/dist/{add-mcp-server-to-clients-amlJWW7W.js.map → add-mcp-server-to-clients-DIaTRWMY.js.map} +1 -1
  5. package/dist/add-mcp-server-to-clients-artmN7mz.js +2 -0
  6. package/dist/agent-BEjARD2a.js +6 -0
  7. package/dist/{agent-CNrEC-9v.js → agent-BWFhuLgo.js} +18 -24
  8. package/dist/{agent-CNrEC-9v.js.map → agent-BWFhuLgo.js.map} +1 -1
  9. package/dist/{agent-interface-BXvmAm4c.js → agent-interface-FkbaBJwz.js} +29 -17
  10. package/dist/agent-interface-FkbaBJwz.js.map +1 -0
  11. package/dist/{agent-prompt-loader-DiKUbhi_.js → agent-prompt-loader-D0weQ-7k.js} +5 -5
  12. package/dist/{agent-prompt-loader-DiKUbhi_.js.map → agent-prompt-loader-D0weQ-7k.js.map} +1 -1
  13. package/dist/analytics-DFtbRjYh.js +2 -0
  14. package/dist/{analytics-VRYdebXW.js → analytics-DXK1gc12.js} +4 -4
  15. package/dist/{analytics-VRYdebXW.js.map → analytics-DXK1gc12.js.map} +1 -1
  16. package/dist/api-Cm9UtKZh.js +2 -0
  17. package/dist/{api-DGuJTzjr.js → api-CrbCIQOz.js} +4 -16
  18. package/dist/{api-DGuJTzjr.js.map → api-CrbCIQOz.js.map} +1 -1
  19. package/dist/bin.js +5 -2960
  20. package/dist/bin.js.map +1 -1
  21. package/dist/{bounded-fs-Cpn129A4.js → bounded-fs-vAq-T-K7.js} +3 -3
  22. package/dist/{bounded-fs-Cpn129A4.js.map → bounded-fs-vAq-T-K7.js.map} +1 -1
  23. package/dist/{ci-install-BPA6gzEq.js → ci-install-COcV8SY2.js} +8 -7
  24. package/dist/{ci-install-BPA6gzEq.js.map → ci-install-COcV8SY2.js.map} +1 -1
  25. package/dist/{constants-CuJfQEcC.js → constants-DHCBSfnx.js} +3 -3
  26. package/dist/{constants-CuJfQEcC.js.map → constants-DHCBSfnx.js.map} +1 -1
  27. package/dist/{debug-B9k4ideV.js → debug-BuYHGr6_.js} +1 -1
  28. package/dist/{debug-Cj-8vfXY.js → debug-kAHwWGg7.js} +2 -2
  29. package/dist/{debug-Cj-8vfXY.js.map → debug-kAHwWGg7.js.map} +1 -1
  30. package/dist/{defaults-C6J7yL4O.js → defaults-a9TelDhJ.js} +1 -1
  31. package/dist/{defaults-C6J7yL4O.js.map → defaults-a9TelDhJ.js.map} +1 -1
  32. package/dist/emit-BSetXzDV.js +69 -0
  33. package/dist/emit-BSetXzDV.js.map +1 -0
  34. package/dist/{endpoints-DnIX0pZH.js → endpoints-BVMYm9F4.js} +3 -3
  35. package/dist/{endpoints-DnIX0pZH.js.map → endpoints-BVMYm9F4.js.map} +1 -1
  36. package/dist/{env-api-key-BWdKpGEr.js → env-api-key-BP-NFFXt.js} +3 -5
  37. package/dist/{env-api-key-BWdKpGEr.js.map → env-api-key-BP-NFFXt.js.map} +1 -1
  38. package/dist/env-api-key-CaWEDj_9.js +2 -0
  39. package/dist/{environment-DZYUSCpV.js → environment-BATlQxcQ.js} +5 -10
  40. package/dist/{environment-DZYUSCpV.js.map → environment-BATlQxcQ.js.map} +1 -1
  41. package/dist/environment-CwD8OPYj.js +2 -0
  42. package/dist/{errors-ddDE6MbA.js → errors-C2domSkK.js} +3 -67
  43. package/dist/errors-C2domSkK.js.map +1 -0
  44. package/dist/file-C5JMsyR1.js +2 -0
  45. package/dist/{file-dEhr-l3n.js → file-DcRKycV8.js} +3 -3
  46. package/dist/{file-dEhr-l3n.js.map → file-DcRKycV8.js.map} +1 -1
  47. package/dist/{file-watcher-CPM-Nn9L.js → file-watcher-Brq2nnHV.js} +2 -2
  48. package/dist/{file-watcher-CPM-Nn9L.js.map → file-watcher-Brq2nnHV.js.map} +1 -1
  49. package/dist/{gateway-CVU1G0H3.js → gateway-C9-GlLO9.js} +8 -7
  50. package/dist/{gateway-CVU1G0H3.js.map → gateway-C9-GlLO9.js.map} +1 -1
  51. package/dist/{headless-ui-pY2xB5ug.js → headless-ui-CqI2gXlD.js} +2 -2
  52. package/dist/{headless-ui-pY2xB5ug.js.map → headless-ui-CqI2gXlD.js.map} +1 -1
  53. package/dist/{interactive-BOGlinZe.js → interactive-B_Ti_CsS.js} +3 -3
  54. package/dist/{interactive-BOGlinZe.js.map → interactive-B_Ti_CsS.js.map} +1 -1
  55. package/dist/{logging-ui-CUxNYF2t.js → logging-ui-Dza4D0MK.js} +5 -5
  56. package/dist/{logging-ui-CUxNYF2t.js.map → logging-ui-Dza4D0MK.js.map} +1 -1
  57. package/dist/main-CgKxbwMP.js +1396 -0
  58. package/dist/main-CgKxbwMP.js.map +1 -0
  59. package/dist/{mcp-JcsBBnWv.js → mcp-DnAyW0-w.js} +4 -4
  60. package/dist/{mcp-JcsBBnWv.js.map → mcp-DnAyW0-w.js.map} +1 -1
  61. package/dist/{mcp-prompt-streaming-B-p_Pvb2.js → mcp-prompt-streaming-DDWQ-FCA.js} +6 -6
  62. package/dist/{mcp-prompt-streaming-B-p_Pvb2.js.map → mcp-prompt-streaming-DDWQ-FCA.js.map} +1 -1
  63. package/dist/{mint-failure-CZFZpHpW.js → mint-failure-u8xQKNOn.js} +23 -22
  64. package/dist/{mint-failure-CZFZpHpW.js.map → mint-failure-u8xQKNOn.js.map} +1 -1
  65. package/dist/{models-DnAY67Lg.js → models-WcwUnSKb.js} +2 -2
  66. package/dist/{models-DnAY67Lg.js.map → models-WcwUnSKb.js.map} +1 -1
  67. package/dist/{non-interactive-DR1CWXY1.js → non-interactive-DyVC1AGc.js} +4 -3
  68. package/dist/{non-interactive-DR1CWXY1.js.map → non-interactive-DyVC1AGc.js.map} +1 -1
  69. package/dist/{oauth-session-CQTFOk-I.js → oauth-session-DYM2Hrl2.js} +2 -2
  70. package/dist/{oauth-session-CQTFOk-I.js.map → oauth-session-DYM2Hrl2.js.map} +1 -1
  71. package/dist/{orchestrator-tools-CBdt-SXO.js → orchestrator-tools-DbgNBFGA.js} +3 -3
  72. package/dist/{orchestrator-tools-CBdt-SXO.js.map → orchestrator-tools-DbgNBFGA.js.map} +1 -1
  73. package/dist/{package-json-DY70kkNp.js → package-json-Atg34fa4.js} +2 -8
  74. package/dist/{package-json-DY70kkNp.js.map → package-json-Atg34fa4.js.map} +1 -1
  75. package/dist/package-json-D8Ga03tK.js +2 -0
  76. package/dist/{pi-BtqcLX3y.js → pi-8KsYsPmM.js} +17 -16
  77. package/dist/{pi-BtqcLX3y.js.map → pi-8KsYsPmM.js.map} +1 -1
  78. package/dist/{playground-Dz-ZVjBk.js → playground-BlYRBMj7.js} +11 -11
  79. package/dist/{playground-Dz-ZVjBk.js.map → playground-BlYRBMj7.js.map} +1 -1
  80. package/dist/{posthog-6Uqw_Eux.js → posthog-Bt0Aplb8.js} +3 -8
  81. package/dist/{posthog-6Uqw_Eux.js.map → posthog-Bt0Aplb8.js.map} +1 -1
  82. package/dist/posthog-CUgCEhH0.js +2 -0
  83. package/dist/{provisioning-Zf7yPcEs.js → provisioning-Bo2NRxFz.js} +5 -11
  84. package/dist/{provisioning-Zf7yPcEs.js.map → provisioning-Bo2NRxFz.js.map} +1 -1
  85. package/dist/provisioning-OGFGlzf7.js +2 -0
  86. package/dist/{queue-tools-B7_aCyd-.js → queue-tools-C8mXOh7e.js} +3 -3
  87. package/dist/{queue-tools-B7_aCyd-.js.map → queue-tools-C8mXOh7e.js.map} +1 -1
  88. package/dist/registry-C06e_x-p.js +2 -0
  89. package/dist/{registry-B6iLGorH.js → registry-CD5RQt38.js} +7 -9
  90. package/dist/{registry-B6iLGorH.js.map → registry-CD5RQt38.js.map} +1 -1
  91. package/dist/run-agent-legacy-ChacZImU.js +2 -0
  92. package/dist/{run-agent-legacy-6WcYMaR9.js → run-agent-legacy-DOlM6DQu.js} +20 -21
  93. package/dist/{run-agent-legacy-6WcYMaR9.js.map → run-agent-legacy-DOlM6DQu.js.map} +1 -1
  94. package/dist/runners-ov3EXF1n.js +834 -0
  95. package/dist/runners-ov3EXF1n.js.map +1 -0
  96. package/dist/{security-lkBwWbrK.js → security-C71pkwqH.js} +5 -5
  97. package/dist/{security-lkBwWbrK.js.map → security-C71pkwqH.js.map} +1 -1
  98. package/dist/{setup-utils-dCViCC6s.js → setup-utils-B26Lf2yF.js} +11 -21
  99. package/dist/{setup-utils-dCViCC6s.js.map → setup-utils-B26Lf2yF.js.map} +1 -1
  100. package/dist/setup-utils-CVS86NYR.js +2 -0
  101. package/dist/{start-tui-oCWMgsDP.js → start-tui-Bo2L0bar.js} +28 -26
  102. package/dist/{start-tui-oCWMgsDP.js.map → start-tui-Bo2L0bar.js.map} +1 -1
  103. package/dist/{steps-gx0Pq4I4.js → steps-BPcg3_3Q.js} +7 -7
  104. package/dist/{steps-gx0Pq4I4.js.map → steps-BPcg3_3Q.js.map} +1 -1
  105. package/dist/{store-xYy_6Ruv.js → store-BTzcvRGT.js} +11 -17
  106. package/dist/{store-xYy_6Ruv.js.map → store-BTzcvRGT.js.map} +1 -1
  107. package/dist/store-BpqySPXm.js +5 -0
  108. package/dist/{subagent-Bfy0sfhU.js → subagent-D1TrTchE.js} +3 -3
  109. package/dist/{subagent-Bfy0sfhU.js.map → subagent-D1TrTchE.js.map} +1 -1
  110. package/dist/{task-BOfw7GPc.js → task-DqRlQBfs.js} +18 -16
  111. package/dist/task-DqRlQBfs.js.map +1 -0
  112. package/dist/{task-stream-kYlm9qd0.js → task-stream-Bw6JaLCX.js} +8 -8
  113. package/dist/{task-stream-kYlm9qd0.js.map → task-stream-Bw6JaLCX.js.map} +1 -1
  114. package/dist/{tasks-Bbv_lOBG.js → tasks-ChWufsdO.js} +1 -1
  115. package/dist/{tasks-Bbv_lOBG.js.map → tasks-ChWufsdO.js.map} +1 -1
  116. package/dist/{telemetry-Bpv-Mh5B.js → telemetry-B7zJdRmA.js} +3 -3
  117. package/dist/{telemetry-Bpv-Mh5B.js.map → telemetry-B7zJdRmA.js.map} +1 -1
  118. package/dist/{terminal-D07EQ2y0.js → terminal-zgkEfoCL.js} +15 -15
  119. package/dist/{terminal-D07EQ2y0.js.map → terminal-zgkEfoCL.js.map} +1 -1
  120. package/dist/{tools-Cc41af5W.js → tools-CkJ2y9Wt.js} +9 -9
  121. package/dist/tools-CkJ2y9Wt.js.map +1 -0
  122. package/dist/{ui-CGXtC7Vn.js → ui-Q6-RvERF.js} +3 -3
  123. package/dist/{ui-CGXtC7Vn.js.map → ui-Q6-RvERF.js.map} +1 -1
  124. package/dist/{version-Cadof0Z_.js → version-CHhJjz_H.js} +2 -2
  125. package/dist/{version-Cadof0Z_.js.map → version-CHhJjz_H.js.map} +1 -1
  126. package/dist/{wizard-abort-HDbP3YcS.js → wizard-abort-BPdv07np.js} +7 -6
  127. package/dist/{wizard-abort-HDbP3YcS.js.map → wizard-abort-BPdv07np.js.map} +1 -1
  128. package/dist/wizard-abort-Br1qMDNa.js +3 -0
  129. package/dist/{wizard-ui-DoyOZxK8.js → wizard-ui-DVqrYaOM.js} +1 -1
  130. package/dist/{wizard-ui-DoyOZxK8.js.map → wizard-ui-DVqrYaOM.js.map} +1 -1
  131. package/dist/{yara-hooks-DCfROpZt.js → yara-hooks-BnxejtXK.js} +5 -5
  132. package/dist/{yara-hooks-DCfROpZt.js.map → yara-hooks-BnxejtXK.js.map} +1 -1
  133. package/dist/yara-hooks-DSuExwb4.js +2 -0
  134. package/package.json +1 -1
  135. package/dist/agent-interface-BXvmAm4c.js.map +0 -1
  136. package/dist/analytics-DxwRi2Hf.js +0 -2
  137. package/dist/errors-ddDE6MbA.js.map +0 -1
  138. package/dist/rolldown-runtime-B_-DWIq7.js +0 -15
  139. package/dist/task-BOfw7GPc.js.map +0 -1
  140. package/dist/tools-Cc41af5W.js.map +0 -1
  141. package/dist/wizard-abort-Y-Ip2K4z.js +0 -3
  142. package/dist/yara-hooks-B49RIk5d.js +0 -2
package/dist/bin.js CHANGED
@@ -1,2954 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { o as emitWizardError, s as ErrorCodes, t as classifyRunFailure } from "./errors-ddDE6MbA.js";
3
- import { a as getLogFilePath, b as isHeadless, s as logToFile, v as runtimeEnv, x as regionOption, y as headlessOption } from "./debug-Cj-8vfXY.js";
4
- import { t as VERSION } from "./version-Cadof0Z_.js";
5
- import { a as getLocalDev, i as checkLocalServices, o as initLocalDev, r as POSTHOG_LOCAL_URL, s as localMcpSkillsNotice } from "./local-dev-McsurOC-.js";
6
- import { $ as getSkillsBaseUrl, k as POSTHOG_DOCS_URL } from "./constants-CuJfQEcC.js";
7
- import "./wizard-session-2w4Ru-Wz.js";
8
- import { n as analytics } from "./analytics-VRYdebXW.js";
9
- import { r as setEntryCommand } from "./telemetry-Bpv-Mh5B.js";
10
- import { t as LoggingUI } from "./logging-ui-CUxNYF2t.js";
11
- import { n as setUI, t as getUI } from "./ui-CGXtC7Vn.js";
12
- import { n as registerShutdown, r as runCleanups } from "./wizard-abort-HDbP3YcS.js";
13
- import { n as isNonInteractiveEnvironment } from "./environment-DZYUSCpV.js";
14
- import { r as currentCredentials } from "./oauth-session-CQTFOk-I.js";
15
- import { I as WIZARD_TOOL_NAMES, et as fetchSkillMenu, m as isGrantRevoked, u as recoverOrphanedSettingsBackups } from "./agent-interface-BXvmAm4c.js";
16
- import "./agent-CNrEC-9v.js";
17
- import { h as AUDIT_CHECKS_FILE } from "./yara-hooks-DCfROpZt.js";
18
- import { d as getAuditChecks, f as authenticate, t as runProgramAgent } from "./run-agent-legacy-6WcYMaR9.js";
19
- import { $ as wordWrap, A as installOrUpdatePostHogCli, B as webAnalyticsDoctorConfig, D as CLI_STEERING_TARGETS, E as errorTrackingUploadSourceMapsConfig, G as createSkillProgram, H as getKindMeta, K as warehouseSourceConfig, O as detectTargets, S as errorTrackingConfig, T as replayVisionConfig, U as fetchHealthIssues, V as posthogDoctorConfig, W as auditConfig, at as maybeStampAiSdkDetected, d as metricsConfig, f as aiObservabilityConfig, i as isRunFailure, it as Icons, j as installSteeringSnippet, k as findTarget, m as selfDrivingConfig, o as Program, p as mcpAnalyticsConfig, q as revenueAnalyticsConfig, rt as Colors, s as agentSkillConfig, u as getProgramConfig, z as migrationConfig } from "./mint-failure-CZFZpHpW.js";
20
- import { n as parseRetryAfter } from "./posthog-6Uqw_Eux.js";
21
- import { n as readApiKeyFromEnv } from "./env-api-key-BWdKpGEr.js";
22
- import { satisfies, valid } from "semver";
23
- import { Agent, setGlobalDispatcher } from "undici";
24
- import yargs from "yargs";
25
- import { hideBin } from "yargs/helpers";
26
- import { validate } from "uuid";
27
- import * as path$1 from "node:path";
28
- import { basename, join, resolve } from "node:path";
29
- import { randomUUID } from "node:crypto";
30
- import { Box, Text, render, useInput, useStdout } from "ink";
31
- import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
32
- import { jsx, jsxs } from "react/jsx-runtime";
33
- import Fuse from "fuse.js";
34
- import * as readline from "node:readline/promises";
35
- //#region src/commands/command.ts
36
- /** Extract the bare command word(s) from a yargs name spec, dropping positionals and aliases' arg syntax. */
37
- function commandKeys(name) {
38
- return (typeof name === "string" ? [name] : name).map((n) => n.trim().split(/\s+/)[0]);
39
- }
40
- function toCommandModule(cmd, parentPath) {
41
- const entryCommand = [...parentPath, commandKeys(cmd.name)[0]].filter((key) => key !== "$0").join("-");
42
- return {
43
- command: cmd.name,
44
- describe: cmd.description,
45
- builder: (y) => {
46
- let next = cmd.options ? y.options(cmd.options) : y;
47
- for (const [key, opts] of Object.entries(cmd.positionals ?? {})) next = next.positional(key, opts);
48
- if (cmd.check) next = next.check(cmd.check);
49
- for (const [usage, description] of cmd.examples ?? []) next = next.example(usage, description);
50
- const ownPath = [...parentPath, commandKeys(cmd.name)[0]];
51
- for (const child of cmd.children ?? []) next = next.command(toCommandModule(child, ownPath));
52
- if (cmd.children?.length && !cmd.handler && !cmd.interactiveDefault) next = next.demandCommand(1);
53
- return next;
54
- },
55
- handler: (argv) => {
56
- if (entryCommand) setEntryCommand(entryCommand);
57
- (cmd.handler ?? cmd.interactiveDefault ?? (() => void 0))(argv);
58
- }
59
- };
60
- }
61
- //#endregion
62
- //#region src/wizard.ts
63
- /**
64
- * Global yargs options applied to every command. These are read from the
65
- * `POSTHOG_WIZARD` env prefix as well as flags.
66
- *
67
- * Options with `hidden: true` are "internal modes" — they don't show up in
68
- * `--help` but are still accepted on every command. The `--local-*` flags live
69
- * in the constructor's `!IS_PRODUCTION_BUILD` block instead, so published
70
- * builds reject them; see `docs/local-dev.md`.
71
- */
72
- const GLOBAL_OPTIONS = {
73
- debug: {
74
- default: false,
75
- describe: "Enable verbose logging\nenv: POSTHOG_WIZARD_DEBUG",
76
- type: "boolean"
77
- },
78
- signup: {
79
- default: false,
80
- describe: "Create a new PostHog account during setup\nenv: POSTHOG_WIZARD_SIGNUP",
81
- type: "boolean"
82
- },
83
- telemetry: {
84
- default: true,
85
- describe: "Send wizard run state to PostHog (pass --no-telemetry to disable)\nenv: POSTHOG_WIZARD_TELEMETRY",
86
- type: "boolean"
87
- },
88
- "api-key": {
89
- describe: "PostHog personal API key (phx_xxx) for authentication\nenv: POSTHOG_WIZARD_API_KEY",
90
- type: "string"
91
- },
92
- "project-id": {
93
- describe: "PostHog project ID to use (optional; when not set, uses default from API key or OAuth)\nenv: POSTHOG_WIZARD_PROJECT_ID",
94
- type: "string"
95
- },
96
- email: {
97
- describe: "Email address for signup (used with --signup)\nenv: POSTHOG_WIZARD_EMAIL",
98
- type: "string"
99
- },
100
- "base-url": {
101
- describe: "Override the PostHog base URL (e.g. http://localhost:8010), bypassing region resolution. Pins the API host, cloud URL, and OAuth server.\nenv: POSTHOG_WIZARD_BASE_URL",
102
- type: "string",
103
- hidden: true
104
- },
105
- "run-id": {
106
- describe: "Assigned cloud WizardRun UUID",
107
- type: "string",
108
- hidden: true
109
- },
110
- benchmark: {
111
- default: false,
112
- describe: "Run in benchmark mode with per-phase token tracking\nenv: POSTHOG_WIZARD_BENCHMARK",
113
- type: "boolean",
114
- hidden: true
115
- },
116
- "yara-report": {
117
- default: false,
118
- describe: "Print YARA scanner summary after the agent run\nenv: POSTHOG_WIZARD_YARA_REPORT",
119
- type: "boolean",
120
- hidden: true
121
- }
122
- };
123
- var Wizard = class Wizard {
124
- cli;
125
- constructor() {
126
- let cli = yargs(hideBin(process.argv)).env("POSTHOG_WIZARD").options(GLOBAL_OPTIONS);
127
- this.cli = cli.middleware((argv) => {
128
- initLocalDev(argv);
129
- const notice = localMcpSkillsNotice({
130
- localDev: argv.localDev,
131
- localMcp: argv.localMcp,
132
- localContextMill: argv.localContextMill
133
- });
134
- if (notice) process.stderr.write(`\n\x1b[33m! ${notice}\x1b[0m\n\n`);
135
- }).strictOptions().strictCommands().fail((msg, err) => {
136
- const text = msg || err && err.message || "Invalid arguments";
137
- process.stderr.write(`\n\x1b[1;91m✖ ${text}\x1b[0m\n Run \`wizard --help\` to see available commands and options.\n\n`);
138
- emitWizardError({
139
- code: ErrorCodes.CliBadArgs,
140
- message: text
141
- });
142
- process.exit(1);
143
- }).help().alias("help", "h").version().alias("version", "v");
144
- }
145
- /** Start a chain; equivalent to `new Wizard().use(...cmds)`. */
146
- static use(...cmds) {
147
- return new Wizard().use(...cmds);
148
- }
149
- /** Register one or more commands with yargs. */
150
- use(...cmds) {
151
- for (const cmd of cmds) this.cli = this.cli.command(toCommandModule(cmd, []));
152
- return this;
153
- }
154
- /** Parse argv and dispatch to the matching registered command. */
155
- init() {
156
- {
157
- const args = process.argv.slice(2);
158
- const argvHasCI = args.some((a) => a === "--ci" || a === "--no-ci" || a.startsWith("--ci="));
159
- const envHasCI = process.env.POSTHOG_WIZARD_CI != null && process.env.POSTHOG_WIZARD_CI !== "";
160
- if (argvHasCI || envHasCI) {
161
- process.stderr.write(`\n\x1b[1;91m✖ CI mode is not currently supported in published builds.\x1b[0m\n\n`);
162
- emitWizardError({
163
- code: ErrorCodes.CliFlagUnavailable,
164
- message: "CI mode is not supported in published builds."
165
- });
166
- process.exit(1);
167
- }
168
- const argvHasOverride = args.some((a) => a === "--harness" || a.startsWith("--harness=") || a === "--sequence" || a.startsWith("--sequence=") || a === "--model" || a.startsWith("--model=") || a === "--capture-aio" || a === "--no-capture-aio" || a.startsWith("--capture-aio="));
169
- const envHasOverride = process.env.POSTHOG_WIZARD_HARNESS != null && process.env.POSTHOG_WIZARD_HARNESS !== "" || process.env.POSTHOG_WIZARD_SEQUENCE != null && process.env.POSTHOG_WIZARD_SEQUENCE !== "" || process.env.POSTHOG_WIZARD_MODEL != null && process.env.POSTHOG_WIZARD_MODEL !== "" || process.env.POSTHOG_WIZARD_CAPTURE_AIO != null && process.env.POSTHOG_WIZARD_CAPTURE_AIO !== "";
170
- if (argvHasOverride || envHasOverride) {
171
- process.stderr.write(`\n\x1b[1;91m✖ The --harness, --sequence, --model, and --capture-aio overrides are not available in published builds.\x1b[0m\n\n`);
172
- emitWizardError({
173
- code: ErrorCodes.CliFlagUnavailable,
174
- message: "The --harness, --sequence, --model, and --capture-aio overrides are not available in published builds."
175
- });
176
- process.exit(1);
177
- }
178
- const argvHasLocalTarget = args.some((a) => LOCAL_TARGET_FLAGS.some((f) => a === `--${f}` || a === `--no-${f}` || a.startsWith(`--${f}=`)));
179
- const envHasLocalTarget = LOCAL_TARGET_ENV_VARS.some((k) => process.env[k] != null && process.env[k] !== "");
180
- if (argvHasLocalTarget || envHasLocalTarget) {
181
- process.stderr.write("\n\x1B[1;91m✖ The --local-dev, --local-context-mill, --local-mcp, and --local-posthog targets are not available in published builds.\x1B[0m\n They point the wizard at development servers on localhost.\n\n");
182
- emitWizardError({
183
- code: ErrorCodes.CliFlagUnavailable,
184
- message: "The --local-dev, --local-context-mill, --local-mcp, and --local-posthog targets are not available in published builds."
185
- });
186
- process.exit(1);
187
- }
188
- }
189
- this.cli.wrap(process.stdout.isTTY ? this.cli.terminalWidth() : 80).argv;
190
- }
191
- };
192
- /** Excludes bare `local`: `wizard mcp add --local` stays available in prod. */
193
- const LOCAL_TARGET_FLAGS = [
194
- "local-dev",
195
- "local-context-mill",
196
- "local-mcp",
197
- "local-posthog"
198
- ];
199
- const LOCAL_TARGET_ENV_VARS = [
200
- "POSTHOG_WIZARD_LOCAL_DEV",
201
- "POSTHOG_WIZARD_LOCAL_CONTEXT_MILL",
202
- "POSTHOG_WIZARD_LOCAL_MCP",
203
- "POSTHOG_WIZARD_LOCAL_POSTHOG"
204
- ];
205
- //#endregion
206
- //#region src/commands/provision.ts
207
- const provisionCommand = {
208
- name: "provision",
209
- description: "Create a new PostHog account (headless, no TUI)",
210
- options: {
211
- email: {
212
- describe: "Email address for the new account",
213
- type: "string",
214
- demandOption: true
215
- },
216
- region: {
217
- describe: "Cloud region (us or eu)",
218
- choices: ["us", "eu"],
219
- default: "us"
220
- },
221
- name: {
222
- describe: "Name for the new account",
223
- type: "string",
224
- default: ""
225
- },
226
- json: {
227
- describe: "Emit JSON result to stdout (defaults to true when stdout is not a TTY)",
228
- type: "boolean"
229
- }
230
- },
231
- examples: [["wizard provision --email matt+test@posthog.com --region us", ""], ["wizard provision --email user@example.com --region eu --json", ""]],
232
- handler: runProvision
233
- };
234
- function runProvision(argv) {
235
- const jsonMode = argv.json === void 0 ? !process.stdout.isTTY : Boolean(argv.json);
236
- if (!jsonMode) setUI(new LoggingUI());
237
- provision({
238
- email: argv.email,
239
- region: argv.region.toUpperCase(),
240
- name: argv.name ?? "",
241
- baseUrl: argv.baseUrl,
242
- jsonMode
243
- });
244
- }
245
- async function provision({ email, region, name, baseUrl, jsonMode }) {
246
- try {
247
- const { provisionNewAccount } = await import("./provisioning-Zf7yPcEs.js").then((n) => n.r);
248
- if (!jsonMode) getUI().log.info(`Provisioning account for ${email} in ${region}...`);
249
- emitResult(await provisionNewAccount(email, name, region, { baseUrl }), jsonMode);
250
- process.exit(0);
251
- } catch (error) {
252
- emitError(error, jsonMode);
253
- process.exit(1);
254
- }
255
- }
256
- function emitResult(result, jsonMode) {
257
- if (jsonMode) {
258
- process.stdout.write(`${JSON.stringify(result)}\n`);
259
- return;
260
- }
261
- getUI().log.success("Account provisioned successfully:");
262
- getUI().log.info(` API Key: ${result.projectApiKey}`);
263
- getUI().log.info(` Host: ${result.host}`);
264
- getUI().log.info(` Project ID: ${result.projectId}`);
265
- getUI().log.info(` Account ID: ${result.accountId}`);
266
- getUI().log.info(` Access Token: ${result.accessToken}`);
267
- getUI().log.info(` Refresh Token: ${result.refreshToken}`);
268
- if (result.personalApiKey) getUI().log.info(` Personal API Key: ${result.personalApiKey}`);
269
- }
270
- function emitError(error, jsonMode) {
271
- const msg = error instanceof Error ? error.message : String(error);
272
- const code = msg.includes("already associated") ? "email_exists" : "provisioning_failed";
273
- if (jsonMode) {
274
- process.stderr.write(`${JSON.stringify({
275
- error: msg,
276
- code
277
- })}\n`);
278
- return;
279
- }
280
- getUI().log.error(`Provisioning failed: ${msg}`);
281
- }
282
- //#endregion
283
- //#region src/commands/basic-integration/index.ts
284
- const basicIntegrationCommand = {
285
- name: ["$0"],
286
- description: "Run the PostHog setup wizard",
287
- children: [provisionCommand],
288
- options: {
289
- "install-dir": {
290
- describe: "Directory to install PostHog in\nenv: POSTHOG_WIZARD_INSTALL_DIR",
291
- type: "string"
292
- },
293
- name: {
294
- describe: "Name for account creation with --ci --signup\nenv: POSTHOG_WIZARD_NAME",
295
- type: "string"
296
- },
297
- playground: {
298
- default: false,
299
- describe: "Launch the TUI primitives playground",
300
- type: "boolean",
301
- hidden: true
302
- },
303
- ...headlessOption,
304
- ...regionOption
305
- },
306
- check: (argv) => {
307
- if (argv.playground && (argv.ci || isHeadless(argv))) throw new Error("--playground cannot be combined with a headless run.");
308
- return true;
309
- },
310
- handler: (argv) => {
311
- setEntryCommand("integrate");
312
- (async () => {
313
- if (isHeadless(argv)) {
314
- const { runHeadlessInstall } = await import("./ci-install-BPA6gzEq.js");
315
- return runHeadlessInstall(argv);
316
- }
317
- if (argv.ci) {
318
- const { runCIInstall } = await import("./ci-install-BPA6gzEq.js");
319
- return runCIInstall(argv);
320
- }
321
- if (isNonInteractiveEnvironment()) {
322
- const { failNonInteractive } = await import("./non-interactive-DR1CWXY1.js");
323
- return failNonInteractive();
324
- }
325
- if (argv.playground) {
326
- const { runPlayground } = await import("./playground-Dz-ZVjBk.js");
327
- return runPlayground();
328
- }
329
- const { runInteractive } = await import("./interactive-BOGlinZe.js");
330
- runInteractive(argv);
331
- })();
332
- }
333
- };
334
- //#endregion
335
- //#region src/commands/mcp/tui-availability.ts
336
- /**
337
- * Ink throws "Raw mode is not supported" when stdin has no TTY (piped input,
338
- * CI, some IDE terminals). That is the only TUI failure the mcp commands
339
- * degrade to LoggingUI for — any other error from the TUI path is a real bug
340
- * and must surface rather than be silently swallowed.
341
- */
342
- function isTUIUnavailable(error) {
343
- return error instanceof Error && /raw mode is not supported/i.test(error.message);
344
- }
345
- //#endregion
346
- //#region src/commands/mcp/add.ts
347
- const mcpAddCommand = {
348
- name: "add",
349
- description: "Install PostHog MCP server to supported clients",
350
- options: {
351
- local: {
352
- default: false,
353
- describe: "Add local development MCP server (http://localhost:8787)",
354
- type: "boolean"
355
- },
356
- features: {
357
- describe: "Comma-separated list of features to enable (default: all)",
358
- type: "string"
359
- },
360
- "api-key": {
361
- describe: "PostHog personal API key (phx_xxx) for MCP authentication",
362
- type: "string"
363
- },
364
- ...headlessOption
365
- },
366
- handler: runMcpAdd
367
- };
368
- function runMcpAdd(argv) {
369
- const features = parseFeatures(argv.features);
370
- (async () => {
371
- const { readApiKeyFromEnv } = await import("./env-api-key-BWdKpGEr.js").then((n) => n.t);
372
- const apiKey = argv.apiKey || readApiKeyFromEnv();
373
- const debug = argv.debug;
374
- const localMcp = argv.local;
375
- const args = {
376
- local: localMcp,
377
- features,
378
- apiKey
379
- };
380
- if (isHeadless(argv)) {
381
- await runHeadlessAdd(args);
382
- return;
383
- }
384
- try {
385
- const { startTUI } = await import("./start-tui-oCWMgsDP.js");
386
- const { buildSession } = await import("./wizard-session-DGaUHOF3.js");
387
- const tui = startTUI(VERSION, Program.McpAdd);
388
- tui.store.session = buildSession({
389
- debug,
390
- localMcp,
391
- mcpFeatures: features,
392
- apiKey,
393
- baseUrl: argv.baseUrl
394
- });
395
- } catch (error) {
396
- if (!isTUIUnavailable(error)) throw error;
397
- await runHeadlessAdd(args);
398
- }
399
- })();
400
- }
401
- async function runHeadlessAdd(args) {
402
- setUI(new LoggingUI());
403
- const { addMCPServerToClientsStep } = await import("./add-mcp-server-to-clients-amlJWW7W.js").then((n) => n.r);
404
- const { installed, failed } = await addMCPServerToClientsStep(args);
405
- if (failed.length > 0 || installed.length === 0) process.exitCode = 1;
406
- }
407
- function parseFeatures(raw) {
408
- if (typeof raw !== "string") return void 0;
409
- return raw.split(",").map((s) => s.trim()).filter(Boolean);
410
- }
411
- //#endregion
412
- //#region src/commands/mcp/remove.ts
413
- const mcpRemoveCommand = {
414
- name: "remove",
415
- description: "Remove PostHog MCP server from supported clients",
416
- options: {
417
- local: {
418
- default: false,
419
- describe: "Remove local development MCP server (http://localhost:8787)",
420
- type: "boolean"
421
- },
422
- ...headlessOption
423
- },
424
- handler: runMcpRemove
425
- };
426
- function runMcpRemove(argv) {
427
- (async () => {
428
- const debug = argv.debug;
429
- const localMcp = argv.local;
430
- if (isHeadless(argv)) {
431
- await runHeadlessRemove(localMcp);
432
- return;
433
- }
434
- try {
435
- const { startTUI } = await import("./start-tui-oCWMgsDP.js");
436
- const { buildSession } = await import("./wizard-session-DGaUHOF3.js");
437
- const tui = startTUI(VERSION, Program.McpRemove);
438
- tui.store.session = buildSession({
439
- debug,
440
- localMcp,
441
- baseUrl: argv.baseUrl
442
- });
443
- } catch (error) {
444
- if (!isTUIUnavailable(error)) throw error;
445
- await runHeadlessRemove(localMcp);
446
- }
447
- })();
448
- }
449
- /** No exit code on an empty result: nothing to remove is the requested end state. */
450
- async function runHeadlessRemove(local) {
451
- setUI(new LoggingUI());
452
- const { removeMCPServerFromClientsStep } = await import("./add-mcp-server-to-clients-amlJWW7W.js").then((n) => n.r);
453
- await removeMCPServerFromClientsStep({ local });
454
- }
455
- //#endregion
456
- //#region src/commands/mcp/tutorial.ts
457
- const mcpTutorialCommand = {
458
- name: "tutorial",
459
- description: "Try the PostHog MCP with your agent (no install needed)",
460
- options: { local: {
461
- default: false,
462
- describe: "Point the tutorial at the local MCP server (http://localhost:8787)",
463
- type: "boolean"
464
- } },
465
- handler: runMcpTutorial
466
- };
467
- function runMcpTutorial(argv) {
468
- (async () => {
469
- const debug = argv.debug;
470
- const localMcp = argv.local;
471
- try {
472
- const { startTUI } = await import("./start-tui-oCWMgsDP.js");
473
- const { buildSession } = await import("./wizard-session-DGaUHOF3.js");
474
- const tui = startTUI(VERSION, Program.McpTutorial);
475
- tui.store.session = buildSession({
476
- debug,
477
- localMcp,
478
- baseUrl: argv.baseUrl
479
- });
480
- } catch (err) {
481
- setUI(new LoggingUI());
482
- getUI().log.error(`The MCP tutorial requires an interactive terminal. ${err instanceof Error ? err.message : String(err)}`);
483
- emitWizardError({
484
- code: ErrorCodes.CliInteractiveRequired,
485
- message: "The MCP tutorial requires an interactive terminal."
486
- });
487
- process.exit(1);
488
- }
489
- })();
490
- }
491
- //#endregion
492
- //#region src/commands/mcp/index.ts
493
- const mcpCommand = {
494
- name: "mcp",
495
- description: "MCP server management commands",
496
- children: [
497
- mcpAddCommand,
498
- mcpRemoveCommand,
499
- mcpTutorialCommand
500
- ]
501
- };
502
- //#endregion
503
- //#region src/lib/runners/resolve-no-telemetry.ts
504
- /**
505
- * `--no-telemetry` flips `telemetry: false` via yargs negation;
506
- * `POSTHOG_WIZARD_NO_TELEMETRY` is honoured separately so the env-var
507
- * form documented in the README keeps working.
508
- */
509
- function resolveNoTelemetry(options) {
510
- if (options.telemetry === false) return true;
511
- const env = process.env.POSTHOG_WIZARD_NO_TELEMETRY;
512
- if (env == null || env === "") return false;
513
- const norm = env.toLowerCase();
514
- return norm !== "0" && norm !== "false";
515
- }
516
- //#endregion
517
- //#region src/programs/task-stream/wizard-run-sync.ts
518
- const STATUS = {
519
- pending: "created",
520
- in_progress: "running",
521
- completed: "completed",
522
- failed: "failed",
523
- skipped: "completed"
524
- };
525
- var RunTaskNames = class {
526
- names = /* @__PURE__ */ new Map();
527
- used = /* @__PURE__ */ new Set();
528
- snapshot(items) {
529
- if (items.length > 100) throw new Error("task limit exceeded (100)");
530
- const occurrences = /* @__PURE__ */ new Map();
531
- const ids = /* @__PURE__ */ new Set();
532
- return items.map((item) => {
533
- const subject = item.label.trim();
534
- if (!subject) throw new Error("blank task name");
535
- const rawStatus = item.sourceStatus ?? item.status;
536
- const status = STATUS[rawStatus];
537
- if (!Object.hasOwn(STATUS, rawStatus)) throw new Error("invalid task status");
538
- const occurrence = (occurrences.get(subject) ?? 0) + 1;
539
- occurrences.set(subject, occurrence);
540
- const id = item.id ? JSON.stringify([item.source, item.id]) : JSON.stringify([subject, occurrence]);
541
- if (ids.has(id)) throw new Error("duplicate task identity");
542
- ids.add(id);
543
- let name = this.names.get(id);
544
- if (!name) {
545
- name = subject.slice(0, 255);
546
- for (let n = 2; this.used.has(name); n++) {
547
- const suffix = ` (${n})`;
548
- name = subject.slice(0, 255 - suffix.length) + suffix;
549
- }
550
- this.names.set(id, name);
551
- this.used.add(name);
552
- }
553
- return {
554
- name,
555
- status
556
- };
557
- });
558
- }
559
- };
560
- function createWizardRunSync(options) {
561
- if (options.noTelemetry || options.mode === "ci") return;
562
- if (options.mode === "headless" && options.assignedId === void 0) return;
563
- return new WizardRunSync({
564
- ...options,
565
- mode: options.assignedId !== void 0 ? "cloud" : "local"
566
- });
567
- }
568
- var WizardRunSync = class {
569
- names = new RunTaskNames();
570
- tasksAbort = new AbortController();
571
- reported = /* @__PURE__ */ new Set();
572
- context;
573
- queue = Promise.resolve();
574
- lastBody;
575
- stopped = false;
576
- tasksDisabled = false;
577
- authDisabled = false;
578
- closing;
579
- constructor(options) {
580
- this.options = options;
581
- }
582
- capture(items) {
583
- if (this.stopped || this.tasksDisabled || !items) return;
584
- if (this.options.mode === "cloud" && !validate(this.options.assignedId ?? "")) {
585
- this.tasksDisabled = true;
586
- this.report("invalid cloud run assignment");
587
- return;
588
- }
589
- const session = this.options.getSession();
590
- if (session.runPhase === "idle") return;
591
- if (!this.context) {
592
- if (session.runPhase !== "running" || !session.credentials) return;
593
- const { host, projectId } = session.credentials;
594
- this.context = {
595
- apiHost: host.appHost.replace(/\/$/, ""),
596
- projectId,
597
- programId: this.options.programId,
598
- mode: this.options.mode,
599
- id: this.options.assignedId
600
- };
601
- this.queue = this.initialize(session);
602
- }
603
- try {
604
- const body = JSON.stringify({ tasks: this.names.snapshot(items) });
605
- if (body === this.lastBody) return;
606
- this.lastBody = body;
607
- this.queue = this.queue.then(async () => {
608
- if (this.tasksDisabled || this.tasksAbort.signal.aborted || !this.context?.id) return;
609
- if (!await this.request("PUT", `${this.context.id}/tasks/`, body, this.tasksAbort.signal)) this.tasksDisabled = true;
610
- });
611
- } catch {
612
- this.report("invalid task snapshot (names, statuses, identities or 100-task limit)");
613
- }
614
- }
615
- shutdown(outcome, timeoutMs) {
616
- if (this.closing) return this.closing;
617
- this.stopped = true;
618
- this.closing = this.finish(outcome, Math.max(0, timeoutMs));
619
- return this.closing;
620
- }
621
- async initialize(session) {
622
- const context = this.context;
623
- if (!context || context.mode === "cloud") return;
624
- const projectName = basename(resolve(session.installDir)).trim().slice(0, 255);
625
- if (!projectName) {
626
- this.tasksDisabled = true;
627
- this.report("unsupported program or workspace configuration");
628
- return;
629
- }
630
- const body = JSON.stringify({
631
- program_id: context.programId,
632
- environment: "local",
633
- workspace: {
634
- type: "local_folder",
635
- project_name: projectName
636
- },
637
- ...valid("2.79.0") ? { wizard_version: VERSION } : {},
638
- idempotency_key: randomUUID()
639
- });
640
- const result = await this.request("POST", "", body, this.tasksAbort.signal);
641
- if (result && typeof result === "object" && "id" in result && typeof result.id === "string" && validate(result.id)) context.id = result.id;
642
- else {
643
- this.tasksDisabled = true;
644
- this.report("local creation failed or returned an invalid ID; creation was not retried");
645
- }
646
- }
647
- credentials(creds = this.options.getSession().credentials) {
648
- const context = this.context;
649
- if (!context) return;
650
- if (!creds || creds.host.appHost.replace(/\/$/, "") !== context.apiHost || creds.projectId !== context.projectId) {
651
- this.report("execution credentials changed host or project");
652
- return;
653
- }
654
- if (creds.missingScopes?.includes("wizard_run:write") || !creds.accessToken.startsWith("pha_")) {
655
- this.authDisabled = true;
656
- this.report("wizard_run:write OAuth grant required; authorize again");
657
- return;
658
- }
659
- return creds;
660
- }
661
- async request(method, suffix, body, signal) {
662
- const context = this.context;
663
- if (!context || this.authDisabled || signal.aborted) return;
664
- let refreshed = false;
665
- let rateLimited = false;
666
- const attempts = method === "POST" ? 1 : 3;
667
- for (let attempt = 0; attempt < attempts && !signal.aborted; attempt++) {
668
- let retryMs = 500 * 2 ** attempt;
669
- try {
670
- const creds = this.credentials();
671
- if (!creds) return;
672
- const { res, data, current } = await this.bounded(async (requestSignal) => {
673
- const current = this.credentials(await currentCredentials(creds));
674
- if (!current) throw new Error("credentials unavailable");
675
- const res = await (this.options.fetchImpl ?? fetch)(`${context.apiHost}/api/projects/${context.projectId}/wizard/runs/${suffix}`, {
676
- method,
677
- body,
678
- signal: requestSignal,
679
- headers: {
680
- Authorization: `Bearer ${current.accessToken}`,
681
- "Content-Type": "application/json"
682
- }
683
- });
684
- return {
685
- res,
686
- data: method === "POST" && (res.status === 200 || res.status === 201) ? await res.json() : void 0,
687
- current
688
- };
689
- }, signal, 5e3);
690
- if (method === "POST" && [200, 201].includes(res.status) || method === "PUT" && res.status === 204 || method === "PATCH" && res.status === 200) return data ?? true;
691
- if (res.status === 401 && current.refreshToken && !isGrantRevoked() && !refreshed && method !== "POST") {
692
- refreshed = true;
693
- if ((await this.bounded(() => currentCredentials(current, true), signal, 5e3)).accessToken === current.accessToken) {
694
- this.authDisabled = true;
695
- this.report("OAuth refresh could not recover the grant; authorize again");
696
- return;
697
- }
698
- continue;
699
- }
700
- if (res.status === 401 || res.status === 403) this.authDisabled = true;
701
- if (res.status === 429 && !rateLimited) {
702
- rateLimited = true;
703
- retryMs = parseRetryAfter(res.headers.get("Retry-After"));
704
- } else if (res.status < 500 || res.status >= 600) {
705
- this.report(`${method} rejected (${res.status}); check assignment, grant and program configuration`);
706
- return;
707
- }
708
- } catch {
709
- if (signal.aborted) return;
710
- }
711
- if (attempt + 1 < attempts) try {
712
- await this.sleep(retryMs, signal);
713
- } catch {
714
- return;
715
- }
716
- }
717
- this.report(`${method} delivery exhausted`);
718
- }
719
- async finish(outcome, timeoutMs) {
720
- const deadline = Date.now() + timeoutMs;
721
- try {
722
- await this.bounded(() => this.queue, new AbortController().signal, Math.floor(timeoutMs * .75));
723
- } catch {
724
- this.report("task drain timed out");
725
- }
726
- this.tasksAbort.abort();
727
- if (this.context?.mode !== "local" || !this.context.id || this.authDisabled) return;
728
- if (Date.now() >= deadline) {
729
- this.report("terminal update budget exhausted");
730
- return;
731
- }
732
- const finalAbort = new AbortController();
733
- const timer = setTimeout(() => finalAbort.abort(), Math.max(0, deadline - Date.now()));
734
- try {
735
- await this.request("PATCH", `${this.context.id}/`, JSON.stringify({ status: outcome }), finalAbort.signal);
736
- } finally {
737
- clearTimeout(timer);
738
- finalAbort.abort();
739
- }
740
- }
741
- async bounded(operation, parent, ms) {
742
- const controller = new AbortController();
743
- const abort = () => controller.abort();
744
- parent.addEventListener("abort", abort, { once: true });
745
- if (parent.aborted) controller.abort();
746
- const timer = setTimeout(abort, ms);
747
- let onAbort = () => void 0;
748
- const cancelled = new Promise((_, reject) => {
749
- onAbort = () => reject(/* @__PURE__ */ new Error("request cancelled"));
750
- controller.signal.addEventListener("abort", onAbort, { once: true });
751
- if (controller.signal.aborted) onAbort();
752
- });
753
- try {
754
- return await Promise.race([operation(controller.signal), cancelled]);
755
- } finally {
756
- clearTimeout(timer);
757
- parent.removeEventListener("abort", abort);
758
- controller.signal.removeEventListener("abort", onAbort);
759
- controller.abort();
760
- }
761
- }
762
- sleep(ms, signal) {
763
- return new Promise((resolve) => {
764
- const finish = () => {
765
- clearTimeout(timer);
766
- signal.removeEventListener("abort", finish);
767
- resolve();
768
- };
769
- const timer = setTimeout(finish, ms);
770
- signal.addEventListener("abort", finish, { once: true });
771
- if (signal.aborted) finish();
772
- });
773
- }
774
- report(message) {
775
- if (this.reported.has(message)) return;
776
- this.reported.add(message);
777
- (this.options.onError ?? ((m) => logToFile(`[wizard-run-sync] ${m}`)))(message);
778
- }
779
- };
780
- //#endregion
781
- //#region src/lib/runners/run-wizard.ts
782
- const WIZARD_VERSION = VERSION;
783
- /** The session a run step's agent runs in: scoped to the step's target dir
784
- * (e.g. a monorepo sub-app) with its own framework context, after any prep.
785
- * A step without `targetDir` runs in the live session, unchanged.
786
- * The frameworkContext copy is shallow and unfiltered — name keys per owning program. */
787
- async function prepareRunSession(step, live) {
788
- const session = step.targetDir ? {
789
- ...live,
790
- installDir: step.targetDir(live),
791
- frameworkContext: { ...live.frameworkContext }
792
- } : live;
793
- if (step.onRunPrep) await step.onRunPrep(session);
794
- return session;
795
- }
796
- /** Advance one step of a composed run to completion: the auth screen
797
- * authenticates (every later run reuses it); a step carrying its own `run`
798
- * thunk runs that agent in its dir and is recorded in `completedRuns`; the
799
- * host program's own run screen runs `config.run`; any other screen waits for
800
- * the user to satisfy `isComplete`. */
801
- async function advanceStep(step, store, config) {
802
- if (step.screenId === "auth") {
803
- await authenticate(store.session, config.id);
804
- maybeStampAiSdkDetected(store.session);
805
- } else if (step.run) {
806
- await step.run(await prepareRunSession(step, store.session));
807
- store.completeRunStep(step.id);
808
- } else if (step.screenId === "run") await runProgramAgent(config, await prepareRunSession(step, store.session));
809
- else if (step.isComplete) await store.waitUntil(step.isComplete);
810
- }
811
- /**
812
- * Run a full wizard program in the TUI. Handles the full lifecycle: start TUI,
813
- * build session, run detection, wait for intro gate, execute the
814
- * agent pipeline, wait for outro dismissal, then exit.
815
- */
816
- function runWizard(config, options) {
817
- let tui = null;
818
- let taskStream = null;
819
- let onSignal = null;
820
- let exitInProgress = false;
821
- let signalled = false;
822
- let unregisterShutdown;
823
- (async () => {
824
- try {
825
- const installDir = options.installDir || process.cwd();
826
- const { startTUI } = await import("./start-tui-oCWMgsDP.js");
827
- const { buildSession, RunPhase } = await import("./wizard-session-DGaUHOF3.js");
828
- const { TaskStreamPush } = await import("./task-stream-kYlm9qd0.js");
829
- const { PostHogDestination } = await import("./posthog-6Uqw_Eux.js").then((n) => n.r);
830
- const { createFileDestination } = await import("./file-dEhr-l3n.js");
831
- const local = getLocalDev();
832
- const localServicesError = await checkLocalServices({
833
- ...local,
834
- localPosthog: local.localPosthog && !options.baseUrl
835
- });
836
- if (localServicesError) {
837
- const { wizardAbort } = await import("./wizard-abort-Y-Ip2K4z.js");
838
- await wizardAbort({ message: localServicesError });
839
- return;
840
- }
841
- tui = startTUI(WIZARD_VERSION, config.id, () => onSignal?.());
842
- const activeTui = tui;
843
- const session = buildSession({
844
- debug: options.debug,
845
- localDev: options.localDev,
846
- localMcp: options.localMcp,
847
- localPosthog: options.localPosthog,
848
- installDir,
849
- ci: false,
850
- signup: options.signup,
851
- apiKey: options.apiKey,
852
- projectId: options.projectId,
853
- email: options.email,
854
- baseUrl: options.baseUrl,
855
- benchmark: options.benchmark,
856
- yaraReport: options.yaraReport,
857
- noTelemetry: resolveNoTelemetry(options),
858
- harness: options.harness,
859
- sequence: options.sequence,
860
- model: options.model,
861
- integrate: options.integrate,
862
- captureAio: options.captureAio
863
- });
864
- session.programLabel = config.id;
865
- if (options.skillId) session.skillId = options.skillId;
866
- else if (config.skillId) session.skillId = config.skillId;
867
- activeTui.store.session = session;
868
- onSignal = () => {
869
- if (signalled || exitInProgress) return;
870
- signalled = true;
871
- logToFile("[run-wizard] signal received, flushing task stream");
872
- runCleanups();
873
- if (activeTui.store.session.runPhase === RunPhase.Running) activeTui.store.setRunPhase(RunPhase.Error);
874
- const teardown = () => {
875
- unregisterShutdown?.();
876
- if (onSignal) {
877
- process.off("SIGINT", onSignal);
878
- process.off("SIGTERM", onSignal);
879
- }
880
- try {
881
- activeTui.unmount();
882
- } catch {}
883
- process.exit(130);
884
- };
885
- Promise.all([taskStream?.shutdown(2e3, "cancelled"), analytics.shutdown("cancelled")]).catch(() => logToFile("[run-wizard] cancellation shutdown failed")).finally(teardown);
886
- };
887
- process.on("SIGINT", onSignal);
888
- process.on("SIGTERM", onSignal);
889
- for (;;) {
890
- await activeTui.store.runReadyHooks();
891
- await activeTui.store.getGate("intro");
892
- const active = activeTui.store.router.activeProgram;
893
- if (active === config.id) break;
894
- config = getProgramConfig(active);
895
- }
896
- const fileDestination = createFileDestination(options.taskStreamLog);
897
- const destinations = [...session.noTelemetry ? [] : [new PostHogDestination({
898
- getCredentials: () => activeTui.store.session.credentials,
899
- onError: (err) => logToFile("[task-stream-push]", err.message)
900
- })], ...fileDestination ? [fileDestination] : []];
901
- const taskStreamEnabled = destinations.length > 0;
902
- const activeStream = new TaskStreamPush({
903
- store: activeTui.store,
904
- getFlags: () => analytics.getCachedWizardFlags(),
905
- programId: config.streamWorkflowId ?? config.id,
906
- runSync: createWizardRunSync({
907
- mode: "local",
908
- programId: config.id,
909
- assignedId: options.runId ?? runtimeEnv("POSTHOG_WIZARD_RUN_ID"),
910
- noTelemetry: session.noTelemetry,
911
- getSession: () => activeTui.store.session
912
- }),
913
- destinations,
914
- eventPlanPath: config.eventPlanFile ? join(session.installDir, config.eventPlanFile) : void 0,
915
- auditChecks: config.auditLedgerFile ? () => getAuditChecks(activeTui.store.session) : void 0,
916
- enabled: taskStreamEnabled
917
- });
918
- taskStream = activeStream;
919
- activeStream.attach();
920
- unregisterShutdown = registerShutdown((outcome) => {
921
- if (activeTui.store.session.runPhase === RunPhase.Running) activeTui.store.setRunPhase(RunPhase.Error);
922
- return activeStream.shutdown(2e3, outcome);
923
- });
924
- await activeTui.store.getGate("integration-check");
925
- await activeTui.store.getGate("health-check");
926
- const skipAgent = config.run == null;
927
- const shown = (s) => !s.show || s.show(activeTui.store.session);
928
- if (config.steps.some((s) => s.run || s.targetDir)) for (const step of config.steps) {
929
- if (step.screenId === "outro") break;
930
- if (shown(step)) await advanceStep(step, activeTui.store, config);
931
- }
932
- else if (skipAgent) {
933
- const { getOrAskForProjectData } = await import("./setup-utils-dCViCC6s.js").then((n) => n.r);
934
- const { projectApiKey, host, accessToken, projectId } = await getOrAskForProjectData({
935
- signup: session.signup,
936
- ci: session.ci,
937
- apiKey: session.apiKey,
938
- projectId: session.projectId,
939
- baseUrl: session.baseUrl,
940
- programId: config.id
941
- });
942
- activeTui.store.setCredentials({
943
- accessToken,
944
- projectApiKey,
945
- host,
946
- projectId
947
- });
948
- } else try {
949
- await runProgramAgent(config, activeTui.store.session);
950
- } catch (error) {
951
- const failure = classifyRunFailure(error);
952
- logToFile("[run-wizard] run failed, handing off:", error);
953
- runCleanups();
954
- analytics.captureException(error instanceof Error ? error : new Error(String(error)), { error_code: failure.code });
955
- getUI().outroError({
956
- kind: "error",
957
- errorCode: failure.code,
958
- message: failure.message
959
- });
960
- }
961
- if (signalled) return;
962
- const runFailed = isRunFailure(activeTui.store.session);
963
- await activeStream.finishRun(runFailed ? "failed" : "completed");
964
- await activeTui.store.waitUntil((s) => {
965
- if (s.mintHandoff === "exit") return true;
966
- if (skipAgent && !runFailed) return s.outroDismissed;
967
- return s.skillsComplete;
968
- });
969
- exitInProgress = true;
970
- await activeStream.shutdown(2e3);
971
- unregisterShutdown?.();
972
- process.off("SIGINT", onSignal);
973
- process.off("SIGTERM", onSignal);
974
- if (runFailed) await analytics.shutdown("error");
975
- activeTui.unmount();
976
- process.exit(runFailed ? 1 : 0);
977
- } catch (err) {
978
- if (signalled) return;
979
- logToFile("[run-wizard] FATAL:", err);
980
- runCleanups();
981
- exitInProgress = true;
982
- if (onSignal) {
983
- process.off("SIGINT", onSignal);
984
- process.off("SIGTERM", onSignal);
985
- }
986
- if (taskStream) try {
987
- await taskStream.shutdown(2e3, "failed");
988
- } catch {}
989
- unregisterShutdown?.();
990
- if (tui) try {
991
- tui.unmount();
992
- } catch {}
993
- const failure = classifyRunFailure(err);
994
- if (failure.coded) console.error(failure.message);
995
- else console.error("Wizard run failed:", err);
996
- console.error(`Full logs: ${getLogFilePath()}`);
997
- emitWizardError({
998
- code: failure.code,
999
- message: failure.message
1000
- });
1001
- process.exit(1);
1002
- }
1003
- })();
1004
- }
1005
- //#endregion
1006
- //#region src/programs/detect-map.ts
1007
- const DETECT_CODES = {
1008
- "bad-directory": ErrorCodes.DetectBadDirectory,
1009
- "unsupported-platform": ErrorCodes.DetectUnsupportedPlatform,
1010
- "no-project-files": ErrorCodes.DetectNoProjectFiles,
1011
- "no-sources": ErrorCodes.DetectNoSources,
1012
- "no-package-json": ErrorCodes.DetectNoPackageJson,
1013
- "no-sdks": ErrorCodes.DetectNoSdks,
1014
- "missing-stripe": ErrorCodes.DetectMissingStripe,
1015
- "no-posthog-sdk": ErrorCodes.DetectNoPosthogSdk,
1016
- "no-posthog": ErrorCodes.DetectNoPosthogSdk,
1017
- "missing-posthog": ErrorCodes.DetectNoPosthogSdk
1018
- };
1019
- /**
1020
- * `kind` arrives as a bare string — `frameworkContext.detectError` is untyped
1021
- * storage — so the lookup can still miss. It falls back to a detect-group code
1022
- * with `retry: 'no'`, never to `InternalUnhandled`: an unrecognized precondition
1023
- * failure is still a precondition failure, and telling a sandbox to retry one
1024
- * costs it the whole budget.
1025
- */
1026
- function detectErrorCode(kind) {
1027
- return DETECT_CODES[kind] ?? ErrorCodes.DetectUnclassified;
1028
- }
1029
- //#endregion
1030
- //#region src/lib/runners/run-non-interactive.ts
1031
- /** User-facing label for a non-interactive mode. */
1032
- function modeLabel(mode) {
1033
- return mode === "headless" ? "Headless" : "CI";
1034
- }
1035
- /** The credentials every non-interactive mode accepts, for error messages. */
1036
- const API_KEY_HINT = "personal API key phx_xxx or wizard-app OAuth access token pha_xxx";
1037
- /**
1038
- * The single non-interactive validation layer: requires api-key and
1039
- * install-dir. Every non-interactive entry point routes through
1040
- * `runNonInteractive`, so this is the one place these checks live. UI must be
1041
- * initialized before calling.
1042
- */
1043
- function validateNonInteractiveOptions(options, mode) {
1044
- const label = modeLabel(mode);
1045
- if (!options.apiKey) {
1046
- getUI().intro("PostHog Wizard");
1047
- getUI().log.error(`${label} mode requires --api-key (${API_KEY_HINT})`);
1048
- emitWizardError({
1049
- code: ErrorCodes.ArgsMissingApiKey,
1050
- message: `${label} mode requires --api-key (${API_KEY_HINT})`
1051
- });
1052
- process.exit(1);
1053
- }
1054
- if (!options.installDir) {
1055
- getUI().intro("PostHog Wizard");
1056
- getUI().log.error(`${label} mode requires --install-dir (directory to install in)`);
1057
- emitWizardError({
1058
- code: ErrorCodes.ArgsMissingInstallDir,
1059
- message: `${label} mode requires --install-dir`
1060
- });
1061
- process.exit(1);
1062
- }
1063
- }
1064
- /**
1065
- * Non-interactive pipeline shared by CI (`runWizardCI`) and headless
1066
- * (`runWizardHeadless`) runs.
1067
- *
1068
- * Validates flags, builds a `ci:true` session, runs `config.ciPreRun` (or the
1069
- * program's `onReady` hooks by default), executes `runProgramAgent`, and routes any
1070
- * failure through `wizardAbort`. `wizardAbort` owns all exits — never add a
1071
- * raw `process.exit` here.
1072
- *
1073
- * `mode` is the only difference between the two callers today (it sets the
1074
- * analytics build tag and the user-facing label). Keeping it a parameter is
1075
- * what lets CI and headless share this body now and diverge later — branch on
1076
- * `mode` here, or stop sharing this function entirely.
1077
- */
1078
- function runNonInteractive(config, options, mode) {
1079
- setUI(new LoggingUI());
1080
- validateNonInteractiveOptions(options, mode);
1081
- analytics.setTag("build", mode);
1082
- (async () => {
1083
- const path = await import("path");
1084
- const { buildSession, RunPhase, OutroKind } = await import("./wizard-session-DGaUHOF3.js");
1085
- const { readEnvironment } = await import("./environment-DZYUSCpV.js").then((n) => n.t);
1086
- const { readApiKeyFromEnv } = await import("./env-api-key-BWdKpGEr.js").then((n) => n.t);
1087
- const { configureLogFileFromEnvironment, logToFile } = await import("./debug-B9k4ideV.js");
1088
- const { wizardAbort, WizardError } = await import("./wizard-abort-Y-Ip2K4z.js");
1089
- configureLogFileFromEnvironment();
1090
- const env = readEnvironment();
1091
- const apiKey = options.apiKey ?? readApiKeyFromEnv() ?? void 0;
1092
- const installDir = path.isAbsolute(options.installDir) ? options.installDir : path.join(process.cwd(), options.installDir);
1093
- const session = buildSession({
1094
- debug: options.debug,
1095
- installDir,
1096
- ci: true,
1097
- signup: options.signup,
1098
- localDev: options.localDev,
1099
- localMcp: options.localMcp,
1100
- localPosthog: options.localPosthog,
1101
- apiKey,
1102
- email: options.email,
1103
- projectId: options.projectId,
1104
- baseUrl: options.baseUrl,
1105
- benchmark: options.benchmark,
1106
- yaraReport: options.yaraReport,
1107
- noTelemetry: resolveNoTelemetry(options),
1108
- harness: options.harness,
1109
- sequence: options.sequence,
1110
- model: options.model,
1111
- captureAio: options.captureAio,
1112
- ...env,
1113
- region: options.region ?? env.region
1114
- });
1115
- session.programLabel = config.id;
1116
- if (config.skillId) session.skillId = config.skillId;
1117
- const runDef = typeof config.run === "object" ? config.run : null;
1118
- getUI().intro("Welcome to the PostHog setup wizard");
1119
- getUI().log.info(`Running ${config.id} in ${modeLabel(mode)} mode`);
1120
- const localServicesError = await checkLocalServices({
1121
- ...getLocalDev(),
1122
- localMcp: session.localMcp,
1123
- localPosthog: session.baseUrl === POSTHOG_LOCAL_URL
1124
- });
1125
- if (localServicesError) {
1126
- await wizardAbort({
1127
- code: ErrorCodes.EnvLocalServicesDown,
1128
- message: localServicesError
1129
- });
1130
- return;
1131
- }
1132
- let store = null;
1133
- let taskStream = null;
1134
- {
1135
- const { WizardStore } = await import("./store-xYy_6Ruv.js").then((n) => n.n);
1136
- const { HeadlessUI } = await import("./headless-ui-pY2xB5ug.js");
1137
- const { TaskStreamPush, PostHogDestination, createFileDestination } = await import("./task-stream-kYlm9qd0.js");
1138
- const fileDestination = createFileDestination(mode === "ci" ? options.taskStreamLog ?? "" : options.taskStreamLog);
1139
- const posthogDestination = mode === "headless" && !session.noTelemetry ? new PostHogDestination({
1140
- getCredentials: () => store?.session.credentials ?? session.credentials,
1141
- onError: (e) => logToFile("[headless task-stream]", e.message)
1142
- }) : null;
1143
- const destinations = [...posthogDestination ? [posthogDestination] : [], ...fileDestination ? [fileDestination] : []];
1144
- const headlessStore = new WizardStore(config.id);
1145
- store = headlessStore;
1146
- headlessStore.session = session;
1147
- setUI(new HeadlessUI(headlessStore));
1148
- taskStream = new TaskStreamPush({
1149
- store: headlessStore,
1150
- getFlags: () => analytics.getCachedWizardFlags(),
1151
- programId: config.streamWorkflowId ?? config.id,
1152
- runSync: createWizardRunSync({
1153
- mode,
1154
- programId: config.id,
1155
- assignedId: options.runId ?? runtimeEnv("POSTHOG_WIZARD_RUN_ID"),
1156
- noTelemetry: session.noTelemetry,
1157
- getSession: () => headlessStore.session
1158
- }),
1159
- destinations,
1160
- eventPlanPath: config.eventPlanFile ? join(session.installDir, config.eventPlanFile) : void 0,
1161
- auditChecks: config.auditLedgerFile ? () => getAuditChecks(headlessStore.session) : void 0,
1162
- enabled: destinations.length > 0
1163
- });
1164
- taskStream.attach();
1165
- if (fileDestination) logToFile(`[task-stream] ${mode} dump: ${fileDestination.path}`);
1166
- }
1167
- const settleStream = async (phase, outroData, outcome = phase === RunPhase.Completed ? "completed" : "failed") => {
1168
- if (!store || !taskStream) return;
1169
- if (outroData) store.setOutroData(outroData);
1170
- store.setRunPhase(phase);
1171
- await taskStream.shutdown(2e3, outcome);
1172
- process.off("SIGINT", onSignal);
1173
- process.off("SIGTERM", onSignal);
1174
- unregisterShutdown();
1175
- };
1176
- const unregisterShutdown = registerShutdown((outcome) => settleStream(RunPhase.Error, void 0, outcome));
1177
- let signalled = false;
1178
- const onSignal = () => {
1179
- if (signalled) return;
1180
- signalled = true;
1181
- runCleanups();
1182
- settleStream(RunPhase.Error, void 0, "cancelled").then(() => wizardAbort({ exitCode: 130 }));
1183
- };
1184
- process.on("SIGINT", onSignal);
1185
- process.on("SIGTERM", onSignal);
1186
- try {
1187
- if (mode === "ci") {
1188
- const { configureGatewayFromCIEnvironment } = await import("./agent-CNrEC-9v.js").then((n) => n.t);
1189
- configureGatewayFromCIEnvironment(Number(session.projectId), session.region ?? "us");
1190
- }
1191
- if (config.ciPreRun) await config.ciPreRun(session, { log: {
1192
- info: (message) => getUI().log.info(message),
1193
- warn: (message) => getUI().log.warn(message)
1194
- } });
1195
- else {
1196
- const readyCtx = {
1197
- session,
1198
- setFrameworkContext: (key, value) => {
1199
- session.frameworkContext[key] = value;
1200
- },
1201
- setFrameworkConfig: () => void 0,
1202
- setDetectedFramework: () => void 0,
1203
- setSkillId: (skillId) => {
1204
- session.skillId = skillId;
1205
- },
1206
- setUnsupportedVersion: (info) => {
1207
- session.unsupportedVersion = info;
1208
- },
1209
- addDiscoveredFeature: () => void 0,
1210
- setDetectionComplete: () => void 0,
1211
- setPosthogSdkDetected: (detected) => {
1212
- session.posthogSdkDetected = detected;
1213
- }
1214
- };
1215
- for (const step of config.steps) if (step.onReady) await step.onReady(readyCtx);
1216
- const detectError = session.frameworkContext.detectError;
1217
- if (session.unsupportedVersion) {
1218
- const { current, minimum, docsUrl } = session.unsupportedVersion;
1219
- const message = `Detected framework version ${current} is not supported. Minimum supported version is ${minimum}.`;
1220
- await settleStream(RunPhase.Error, {
1221
- kind: OutroKind.Error,
1222
- message,
1223
- errorCode: ErrorCodes.DetectUnsupportedVersion
1224
- });
1225
- await wizardAbort({
1226
- code: ErrorCodes.DetectUnsupportedVersion,
1227
- message: `${message}\n\nSee ${docsUrl}`,
1228
- error: new WizardError(`${config.id} unsupported framework version`, {
1229
- integration: config.id,
1230
- current,
1231
- minimum
1232
- }, ErrorCodes.DetectUnsupportedVersion)
1233
- });
1234
- }
1235
- if (detectError) {
1236
- const code = detectErrorCode(detectError.kind);
1237
- const detectKind = detectError.kind;
1238
- const detail = { ...detectError };
1239
- await settleStream(RunPhase.Error, {
1240
- kind: OutroKind.Error,
1241
- message: `Prerequisites not met: ${detectKind}`,
1242
- errorCode: code,
1243
- errorDetail: detail
1244
- });
1245
- await wizardAbort({
1246
- code,
1247
- detail,
1248
- message: `Prerequisites not met: ${detectKind}\n\nSee ${runDef?.docsUrl ?? "https://posthog.com/docs"}`,
1249
- error: new WizardError(`${config.id} prerequisites failed`, {
1250
- integration: config.id,
1251
- detect_error_kind: detectKind
1252
- }, code)
1253
- });
1254
- }
1255
- }
1256
- const { runProgramAgent } = await import("./run-agent-legacy-6WcYMaR9.js").then((n) => n.n);
1257
- await runProgramAgent(config, session);
1258
- if (signalled) return;
1259
- await settleStream(RunPhase.Completed);
1260
- } catch (error) {
1261
- if (signalled) return;
1262
- const errorMessage = error instanceof Error ? error.message : String(error);
1263
- const errorStack = error instanceof Error && error.stack ? error.stack : void 0;
1264
- logToFile(`[${mode}] ERROR: ${errorMessage}`);
1265
- if (errorStack) logToFile(`[${mode}] STACK: ${errorStack}`);
1266
- const debugInfo = session.debug && errorStack ? `\n\n${errorStack}` : "";
1267
- const docsUrl = session.frameworkConfig?.metadata.docsUrl ?? runDef?.docsUrl ?? "https://posthog.com/docs";
1268
- const failure = classifyRunFailure(error);
1269
- await settleStream(RunPhase.Error, {
1270
- kind: OutroKind.Error,
1271
- message: errorMessage,
1272
- errorCode: failure.code
1273
- });
1274
- await wizardAbort({
1275
- code: failure.code,
1276
- message: failure.coded ? `${errorMessage}${debugInfo}` : `Something went wrong: ${errorMessage}\n\nYou can read the documentation at ${docsUrl} to set up manually.${debugInfo}`,
1277
- error
1278
- });
1279
- }
1280
- })().catch((error) => {
1281
- emitWizardError({
1282
- code: ErrorCodes.InternalUnhandled,
1283
- message: error instanceof Error ? error.message : String(error)
1284
- });
1285
- process.exit(1);
1286
- });
1287
- }
1288
- //#endregion
1289
- //#region src/lib/runners/run-wizard-ci.ts
1290
- /**
1291
- * CI-mode entry point (`--ci`, dev/test builds). A thin shell over the shared
1292
- * non-interactive pipeline — see `runNonInteractive`. Kept as its own function
1293
- * so CI and headless (`runWizardHeadless`) can diverge without re-threading the
1294
- * many callers that route here.
1295
- */
1296
- function runWizardCI(config, options) {
1297
- runNonInteractive(config, options, "ci");
1298
- }
1299
- //#endregion
1300
- //#region src/lib/runners/run-wizard-headless.ts
1301
- /**
1302
- * Headless entry point (the experimental published-build, non-interactive run
1303
- * path; see @lib/headless-mode). A thin shell over the shared non-interactive
1304
- * pipeline — see `runNonInteractive`. Today it behaves exactly like
1305
- * `runWizardCI`; it exists as a separate function so headless can diverge later
1306
- * (its own auth handling, telemetry, prompts, …) without touching CI or its
1307
- * callers. Diverge by branching on the mode inside `runNonInteractive`, or by
1308
- * giving this function its own body.
1309
- */
1310
- function runWizardHeadless(config, options) {
1311
- runNonInteractive(config, options, "headless");
1312
- }
1313
- //#endregion
1314
- //#region src/commands/skill-program-options.ts
1315
- /**
1316
- * Per-command options shared by every skill-based program command
1317
- * (`audit events`, `migrate statsig`, `revenue`, `source-maps`, …).
1318
- *
1319
- * Only flags unique to skill commands live here. Global flags are declared
1320
- * once in `wizard.ts` — both in `GLOBAL_OPTIONS` and, for the dev-only ones,
1321
- * the `Wizard` constructor — and apply to every command automatically.
1322
- */
1323
- const skillProgramOptions = { "install-dir": {
1324
- describe: "Directory to install in",
1325
- type: "string"
1326
- } };
1327
- //#endregion
1328
- //#region src/commands/factories/shared.ts
1329
- /**
1330
- * Dispatch a parsed yargs invocation to the wizard runner. Applies the
1331
- * program's `mapCliOptions` transform, then routes to `runWizardHeadless`,
1332
- * `runWizardCI`, or `runWizard` based on the headless / `--ci` flags.
1333
- *
1334
- * Every command file used to inline this; the factories call it instead.
1335
- */
1336
- /**
1337
- * Run a command's async body as fire-and-forget while still surfacing failures.
1338
- * yargs handlers are synchronous, so async work kicks off a detached promise —
1339
- * without this, a rejection becomes an unhandled promise rejection (no message,
1340
- * wrong exit code). This awaits the work and turns any error into a clean
1341
- * message + non-zero exit.
1342
- */
1343
- function runCommandHandler(work) {
1344
- (async () => {
1345
- try {
1346
- await work();
1347
- } catch (err) {
1348
- const msg = err instanceof Error ? err.message : String(err);
1349
- process.stderr.write(`\n\x1b[1;91m✖ ${msg}\x1b[0m\n\n`);
1350
- emitWizardError({
1351
- code: ErrorCodes.InternalUnhandled,
1352
- message: msg
1353
- });
1354
- process.exit(1);
1355
- }
1356
- })();
1357
- }
1358
- function dispatchProgram(config, argv) {
1359
- const argvRecord = { ...argv };
1360
- const extras = config.mapCliOptions?.(argvRecord) ?? {};
1361
- const options = {
1362
- ...argvRecord,
1363
- ...extras
1364
- };
1365
- if (isHeadless(options)) runWizardHeadless(config, options);
1366
- else if (options.ci) runWizardCI(config, options);
1367
- else runWizard(config, options);
1368
- }
1369
- /**
1370
- * Merge the standard skill-program flags (`--debug`, `--install-dir`, etc.)
1371
- * with any program-specific options declared on `cliOptions`.
1372
- *
1373
- * Program-specific options shadow the standard ones — that's intentional, so
1374
- * a program can override a default flag if it ever needs to.
1375
- */
1376
- function mergeCommandOptions(config) {
1377
- return {
1378
- ...skillProgramOptions,
1379
- ...config.cliOptions ?? {}
1380
- };
1381
- }
1382
- //#endregion
1383
- //#region src/commands/factories/native-command-factory.ts
1384
- /**
1385
- * Build a yargs `Command` from a wizard-native `ProgramConfig`.
1386
- *
1387
- * Collapses the previously duplicated boilerplate (read `config.command`,
1388
- * merge skill-program flags with program-specific options, dispatch via
1389
- * `runWizard` / `runWizardCI`) into a single call.
1390
- */
1391
- function nativeCommandFactory(config, opts = {}) {
1392
- if (!config.command) throw new Error(`nativeCommandFactory: program "${config.id}" has no \`command\` — wizard-native programs must declare a CLI name`);
1393
- return {
1394
- name: config.command,
1395
- description: config.description,
1396
- options: mergeCommandOptions(config),
1397
- children: opts.children,
1398
- handler: (argv) => dispatchProgram(config, argv)
1399
- };
1400
- }
1401
- //#endregion
1402
- //#region src/commands/mcp-analytics.ts
1403
- /**
1404
- * `wizard mcp-analytics` — flat skill command, instrument-an-MCP-server today.
1405
- *
1406
- * Distinct from `wizard mcp add`: this instruments the user's own MCP server
1407
- * with the `@posthog/mcp` SDK, rather than installing the PostHog MCP server
1408
- * into a coding agent. Stays flat while instrumenting is the only action.
1409
- */
1410
- const mcpAnalyticsCommand = nativeCommandFactory(mcpAnalyticsConfig);
1411
- //#endregion
1412
- //#region src/commands/replay-vision.ts
1413
- /**
1414
- * `wizard replay-vision` — flat skill command, set up Replay vision today.
1415
- *
1416
- * Enables session replay recording and creates vision scanners tailored to
1417
- * the product's key flows. Runs the `replay-vision` orchestrator flow, which
1418
- * reuses the integration-v2 install/init mini-agents when the repo has no
1419
- * PostHog integration yet.
1420
- */
1421
- const replayVisionCommand = nativeCommandFactory(replayVisionConfig);
1422
- //#endregion
1423
- //#region src/commands/ai-observability.ts
1424
- /**
1425
- * `wizard ai-observability` — flat skill command, wire AI Observability into a
1426
- * project today.
1427
- *
1428
- * Installs the OpenTelemetry SDK, the PostHog span processor, and the
1429
- * provider-specific instrumentation so LLM calls emit `$ai_generation` events.
1430
- * The `ai-observability` context-mill skill has one variant per (LLM provider ×
1431
- * language); the agent picks the right one at run time by scanning the
1432
- * project's manifest and (when ambiguous) asking the user via `wizard_ask`.
1433
- * Stays flat while a single "add AIO to a project" flow is the only action.
1434
- */
1435
- const aiObservabilityCommand = nativeCommandFactory(aiObservabilityConfig);
1436
- //#endregion
1437
- //#region src/commands/metrics.ts
1438
- /**
1439
- * `wizard metrics` — flat skill command, wire PostHog application metrics
1440
- * (counters, gauges, histograms via \`posthog.metrics\`) into a project.
1441
- *
1442
- * The `metrics` context-mill skill has one variant per platform (python,
1443
- * nodejs, javascript, kubernetes, other/OTLP); the agent picks the right one
1444
- * at run time by scanning the project's manifest and (when ambiguous) asking
1445
- * the user via `wizard_ask`. Stays flat while a single "add metrics to a
1446
- * project" flow is the only action.
1447
- */
1448
- const metricsCommand = nativeCommandFactory(metricsConfig);
1449
- //#endregion
1450
- //#region src/programs/dispatch-family.ts
1451
- /**
1452
- * Capture a CLI dispatch error, flush analytics, and exit. The wizard never
1453
- * starts a run from these paths — use flush() (not shutdown()) so we don't
1454
- * fire a "setup wizard finished" event for a parse error that didn't run.
1455
- */
1456
- async function exitDispatchError(reason, properties, message, code = 1) {
1457
- analytics.wizardCapture("cli dispatch error", {
1458
- reason,
1459
- ...properties
1460
- });
1461
- try {
1462
- await analytics.flush();
1463
- } catch {}
1464
- process.stderr.write(message);
1465
- emitWizardError({
1466
- code: ErrorCodes.CliBadArgs,
1467
- message: reason
1468
- });
1469
- return process.exit(code);
1470
- }
1471
- /**
1472
- * Family commands (`wizard audit`, `wizard migrate`, ...) resolve their
1473
- * subcommands at runtime against the published `cliEntries` inside
1474
- * `skill-menu.json`. Adding a subcommand is a context-mill release — no
1475
- * wizard release needed.
1476
- *
1477
- * Wizard-native subcommands (programs that aren't backed by a single skill,
1478
- * e.g. `wizard audit web-analytics`) live here in code, dispatched directly
1479
- * without touching the registry. Adding a native is a wizard PR.
1480
- */
1481
- /** Wizard-native subcommands keyed by family. */
1482
- const NATIVE_HANDLERS = { audit: { "web-analytics": webAnalyticsDoctorConfig } };
1483
- /**
1484
- * Resolve a fetched CliEntry to the ProgramConfig that actually runs it.
1485
- * Most entries run via the generic agent-skill program with the entry's
1486
- * `skillId` injected. The comprehensive `audit all` is the one exception —
1487
- * skillId 'audit' triggers the specialized auditConfig (custom hooks,
1488
- * content blocks, screens).
1489
- *
1490
- * This is the one place that knows a subcommand belongs to `audit`, so the
1491
- * generic skill program picks up the ledger here rather than for every skill.
1492
- */
1493
- function configForCliEntry(entry, family) {
1494
- if (entry.skillId === "audit") return auditConfig;
1495
- return {
1496
- ...agentSkillConfig,
1497
- skillId: entry.skillId,
1498
- ...family === "audit" ? {
1499
- auditLedgerFile: AUDIT_CHECKS_FILE,
1500
- streamWorkflowId: family,
1501
- allowedTools: [
1502
- ...agentSkillConfig.allowedTools ?? [],
1503
- WIZARD_TOOL_NAMES.auditSeedChecks,
1504
- WIZARD_TOOL_NAMES.auditAddChecks,
1505
- WIZARD_TOOL_NAMES.auditResolveChecks
1506
- ]
1507
- } : {}
1508
- };
1509
- }
1510
- function familyEntries(family, entries) {
1511
- return entries.filter((e) => e.role === "command" && e.parentCommand === family && Boolean(e.command));
1512
- }
1513
- /**
1514
- * Dispatch `wizard <family> <sub>` to the right program.
1515
- *
1516
- * Order:
1517
- * 1. Native handler for (family, sub) — runs immediately, no network.
1518
- * 2. Fetched CliEntry — runs the resolved skill.
1519
- * 3. Unknown — prints the available list and exits non-zero.
1520
- */
1521
- async function dispatchFamily(family, argv) {
1522
- const sub = argv.skill?.trim();
1523
- if (!sub) return exitDispatchError("missing subcommand", { family }, `\n\x1b[1;91m✖ \`wizard ${family}\` requires a subcommand.\x1b[0m\n Pass one (e.g. \`wizard ${family} <subcommand>\`), or run it in an interactive terminal to pick from a menu.\n\n`);
1524
- const native = NATIVE_HANDLERS[family]?.[sub];
1525
- if (native) {
1526
- dispatchProgram(native, argv);
1527
- return;
1528
- }
1529
- const skillsBaseUrl = getSkillsBaseUrl();
1530
- const menu = await fetchSkillMenu(skillsBaseUrl);
1531
- if (!menu) return exitDispatchError("registry unreachable", {
1532
- family,
1533
- sub,
1534
- skillsBaseUrl
1535
- }, `\n\x1b[1;91m✖ Couldn't reach the skill registry at ${skillsBaseUrl}.\x1b[0m\n Check your network connection and try again.\n\n`);
1536
- const entries = menu.cliEntries ?? [];
1537
- const entry = familyEntries(family, entries).find((e) => e.command === sub);
1538
- if (entry) {
1539
- dispatchProgram(configForCliEntry(entry, family), argv);
1540
- return;
1541
- }
1542
- const available = [...Object.keys(NATIVE_HANDLERS[family] ?? {}), ...familyEntries(family, entries).map((e) => e.command)].sort();
1543
- return exitDispatchError("unknown subcommand", {
1544
- family,
1545
- sub,
1546
- available
1547
- }, `\n\x1b[1;91m✖ Unknown subcommand "${sub}" under \`${family}\`.\x1b[0m\n` + (available.length ? ` Available: ${available.join(", ")}\n\n` : ` No subcommands published for "${family}" yet.\n\n`));
1548
- }
1549
- /**
1550
- * Build the children list shown in the family's interactive picker.
1551
- * Combines native handlers with skill-backed entries from the live registry.
1552
- * Used by `familyCommandFactory`'s `interactiveDefault`.
1553
- */
1554
- function buildFamilyPickerChildren(family, entries) {
1555
- const natives = Object.entries(NATIVE_HANDLERS[family] ?? {}).map(([cmd, program]) => ({
1556
- name: cmd,
1557
- description: program.description,
1558
- handler: (argv) => dispatchProgram(program, argv)
1559
- }));
1560
- const live = familyEntries(family, entries).map((entry) => ({
1561
- name: entry.command,
1562
- description: entry.description,
1563
- handler: (argv) => {
1564
- dispatchFamily(family, {
1565
- ...argv,
1566
- skill: entry.command
1567
- });
1568
- },
1569
- default: entry.default
1570
- }));
1571
- return [...natives, ...live];
1572
- }
1573
- /**
1574
- * The children the family picker shows **today**: only the leaf marked
1575
- * `default` (e.g. `audit events`). Every other subcommand stays runnable
1576
- * directly (`wizard audit <name>`) — they just aren't listed in the picker yet.
1577
- * Falls back to all children when nothing is marked `default`.
1578
- *
1579
- * Temporary: when we're ready to surface the full menu, return `children`
1580
- * unchanged (and delete this note).
1581
- */
1582
- function pickerChildrenToShow(children) {
1583
- const defaults = children.filter((c) => c.default);
1584
- return defaults.length > 0 ? [...defaults] : [...children];
1585
- }
1586
- //#endregion
1587
- //#region src/ui/tui/primitives/picker-filter.ts
1588
- /**
1589
- * Filter-as-you-type matching for PickerMenu. Split out from the component so the
1590
- * ranking is testable on its own — the component only decides when to call it.
1591
- */
1592
- /**
1593
- * Fuzzy fallback config. `ignoreLocation` because a term matching at the end of a
1594
- * description is as good as one at the start, and Fuse's default distance window
1595
- * would score the late match away. 0.5 is the loosest threshold that still bottoms
1596
- * out: below it `gthb` misses `GitHub` entirely, which is the whole point of having
1597
- * a fuzzy pass; above it the tail grows without surfacing anything new at the top.
1598
- */
1599
- const FUSE_OPTIONS = {
1600
- keys: [
1601
- {
1602
- name: "label",
1603
- weight: 3
1604
- },
1605
- {
1606
- name: "hint",
1607
- weight: 1
1608
- },
1609
- {
1610
- name: "description",
1611
- weight: 1
1612
- }
1613
- ],
1614
- ignoreLocation: true,
1615
- threshold: .5,
1616
- includeScore: true
1617
- };
1618
- function buildPickerIndex(options) {
1619
- return new Fuse(options, FUSE_OPTIONS);
1620
- }
1621
- function haystack(option) {
1622
- return `${option.label} ${option.hint ?? ""} ${option.description ?? ""}`.toLowerCase();
1623
- }
1624
- /**
1625
- * Rank options against a query, best first, or `null` for an empty query.
1626
- *
1627
- * Two passes, literal before fuzzy. Anything that literally contains every
1628
- * whitespace-separated term wins outright, in the list's own order — that covers how
1629
- * people actually type (`git iss` → `GitHub issues`) and keeps the common case as
1630
- * tight as a plain substring filter, which fuzzy matching on its own is not: Fuse at
1631
- * a threshold loose enough to forgive `gthb` also lets a third of the list through
1632
- * on `replay`.
1633
- *
1634
- * Only when nothing matches literally does Fuse get a turn, so a typo degrades to a
1635
- * ranked guess instead of an empty list. Terms are AND-ed there too, each matched
1636
- * fuzzily on its own — Fuse's bitap pass over the whole query would otherwise need
1637
- * `git iss` to be a near-edit of the text it's matching. Scores are distances (0 is
1638
- * exact) and sum across terms, hence the ascending sort; ties keep the order the
1639
- * first term put them in, since the sort is stable.
1640
- */
1641
- function rankOptions(fuse, options, query) {
1642
- const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
1643
- if (!terms.length) return null;
1644
- const literal = options.filter((option) => terms.every((term) => haystack(option).includes(term)));
1645
- if (literal.length) return literal;
1646
- let surviving = null;
1647
- for (const term of terms) {
1648
- const hits = new Map(fuse.search(term).map(({ item, score }) => [item, score ?? 0]));
1649
- if (surviving === null) {
1650
- surviving = hits;
1651
- continue;
1652
- }
1653
- for (const [option, total] of surviving) {
1654
- const score = hits.get(option);
1655
- if (score === void 0) surviving.delete(option);
1656
- else surviving.set(option, total + score);
1657
- }
1658
- }
1659
- return [...surviving ?? []].sort(([, a], [, b]) => a - b).map(([option]) => option);
1660
- }
1661
- //#endregion
1662
- //#region src/ui/tui/primitives/PromptLabel.tsx
1663
- /**
1664
- * PromptLabel — Compact inline label for input prompts.
1665
- *
1666
- * Renders: [!] message
1667
- * where [!] is black text on accent background.
1668
- */
1669
- const PromptLabel = ({ message }) => {
1670
- if (!message) return null;
1671
- return /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsxs(Text, {
1672
- bold: true,
1673
- color: Colors.accent,
1674
- children: [" ", message]
1675
- }) });
1676
- };
1677
- //#endregion
1678
- //#region src/ui/tui/primitives/ConfirmButton.tsx
1679
- /**
1680
- * ConfirmButton — the confirm row used to submit a selection.
1681
- *
1682
- * Pure render. Multi-select menus (PickerMenu mode="multi", GroupedPickerMenu)
1683
- * append this below their options as the final focusable row: the user toggles
1684
- * options with enter, then arrows down onto this row and presses enter to
1685
- * submit. This replaces the older "enter anywhere submits" pattern, which
1686
- * confused people who expected enter to toggle the focused item.
1687
- *
1688
- * Renders flat, mirroring the option rows — a focus triangle and the label,
1689
- * accent and bold when focused, dimmed otherwise — so it lines up under the
1690
- * options instead of sitting in a separate boxed target.
1691
- */
1692
- const ConfirmButton = ({ label = "Confirm", focused, count }) => {
1693
- const text = count && count > 0 ? `${label} (${count})` : label;
1694
- return /* @__PURE__ */ jsxs(Text, {
1695
- color: focused ? Colors.accent : void 0,
1696
- bold: focused,
1697
- dimColor: !focused,
1698
- children: [
1699
- focused ? Icons.triangleSmallRight : " ",
1700
- " ",
1701
- text
1702
- ]
1703
- });
1704
- };
1705
- //#endregion
1706
- //#region src/ui/tui/hooks/useStdoutDimensions.ts
1707
- /**
1708
- * useStdoutDimensions — Returns [columns, rows] and re-renders on terminal resize.
1709
- *
1710
- * Ink's useStdout() does not subscribe to resize events, so layout only updates
1711
- * when something else causes a re-render. This hook listens to the stream's
1712
- * 'resize' event (Node TTY) and updates state so the component re-renders
1713
- * with the new dimensions.
1714
- */
1715
- function useStdoutDimensions() {
1716
- const { stdout } = useStdout();
1717
- const [size, setSize] = useState(() => [stdout.columns || 80, stdout.rows || 24]);
1718
- useEffect(() => {
1719
- setSize([stdout.columns || 80, stdout.rows || 24]);
1720
- const stream = stdout;
1721
- if (typeof stream.on !== "function") return;
1722
- const onResize = () => {
1723
- const c = stdout.columns || 80;
1724
- const r = stdout.rows || 24;
1725
- if (c > 0 && r > 0) setSize([c, r]);
1726
- };
1727
- stream.on("resize", onResize);
1728
- return () => {
1729
- stream.off?.("resize", onResize);
1730
- };
1731
- }, [stdout]);
1732
- return size;
1733
- }
1734
- //#endregion
1735
- //#region src/ui/tui/hooks/keyboard-hints-utils.ts
1736
- /** Default priorities by key type. */
1737
- const DEFAULT_PRIORITY = {
1738
- ["upArrow"]: 0,
1739
- ["downArrow"]: 0,
1740
- ["leftArrow"]: 1,
1741
- ["rightArrow"]: 1,
1742
- ["space"]: 10,
1743
- ["printable"]: 12,
1744
- ["backspace"]: 13,
1745
- ["escape"]: 20,
1746
- ["return"]: 21
1747
- };
1748
- /** Get the default display priority for a key match. */
1749
- function getDefaultPriority(match) {
1750
- return DEFAULT_PRIORITY[Array.isArray(match) ? match[0] : match] ?? 15;
1751
- }
1752
- /** Check if a KeyMatchOrChar matches the given input string and key flags. */
1753
- function matchesKey(m, input, key) {
1754
- switch (m) {
1755
- case "upArrow": return !!key.upArrow;
1756
- case "downArrow": return !!key.downArrow;
1757
- case "leftArrow": return !!key.leftArrow;
1758
- case "rightArrow": return !!key.rightArrow;
1759
- case "return": return !!key.return;
1760
- case "escape": return !!key.escape;
1761
- case "space": return input === " ";
1762
- case "backspace": return !!key.backspace || !!key.delete;
1763
- case "printable": return input.length === 1 && input >= " " && input !== "" && Object.entries(key).every(([flag, on]) => !on || flag === "shift");
1764
- default: return input === m;
1765
- }
1766
- }
1767
- /** Serialize hints for comparison. */
1768
- function hintsKey(hints) {
1769
- return hints.map((h) => `${h.label}:${h.action}`).join("|");
1770
- }
1771
- /** Deduplicate hints by label+action and sort by priority. */
1772
- function deduplicateAndSort(hints) {
1773
- const seen = /* @__PURE__ */ new Set();
1774
- const deduped = [];
1775
- for (const hint of hints) {
1776
- const k = `${hint.label}:${hint.action}`;
1777
- if (!seen.has(k)) {
1778
- seen.add(k);
1779
- deduped.push(hint);
1780
- }
1781
- }
1782
- deduped.sort((a, b) => a.priority - b.priority);
1783
- return deduped;
1784
- }
1785
- //#endregion
1786
- //#region src/ui/tui/hooks/useKeyboardHints.tsx
1787
- /**
1788
- * KeyboardHintsProvider — Context for collecting and displaying keyboard hints.
1789
- *
1790
- * Input components register their hints via useKeyBindings. The provider
1791
- * flattens, deduplicates, and sorts them. The hints bar stays visible for as
1792
- * long as a screen has registered hints — it never auto-dismisses.
1793
- */
1794
- const KeyboardHintsContext = createContext({
1795
- register: () => void 0,
1796
- unregister: () => void 0,
1797
- hints: []
1798
- });
1799
- const useKeyboardHintsContext = () => useContext(KeyboardHintsContext);
1800
- const KeyboardHintsProvider = ({ children }) => {
1801
- const registrationsRef = useRef(/* @__PURE__ */ new Map());
1802
- const [hints, setHints] = useState([]);
1803
- const prevHintsKeyRef = useRef("");
1804
- const recompute = useCallback(() => {
1805
- const all = [];
1806
- for (const h of registrationsRef.current.values()) all.push(...h);
1807
- const deduped = deduplicateAndSort(all);
1808
- const newKey = hintsKey(deduped);
1809
- if (newKey !== prevHintsKeyRef.current) {
1810
- prevHintsKeyRef.current = newKey;
1811
- setHints(deduped);
1812
- }
1813
- }, []);
1814
- const register = useCallback((id, h) => {
1815
- registrationsRef.current.set(id, h);
1816
- recompute();
1817
- }, [recompute]);
1818
- const unregister = useCallback((id) => {
1819
- registrationsRef.current.delete(id);
1820
- recompute();
1821
- }, [recompute]);
1822
- return /* @__PURE__ */ jsx(KeyboardHintsContext.Provider, {
1823
- value: {
1824
- register,
1825
- unregister,
1826
- hints
1827
- },
1828
- children
1829
- });
1830
- };
1831
- //#endregion
1832
- //#region src/ui/tui/hooks/useKeyBindings.ts
1833
- /**
1834
- * useKeyBindings — Declarative keyboard input + automatic hint registration.
1835
- *
1836
- * Replaces raw `useInput` in input components. Define bindings as data;
1837
- * the hook wires up the Ink input handler AND registers hints in the
1838
- * KeyboardHintsProvider. One source of truth for keys and their labels.
1839
- */
1840
- /**
1841
- * Declarative key bindings hook. Replaces `useInput` in input components.
1842
- * Registers hints automatically with the KeyboardHintsProvider.
1843
- *
1844
- * @param id Unique identifier for this component's hints registration
1845
- * @param bindings Array of key binding definitions
1846
- */
1847
- function useKeyBindings(id, bindings) {
1848
- const ctx = useKeyboardHintsContext();
1849
- const hintsRef = useRef("");
1850
- const hints = bindings.map((b) => ({
1851
- label: b.label,
1852
- action: b.action,
1853
- priority: b.priority ?? getDefaultPriority(b.match)
1854
- }));
1855
- const serialized = hints.map((h) => `${h.label}:${h.action}:${h.priority}`).join("|");
1856
- useEffect(() => {
1857
- if (serialized !== hintsRef.current) {
1858
- hintsRef.current = serialized;
1859
- ctx.register(id, hints);
1860
- }
1861
- return () => ctx.unregister(id);
1862
- }, [id, serialized]);
1863
- useInput((input, key) => {
1864
- for (const binding of bindings) if ((Array.isArray(binding.match) ? binding.match : [binding.match]).some((m) => matchesKey(m, input, key))) {
1865
- binding.handler(input, key);
1866
- return;
1867
- }
1868
- });
1869
- }
1870
- //#endregion
1871
- //#region src/ui/tui/primitives/PickerMenu.tsx
1872
- /**
1873
- * PickerMenu — Single and multi select.
1874
- * Single mode: custom renderer with small triangle indicator; enter selects.
1875
- * Multi mode: checkbox glyphs toggled with enter, plus a focusable
1876
- * Confirm button below the options. The cursor moves onto the button and
1877
- * enter submits — see MultiPickerMenu for the rationale.
1878
- *
1879
- * Key bindings are declared via useKeyBindings, which auto-registers
1880
- * hints in the KeyboardHintsBar.
1881
- */
1882
- /**
1883
- * Step through a column's options in `dir`, wrapping, until an enabled
1884
- * option is found. Returns `from` unchanged if the column is entirely
1885
- * disabled.
1886
- */
1887
- function stepEnabled(options, rows, from, dir) {
1888
- const colStart = Math.floor(from / rows) * rows;
1889
- const colLen = Math.min(rows, options.length - colStart);
1890
- let row = from % rows;
1891
- for (let i = 0; i < colLen; i++) {
1892
- row = (row + dir + colLen) % colLen;
1893
- const idx = colStart + row;
1894
- if (!options[idx]?.disabled) return idx;
1895
- }
1896
- return from;
1897
- }
1898
- /** First enabled option in [start, end), for initial focus and for entering
1899
- * a page from the Confirm button. */
1900
- function firstEnabled(options, start = 0, end = options.length) {
1901
- for (let i = start; i < end; i++) if (!options[i]?.disabled) return i;
1902
- return start;
1903
- }
1904
- /** Last enabled option in [start, end), for wrapping from the button onto
1905
- * the bottom of the page. */
1906
- function lastEnabled(options, start = 0, end = options.length) {
1907
- for (let i = end - 1; i >= start; i--) if (!options[i]?.disabled) return i;
1908
- return end - 1;
1909
- }
1910
- /**
1911
- * Rows the surrounding screen or overlay consumes above and below a picker —
1912
- * border + padding, title, prompt text, and the keyboard-hints bar. A
1913
- * deliberately generous estimate: overshooting just shows a few fewer rows,
1914
- * whereas undershooting lets a long list overflow the viewport (the bug this
1915
- * windowing guards against). Mirrors GroupedPickerMenu's budgeting.
1916
- */
1917
- const CHROME_OVERHEAD = 13;
1918
- /**
1919
- * Max visual rows a picker renders regardless of terminal height. Without a
1920
- * ceiling a tall terminal lets a long list fill the whole viewport, which
1921
- * reads as a wall of options; ~12 rows keeps the menu scannable and leaves
1922
- * known breathing room above and below.
1923
- */
1924
- const MAX_LIST_ROWS = 12;
1925
- /** Extra rows a multi-select adds below its options: marginTop + Confirm button. */
1926
- const CONFIRM_CHROME = 3;
1927
- /** Lists shorter than this never page — tall rows would split 2-3 options into pages of one. */
1928
- const MIN_COUNT_TO_PAGE = 5;
1929
- /** Width the multi-select wraps option descriptions to (matches the render). */
1930
- const DESCRIPTION_WIDTH = 56;
1931
- /**
1932
- * Pages a single-column option list to the terminal height. The visible page
1933
- * is derived from the focused index — no scroll state — so ↑/↓ flip pages as
1934
- * focus crosses a page edge and n/p jump a whole page. Pages hold a fixed
1935
- * option count sized to the tallest row (`rowCost`), trading a sparser page
1936
- * on mixed-height lists for arithmetic-only paging. Engages only for
1937
- * single-column pickers — multi-column grids already compress vertically.
1938
- */
1939
- function usePickerViewport(count, rowCost, chromeBelow, enabled, focused) {
1940
- const [, termRows] = useStdoutDimensions();
1941
- const budget = Math.max(5, Math.min(termRows - CHROME_OVERHEAD - chromeBelow, MAX_LIST_ROWS));
1942
- const needsScroll = enabled && count >= MIN_COUNT_TO_PAGE && count * rowCost > budget;
1943
- const perPage = needsScroll ? Math.max(1, Math.floor((budget - 2) / rowCost)) : count;
1944
- const pageCount = Math.max(1, Math.ceil(count / perPage));
1945
- const start = Math.floor(focused / perPage) * perPage;
1946
- const end = Math.min(start + perPage, count);
1947
- return {
1948
- needsScroll,
1949
- start,
1950
- end,
1951
- hiddenAbove: start,
1952
- hiddenBelow: count - end,
1953
- pageStep: (f, dir) => (Math.floor(f / perPage) + dir + pageCount) % pageCount * perPage
1954
- };
1955
- }
1956
- /** Lists at least this long get filtering. Shorter ones fit on a page or two,
1957
- * where a filter row costs more rows than it saves. */
1958
- const FILTER_MIN_OPTIONS = 10;
1959
- const PickerMenu = ({ message, options, mode = "single", centered = false, columns = 1, optionMarginBottom = 0, filterable, onSelect }) => {
1960
- const canFilter = filterable ?? options.length >= FILTER_MIN_OPTIONS;
1961
- const [filter, setFilter] = useState("");
1962
- const fuse = useMemo(() => canFilter ? buildPickerIndex(options) : null, [options, canFilter]);
1963
- const visible = useMemo(() => fuse ? rankOptions(fuse, options, filter) ?? options : options, [
1964
- fuse,
1965
- options,
1966
- filter
1967
- ]);
1968
- const [selected, setSelected] = useState(/* @__PURE__ */ new Set());
1969
- const shared = {
1970
- message,
1971
- options: visible,
1972
- centered,
1973
- optionMarginBottom,
1974
- onSelect,
1975
- filter: canFilter ? filter : null,
1976
- setFilter,
1977
- totalCount: options.length
1978
- };
1979
- const key = String(filter);
1980
- if (mode === "multi") return /* @__PURE__ */ jsx(MultiPickerMenu, {
1981
- ...shared,
1982
- columns,
1983
- allOptions: options,
1984
- selected,
1985
- setSelected
1986
- }, key);
1987
- return /* @__PURE__ */ jsx(SinglePickerMenu, {
1988
- ...shared,
1989
- columns
1990
- }, key);
1991
- };
1992
- /**
1993
- * Backspace and free typing. Append these last: `Printable` matches almost any
1994
- * key, and bindings resolve in order, so anything specific has to be registered
1995
- * first to keep working. Both share a label/action so the hints bar shows one.
1996
- */
1997
- function filterBindings(filter, setFilter) {
1998
- return [{
1999
- match: "backspace",
2000
- label: "type",
2001
- action: "filter",
2002
- handler: () => setFilter(filter.slice(0, -1))
2003
- }, {
2004
- match: "printable",
2005
- label: "type",
2006
- action: "filter",
2007
- handler: (input) => setFilter(filter + input)
2008
- }];
2009
- }
2010
- /** The filter row above a filterable list: what's typed, and how much it left. */
2011
- const FilterRow = ({ filter, shown, total }) => /* @__PURE__ */ jsx(Box, {
2012
- paddingLeft: 1,
2013
- children: /* @__PURE__ */ jsx(Text, {
2014
- dimColor: true,
2015
- children: filter ? `Filter: ${filter} (${shown} of ${total})` : `Type to filter ${total} options`
2016
- })
2017
- });
2018
- /** Custom single-select with triangle indicator and accent highlight. */
2019
- const SinglePickerMenu = ({ message, options, centered = false, columns = 1, optionMarginBottom = 0, filter, setFilter, totalCount, onSelect }) => {
2020
- const [focused, setFocused] = useState(() => firstEnabled(options));
2021
- const rows = Math.ceil(options.length / columns);
2022
- const viewport = usePickerViewport(options.length, 1 + optionMarginBottom, filter !== null ? 1 : 0, columns === 1, focused);
2023
- useEffect(() => {
2024
- if (focused >= options.length || options[focused]?.disabled) setFocused(firstEnabled(options));
2025
- }, [options, focused]);
2026
- const bindings = [
2027
- {
2028
- match: ["upArrow", "downArrow"],
2029
- label: "↑↓",
2030
- action: "navigate",
2031
- handler: (_input, key) => {
2032
- setFocused(stepEnabled(options, rows, focused, key.upArrow ? -1 : 1));
2033
- }
2034
- },
2035
- ...viewport.needsScroll && filter === null ? [{
2036
- match: ["n", "p"],
2037
- label: "n/p",
2038
- action: "page",
2039
- handler: (input) => {
2040
- const target = viewport.pageStep(focused, input === "n" ? 1 : -1);
2041
- setFocused(options[target]?.disabled ? stepEnabled(options, rows, target, 1) : target);
2042
- }
2043
- }] : [],
2044
- {
2045
- match: "return",
2046
- label: "enter",
2047
- action: "select",
2048
- handler: () => {
2049
- const selected = options[focused];
2050
- if (selected && !selected.disabled) onSelect(selected.value);
2051
- }
2052
- }
2053
- ];
2054
- if (columns > 1) bindings.splice(1, 0, {
2055
- match: ["leftArrow", "rightArrow"],
2056
- label: "←→",
2057
- action: "navigate",
2058
- handler: (_input, key) => {
2059
- const col = Math.floor(focused / rows);
2060
- const row = focused % rows;
2061
- let next = focused;
2062
- if (key.leftArrow) {
2063
- const prevCol = col > 0 ? col - 1 : columns - 1;
2064
- next = Math.min(prevCol * rows + row, options.length - 1);
2065
- }
2066
- if (key.rightArrow) {
2067
- const nextCol = col < columns - 1 ? col + 1 : 0;
2068
- next = Math.min(nextCol * rows + row, options.length - 1);
2069
- }
2070
- if (options[next]?.disabled) next = stepEnabled(options, rows, next, 1);
2071
- setFocused(next);
2072
- }
2073
- });
2074
- if (filter !== null) bindings.push(...filterBindings(filter, setFilter));
2075
- useKeyBindings("single-picker", bindings);
2076
- const columnArrays = [];
2077
- for (let c = 0; c < columns; c++) columnArrays.push(options.slice(c * rows, c * rows + rows));
2078
- const align = centered ? "center" : void 0;
2079
- const renderOption = (opt, flatIdx) => {
2080
- const isFocused = flatIdx === focused;
2081
- const base = opt.hint ? `${opt.label} (${opt.hint})` : opt.label;
2082
- const label = opt.indent ? ` ${base}` : base;
2083
- return /* @__PURE__ */ jsxs(Box, {
2084
- gap: 1,
2085
- marginBottom: optionMarginBottom,
2086
- children: [
2087
- /* @__PURE__ */ jsx(Text, {
2088
- color: isFocused ? Colors.accent : void 0,
2089
- dimColor: !isFocused,
2090
- children: isFocused && !opt.header ? Icons.triangleSmallRight : " "
2091
- }),
2092
- opt.icon && /* @__PURE__ */ jsx(Text, {
2093
- color: opt.icon.color,
2094
- children: opt.icon.glyph
2095
- }),
2096
- /* @__PURE__ */ jsx(Text, {
2097
- color: opt.header ? void 0 : opt.disabled ? Colors.muted : isFocused ? Colors.accent : void 0,
2098
- bold: opt.header || isFocused && !opt.disabled,
2099
- dimColor: !opt.header && (!isFocused || opt.disabled),
2100
- children: label
2101
- })
2102
- ]
2103
- }, flatIdx);
2104
- };
2105
- return /* @__PURE__ */ jsxs(Box, {
2106
- flexDirection: "column",
2107
- alignItems: align,
2108
- children: [
2109
- /* @__PURE__ */ jsx(PromptLabel, { message }),
2110
- filter !== null && /* @__PURE__ */ jsx(FilterRow, {
2111
- filter,
2112
- shown: options.length,
2113
- total: totalCount
2114
- }),
2115
- filter && options.length === 0 ? /* @__PURE__ */ jsx(Text, {
2116
- dimColor: true,
2117
- children: "No options match. Backspace to widen the filter."
2118
- }) : viewport.needsScroll ? /* @__PURE__ */ jsxs(Box, {
2119
- flexDirection: "column",
2120
- children: [
2121
- /* @__PURE__ */ jsx(Text, {
2122
- dimColor: true,
2123
- children: viewport.hiddenAbove > 0 ? `↑ ${viewport.hiddenAbove} more${filter === null ? " [P] for previous page" : ""}` : " "
2124
- }),
2125
- options.slice(viewport.start, viewport.end).map((opt, relIdx) => renderOption(opt, viewport.start + relIdx)),
2126
- /* @__PURE__ */ jsx(Text, {
2127
- dimColor: true,
2128
- children: viewport.hiddenBelow > 0 ? `↓ ${viewport.hiddenBelow} more${filter === null ? " [N] for next page" : ""}` : " "
2129
- })
2130
- ]
2131
- }) : /* @__PURE__ */ jsx(Box, {
2132
- flexDirection: "row",
2133
- gap: 4,
2134
- children: columnArrays.map((colOpts, colIdx) => /* @__PURE__ */ jsx(Box, {
2135
- flexDirection: "column",
2136
- children: colOpts.map((opt, rowIdx) => renderOption(opt, colIdx * rows + rowIdx))
2137
- }, colIdx))
2138
- })
2139
- ]
2140
- });
2141
- };
2142
- /**
2143
- * Custom multi-select with checkbox glyphs and accent highlight.
2144
- *
2145
- * Interaction model (shared with GroupedPickerMenu):
2146
- * - \u2191\u2193 move the cursor through the options AND onto the Confirm button,
2147
- * which lives just past the last option.
2148
- * - enter toggles the focused option (no more "space toggles but enter
2149
- * advances" split that tripped people up). Space is kept as an
2150
- * undocumented alias, but the hints bar advertises only enter.
2151
- * - moving onto the Confirm button and pressing enter submits the
2152
- * current selection.
2153
- */
2154
- const MultiPickerMenu = ({ message, options, centered = false, columns = 1, optionMarginBottom = 0, filter, setFilter, totalCount, allOptions, selected, setSelected, onSelect }) => {
2155
- const [focused, setFocused] = useState(() => firstEnabled(options));
2156
- const [onButton, setOnButton] = useState(false);
2157
- const rows = Math.ceil(options.length / columns);
2158
- const rowCost = options.reduce((max, opt) => Math.max(max, 1 + optionMarginBottom + (opt.description ? wordWrap(opt.description, DESCRIPTION_WIDTH).length : 0)), 1);
2159
- const viewport = usePickerViewport(options.length, rowCost, CONFIRM_CHROME + (filter !== null ? 1 : 0), columns === 1, focused);
2160
- useEffect(() => {
2161
- if (focused >= options.length || options[focused]?.disabled) setFocused(firstEnabled(options));
2162
- }, [options, focused]);
2163
- const confirm = () => {
2164
- onSelect(allOptions.filter((option) => selected.has(option.label)).map((option) => option.value));
2165
- };
2166
- const bindings = [
2167
- {
2168
- match: ["upArrow", "downArrow"],
2169
- label: "↑↓",
2170
- action: "navigate",
2171
- handler: (_input, key) => {
2172
- const dir = key.upArrow ? -1 : 1;
2173
- if (onButton) {
2174
- setOnButton(false);
2175
- setFocused(dir === -1 ? lastEnabled(options, viewport.start, viewport.end) : firstEnabled(options, viewport.start, viewport.end));
2176
- return;
2177
- }
2178
- const col = Math.floor(focused / rows);
2179
- const row = focused % rows;
2180
- const colLen = Math.min(rows, options.length - col * rows);
2181
- let r = row + dir;
2182
- while (r >= 0 && r < colLen && options[col * rows + r]?.disabled) r += dir;
2183
- if (r >= 0 && r < colLen) setFocused(col * rows + r);
2184
- else setOnButton(true);
2185
- }
2186
- },
2187
- ...viewport.needsScroll && filter === null ? [{
2188
- match: ["n", "p"],
2189
- label: "n/p",
2190
- action: "page",
2191
- handler: (input) => {
2192
- const target = viewport.pageStep(focused, input === "n" ? 1 : -1);
2193
- setOnButton(false);
2194
- setFocused(options[target]?.disabled ? stepEnabled(options, rows, target, 1) : target);
2195
- }
2196
- }] : [],
2197
- {
2198
- match: filter !== null ? "return" : ["space", "return"],
2199
- label: "enter",
2200
- action: "select",
2201
- handler: () => {
2202
- if (onButton) {
2203
- confirm();
2204
- return;
2205
- }
2206
- const option = options[focused];
2207
- if (!option || option.disabled) return;
2208
- const label = option.label;
2209
- setSelected((prev) => {
2210
- const next = new Set(prev);
2211
- if (next.has(label)) {
2212
- next.delete(label);
2213
- return next;
2214
- }
2215
- if (option.exclusive) return new Set([label]);
2216
- for (const picked of next) if (allOptions.find((o) => o.label === picked)?.exclusive) next.delete(picked);
2217
- next.add(label);
2218
- return next;
2219
- });
2220
- }
2221
- }
2222
- ];
2223
- if (columns > 1) bindings.splice(1, 0, {
2224
- match: ["leftArrow", "rightArrow"],
2225
- label: "←→",
2226
- action: "navigate",
2227
- handler: (_input, key) => {
2228
- if (onButton) return;
2229
- const col = Math.floor(focused / rows);
2230
- const row = focused % rows;
2231
- let next = focused;
2232
- if (key.leftArrow) {
2233
- const prevCol = col > 0 ? col - 1 : columns - 1;
2234
- next = Math.min(prevCol * rows + row, options.length - 1);
2235
- }
2236
- if (key.rightArrow) {
2237
- const nextCol = col < columns - 1 ? col + 1 : 0;
2238
- next = Math.min(nextCol * rows + row, options.length - 1);
2239
- }
2240
- if (options[next]?.disabled) next = stepEnabled(options, rows, next, 1);
2241
- setFocused(next);
2242
- }
2243
- });
2244
- if (filter !== null) bindings.push(...filterBindings(filter, setFilter));
2245
- useKeyBindings("multi-picker", bindings);
2246
- const columnArrays = [];
2247
- for (let c = 0; c < columns; c++) columnArrays.push(options.slice(c * rows, c * rows + rows));
2248
- const renderOption = (opt, flatIdx) => {
2249
- const isFocused = !onButton && flatIdx === focused;
2250
- const isSelected = selected.has(opt.label);
2251
- const label = opt.hint ? `${opt.label} (${opt.hint})` : opt.label;
2252
- const checkbox = isSelected ? Icons.squareFilled : Icons.squareOpen;
2253
- return /* @__PURE__ */ jsxs(Box, {
2254
- flexDirection: "column",
2255
- marginBottom: optionMarginBottom,
2256
- children: [/* @__PURE__ */ jsxs(Box, {
2257
- gap: 1,
2258
- children: [
2259
- /* @__PURE__ */ jsx(Text, {
2260
- color: isSelected ? "white" : Colors.muted,
2261
- dimColor: !isFocused && !isSelected,
2262
- children: checkbox
2263
- }),
2264
- opt.icon && /* @__PURE__ */ jsx(Text, {
2265
- color: opt.icon.color,
2266
- children: opt.icon.glyph
2267
- }),
2268
- /* @__PURE__ */ jsx(Text, {
2269
- color: opt.disabled ? Colors.muted : isFocused ? Colors.accent : void 0,
2270
- bold: isFocused && !opt.disabled,
2271
- dimColor: !isFocused || opt.disabled,
2272
- children: label
2273
- })
2274
- ]
2275
- }), opt.description && /* @__PURE__ */ jsx(Box, {
2276
- marginLeft: 4,
2277
- width: DESCRIPTION_WIDTH,
2278
- children: /* @__PURE__ */ jsx(Text, {
2279
- dimColor: true,
2280
- wrap: "wrap",
2281
- children: opt.description
2282
- })
2283
- })]
2284
- }, flatIdx);
2285
- };
2286
- return /* @__PURE__ */ jsxs(Box, {
2287
- flexDirection: "column",
2288
- alignItems: centered ? "center" : void 0,
2289
- children: [
2290
- /* @__PURE__ */ jsx(PromptLabel, { message }),
2291
- filter !== null && /* @__PURE__ */ jsx(FilterRow, {
2292
- filter,
2293
- shown: options.length,
2294
- total: totalCount
2295
- }),
2296
- filter && options.length === 0 && /* @__PURE__ */ jsx(Text, {
2297
- dimColor: true,
2298
- children: "No options match. Backspace to widen the filter."
2299
- }),
2300
- viewport.needsScroll ? /* @__PURE__ */ jsxs(Box, {
2301
- flexDirection: "column",
2302
- marginLeft: centered ? 0 : 2,
2303
- marginTop: message ? 1 : 0,
2304
- children: [
2305
- /* @__PURE__ */ jsx(Text, {
2306
- dimColor: true,
2307
- children: viewport.hiddenAbove > 0 ? `↑ ${viewport.hiddenAbove} more${filter === null ? " [P] for previous page" : ""}` : " "
2308
- }),
2309
- options.slice(viewport.start, viewport.end).map((opt, relIdx) => renderOption(opt, viewport.start + relIdx)),
2310
- /* @__PURE__ */ jsx(Text, {
2311
- dimColor: true,
2312
- children: viewport.hiddenBelow > 0 ? `↓ ${viewport.hiddenBelow} more${filter === null ? " [N] for next page" : ""}` : " "
2313
- })
2314
- ]
2315
- }) : /* @__PURE__ */ jsx(Box, {
2316
- flexDirection: "row",
2317
- gap: 4,
2318
- marginLeft: centered ? 0 : 2,
2319
- marginTop: message ? 1 : 0,
2320
- children: columnArrays.map((colOpts, colIdx) => /* @__PURE__ */ jsx(Box, {
2321
- flexDirection: "column",
2322
- children: colOpts.map((opt, rowIdx) => renderOption(opt, colIdx * rows + rowIdx))
2323
- }, colIdx))
2324
- }),
2325
- /* @__PURE__ */ jsx(Box, {
2326
- marginTop: 1,
2327
- marginLeft: centered ? 0 : 2,
2328
- children: /* @__PURE__ */ jsx(ConfirmButton, {
2329
- focused: onButton,
2330
- count: selected.size
2331
- })
2332
- })
2333
- ]
2334
- });
2335
- };
2336
- //#endregion
2337
- //#region src/commands/factories/family-picker.tsx
2338
- function FamilyPickerApp(props) {
2339
- return createElement(Box, {
2340
- flexDirection: "column",
2341
- paddingX: 1,
2342
- paddingY: 1
2343
- }, createElement(Text, {
2344
- bold: true,
2345
- color: Colors.accent
2346
- }, props.parentLabel), createElement(Box, { height: 1 }), createElement(PickerMenu, {
2347
- message: "Pick a subcommand",
2348
- options: props.options,
2349
- optionMarginBottom: 1,
2350
- onSelect: (value) => {
2351
- const cmd = Array.isArray(value) ? value[0] : value;
2352
- if (cmd) props.onSelect(cmd);
2353
- }
2354
- }));
2355
- }
2356
- function describe(child) {
2357
- return commandKeys(child.name)[0] ?? "";
2358
- }
2359
- /**
2360
- * Reorder children so the `default`-marked entry is first, while
2361
- * preserving the relative order of the rest. The picker's initial
2362
- * focus is index 0, so this is what makes "press Enter on
2363
- * `wizard audit`" run the default leaf (today `audit events`).
2364
- *
2365
- * Exported for testability — the ordering logic stays pure and
2366
- * inspectable without mounting Ink.
2367
- */
2368
- function orderFamilyChildren(children) {
2369
- const selectable = children.filter((c) => c.handler || c.children?.length);
2370
- const defaults = selectable.filter((c) => c.default);
2371
- const rest = selectable.filter((c) => !c.default);
2372
- return [...defaults, ...rest];
2373
- }
2374
- /**
2375
- * Render the picker. Resolves once the user has selected a child;
2376
- * dispatching the child's handler is the caller's responsibility (so this
2377
- * function stays pure-UI and easy to test by stubbing `render`).
2378
- */
2379
- function chooseFamilyChild(parentLabel, children) {
2380
- const ordered = orderFamilyChildren(children);
2381
- if (ordered.length === 0) return Promise.resolve(null);
2382
- const options = ordered.map((child) => ({
2383
- label: describe(child),
2384
- value: child,
2385
- hint: child.description
2386
- }));
2387
- return new Promise((resolve) => {
2388
- let app = null;
2389
- const handleSelect = (cmd) => {
2390
- app?.unmount();
2391
- resolve(cmd);
2392
- };
2393
- app = render(createElement(FamilyPickerApp, {
2394
- parentLabel,
2395
- options,
2396
- onSelect: handleSelect
2397
- }));
2398
- });
2399
- }
2400
- /**
2401
- * Returns an `interactiveDefault` handler for a family parent's no-leaf
2402
- * invocation. Always opens the picker; the `default`-marked child is
2403
- * shown first (pre-highlighted), so a single Enter keystroke runs it.
2404
- *
2405
- * Discovery + consent in one extra keystroke vs. auto-running silently.
2406
- *
2407
- * Wire onto a family parent:
2408
- * export const auditCommand: Command = {
2409
- * name: 'audit',
2410
- * description: '...',
2411
- * children: [...],
2412
- * interactiveDefault: createFamilyPickerDefault('audit', auditChildren),
2413
- * };
2414
- */
2415
- function createFamilyPickerDefault(parentLabel, children, chooser = chooseFamilyChild) {
2416
- return async (argv) => {
2417
- const chosen = await chooser(parentLabel, children);
2418
- if (!chosen) return;
2419
- await Promise.resolve(chosen.handler?.(argv));
2420
- };
2421
- }
2422
- //#endregion
2423
- //#region src/commands/factories/family-command-factory.ts
2424
- /**
2425
- * Build a yargs `Command` for a family parent (`wizard audit`, etc.).
2426
- *
2427
- * - `wizard <family> <sub>` — `dispatchFamily` resolves `<sub>` against
2428
- * native handlers first, then the live `cliEntries` from
2429
- * `skill-menu.json`. Unknown subs error with the available list.
2430
- * - `wizard <family>` (no positional) — in an interactive terminal, runs the
2431
- * family's single shown entry directly (today `audit events`, so the user
2432
- * lands on its intro screen); opens the picker once a family shows more than
2433
- * one. In non-TTY/CI, falls through to `dispatchFamily`, which prints
2434
- * "requires a subcommand" rather than running something unprompted.
2435
- *
2436
- * No static yargs children. New skill-backed subcommands appear after a
2437
- * context-mill release without a wizard release. New *native* subcommands
2438
- * (rare) are added by updating `NATIVE_HANDLERS` in `dispatch-family.ts`.
2439
- */
2440
- function familyCommandFactory({ family, description, optionsFrom }) {
2441
- const openFamilyEntry = async (argv) => {
2442
- const toShow = pickerChildrenToShow(buildFamilyPickerChildren(family, (await fetchSkillMenu(getSkillsBaseUrl()))?.cliEntries ?? []));
2443
- if (toShow.length === 1 && toShow[0]?.handler) {
2444
- await Promise.resolve(toShow[0].handler(argv));
2445
- return;
2446
- }
2447
- await createFamilyPickerDefault(`wizard ${family}`, toShow)(argv);
2448
- };
2449
- return {
2450
- name: `${family} [skill]`,
2451
- description,
2452
- options: mergeCommandOptions(optionsFrom),
2453
- positionals: { skill: {
2454
- type: "string",
2455
- describe: "Subcommand to run (omit to run the default)"
2456
- } },
2457
- handler: (argv) => {
2458
- const sub = argv.skill?.trim();
2459
- runCommandHandler(() => sub || !process.stdout.isTTY ? dispatchFamily(family, argv) : openFamilyEntry(argv));
2460
- },
2461
- interactiveDefault: openFamilyEntry
2462
- };
2463
- }
2464
- //#endregion
2465
- //#region src/commands/audit.ts
2466
- /**
2467
- * The `wizard audit` family.
2468
- *
2469
- * Subcommands are resolved at runtime: the wizard fetches `cliEntries` from
2470
- * `skill-menu.json` and dispatches based on `parentCommand: 'audit'`. The
2471
- * wizard-native handler for `web-analytics` lives in `NATIVE_HANDLERS` over
2472
- * in `dispatch-family.ts`. `wizard audit` with no positional opens the
2473
- * family picker, which combines native + live entries.
2474
- *
2475
- * Adding a new skill-backed audit subcommand is a context-mill release —
2476
- * no wizard release needed.
2477
- */
2478
- const auditCommand = familyCommandFactory({
2479
- family: "audit",
2480
- description: auditConfig.description,
2481
- optionsFrom: auditConfig
2482
- });
2483
- //#endregion
2484
- //#region src/commands/doctor.ts
2485
- const doctorCommand = {
2486
- name: "doctor",
2487
- description: posthogDoctorConfig.description,
2488
- options: {
2489
- ...skillProgramOptions,
2490
- ...posthogDoctorConfig.cliOptions ?? {}
2491
- },
2492
- handler: (argv) => {
2493
- const extras = posthogDoctorConfig.mapCliOptions?.(argv) ?? {};
2494
- const options = {
2495
- ...argv,
2496
- ...extras
2497
- };
2498
- if (options.ci) runDoctorCI(options);
2499
- else runWizard(posthogDoctorConfig, options);
2500
- }
2501
- };
2502
- const SEVERITY_ORDER = {
2503
- critical: 0,
2504
- warning: 1,
2505
- info: 2
2506
- };
2507
- async function runDoctorCI(options) {
2508
- setUI(new LoggingUI());
2509
- const apiKey = options.apiKey ?? readApiKeyFromEnv() ?? void 0;
2510
- if (!apiKey) {
2511
- getUI().intro("PostHog Wizard");
2512
- getUI().log.error("CI mode requires --api-key (personal API key phx_xxx)");
2513
- emitWizardError({
2514
- code: ErrorCodes.ArgsMissingApiKey,
2515
- message: "CI mode requires --api-key (personal API key phx_xxx)"
2516
- });
2517
- process.exit(1);
2518
- }
2519
- getUI().intro("Welcome to the PostHog setup wizard");
2520
- getUI().log.info("Running posthog-doctor in CI mode");
2521
- try {
2522
- const { getOrAskForProjectData } = await import("./setup-utils-dCViCC6s.js").then((n) => n.r);
2523
- const { host, accessToken, projectId } = await getOrAskForProjectData({
2524
- signup: false,
2525
- ci: true,
2526
- apiKey,
2527
- projectId: options.projectId ? Number(options.projectId) : void 0,
2528
- baseUrl: options.baseUrl
2529
- });
2530
- const issues = await fetchHealthIssues(accessToken, host.apiHost, projectId);
2531
- if (issues.length === 0) {
2532
- getUI().log.success("No active issues — your project looks healthy.");
2533
- process.exit(0);
2534
- }
2535
- const sorted = [...issues].sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
2536
- getUI().log.warn(`${issues.length} active issue${issues.length === 1 ? "" : "s"} found:`);
2537
- for (const issue of sorted) getUI().log.info(` • [${issue.severity}] ${getKindMeta(issue.kind).title}`);
2538
- process.exit(1);
2539
- } catch (error) {
2540
- const { ApiError } = await import("./api-DGuJTzjr.js").then((n) => n.n);
2541
- const message = error instanceof ApiError && error.statusCode === 401 ? "Your PostHog API key is invalid or expired." : error instanceof Error ? error.message : String(error);
2542
- getUI().log.error(`Doctor failed: ${message}`);
2543
- emitWizardError({
2544
- code: error instanceof ApiError && error.statusCode === 401 ? ErrorCodes.AuthInvalidOrExpired : ErrorCodes.InternalUnhandled,
2545
- message
2546
- });
2547
- process.exit(1);
2548
- }
2549
- }
2550
- //#endregion
2551
- //#region src/commands/migrate.ts
2552
- /**
2553
- * `wizard migrate` — flat skill command, Statsig today.
2554
- *
2555
- * Stays flat while there's only one vendor. When a second vendor lands,
2556
- * restructure into a family with `familyCommandFactory` and publish each
2557
- * vendor as a `cliEntries` entry with `parentCommand: 'migrate'` from
2558
- * context-mill. That move is a deliberate breaking change for users
2559
- * (`wizard migrate` stops running Statsig directly), so do it explicitly
2560
- * when the second vendor arrives, not pre-emptively.
2561
- */
2562
- const migrateCommand = nativeCommandFactory(migrationConfig);
2563
- //#endregion
2564
- //#region src/commands/revenue.ts
2565
- /**
2566
- * `wizard revenue-analytics` — flat skill command, Stripe today.
2567
- *
2568
- * Stays flat while there's only one provider. Restructure into a family
2569
- * if/when a second provider lands.
2570
- */
2571
- const revenueCommand = nativeCommandFactory(revenueAnalyticsConfig);
2572
- //#endregion
2573
- //#region src/commands/warehouse.ts
2574
- /**
2575
- * `wizard warehouse` — detect and connect a data warehouse source.
2576
- *
2577
- * Mirrors `revenue-analytics`: flat skill command driven by the
2578
- * warehouse-source program.
2579
- */
2580
- const warehouseCommand = nativeCommandFactory(warehouseSourceConfig);
2581
- //#endregion
2582
- //#region src/commands/self-driving.ts
2583
- const selfDrivingCommand = {
2584
- name: "self-driving",
2585
- description: selfDrivingConfig.description,
2586
- options: {
2587
- ...skillProgramOptions,
2588
- integrate: {
2589
- describe: "Integrate the PostHog SDK first, then set up Self-driving — skips the integration prompt and logs you in via OAuth (no \"create an account?\" question). Use when the project isn't set up yet but you already have a PostHog account.",
2590
- type: "boolean",
2591
- default: false
2592
- },
2593
- ...selfDrivingConfig.cliOptions ?? {}
2594
- },
2595
- check: (argv) => {
2596
- if (argv.signup) throw new Error("`self-driving` cannot run with --signup. Just run `wizard self-driving`: when your project has no PostHog, it asks whether you already have an account and offers to create one for you (no flag needed).");
2597
- if (argv.ci) throw new Error("`self-driving` cannot run in CI mode — it requires interactive steps (GitHub connect, issue-tracker selection, custom-scout approval).");
2598
- return true;
2599
- },
2600
- handler: (argv) => {
2601
- const extras = selfDrivingConfig.mapCliOptions?.(argv) ?? {};
2602
- const options = {
2603
- ...argv,
2604
- ...extras
2605
- };
2606
- if (options.ci) runWizardCI(selfDrivingConfig, options);
2607
- else runWizard(selfDrivingConfig, options);
2608
- }
2609
- };
2610
- //#endregion
2611
- //#region src/commands/slack.ts
2612
- const slackCommand = {
2613
- name: "slack",
2614
- description: "Connect PostHog to your Slack",
2615
- handler: runSlackConnect,
2616
- children: [{
2617
- name: "add",
2618
- description: "Connect PostHog to your Slack",
2619
- handler: runSlackConnect
2620
- }]
2621
- };
2622
- function runSlackConnect(argv) {
2623
- (async () => {
2624
- const debug = argv.debug;
2625
- try {
2626
- const { startTUI } = await import("./start-tui-oCWMgsDP.js");
2627
- const { buildSession } = await import("./wizard-session-DGaUHOF3.js");
2628
- const tui = startTUI(VERSION, Program.SlackConnect);
2629
- tui.store.session = buildSession({
2630
- debug,
2631
- baseUrl: argv.baseUrl
2632
- });
2633
- } catch (err) {
2634
- setUI(new LoggingUI());
2635
- getUI().log.error(`Connecting Slack requires an interactive terminal. ${err instanceof Error ? err.message : String(err)}`);
2636
- emitWizardError({
2637
- code: ErrorCodes.CliInteractiveRequired,
2638
- message: "Connecting Slack requires an interactive terminal."
2639
- });
2640
- process.exit(1);
2641
- }
2642
- })();
2643
- }
2644
- //#endregion
2645
- //#region src/commands/upload-sourcemaps.ts
2646
- const uploadSourcemapsCommand = {
2647
- name: [errorTrackingUploadSourceMapsConfig.command, "upload-sourcemaps"],
2648
- description: errorTrackingUploadSourceMapsConfig.description,
2649
- options: {
2650
- ...skillProgramOptions,
2651
- ...errorTrackingUploadSourceMapsConfig.cliOptions ?? {}
2652
- },
2653
- handler: (argv) => {
2654
- const extras = errorTrackingUploadSourceMapsConfig.mapCliOptions?.(argv) ?? {};
2655
- const options = {
2656
- ...argv,
2657
- ...extras
2658
- };
2659
- if (options.ci) runWizardCI(errorTrackingUploadSourceMapsConfig, options);
2660
- else runWizard(errorTrackingUploadSourceMapsConfig, options);
2661
- }
2662
- };
2663
- //#endregion
2664
- //#region src/commands/error-tracking.ts
2665
- /**
2666
- * `wizard error-tracking` — flat skill command, set up error tracking today.
2667
- *
2668
- * Wires up exception capture and — where the platform needs it — source-map /
2669
- * debug-symbol upload. Runs the `error-tracking` orchestrator flow, which
2670
- * reuses the integration-v2 install/init mini-agents when the repo has no
2671
- * PostHog integration yet, so it works on uninstrumented projects too.
2672
- */
2673
- const errorTrackingCommand = nativeCommandFactory(errorTrackingConfig);
2674
- //#endregion
2675
- //#region src/commands/basic-integration/skill.ts
2676
- /** Run an arbitrary context-mill skill by id (`wizard skill <id>`, headless with `--ci`). */
2677
- function runSkillMode(argv) {
2678
- const skillId = argv.skill;
2679
- const config = createSkillProgram({
2680
- skillId,
2681
- command: "skill",
2682
- id: "agent-skill",
2683
- description: `Run skill: ${skillId}`,
2684
- integrationLabel: skillId,
2685
- successMessage: `${skillId} completed!`,
2686
- reportFile: `posthog-${skillId}-report.md`,
2687
- docsUrl: POSTHOG_DOCS_URL,
2688
- spinnerMessage: `Running ${skillId}...`,
2689
- estimatedDurationMinutes: 5
2690
- });
2691
- const options = {
2692
- ...argv,
2693
- skillId
2694
- };
2695
- if (argv.ci) runWizardCI(config, options);
2696
- else runWizard(config, options);
2697
- }
2698
- //#endregion
2699
- //#region src/commands/skill.ts
2700
- /** Read the `<skill-name>` positional (yargs camelCases the hyphenated key). */
2701
- function readSkillName(argv) {
2702
- return String(argv.skillName ?? argv["skill-name"] ?? "").trim();
2703
- }
2704
- const BROWSABLE_ROLES = new Set(["command", "skill"]);
2705
- /**
2706
- * Reject an unknown skill id before the wizard authenticates.
2707
- *
2708
- * Without this, `readSkillName` accepts any non-empty string and the name is
2709
- * only validated far downstream, when the agent tries to download it — after
2710
- * the user has already logged in. A typo then costs a full auth round-trip
2711
- * (the concern raised in review). We resolve against the same set
2712
- * `downloadSkill` uses (`categories` flattened by `id`), so this never
2713
- * false-rejects a skill the download would have accepted.
2714
- *
2715
- * If the registry is unreachable we stay silent and defer to the download
2716
- * step's own `menu-fetch-failed` handling, rather than adding a second network
2717
- * dependency that could block an otherwise-valid run.
2718
- */
2719
- async function assertSkillExists(skillName) {
2720
- const skillsBaseUrl = getSkillsBaseUrl();
2721
- const menu = await fetchSkillMenu(skillsBaseUrl);
2722
- if (!menu) return;
2723
- if (Object.values(menu.categories).flat().some((s) => s.id === skillName)) return;
2724
- analytics.wizardCapture("cli dispatch error", {
2725
- reason: "unknown skill",
2726
- family: "skill",
2727
- sub: skillName,
2728
- skillsBaseUrl
2729
- });
2730
- try {
2731
- await analytics.flush();
2732
- } catch {}
2733
- throw new Error(`Unknown skill "${skillName}". Run \`wizard skill list\` to see available skills.`);
2734
- }
2735
- function formatEntry(entry) {
2736
- const path = entry.parentCommand ? `wizard ${entry.parentCommand} ${entry.command}` : entry.command ? `wizard ${entry.command}` : `wizard skill ${entry.skillId}`;
2737
- return ` ${entry.skillId.padEnd(38)} ${path.padEnd(36)} ${entry.description}`;
2738
- }
2739
- /**
2740
- * `wizard skill <skill-name>` — run a single context-mill skill by id.
2741
- * `wizard skill list` — list every browsable skill in the catalog.
2742
- *
2743
- * Replaces the old `--skill=<id>` flag on the default command. The skill id
2744
- * is fetched from context-mill's release at runtime (same mechanism the flag
2745
- * used), so any published skill id works. Pass `--ci` to run headlessly.
2746
- */
2747
- const skillCommand = {
2748
- name: "skill <skill-name>",
2749
- description: "Run a specific context-mill skill by name (or `list` them)",
2750
- children: [{
2751
- name: "list",
2752
- description: "List every browsable skill in the catalog",
2753
- handler: () => {
2754
- runCommandHandler(async () => {
2755
- const skillsBaseUrl = getSkillsBaseUrl();
2756
- const menu = await fetchSkillMenu(skillsBaseUrl);
2757
- if (!menu) {
2758
- analytics.wizardCapture("cli dispatch error", {
2759
- reason: "registry unreachable",
2760
- family: "skill",
2761
- sub: "list",
2762
- skillsBaseUrl
2763
- });
2764
- try {
2765
- await analytics.flush();
2766
- } catch {}
2767
- process.stderr.write("\n\x1B[1;91m✖ Couldn't reach the skill registry.\x1B[0m\n Check your network connection and try again.\n\n");
2768
- emitWizardError({
2769
- code: ErrorCodes.SkillMenuFetchFailed,
2770
- message: "Couldn't reach the skill registry."
2771
- });
2772
- process.exit(1);
2773
- }
2774
- const entries = (menu.cliEntries ?? []).filter((e) => BROWSABLE_ROLES.has(e.role));
2775
- if (entries.length === 0) {
2776
- process.stdout.write("No skills found.\n");
2777
- return;
2778
- }
2779
- process.stdout.write(`${entries.length} skill${entries.length === 1 ? "" : "s"}:\n`);
2780
- process.stdout.write(` ${"SKILL ID".padEnd(38)} ${"COMMAND".padEnd(36)} DESCRIPTION\n`);
2781
- for (const entry of entries) process.stdout.write(`${formatEntry(entry)}\n`);
2782
- });
2783
- }
2784
- }],
2785
- options: { ...skillProgramOptions },
2786
- positionals: { "skill-name": {
2787
- type: "string",
2788
- describe: "Skill id to run (e.g. audit-events), or `list`"
2789
- } },
2790
- check: (argv) => {
2791
- if (argv.skillName == null && argv["skill-name"] == null) return true;
2792
- if (!readSkillName(argv)) throw new Error("skill needs a skill name, e.g. `wizard skill audit-events`");
2793
- return true;
2794
- },
2795
- handler: (argv) => {
2796
- runCommandHandler(async () => {
2797
- const skillName = readSkillName(argv);
2798
- await assertSkillExists(skillName);
2799
- runSkillMode({
2800
- ...argv,
2801
- skill: skillName
2802
- });
2803
- });
2804
- }
2805
- };
2806
- //#endregion
2807
- //#region src/commands/cli/add.ts
2808
- const cliAddCommand = {
2809
- name: "add",
2810
- description: "Install or update PostHog CLI and add steering instructions to your coding agent's global instructions file",
2811
- options: {
2812
- agent: {
2813
- describe: "Agent to install the instructions for",
2814
- choices: CLI_STEERING_TARGETS.map((target) => target.id),
2815
- type: "string"
2816
- },
2817
- path: {
2818
- describe: "Write to an explicit instructions file instead of a detected agent",
2819
- type: "string"
2820
- },
2821
- all: {
2822
- default: false,
2823
- describe: "Install for every detected agent without prompting",
2824
- type: "boolean"
2825
- }
2826
- },
2827
- examples: [
2828
- ["wizard cli add", "Detect your coding agents and pick one"],
2829
- ["wizard cli add --agent claude-code", "Install for Claude Code (~/.claude/CLAUDE.md)"],
2830
- ["wizard cli add --all", "Install for every detected agent"],
2831
- ["wizard cli add --path ./AGENTS.md", "Install into a specific instructions file"]
2832
- ],
2833
- check: (argv) => {
2834
- if (argv.all && (argv.agent || argv.path)) throw new Error("--all cannot be combined with --agent or --path");
2835
- return true;
2836
- },
2837
- handler: (argv) => {
2838
- runCliAdd(argv);
2839
- }
2840
- };
2841
- async function runCliAdd(argv) {
2842
- setUI(new LoggingUI());
2843
- const ui = getUI();
2844
- ui.intro("PostHog CLI setup");
2845
- const files = await resolveTargetFiles(argv);
2846
- if (files.length === 0) {
2847
- process.exit(1);
2848
- return;
2849
- }
2850
- ui.log.info("Installing or updating PostHog CLI...");
2851
- const cliInstallResult = installOrUpdatePostHogCli();
2852
- if (!cliInstallResult.success) {
2853
- ui.log.error(`Failed to install or update PostHog CLI: ${cliInstallResult.error ?? ""}`);
2854
- analytics.wizardCapture("cli steering installed", {
2855
- files: files.length,
2856
- failures: files.length,
2857
- cli_install_failed: true,
2858
- agent: typeof argv.agent === "string" ? argv.agent : void 0
2859
- });
2860
- process.exit(1);
2861
- return;
2862
- }
2863
- ui.log.success("Installed or updated PostHog CLI.");
2864
- let failures = 0;
2865
- for (const file of files) {
2866
- const result = installSteeringSnippet(file);
2867
- if (result.success) ui.log.success(`Installed PostHog steering instructions in ${file}`);
2868
- else {
2869
- failures += 1;
2870
- ui.log.error(`Failed to update ${file}: ${result.error ?? ""}`);
2871
- }
2872
- }
2873
- analytics.wizardCapture("cli steering installed", {
2874
- files: files.length,
2875
- failures,
2876
- agent: typeof argv.agent === "string" ? argv.agent : void 0
2877
- });
2878
- if (failures > 0) {
2879
- process.exit(1);
2880
- return;
2881
- }
2882
- ui.outro("Done. PostHog CLI is installed and your agent will now use `posthog-cli api` for PostHog tasks.");
2883
- process.exit(0);
2884
- }
2885
- /** Resolve which instruction files to write, from flags, detection, or a prompt. */
2886
- async function resolveTargetFiles(argv) {
2887
- const ui = getUI();
2888
- if (typeof argv.path === "string" && argv.path.trim()) return [path$1.resolve(argv.path.trim())];
2889
- if (typeof argv.agent === "string") {
2890
- const target = findTarget(argv.agent);
2891
- if (!target) {
2892
- ui.log.error(`Unsupported agent: ${argv.agent}`);
2893
- return [];
2894
- }
2895
- return [target.instructionsPath()];
2896
- }
2897
- const detected = detectTargets();
2898
- if (detected.length === 0) {
2899
- ui.log.error("No supported coding agents detected. Pass --agent <id> or --path <file> to choose a target.");
2900
- ui.log.info(`Supported agents: ${CLI_STEERING_TARGETS.map((t) => t.id).join(", ")}`);
2901
- return [];
2902
- }
2903
- if (argv.all === true) {
2904
- ui.log.info(`Installing for all detected agents: ${detected.map((t) => t.name).join(", ")}`);
2905
- return detected.map((target) => target.instructionsPath());
2906
- }
2907
- if (detected.length === 1) {
2908
- ui.log.info(`Detected ${detected[0].name} (${detected[0].instructionsPath()})`);
2909
- return [detected[0].instructionsPath()];
2910
- }
2911
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
2912
- ui.log.info(`Installing for all detected agents: ${detected.map((t) => t.name).join(", ")}`);
2913
- return detected.map((target) => target.instructionsPath());
2914
- }
2915
- return (await promptForTargets(detected)).map((target) => target.instructionsPath());
2916
- }
2917
- /** Minimal numbered selection — this command is intentionally not a TUI flow. */
2918
- async function promptForTargets(detected) {
2919
- const ui = getUI();
2920
- ui.log.info("Which coding agent are you using?");
2921
- detected.forEach((target, index) => {
2922
- ui.log.info(` ${index + 1}) ${target.name} (${target.instructionsPath()})`);
2923
- });
2924
- ui.log.info(` ${detected.length + 1}) All of the above`);
2925
- const rl = readline.createInterface({
2926
- input: process.stdin,
2927
- output: process.stdout
2928
- });
2929
- try {
2930
- for (;;) {
2931
- const answer = (await rl.question(`Select 1-${detected.length + 1}: `)).trim();
2932
- const choice = Number(answer);
2933
- if (Number.isInteger(choice) && choice >= 1 && choice <= detected.length) return [detected[choice - 1]];
2934
- if (choice === detected.length + 1) return detected;
2935
- ui.log.warn(`Enter a number between 1 and ${detected.length + 1}.`);
2936
- }
2937
- } finally {
2938
- rl.close();
2939
- }
2940
- }
2941
- //#endregion
2942
- //#region src/commands/cli/index.ts
2943
- const cliCommand = {
2944
- name: "cli",
2945
- description: "PostHog CLI agent integration commands",
2946
- children: [cliAddCommand]
2947
- };
2948
- //#endregion
2
+ import { n as ErrorCodes, t as emitWizardError } from "./emit-BSetXzDV.js";
3
+ import { satisfies } from "semver";
2949
4
  //#region bin.ts
2950
5
  const NODE_VERSION_RANGE = ">=22.22.0";
2951
- setGlobalDispatcher(new Agent({ allowH2: false }));
2952
6
  if (!satisfies(process.version, NODE_VERSION_RANGE)) {
2953
7
  console.log([
2954
8
  `The PostHog wizard needs a newer version of Node.js to run.`,
@@ -2959,7 +13,7 @@ if (!satisfies(process.version, NODE_VERSION_RANGE)) {
2959
13
  `To update Node.js:`,
2960
14
  ``,
2961
15
  ` Download the latest version from https://nodejs.org/en/download`,
2962
- ` Or, if you use nvm, run: nvm install 22 && nvm use 22`,
16
+ ` Or, if you use nvm, run: nvm install 24 && nvm use 24`,
2963
17
  ``,
2964
18
  `Then run the wizard again. Stuck? Email wizard@posthog.com and we'll help.`
2965
19
  ].join("\n"));
@@ -2969,17 +23,8 @@ if (!satisfies(process.version, NODE_VERSION_RANGE)) {
2969
23
  });
2970
24
  process.exit(1);
2971
25
  }
2972
- recoverOrphanedSettingsBackups(resolveInstallDir());
2973
- function resolveInstallDir() {
2974
- const args = process.argv.slice(2);
2975
- const flagIndex = args.indexOf("--install-dir");
2976
- if (flagIndex !== -1 && args[flagIndex + 1]) return args[flagIndex + 1];
2977
- const inline = args.find((a) => a.startsWith("--install-dir="));
2978
- if (inline) return inline.slice(14);
2979
- return process.env.POSTHOG_WIZARD_INSTALL_DIR ?? process.cwd();
2980
- }
2981
- Wizard.use(basicIntegrationCommand).use(mcpCommand).use(mcpAnalyticsCommand).use(replayVisionCommand).use(aiObservabilityCommand).use(metricsCommand).use(cliCommand).use(auditCommand).use(doctorCommand).use(migrateCommand).use(revenueCommand).use(warehouseCommand).use(selfDrivingCommand).use(slackCommand).use(uploadSourcemapsCommand).use(errorTrackingCommand).use(skillCommand).init();
26
+ await import("./main-CgKxbwMP.js");
2982
27
  //#endregion
2983
- export { useStdoutDimensions as a, runWizardHeadless as c, runWizard as d, useKeyboardHintsContext as i, runWizardCI as l, useKeyBindings as n, ConfirmButton as o, KeyboardHintsProvider as r, PromptLabel as s, PickerMenu as t, API_KEY_HINT as u };
28
+ export {};
2984
29
 
2985
30
  //# sourceMappingURL=bin.js.map