@posthog/wizard 2.71.0 → 2.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +10 -2
  2. package/dist/{add-mcp-server-to-clients-B6-ZL--P.js → add-mcp-server-to-clients-B8t2xAPf.js} +4 -4
  3. package/dist/{add-mcp-server-to-clients-B6-ZL--P.js.map → add-mcp-server-to-clients-B8t2xAPf.js.map} +1 -1
  4. package/dist/{agent-interface-DFm4jB4d.js → agent-interface-tcCEmyPQ.js} +467 -382
  5. package/dist/agent-interface-tcCEmyPQ.js.map +1 -0
  6. package/dist/{agent-prompt-loader-Bi3IzSBW.js → agent-prompt-loader-V2smIztP.js} +5 -5
  7. package/dist/{agent-prompt-loader-Bi3IzSBW.js.map → agent-prompt-loader-V2smIztP.js.map} +1 -1
  8. package/dist/{agent-runner-Cp6iLqDk.js → agent-runner-DUyO1Ehj.js} +3178 -18
  9. package/dist/agent-runner-DUyO1Ehj.js.map +1 -0
  10. package/dist/analytics-DEL7clQK.js +2 -0
  11. package/dist/{analytics-D54mLptm.js → analytics-DsMH06jo.js} +3 -3
  12. package/dist/{analytics-D54mLptm.js.map → analytics-DsMH06jo.js.map} +1 -1
  13. package/dist/{api-BNBVOguz.js → api-R6bXIwII.js} +3 -3
  14. package/dist/{api-BNBVOguz.js.map → api-R6bXIwII.js.map} +1 -1
  15. package/dist/bin.js +56 -52
  16. package/dist/bin.js.map +1 -1
  17. package/dist/{bounded-fs-DHIaH3Sc.js → bounded-fs-BV-KhOtU.js} +3 -3
  18. package/dist/{bounded-fs-DHIaH3Sc.js.map → bounded-fs-BV-KhOtU.js.map} +1 -1
  19. package/dist/{ci-install-Can8LRdJ.js → ci-install-mR8CeIt2.js} +4 -4
  20. package/dist/{ci-install-Can8LRdJ.js.map → ci-install-mR8CeIt2.js.map} +1 -1
  21. package/dist/{debug-C4RPcEIX.js → debug-PfLVvLhT.js} +1 -1
  22. package/dist/{debug-YQdeZulR.js → debug-aXxgvtal.js} +50 -16
  23. package/dist/debug-aXxgvtal.js.map +1 -0
  24. package/dist/{env-api-key-9yogO8OI.js → env-api-key-_lBt9tHl.js} +2 -2
  25. package/dist/{env-api-key-9yogO8OI.js.map → env-api-key-_lBt9tHl.js.map} +1 -1
  26. package/dist/{environment-6ZuAWRpQ.js → environment-DRhZbhxU.js} +4 -4
  27. package/dist/{environment-6ZuAWRpQ.js.map → environment-DRhZbhxU.js.map} +1 -1
  28. package/dist/{file-watcher-CeWdvMVT.js → file-watcher-BZw1_Y84.js} +2 -2
  29. package/dist/{file-watcher-CeWdvMVT.js.map → file-watcher-BZw1_Y84.js.map} +1 -1
  30. package/dist/{headless-ui-BxSVgNoT.js → headless-ui-Cdqfufhk.js} +2 -2
  31. package/dist/{headless-ui-BxSVgNoT.js.map → headless-ui-Cdqfufhk.js.map} +1 -1
  32. package/dist/{interactive-CRR9zPl4.js → interactive-BCI9b-dp.js} +2 -2
  33. package/dist/{interactive-CRR9zPl4.js.map → interactive-BCI9b-dp.js.map} +1 -1
  34. package/dist/{mcp-D_rRzruj.js → mcp-CzB3lWsm.js} +2 -2
  35. package/dist/{mcp-D_rRzruj.js.map → mcp-CzB3lWsm.js.map} +1 -1
  36. package/dist/{mcp-prompt-streaming-DRAK8CMP.js → mcp-prompt-streaming-RZGAH4YO.js} +4 -4
  37. package/dist/{mcp-prompt-streaming-DRAK8CMP.js.map → mcp-prompt-streaming-RZGAH4YO.js.map} +1 -1
  38. package/dist/{non-interactive-1EJRlN6u.js → non-interactive-CgjTZZ9J.js} +2 -2
  39. package/dist/{non-interactive-1EJRlN6u.js.map → non-interactive-CgjTZZ9J.js.map} +1 -1
  40. package/dist/{orchestrator-tools-DjZWqWmd.js → orchestrator-tools-OWgPinUt.js} +21 -13
  41. package/dist/orchestrator-tools-OWgPinUt.js.map +1 -0
  42. package/dist/{package-manager-DMbzbdkL.js → package-manager-B-Z3IVYu.js} +2 -2
  43. package/dist/{package-manager-DMbzbdkL.js.map → package-manager-B-Z3IVYu.js.map} +1 -1
  44. package/dist/{pi-D4JQMC-7.js → pi-CLLkGrND.js} +11 -11
  45. package/dist/{pi-D4JQMC-7.js.map → pi-CLLkGrND.js.map} +1 -1
  46. package/dist/{playground-Y1nSGXpn.js → playground-D1TgX0EU.js} +9 -9
  47. package/dist/playground-D1TgX0EU.js.map +1 -0
  48. package/dist/{posthog-D9VwcWvJ.js → posthog-CMef8KLR.js} +2 -2
  49. package/dist/{posthog-D9VwcWvJ.js.map → posthog-CMef8KLR.js.map} +1 -1
  50. package/dist/posthog-integration-wiunwp8X.js +1475 -0
  51. package/dist/posthog-integration-wiunwp8X.js.map +1 -0
  52. package/dist/{provisioning-f7lA29tW.js → provisioning-94OneD64.js} +3 -3
  53. package/dist/{provisioning-f7lA29tW.js.map → provisioning-94OneD64.js.map} +1 -1
  54. package/dist/{queue-tools-DGaHf3n-.js → queue-tools--k2v8QYY.js} +108 -44
  55. package/dist/queue-tools--k2v8QYY.js.map +1 -0
  56. package/dist/{registry-D1By1SgH.js → registry-C60oJv02.js} +5 -5
  57. package/dist/{registry-D1By1SgH.js.map → registry-C60oJv02.js.map} +1 -1
  58. package/dist/{security-C2c3_Ycy.js → security-DnOP36w-.js} +5 -5
  59. package/dist/{security-C2c3_Ycy.js.map → security-DnOP36w-.js.map} +1 -1
  60. package/dist/{setup-utils-BRrCeajl.js → setup-utils-BwX6QmL_.js} +9 -9
  61. package/dist/{setup-utils-BRrCeajl.js.map → setup-utils-BwX6QmL_.js.map} +1 -1
  62. package/dist/{start-tui-r4Spgptv.js → start-tui-C3PdKFtP.js} +53 -32
  63. package/dist/start-tui-C3PdKFtP.js.map +1 -0
  64. package/dist/{steps-BZd65XfI.js → steps-BpCRk8Ef.js} +7 -7
  65. package/dist/{steps-BZd65XfI.js.map → steps-BpCRk8Ef.js.map} +1 -1
  66. package/dist/{store-DGVXu7xt.js → store-EzqWyb60.js} +7 -8
  67. package/dist/store-EzqWyb60.js.map +1 -0
  68. package/dist/{subagent-BaMxO7OT.js → subagent-DwdrVprk.js} +2 -2
  69. package/dist/{subagent-BaMxO7OT.js.map → subagent-DwdrVprk.js.map} +1 -1
  70. package/dist/{task-DpKoEZ5I.js → task-CrXgNEUB.js} +12 -12
  71. package/dist/{task-DpKoEZ5I.js.map → task-CrXgNEUB.js.map} +1 -1
  72. package/dist/{task-stream-CdrBraqP.js → task-stream-ZBbfHo7l.js} +5 -5
  73. package/dist/{task-stream-CdrBraqP.js.map → task-stream-ZBbfHo7l.js.map} +1 -1
  74. package/dist/{tasks-KsP66Cis.js → tasks-CbMEKWZ9.js} +2 -2
  75. package/dist/{tasks-KsP66Cis.js.map → tasks-CbMEKWZ9.js.map} +1 -1
  76. package/dist/{telemetry-DedDTtSa.js → telemetry-B2dz2-PT.js} +3 -3
  77. package/dist/{telemetry-DedDTtSa.js.map → telemetry-B2dz2-PT.js.map} +1 -1
  78. package/dist/{terminal-BH8yLclG.js → terminal-DTe59M4j.js} +12 -12
  79. package/dist/{terminal-BH8yLclG.js.map → terminal-DTe59M4j.js.map} +1 -1
  80. package/dist/{tools-CJw5vnZd.js → tools-DZ9lZgJI.js} +6 -6
  81. package/dist/{tools-CJw5vnZd.js.map → tools-DZ9lZgJI.js.map} +1 -1
  82. package/dist/{wizard-abort-D54j2gmb.js → wizard-abort-CUT8MXXt.js} +4 -4
  83. package/dist/{wizard-abort-D54j2gmb.js.map → wizard-abort-CUT8MXXt.js.map} +1 -1
  84. package/dist/{wizard-abort-Q1NiYELE.js → wizard-abort-CfKnrSlX.js} +1 -1
  85. package/dist/{wizard-session-Dwc1Rh_7.js → wizard-session-BWAQoi9q.js} +1 -1
  86. package/dist/{wizard-session-CwQPZN4y.js → wizard-session-GdDN_aMS.js} +2 -1
  87. package/dist/wizard-session-GdDN_aMS.js.map +1 -0
  88. package/dist/yara-hooks-CLeMu2EY.js +2 -0
  89. package/dist/{yara-hooks-CL2LVEgO.js → yara-hooks-VvwkZn5s.js} +7 -6
  90. package/dist/yara-hooks-VvwkZn5s.js.map +1 -0
  91. package/package.json +2 -1
  92. package/dist/agent-interface-DFm4jB4d.js.map +0 -1
  93. package/dist/agent-runner-Cp6iLqDk.js.map +0 -1
  94. package/dist/analytics-Ge1LsCNg.js +0 -2
  95. package/dist/debug-YQdeZulR.js.map +0 -1
  96. package/dist/orchestrator-tools-DjZWqWmd.js.map +0 -1
  97. package/dist/playground-Y1nSGXpn.js.map +0 -1
  98. package/dist/posthog-integration-B8f4xRBd.js +0 -4618
  99. package/dist/posthog-integration-B8f4xRBd.js.map +0 -1
  100. package/dist/queue-tools-DGaHf3n-.js.map +0 -1
  101. package/dist/start-tui-r4Spgptv.js.map +0 -1
  102. package/dist/store-DGVXu7xt.js.map +0 -1
  103. package/dist/wizard-session-CwQPZN4y.js.map +0 -1
  104. package/dist/yara-hooks-BI6WY0Sl.js +0 -2
  105. package/dist/yara-hooks-CL2LVEgO.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posthog-integration-wiunwp8X.js","names":[],"sources":["../src/lib/detection/project-scope.ts","../src/lib/programs/shared/health-check-step.ts","../src/lib/programs/posthog-integration/steps.ts","../src/ui/tui/styles.ts","../src/ui/tui/primitives/text-helpers.ts","../src/ui/tui/primitives/content-types.ts","../src/ui/tui/primitives/layout-helpers.ts","../src/ui/tui/primitives/TextBlock.tsx","../src/ui/tui/components/StatusPeekTrigger.tsx","../src/lib/programs/posthog-integration/content/data-flow.tsx","../src/lib/programs/posthog-integration/content/product-suite.tsx","../src/lib/programs/posthog-integration/content/line-chart.tsx","../src/lib/programs/posthog-integration/content/funnel.tsx","../src/lib/programs/posthog-integration/content/index.tsx","../src/lib/programs/posthog-integration/handoff.ts","../src/lib/programs/posthog-integration/index.ts"],"sourcesContent":["/** Non-interactive project scoping — scan the repo agentically and pick which project the run integrates. */\n\nimport {\n detectProjectsWithAgent,\n resolveProjectDir,\n type AgenticDetectionReport,\n type AgenticProject,\n type DetectEvent,\n type DetectTarget,\n} from './agentic.js';\nimport { authenticate } from '@lib/agent/runner/shared/authenticate';\nimport { FRAMEWORK_REGISTRY } from '@lib/registry';\nimport {\n AGENTIC_DETECTION_TIMEOUT_MS,\n WIZARD_BASIC_INTEGRATION_AGENTIC_DETECTION_FLAG_KEY,\n} from '@lib/constants';\nimport type { WizardSession } from '@lib/wizard-session';\nimport { getUI } from '@ui/index';\nimport { analytics } from '@utils/analytics';\nimport { logToFile } from '@utils/debug';\n\n/** Integration framework targets for the agentic detector (id → display name). */\nconst INTEGRATION_TARGETS: DetectTarget[] = Object.entries(\n FRAMEWORK_REGISTRY,\n).map(([id, config]) => ({ id, name: config.metadata.name }));\n\n/** Run the agentic detector for the wizard's integration frameworks — the single home of targets + purpose. */\nexport async function detectIntegrationProjects(\n session: WizardSession,\n options: {\n /** Program the scan bills to. Required so no caller can go unattributed. */\n programId: string;\n recommend?: boolean;\n onEvent?: DetectEvent;\n },\n): Promise<AgenticDetectionReport> {\n // Spread first so the targets and purpose this function owns always win.\n return detectProjectsWithAgent(session, {\n ...options,\n targets: INTEGRATION_TARGETS,\n purpose: 'set up a PostHog SDK integration',\n });\n}\n\n/** Pick the recommended-if-supported project (even with PostHog — the main app wins), else the first supported PostHog-free one. */\nexport function chooseIntegrationProject(\n projects: AgenticProject[],\n): AgenticProject | undefined {\n return (\n projects.find((p) => p.recommended === true && p.targetId != null) ??\n projects.find((p) => p.targetId != null && !p.hasPostHog)\n );\n}\n\n/** Every run fires exactly one `wizard: agentic detection` event with one of these outcomes — no untracked exits. */\nexport type AgenticDetectionOutcome =\n | 'flag-off'\n | 'error'\n | 'timeout'\n | 'no-project'\n | 'recommended'\n | 'first-instrumentable';\n\n/** Sentinel for a scan that outran AGENTIC_DETECTION_TIMEOUT_MS. */\nconst TIMED_OUT = Symbol('timed-out');\n\nfunction captureOutcome(\n outcome: AgenticDetectionOutcome,\n properties: Record<string, unknown> = {},\n): void {\n analytics.wizardCapture('agentic detection', { outcome, ...properties });\n}\n\n/** Flag-gated non-interactive monorepo phase: scan, auto-choose the recommended project, re-point session.installDir; every failure leaves the session untouched. */\nexport async function scopeInstallDirToProject(\n session: WizardSession,\n): Promise<void> {\n // Idempotent early auth: the detector needs credentials and the flag must evaluate as the logged-in user.\n await authenticate(session, 'posthog-integration');\n const flags = await analytics.getAllFlagsForWizard();\n if (flags[WIZARD_BASIC_INTEGRATION_AGENTIC_DETECTION_FLAG_KEY] !== 'true') {\n // A failed flag fetch surfaces as an empty map, so flag-off also covers \"flags unavailable\".\n captureOutcome('flag-off');\n return;\n }\n\n getUI().log.info('Scanning the repo for projects...');\n const startedAt = Date.now();\n let report: AgenticDetectionReport | typeof TIMED_OUT;\n try {\n report = await Promise.race([\n detectIntegrationProjects(session, {\n // Literal, like the `authenticate` call above: importing the program\n // registry here would cycle.\n programId: 'posthog-integration',\n recommend: true,\n onEvent: (line) => logToFile('[agentic detect]', line),\n }),\n // The agent has no abort plumbing, so a timed-out scan is abandoned in the\n // background rather than cancelled; the run stops waiting on it either way.\n new Promise<typeof TIMED_OUT>((resolve) =>\n setTimeout(() => resolve(TIMED_OUT), AGENTIC_DETECTION_TIMEOUT_MS),\n ),\n ]);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n analytics.captureException(error, { step: 'agentic_detection' });\n captureOutcome('error', {\n duration_ms: Date.now() - startedAt,\n error_message: error.message,\n });\n getUI().log.warn(\n `Project scan failed (${error.message}); continuing with the install dir as-is.`,\n );\n return;\n }\n\n if (report === TIMED_OUT) {\n captureOutcome('timeout', { duration_ms: Date.now() - startedAt });\n getUI().log.warn(\n `Project scan timed out after ${\n AGENTIC_DETECTION_TIMEOUT_MS / 1000\n }s; continuing with the install dir as-is.`,\n );\n return;\n }\n\n const { projects } = report;\n const recommended = projects.find((p) => p.recommended === true);\n // The event carries at most this many projects; project_count is the true total.\n const MAX_PROJECTS_CAPTURED = 25;\n const scanProperties = {\n duration_ms: Date.now() - startedAt,\n repo_type: report.repoType,\n project_count: projects.length,\n supported_count: projects.filter((p) => p.targetId != null).length,\n has_recommendation: recommended !== undefined,\n recommended_path: recommended?.path ?? null,\n projects: projects.slice(0, MAX_PROJECTS_CAPTURED),\n };\n\n const project = chooseIntegrationProject(projects);\n if (!project) {\n captureOutcome('no-project', scanProperties);\n getUI().log.info(\n 'The scan found no supported project; continuing with the install dir as-is.',\n );\n return;\n }\n\n session.installDir = resolveProjectDir(session.installDir, project.path);\n captureOutcome(project.recommended ? 'recommended' : 'first-instrumentable', {\n ...scanProperties,\n chosen_framework: project.targetId,\n chosen_path: project.path,\n });\n getUI().log.info(`Continuing with ${project.path} (${project.framework}).`);\n}\n","/**\n * Shared health-check step used by every program that runs an agent.\n *\n * Renders the HealthCheckScreen between intro and auth, kicks off the\n * readiness probe in onInit, and gates the screen on either a clean\n * readiness result or an explicit user dismissal of the outage.\n *\n * Programs without this step that hit a blocking outage gridlock the\n * router: agent-runner calls wizardAbort, which awaits outroDismissed,\n * but the router can't advance past the still-incomplete auth step to\n * render the OutroScreen.\n */\n\nimport type { ProgramStep } from '@lib/programs/program-step';\nimport type { WizardSession } from '@lib/wizard-session';\nimport {\n evaluateWizardReadiness,\n WizardReadiness,\n SIGNUP_WIZARD_READINESS_CONFIG,\n getBlockingServiceKeys,\n} from '@lib/health-checks/readiness';\nimport { logToFile } from '@utils/debug';\n\nexport function healthCheckReady(session: WizardSession): boolean {\n if (!session.readinessResult) return false;\n\n if (session.signup) {\n const hardBlocking = getBlockingServiceKeys(\n session.readinessResult.health,\n SIGNUP_WIZARD_READINESS_CONFIG,\n );\n const defaultBlocking = getBlockingServiceKeys(\n session.readinessResult.health,\n );\n if (hardBlocking.length === 0 && defaultBlocking.length === 0) return true;\n return session.outageDismissed;\n }\n\n if (session.readinessResult.decision === WizardReadiness.No) {\n return session.outageDismissed;\n }\n return true;\n}\n\nexport const HEALTH_CHECK_STEP: ProgramStep = {\n id: 'health-check',\n label: 'Health check',\n screenId: 'health-check',\n gate: healthCheckReady,\n onInit: (ctx) => {\n evaluateWizardReadiness()\n .then((readiness) => {\n logToFile(\n `[health-checks] TUI pre-flight complete: decision=${readiness.decision}`,\n );\n ctx.setReadinessResult(readiness);\n })\n .catch((err) => {\n logToFile('[health-checks] TUI pre-flight failed:', err);\n ctx.setReadinessResult({\n decision: WizardReadiness.Yes,\n health: {} as never,\n reasons: [],\n });\n });\n },\n};\n","/**\n * PostHog integration program — the default wizard flow.\n *\n * Steps define their own gate predicates and onInit callbacks.\n * The store derives gate promises and fires init work from these\n * definitions — no hardcoded per-flow logic in the store.\n */\n\nimport type { ProgramStep } from '@lib/programs/program-step';\nimport type { WizardSession } from '@lib/wizard-session';\nimport { RunPhase } from '@lib/wizard-session';\nimport { HEALTH_CHECK_STEP } from '@lib/programs/shared/health-check-step';\nimport { detectPostHogIntegration } from './detect.js';\n\nfunction needsSetup(session: WizardSession): boolean {\n const config = session.frameworkConfig;\n if (!config?.metadata.setup?.questions) return false;\n\n return config.metadata.setup.questions.some(\n (q: { key: string }) => !(q.key in session.frameworkContext),\n );\n}\n\nexport const POSTHOG_INTEGRATION_PROGRAM: ProgramStep[] = [\n {\n id: 'detect',\n label: 'Detecting framework',\n // Headless step: no screen. onReady fires after bin.ts assigns the\n // session — runs framework detection, context gathering, version\n // check, and feature discovery. Results are written to the store\n // for the IntroScreen to render.\n onReady: (ctx) => detectPostHogIntegration(ctx),\n },\n {\n id: 'intro',\n label: 'Welcome',\n screenId: 'intro',\n gate: (session) => session.setupConfirmed,\n },\n HEALTH_CHECK_STEP,\n {\n id: 'setup',\n label: 'Setup',\n screenId: 'setup',\n show: needsSetup,\n isComplete: (session) => !needsSetup(session),\n },\n {\n id: 'auth',\n label: 'Authentication',\n screenId: 'auth',\n isComplete: (session) => session.credentials !== null,\n },\n {\n id: 'run',\n label: 'Integration',\n screenId: 'run',\n isComplete: (session) =>\n session.runPhase === RunPhase.Completed ||\n session.runPhase === RunPhase.Error,\n },\n {\n id: 'outro',\n label: 'Done',\n screenId: 'outro',\n isComplete: (session) => session.outroDismissed,\n },\n {\n id: 'mcp',\n label: 'MCP servers',\n screenId: 'mcp',\n isComplete: (session) => session.mcpComplete,\n },\n {\n id: 'slack-connect',\n label: 'Connect Slack',\n screenId: 'slack-connect',\n // Always shown — the user declines via Skip/esc, never bypassed.\n isComplete: (session) => session.slackStepDismissed,\n },\n {\n id: 'keep-skills',\n label: 'Keep Skills',\n screenId: 'keep-skills',\n },\n];\n","/**\n * Shared style constants for TUI layout primitives.\n */\n\nexport enum HAlign {\n Left = 'flex-start',\n Center = 'center',\n Right = 'flex-end',\n}\n\nexport enum VAlign {\n Top = 'flex-start',\n Center = 'center',\n Bottom = 'flex-end',\n}\n\nexport const Colors = {\n primary: 'cyan',\n accent: '#DC9300',\n titleColor: '#3D2800',\n success: 'green',\n error: 'red',\n muted: 'gray',\n} as const;\n\nexport const Icons = {\n diamond: '\\u25C6',\n diamondOpen: '\\u25C7',\n check: '\\u2714',\n warning: '\\u26A0',\n squareFilled: '\\u25FC',\n squareOpen: '\\u25FB',\n triangleRight: '\\u25B6',\n triangleSmallRight: '\\u25B8',\n bullet: '\\u2022',\n} as const;\n","/**\n * Text-splitting helpers for sentence boundary detection.\n * Used by TextBlock for animation pauses at punctuation.\n */\n\n/** Split text into sentences (keeps the delimiter attached) */\nexport function splitSentences(text: string): string[] {\n const parts: string[] = [];\n const re = /[^.!?]*[.!?]+\\s*/g;\n let match: RegExpExecArray | null;\n let lastIndex = 0;\n while ((match = re.exec(text)) !== null) {\n parts.push(match[0]);\n lastIndex = re.lastIndex;\n }\n if (lastIndex < text.length) {\n parts.push(text.slice(lastIndex));\n }\n return parts;\n}\n\n/** Build a set of character indices where sentences end (for typewriter pause) */\nexport function sentenceEndChars(text: string): Set<number> {\n const ends = new Set<number>();\n const sentences = splitSentences(text);\n let pos = 0;\n for (const s of sentences) {\n pos += s.length;\n ends.add(pos - 1);\n }\n return ends;\n}\n\n/** Build a set of word indices where sentences end (for word-by-word pause) */\nexport function sentenceEndWords(text: string): Set<number> {\n const ends = new Set<number>();\n const sentences = splitSentences(text);\n let wordCount = 0;\n for (const s of sentences) {\n const words = s.trim().split(/\\s+/).filter(Boolean);\n wordCount += words.length;\n ends.add(wordCount - 1);\n }\n return ends;\n}\n","/**\n * Content block types and type guards.\n *\n * Extracted from ContentSequencer so that pure-logic modules (like\n * layout-helpers) can import them without pulling in Ink/React.\n */\n\nimport type { ReactNode } from 'react';\nimport type { TextRevealMode } from './TextBlock.js';\n\n/** Object form — string or ReactNode content with per-block overrides. */\nexport interface ContentObjectBlock {\n content: string | ReactNode;\n mode?: TextRevealMode;\n animationInterval?: number;\n sentenceInterval?: number;\n pause?: number;\n persist?: boolean;\n /**\n * When the sequencer advances past this block, should it render dim?\n * Defaults to `true` — the standard \"completed step\" treatment. Set to\n * `false` to keep the block at full opacity even after it's complete\n * (useful for headings or greetings that should stay readable while\n * later blocks animate in).\n *\n * Only meaningful for blocks whose `content` is a string (TextBlock\n * renders the dim treatment). NodeBlocks render whatever JSX you pass\n * verbatim regardless of completion state.\n */\n dimWhenComplete?: boolean;\n}\n\n/** Lines block — reveals ReactNode lines one at a time. */\nexport interface ContentLinesBlock {\n type: 'lines';\n lines: ReactNode[];\n interval?: number;\n pause?: number;\n}\n\n/** Clear block — page break that hides all prior blocks. */\nexport interface ContentClearBlock {\n type: 'clear';\n pause?: number;\n}\n\n/** A content block in the sequence. Bare strings are sugar for { content: '...' }. */\nexport type ContentBlock =\n | string\n | ContentObjectBlock\n | ContentLinesBlock\n | ContentClearBlock;\n\n/** Type guard for lines blocks. */\nexport function isLinesBlock(block: ContentBlock): block is ContentLinesBlock {\n return typeof block !== 'string' && 'type' in block && block.type === 'lines';\n}\n\n/** Type guard for clear blocks. */\nexport function isClearBlock(block: ContentBlock): block is ContentClearBlock {\n return typeof block !== 'string' && 'type' in block && block.type === 'clear';\n}\n\n/** Type guard for object blocks (text or node content). */\nexport function isObjectBlock(\n block: ContentBlock,\n): block is ContentObjectBlock {\n return typeof block !== 'string' && !('type' in block);\n}\n","/**\n * Layout helpers — pure functions for height estimation and viewport eviction.\n *\n * These are the core of the responsive content system. They estimate how many\n * terminal rows a content block will occupy and determine which blocks fit\n * within a given height budget.\n */\n\nimport type { ContentBlock } from './content-types.js';\nimport { isLinesBlock, isClearBlock, isObjectBlock } from './content-types.js';\n\n/**\n * Estimate the number of terminal rows a content block will occupy,\n * including 1 row of marginBottom.\n */\nexport function estimateBlockHeight(\n block: ContentBlock,\n availableWidth: number,\n): number {\n if (typeof block === 'string') {\n return wordWrap(block, availableWidth).length + 1; // +1 for marginBottom\n }\n\n if (isClearBlock(block)) return 0;\n\n if (isLinesBlock(block)) {\n return block.lines.length + 1;\n }\n\n if (isObjectBlock(block)) {\n if (typeof block.content === 'string') {\n return wordWrap(block.content, availableWidth).length + 1;\n }\n return 4; // conservative fixed estimate for ReactNode\n }\n\n return 1;\n}\n\n/**\n * Given all blocks, the active index, available width, and a row budget,\n * return [startIdx, endIdx] — the range of blocks to render.\n *\n * Always includes activeIdx. Walks backward to include as many completed\n * blocks as fit within maxHeight.\n */\nexport function computeVisibleRange(\n blocks: ContentBlock[],\n activeIdx: number,\n availableWidth: number,\n maxHeight: number,\n): [number, number] {\n // Reserve a 2-row buffer so resize-induced estimate drift doesn't\n // cause overflow=\"hidden\" to clip the margin between blocks.\n const budget = Math.max(4, maxHeight - 2);\n\n let totalHeight = estimateBlockHeight(blocks[activeIdx], availableWidth);\n let start = activeIdx;\n\n for (let i = activeIdx - 1; i >= 0; i--) {\n // Clear blocks act as a hard boundary — don't show anything before them\n if (isClearBlock(blocks[i])) break;\n const h = estimateBlockHeight(blocks[i], availableWidth);\n if (totalHeight + h > budget) break;\n totalHeight += h;\n start = i;\n }\n\n return [start, activeIdx];\n}\n\n/**\n * Word-wrap text at clean word boundaries. Always returns pre-wrapped text\n * joined with \\n — this avoids Ink's native wrap which can leave leading\n * spaces on continuation lines.\n *\n * Uses a 1-char safety margin so slight width estimate mismatches don't\n * cause Ink to re-wrap our already-wrapped lines.\n */\nexport function wordWrap(text: string, availableWidth: number): string[] {\n const safeWidth = Math.max(10, availableWidth - 1);\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (\n currentLine.length + word.length + 1 > safeWidth &&\n currentLine.length > 0\n ) {\n lines.push(currentLine);\n currentLine = word;\n } else {\n currentLine += (currentLine.length > 0 ? ' ' : '') + word;\n }\n }\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n\n return lines;\n}\n\n/**\n * Word-wrap text and return only the last `maxRows` lines.\n * Used for intra-block truncation when a single text block exceeds the viewport.\n * Also used for normal rendering to avoid Ink's leading-space wrap artifacts.\n */\nexport function wrapAndTruncate(\n text: string,\n availableWidth: number,\n maxRows: number,\n): string {\n const lines = wordWrap(text, availableWidth);\n\n if (lines.length <= maxRows) {\n return lines.join('\\n');\n }\n\n return lines.slice(-maxRows).join('\\n');\n}\n","/**\n * TextBlock — Animates a single string paragraph.\n *\n * Self-contained: owns its own animIdx and timer.\n * Calls onComplete() when the animation finishes.\n *\n * Five animation modes:\n * 1. Typewriter — character-by-character reveal\n * 2. Word by word — each word appears in order\n * 3. Sentence by sentence — sentences appear one at a time\n * 4. Paragraph fade — paragraph appears at full opacity immediately\n * 5. Sentence fade — paragraph dim, sentences light up in order\n */\n\nimport { Text } from 'ink';\nimport { useState, useEffect, useRef, useMemo, type ReactNode } from 'react';\nimport { Colors } from '@ui/tui/styles';\nimport {\n splitSentences,\n sentenceEndChars,\n sentenceEndWords,\n} from './text-helpers.js';\nimport { wrapAndTruncate } from './layout-helpers.js';\n\nexport enum TextRevealMode {\n Typewriter = 0,\n WordByWord = 1,\n SentenceBySentence = 2,\n ParagraphFade = 3,\n SentenceFade = 4,\n}\n\nexport const TEXT_REVEAL_MODE_LABELS = [\n 'Typewriter',\n 'Word by word',\n 'Sentence by sentence',\n 'Paragraph fade',\n 'Sentence fade',\n];\n\nexport const TEXT_REVEAL_MODE_COUNT = 5;\n\n/** Default interval per mode (ms) */\nexport const TEXT_REVEAL_MODE_DEFAULTS: Record<TextRevealMode, number> = {\n [TextRevealMode.WordByWord]: 240,\n [TextRevealMode.Typewriter]: 32,\n [TextRevealMode.SentenceBySentence]: 1800,\n [TextRevealMode.ParagraphFade]: 4800,\n [TextRevealMode.SentenceFade]: 2400,\n};\n\ninterface TextBlockProps {\n text: string;\n active: boolean;\n completed: boolean;\n onComplete: () => void;\n mode: TextRevealMode;\n bullet?: ReactNode;\n animationInterval?: number;\n sentenceInterval?: number;\n /** Max rows this block may occupy. When exceeded, top lines are truncated. */\n maxHeight?: number;\n /** Available text width in columns (for truncation wrapping). */\n availableWidth?: number;\n /**\n * When `completed === true`, render the text dim. Defaults to `true` —\n * the standard \"completed step\" treatment. Pass `false` to keep the\n * text at full opacity even after the sequencer has moved on.\n */\n dimWhenComplete?: boolean;\n}\n\nexport const TextBlock = ({\n text,\n active,\n completed,\n onComplete,\n mode,\n bullet,\n animationInterval,\n sentenceInterval = 1600,\n maxHeight,\n availableWidth,\n dimWhenComplete = true,\n}: TextBlockProps) => {\n const speed = animationInterval ?? TEXT_REVEAL_MODE_DEFAULTS[mode];\n\n const [animIdx, setAnimIdx] = useState(\n mode === TextRevealMode.SentenceFade ? 1 : 0,\n );\n\n // Reset synchronously during render to avoid a one-frame flash\n const resetRef = useRef(0);\n const prevMode = useRef(mode);\n if (prevMode.current !== mode) {\n prevMode.current = mode;\n resetRef.current += 1;\n setAnimIdx(mode === TextRevealMode.SentenceFade ? 1 : 0);\n }\n\n const words = text.split(/\\s+/);\n const sentences = splitSentences(text);\n\n const sentenceCharEnds = useMemo(() => sentenceEndChars(text), [text]);\n const sentenceWordEnds = useMemo(() => sentenceEndWords(text), [text]);\n\n const isDone =\n mode === TextRevealMode.Typewriter\n ? animIdx >= text.length\n : mode === TextRevealMode.ParagraphFade\n ? true\n : mode === TextRevealMode.WordByWord\n ? animIdx >= words.length\n : mode === TextRevealMode.SentenceFade ||\n mode === TextRevealMode.SentenceBySentence\n ? animIdx >= sentences.length\n : true;\n\n // Fire onComplete when done\n useEffect(() => {\n if (isDone && active) onComplete();\n }, [isDone, active, onComplete]);\n\n // Animate: single effect for all tick-based modes\n useEffect(() => {\n if (!active || mode === TextRevealMode.ParagraphFade || isDone) return;\n const token = resetRef.current;\n\n const isFirstTick = animIdx === 0;\n\n let delay = isFirstTick ? 0 : speed;\n if (\n !isFirstTick &&\n mode === TextRevealMode.Typewriter &&\n animIdx > 0 &&\n sentenceCharEnds.has(animIdx - 1)\n ) {\n delay = sentenceInterval;\n } else if (\n !isFirstTick &&\n mode === TextRevealMode.WordByWord &&\n animIdx > 0 &&\n sentenceWordEnds.has(animIdx - 1)\n ) {\n delay = sentenceInterval;\n }\n\n const timer = setTimeout(() => {\n if (token !== resetRef.current) return;\n setAnimIdx((c) => c + 1);\n }, delay);\n return () => clearTimeout(timer);\n }, [\n active,\n mode,\n animIdx,\n isDone,\n speed,\n sentenceInterval,\n sentenceCharEnds,\n sentenceWordEnds,\n ]);\n\n // Pre-wrap text ourselves to avoid Ink's native wrap leaving leading spaces\n // on continuation lines. When maxHeight is set, also truncates to last N rows.\n const wrap = (visibleText: string): string => {\n if (availableWidth == null) return visibleText;\n if (maxHeight == null) {\n return wrapAndTruncate(visibleText, availableWidth, Infinity);\n }\n return wrapAndTruncate(visibleText, availableWidth, maxHeight);\n };\n\n // Completed: dimmed by default, but can be overridden per-block.\n if (completed) {\n return (\n <Text dimColor={dimWhenComplete}>\n {bullet}\n {wrap(text)}\n </Text>\n );\n }\n\n // Active: mode-specific rendering\n if (mode === TextRevealMode.Typewriter) {\n const revealed = text.slice(0, animIdx);\n const atSentenceEnd = /[.!?]\\s*$/.test(revealed);\n const display = atSentenceEnd ? revealed.trimEnd() : revealed;\n return (\n <Text>\n {bullet}\n {wrap(display)}\n <Text color={Colors.muted}>{'\\u258C'}</Text>\n </Text>\n );\n }\n\n if (mode === TextRevealMode.WordByWord) {\n const visible = words.slice(0, animIdx).join(' ');\n return (\n <Text>\n {bullet}\n {wrap(visible)}\n </Text>\n );\n }\n\n if (mode === TextRevealMode.ParagraphFade) {\n return (\n <Text>\n {bullet}\n {wrap(text)}\n </Text>\n );\n }\n\n if (mode === TextRevealMode.SentenceBySentence) {\n const visible = sentences.slice(0, animIdx).join('');\n return (\n <Text>\n {bullet}\n {wrap(visible)}\n </Text>\n );\n }\n\n // SentenceFade\n return (\n <Text>\n {bullet}\n {sentences.map((s, si) => (\n <Text key={si} dimColor={si >= animIdx}>\n {s}\n </Text>\n ))}\n </Text>\n );\n};\n","/**\n * StatusPeekTrigger — Fires the status-bar expansion once, renders a hint.\n *\n * Module-level `peekedOnce` guards against re-mounts (resize, tab switch)\n * so the peek only happens a single time per process.\n */\n\nimport { Text } from 'ink';\nimport { useEffect } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\n\nlet peekedOnce = false;\n\ninterface StatusPeekTriggerProps {\n store?: WizardStore;\n /** How long the status bar stays expanded, in ms. */\n duration?: number;\n}\n\nexport const StatusPeekTrigger = ({\n store,\n duration = 10000,\n}: StatusPeekTriggerProps) => {\n useEffect(() => {\n if (peekedOnce) return;\n peekedOnce = true;\n store?.setStatusExpanded(true);\n // No cleanup — the store call is safe after unmount and the component\n // may be evicted before the timer fires (non-persist NodeBlock).\n setTimeout(() => {\n store?.setStatusExpanded(false);\n }, duration);\n }, [store, duration]);\n\n return <Text>You can view the Wizard&apos;s status below.</Text>;\n};\n","/**\n * POSTHOG_DATA_FLOW — ASCII diagram of the PostHog event ingestion flow.\n */\n\nimport { Text } from 'ink';\nimport { Colors } from '@ui/tui/styles';\nimport type { ContentBlock } from '@ui/tui/primitives/content-types';\n\nexport const POSTHOG_DATA_FLOW: ContentBlock = {\n type: 'lines',\n interval: 500,\n pause: 8000,\n // Box is 30 chars wide between │ borders.\n // Labels: 1-char indent. Arrows: \" ↓ \" (5). Sub-items: \" │ \" (7).\n lines: [\n <Text color=\"gray\">{' ┌──────────────────────────────┐'}</Text>,\n <Text>\n <Text color=\"gray\">{' │ '}</Text>\n <Text bold color=\"cyan\">\n Your App\n </Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ │ '}</Text>\n <Text>posthog.capture()</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ │ '}</Text>\n <Text dimColor>custom events</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ │ '}</Text>\n <Text dimColor>custom properties</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ │ '}</Text>\n <Text dimColor>person profiles</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ ↓ '}</Text>\n <Text dimColor>groups</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ '}</Text>\n <Text bold color={Colors.accent}>\n PostHog SDK\n </Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ ↓ '}</Text>\n <Text>HTTP</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ '}</Text>\n <Text bold color={Colors.accent}>\n PostHog Cloud\n </Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ ↓ '}</Text>\n <Text>query + visualize</Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │ '}</Text>\n <Text bold color=\"green\">\n Dashboards & Insights\n </Text>\n <Text color=\"gray\">{' │'}</Text>\n </Text>,\n <Text color=\"gray\">{' └──────────────────────────────┘'}</Text>,\n ],\n};\n","/**\n * PRODUCT_SUITE_BLOCK — Two-column listing of PostHog products.\n */\n\nimport { Text } from 'ink';\nimport type { ContentBlock } from '@ui/tui/primitives/content-types';\n\nexport const PRODUCT_SUITE_BLOCK: ContentBlock = {\n type: 'lines',\n interval: 1000,\n pause: 15000,\n lines: [\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Product Analytics '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Error Tracking'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Web Analytics '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Session Replay'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Feature Flags '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Data Pipelines'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Experiments '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Data Warehouse'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'AI Observability '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Surveys'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Workflows '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Logs'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Product Tours '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Support'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Revenue Analytics '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'Endpoints'}\n </Text>,\n <Text>\n <Text color=\"cyan\">{' ◆ '}</Text>\n {'Customer Analytics '}\n <Text color=\"cyan\">{'◆ '}</Text>\n {'PostHog Code'}\n </Text>,\n ],\n};\n","/**\n * LINE_CHART_BLOCK — ASCII trends chart illustrating an insight.\n */\n\nimport { Text } from 'ink';\nimport type { ContentBlock } from '@ui/tui/primitives/content-types';\n\nexport const LINE_CHART_BLOCK: ContentBlock = {\n type: 'lines',\n interval: 300,\n pause: 6000,\n lines: [\n <Text bold>{' Trends · user signups (monthly)'}</Text>,\n <Text> </Text>,\n // 10k\n <Text>\n <Text color=\"gray\">{' 10k ┤'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭──'}</Text>\n <Text dimColor>{' 9,575'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭╯'}</Text>\n </Text>,\n // 7.5k\n <Text>\n <Text color=\"gray\">{' 7.5k ┤'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭╯'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭─╯'}</Text>\n </Text>,\n // 5k\n <Text>\n <Text color=\"gray\">{' 5k ┤'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭─╯'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭──╯'}</Text>\n </Text>,\n // 2.5k\n <Text>\n <Text color=\"gray\">{' 2.5k ┤'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭───╯'}</Text>\n </Text>,\n <Text>\n <Text color=\"gray\">{' │'}</Text>\n {' '}\n <Text color=\"cyan\">{'╭──────╯'}</Text>\n </Text>,\n // 0\n <Text>\n <Text color=\"gray\">{' 0 ┤'}</Text>\n <Text color=\"cyan\">{'──────╯'}</Text>\n </Text>,\n // X-axis\n <Text color=\"gray\">{' └┬─────┬─────┬─────┬─────┬──'}</Text>,\n <Text dimColor>{' May Aug Nov Feb May'}</Text>,\n ],\n};\n","/**\n * FUNNEL_BLOCK — ASCII funnel illustrating step conversion.\n */\n\nimport { Text } from 'ink';\nimport type { ContentBlock } from '@ui/tui/primitives/content-types';\n\nexport const FUNNEL_BLOCK: ContentBlock = {\n type: 'lines',\n interval: 200,\n pause: 8000,\n lines: [\n <Text bold>{' Funnel · ride conversion'}</Text>,\n <Text> </Text>,\n // Step 1\n <Text>\n {' '}\n <Text bold>1</Text>\n {' app_launched'}\n {' '}\n <Text bold color=\"green\">\n 100.00%\n </Text>\n </Text>,\n <Text color=\"cyan\">{' ██████████████████████████████'}</Text>,\n <Text dimColor>{' → 1,200 users'}</Text>,\n <Text> </Text>,\n // Step 2\n <Text>\n {' '}\n <Text bold>2</Text>\n {' ride_requested'}\n {' '}\n <Text dimColor>{'avg 2m 30s'}</Text>\n {' '}\n <Text bold color=\"green\">\n 72.00%\n </Text>\n </Text>,\n <Text>\n {' '}\n <Text color=\"cyan\">{'██████████████████████'}</Text>\n <Text dimColor>{'░░░░░░░░░'}</Text>\n </Text>,\n <Text>\n {' '}\n <Text dimColor>→ 864 users</Text>\n {' '}\n <Text color=\"red\">↘</Text>\n <Text dimColor>{' 336 (28%)'}</Text>\n </Text>,\n <Text> </Text>,\n // Step 3\n <Text>\n {' '}\n <Text bold>3</Text>\n {' ride_accepted'}\n {' '}\n <Text dimColor>{'avg 5m 12s'}</Text>\n {' '}\n <Text bold color=\"green\">\n 51.00%\n </Text>\n </Text>,\n <Text>\n {' '}\n <Text color=\"cyan\">{'██████████████████'}</Text>\n <Text dimColor>{'░░░░░░░░░░░░░'}</Text>\n </Text>,\n <Text>\n {' '}\n <Text dimColor>→ 612 users</Text>\n {' '}\n <Text color=\"red\">↘</Text>\n <Text dimColor>{' 252 (29%)'}</Text>\n </Text>,\n <Text> </Text>,\n // Step 4\n <Text>\n {' '}\n <Text bold>4</Text>\n {' ride_started'}\n {' '}\n <Text dimColor>{'avg 1m 45s'}</Text>\n {' '}\n <Text bold color=\"green\">\n 38.00%\n </Text>\n </Text>,\n <Text>\n {' '}\n <Text color=\"cyan\">{'█████████████'}</Text>\n <Text dimColor>{'░░░░░░░░░░░░░░░░░░'}</Text>\n </Text>,\n <Text>\n {' '}\n <Text dimColor>→ 456 users</Text>\n {' '}\n <Text color=\"red\">↘</Text>\n <Text dimColor>{' 156 (25%)'}</Text>\n </Text>,\n ],\n};\n","/**\n * Integration learn-deck — the narrative script played while the agent\n * runs the PostHog integration flow. Weaves typewriter lines, pauses,\n * `clear` markers, and the diagram blocks into one sequence.\n */\n\nimport { Text } from 'ink';\nimport { Colors } from '@ui/tui/styles';\nimport type { WizardStore } from '@ui/tui/store';\nimport { TextRevealMode } from '@ui/tui/primitives/TextBlock';\nimport type { ContentBlock } from '@ui/tui/primitives/content-types';\nimport { StatusPeekTrigger } from '@ui/tui/components/StatusPeekTrigger';\nimport { POSTHOG_DATA_FLOW } from './data-flow.js';\nimport { PRODUCT_SUITE_BLOCK } from './product-suite.js';\nimport { LINE_CHART_BLOCK } from './line-chart.js';\nimport { FUNNEL_BLOCK } from './funnel.js';\n\nexport const getContentBlocks = (store?: WizardStore): ContentBlock[] => [\n {\n // Name comes from the login profile; falls back when absent (CI keys).\n content: store?.session.apiUser?.first_name\n ? `Welcome, ${store.session.apiUser.first_name}.`\n : 'Welcome.',\n pause: 3000,\n mode: TextRevealMode.Typewriter,\n animationInterval: 160,\n },\n\n { content: 'The Wizard is an agent.', pause: 4000 },\n\n {\n content: 'It handles the entire PostHog setup process on your behalf.',\n pause: 5000,\n },\n\n {\n content:\n \"As we speak, it's building a plan to set up PostHog in your project.\",\n pause: 6000,\n },\n\n { type: 'clear', pause: 2000 },\n\n {\n pause: 5000,\n persist: true,\n content: <StatusPeekTrigger store={store} />,\n },\n\n {\n pause: 6000,\n content: (\n <Text>\n Press{' '}\n <Text color={Colors.accent} bold>\n S\n </Text>{' '}\n to expand or collapse the status.\n </Text>\n ),\n },\n\n { type: 'clear', pause: 2000 },\n\n {\n content: 'It takes about eight minutes.',\n pause: 2000,\n },\n\n {\n content: 'So grab some coffee ☕️.',\n pause: 2000,\n },\n\n {\n content: 'Or stick around and learn about PostHog.',\n pause: 5000,\n },\n\n { type: 'clear', pause: 3000 },\n\n {\n content: 'Events are the foundation of the PostHog platform.',\n pause: 4000,\n },\n\n {\n content:\n 'Every time an action is performed in your codebase — like button clicks, function calls, or thrown errors — we can capture an event.',\n pause: 6000,\n },\n\n {\n content: 'Events are sent to PostHog and joined with other product data.',\n pause: 6000,\n },\n\n { type: 'clear', pause: 1000 },\n\n { content: \"Here's the flow.\", pause: 1000 },\n\n POSTHOG_DATA_FLOW,\n\n { type: 'clear', pause: 2000 },\n\n {\n content:\n 'With enough event data, you can answer powerful questions about your product.',\n pause: 4000,\n },\n\n { content: 'And create insights.', pause: 4000 },\n\n { type: 'clear', pause: 500 },\n\n { content: 'Like trends to measure growth.', pause: 2500 },\n\n LINE_CHART_BLOCK,\n\n { type: 'clear', pause: 500 },\n\n { content: 'Or funnels to reveal bottlenecks.', pause: 2500 },\n\n FUNNEL_BLOCK,\n\n { type: 'clear', pause: 1000 },\n\n {\n content: 'Use those signals to decide what to build next.',\n pause: 4000,\n },\n\n { content: 'PostHog has all the dev tools you need.', pause: 3000 },\n\n PRODUCT_SUITE_BLOCK,\n];\n","/**\n * The one-line prompt the operator pastes into their own coding agent after a\n * run: open the setup-report notebook, work its \"Verify before merging\"\n * checklist. Surfaced via `OutroData.handoffPrompt` (printed to scrollback on\n * exit); only exists when the run captured a notebook URL, since no report\n * file is written. The wording demands investigate-then-approval, and stops\n * there — the operator's own agent governs how changes land. Background:\n * https://github.com/PostHog/wizard/issues/447\n */\nexport function buildCodingAgentPrompt(notebookUrl: string): string {\n return `Open ${notebookUrl} (the PostHog setup report) and work through its \"Verify before merging\" checklist: investigate each item, then list the changes you'd make and get my approval before applying any of them.`;\n}\n","import type { ProgramConfig, ProgramStep } from '@lib/programs/program-step';\nimport { runAgent, type ProgramRun } from '@lib/agent/agent-runner';\nimport { WIZARD_TOOL_NAMES } from '@lib/wizard-tools';\nimport type { WizardSession } from '@lib/wizard-session';\nimport { mayReportScanResults, OutroKind, RunPhase } from '@lib/wizard-session';\nimport { AgentSignals } from '@lib/agent/agent-interface';\nimport {\n DEFAULT_PACKAGE_INSTALLATION,\n SPINNER_MESSAGE,\n} from '@lib/framework-config';\nimport { tryGetPackageJson, isUsingTypeScript } from '@utils/setup-utils';\nimport { analytics } from '@utils/analytics';\nimport { detectFramework, gatherFrameworkContext } from '@lib/detection/index';\nimport { scopeInstallDirToProject } from '@lib/detection/project-scope';\nimport { FRAMEWORK_REGISTRY } from '@lib/registry';\nimport { wizardAbort } from '@utils/wizard-abort';\nimport { ErrorCodes } from '@lib/errors';\nimport { WIZARD_INTERACTION_EVENT_NAME } from '@lib/constants';\nimport { getUI } from '@ui/index';\nimport { requestDeepLink } from '@utils/provisioning';\nimport { openTrackedLink, withUtm } from '@utils/links';\nimport type { HostResolution } from '@lib/host-resolution';\nimport { getDetectedWarehouseSources } from '@lib/programs/warehouse-source/detect';\nimport { shouldDisableAsk } from '@lib/agent/runner/shared/bootstrap';\nimport { POSTHOG_INTEGRATION_PROGRAM } from './steps.js';\nimport { getContentBlocks } from './content/index.js';\nimport { buildCodingAgentPrompt } from './handoff.js';\nimport { EVENT_PLAN_FILE } from './constants.js';\n\nconst DASHBOARD_DEEP_LINK_KEY = 'dashboardDeepLink';\n\nconst WAREHOUSE_SOURCES_DOCS_URL =\n 'https://posthog.com/docs/data-warehouse/sources';\n\nfunction resolveContinueUrl(\n sess: WizardSession,\n host: HostResolution,\n deepLink: unknown,\n): string | undefined {\n if (!sess.signup) return undefined;\n if (typeof deepLink === 'string' && deepLink) return deepLink;\n return withUtm(`${host.appHost}/products?source=wizard`, 'outro-continue');\n}\n\n/** Sources listed with their own link before the outro falls back to a summary line. */\nconst WAREHOUSE_LINK_LIMIT = 3;\n\n/**\n * The app's new-source page, pre-selected to one source kind.\n *\n * `kind` is matched case-insensitively against the connector list, and a kind\n * the app cannot resolve lands on the source catalog rather than erroring. So a\n * source we detect but the app has not shipped a connector for still takes the\n * user somewhere useful.\n */\nfunction warehouseSourceUrl(\n host: HostResolution,\n projectId: number | string,\n kind: string,\n): string {\n const path = `${\n host.appHost\n }/project/${projectId}/data-warehouse/new-source?kind=${encodeURIComponent(\n kind,\n )}`;\n return withUtm(path, 'outro-warehouse');\n}\n\n/**\n * Outro suggestion for data sources found in the project but not connected.\n *\n * A pointer at the app, not an inline flow. Connecting a source needs\n * interactive credential collection, and chaining that as a second agent run\n * before the outro would let any of its terminal failure paths `process.exit()`\n * — costing the user the success outro and the post-outro MCP / Slack steps on\n * a run where PostHog installed fine.\n *\n * Each source gets its own pre-filled link, because the alternative we shipped\n * first — naming the `wizard warehouse` command — asks the user to start a\n * second CLI run before they can connect anything. A link opens the form for\n * that one source. The command line stays for anyone who wants every source in\n * one pass, and it is the only route offered once the list is too long to read.\n *\n * Returns undefined when nothing was detected, so the outro is unchanged for\n * projects with no connectable source.\n */\nfunction buildWarehouseNextSteps(\n sess: WizardSession,\n host: HostResolution,\n projectId: number | string,\n): { heading: string; items: string[] } | undefined {\n const sources = getDetectedWarehouseSources(sess);\n if (sources.length === 0) return undefined;\n\n const listed = sources.slice(0, WAREHOUSE_LINK_LIMIT);\n const items = listed.map(\n (s) => `Connect ${s.label}: ${warehouseSourceUrl(host, projectId, s.kind)}`,\n );\n\n const remaining = sources.length - listed.length;\n if (remaining > 0) {\n items.push(`And ${remaining} more we found in this project.`);\n }\n items.push('Connect them all at once with: npx @posthog/wizard warehouse');\n\n return { heading: 'Query your other data in PostHog:', items };\n}\n\n/**\n * Prompt fragment asking the agent to note the detected data sources in the\n * setup report's checklist.\n *\n * Empty string when nothing was detected, so the prompt is byte-identical to\n * today for projects with no connectable source. Best-effort by nature — the\n * agent may word it differently or skip it. That is acceptable here precisely\n * because it is a note in a report: the outro `nextSteps` bullet carries the\n * same information deterministically, so nothing is lost if the agent drops it.\n */\nfunction warehouseReportInstruction(sess: WizardSession): string {\n const sources = getDetectedWarehouseSources(sess);\n if (sources.length === 0) return '';\n\n const labels = sources.map((s) => s.label).join(', ');\n return `Finally: this project also contains data sources PostHog can import (${labels}). In the setup report's \"Verify before merging\" checklist, add one item noting these were found and that \\`npx @posthog/wizard warehouse\\` will connect them to PostHog's data warehouse. Do not attempt to set them up yourself in this run.`;\n}\n\n/**\n * The orchestrator task that connects the data sources detection found in the\n * project — the one step of the flow that stops to ask the user for\n * credentials. Queued here rather than by the planner: whether it belongs in\n * the run is a fact about the project the wizard already scanned, so a model\n * can neither invent it nor forget it.\n *\n * It runs at the end of the queue, not the start. Where exactly is the agent\n * prompt's business (`dependsOn` in the warehouse agent's frontmatter, resolved\n * by `seeded-deps.ts` once the planner has run) — this file only decides whether\n * the task belongs in the run at all.\n *\n * Empty when nothing was detected, and in CI, signup, and any other run where\n * `wizard_ask` is disabled — a credential prompt nobody can answer would burn\n * the task's whole timeout and then fail the run.\n */\nconst warehouseSeedTasks: NonNullable<ProgramConfig['seedTasks']> = (sess) => {\n if (shouldDisableAsk(sess)) return [];\n const sources = getDetectedWarehouseSources(sess);\n if (sources.length === 0) return [];\n\n // The task is queued either way. A decline withholds reporting, not the\n // feature. See the matching gate in reportWarehouseSourcesDetected.\n if (mayReportScanResults(sess)) {\n analytics.wizardCapture('orchestrator warehouse task queued', {\n warehouse_source_count: sources.length,\n warehouse_source_kinds: sources.map((s) => s.kind),\n });\n }\n return [\n {\n type: 'warehouse',\n inputs: {\n sources: sources.map((s) => ({\n kind: s.kind,\n label: s.label,\n mode: s.mode,\n matchedSignal: s.matchedSignal,\n })),\n },\n notice: {\n title: 'Connect your data sources',\n // Two moments, and the copy has to name both. The answer is given here,\n // at the start of the run. The credential questions arrive at the end of\n // it, minutes later. So this must not read as \"expect a prompt any\n // moment now\", and equally must not read as \"walk away for the run\".\n body: [\n 'We detected some warehouse sources we can connect to enrich your PostHog data. Answer now, and we connect them at the end of the run, after your code changes. We will ask you for the credentials at that point, and beep when we do.',\n \"You can select [Skip] if you'd like to do this later in PostHog.\",\n ],\n items: sources.map((s) => s.label),\n docsLabel: 'Learn more about warehouse sources',\n docsUrl: WAREHOUSE_SOURCES_DOCS_URL,\n prompt: 'Connect these during setup?',\n confirmLabel: 'Continue [Enter]',\n cancelLabel: 'Skip [Esc]',\n },\n },\n ];\n};\n\nexport const SETUP_REPORT_FILE = 'posthog-setup-report.md';\nexport { EVENT_PLAN_FILE } from './constants.js';\n\nexport const posthogIntegrationConfig: ProgramConfig = {\n command: 'integrate',\n description: 'Set up PostHog SDK integration',\n id: 'posthog-integration',\n agentFlow: 'integration-v2',\n eventPlanFile: EVENT_PLAN_FILE,\n steps: POSTHOG_INTEGRATION_PROGRAM,\n getContentBlocks,\n // Basic integration runs without structured user input; drop wizard_ask\n // so the model can't pop modal prompts mid-run. The runner forwards this\n // list to the general-purpose subagent as well, so dispatched subagents\n // can't reach around the parent and ask either.\n disallowedTools: [WIZARD_TOOL_NAMES.wizardAsk],\n\n seedTasks: warehouseSeedTasks,\n\n // CI-mode prerequisite work: the headless equivalent of the detect step's\n // onReady hook. Auto-detect the framework, then gather context.\n ciPreRun: async (session: WizardSession): Promise<void> => {\n await scopeInstallDirToProject(session);\n\n const integration = await detectFramework(session.installDir);\n if (!integration) {\n await wizardAbort({\n code: ErrorCodes.DetectNoFramework,\n message: 'Could not auto-detect your framework for this project.',\n });\n return;\n }\n session.integration = integration;\n analytics.setTag('integration', integration);\n\n const frameworkConfig = FRAMEWORK_REGISTRY[integration];\n session.frameworkConfig = frameworkConfig;\n\n const context = await gatherFrameworkContext(frameworkConfig, {\n installDir: session.installDir,\n debug: session.debug,\n signup: session.signup,\n ci: true,\n benchmark: session.benchmark,\n yaraReport: session.yaraReport,\n });\n for (const [key, value] of Object.entries(context)) {\n if (!(key in session.frameworkContext)) {\n session.frameworkContext[key] = value;\n }\n }\n },\n\n run: async (session: WizardSession): Promise<ProgramRun> => {\n const config = session.frameworkConfig!;\n\n const typeScriptDetected = isUsingTypeScript({\n installDir: session.installDir,\n });\n session.typescript = typeScriptDetected;\n analytics.setTag('typescript', typeScriptDetected);\n\n // Read package.json and resolve framework version\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n const packageJson = await tryGetPackageJson({\n installDir: session.installDir,\n });\n if (packageJson) {\n const { hasDeclaredDependency } = await import('@utils/package-json');\n if (!hasDeclaredDependency(config.detection.packageName, packageJson)) {\n getUI().log.warn(\n `${config.detection.packageDisplayName} does not seem to be installed. Continuing anyway — the agent will handle it.`,\n );\n }\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n getUI().log.warn(\n 'Could not find package.json. Continuing anyway — the agent will handle it.',\n );\n }\n } else {\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Analytics tags\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n const frameworkContext = session.frameworkContext;\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n return {\n integrationLabel: config.metadata.integration,\n additionalMcpServers: config.metadata.additionalMcpServers,\n detectPackageManager: config.detection.detectPackageManager,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n reportFile: SETUP_REPORT_FILE,\n docsUrl: config.metadata.docsUrl,\n errorMessage: 'Integration failed',\n additionalFeatureQueue: session.additionalFeatureQueue,\n // The seeded warehouse task's fallback, when a user cannot hand over a\n // credential, is to give them the pre-filled new-source URL. That only\n // works if the overlay renders it as a link they can open or copy.\n richLinks: true,\n\n customPrompt: (ctx) => {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- PostHog Project ID: ${ctx.projectId}\n- Framework: ${config.metadata.name} ${frameworkVersion || 'latest'}\n- TypeScript: ${typeScriptDetected ? 'Yes' : 'No'}\n- PostHog public token: ${ctx.projectApiKey}\n- PostHog Host: ${ctx.host.apiHost}\n- Project type: ${config.prompts.projectTypeDetection}\n- Package installation: ${\n config.prompts.packageInstallation ?? DEFAULT_PACKAGE_INSTALLATION\n }${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: Call load_skill_menu (from the wizard-tools MCP server) to see available skills.\n If the tool fails, emit: ${\n AgentSignals.ERROR_MCP_MISSING\n } Could not load skill menu and halt.\n\n Choose a skill from the \\`integration\\` category that matches this project's framework. Do NOT pick skills from other categories (llm-analytics, error-tracking, feature-flags, omnibus, etc.) — those are handled separately.\n If no suitable integration skill is found, emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Call install_skill (from the wizard-tools MCP server) with the chosen skill ID (e.g., \"integration-nextjs-app-router\").\n Do NOT run any shell commands to install skills.\n If install_skill fails, emit on its own line: ${\n AgentSignals.SKILL_INSTALL_FAILED\n } <skill id — one-line reason>. Then CONTINUE and SKIP to STEP 5 the integration without the skill, following these steps and your knowledge of ${\n config.metadata.name\n } and PostHog's official docs, and note in the setup report that the skill could not be installed.\n\nSTEP 3: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 4: Follow the skill's program files in sequence. Look for numbered program files in the references (e.g., files with patterns like \"1-\", \"2-\", \"3-\"). Start with the first one and proceed through each step until completion. Each program file will tell you what to do and which file comes next. Never directly write PostHog tokens directly to code files; always use environment variables.\n\nSTEP 5: Set up environment variables for PostHog using the wizard-tools MCP server (this runs locally — secret values never leave the machine):\n - Use check_env_keys to see which keys the project already sets, and where. Omit filePath and it scans every .env file in the project, so you don't have to guess between .env, .env.local and a nested one. It answers { status, foundIn } per key: \"present\" means a real env file sets the key, while a key found only in a committed template (.env.example and friends) reads as \"missing\" — a template documents a key rather than setting it, and is never a file to write credentials into.\n - Use set_env_values to create or update the PostHog public token and host, using the appropriate environment variable naming convention for ${\n config.metadata.name\n }, which you'll find in example code. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.\n - Reference these environment variables in the code files you create instead of hardcoding the public token and host.\n\nImportant: Use the detect_package_manager tool (from the wizard-tools MCP server) to determine which package manager the project uses, then run its install command to add the SDK. Do not manually search for lockfiles or config files. If a file already EXISTS, read it immediately before you edit or overwrite it — writing from a stale read causes a tool failure. Creating a brand-new file needs no prior read: never read a path that does not exist yet; just write it.\n\n${warehouseReportInstruction(session)}\n`;\n },\n\n postRun: async (sess, credentials) => {\n const envVars = config.environment.getEnvVars(\n credentials.projectApiKey,\n credentials.host.apiHost,\n );\n if (config.environment.uploadToHosting) {\n const { uploadEnvironmentVariablesStep } = await import(\n '@steps/index'\n );\n const uploadedEnvVars = await uploadEnvironmentVariablesStep(\n envVars,\n {\n integration: config.metadata.integration,\n session: sess,\n },\n );\n if (uploadedEnvVars.length > 0) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'wizard_env_vars_uploaded',\n integration: config.metadata.integration,\n variable_count: uploadedEnvVars.length,\n variable_keys: uploadedEnvVars,\n });\n }\n }\n\n if (sess.signup) {\n const deepLink = await requestDeepLink(\n credentials.accessToken,\n credentials.host,\n );\n if (deepLink) {\n const taggedDeepLink = withUtm(deepLink, 'dashboard-deeplink');\n sess.frameworkContext[DASHBOARD_DEEP_LINK_KEY] = taggedDeepLink;\n openTrackedLink(taggedDeepLink, 'dashboard-deeplink', {\n auto: true,\n });\n }\n }\n },\n\n buildOutroData: (sess, credentials) => {\n const envVars = config.environment.getEnvVars(\n credentials.projectApiKey,\n credentials.host.apiHost,\n );\n const deepLink = sess.frameworkContext[DASHBOARD_DEEP_LINK_KEY];\n const continueUrl = resolveContinueUrl(\n sess,\n credentials.host,\n deepLink,\n );\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? 'Added environment variables to .env file'\n : '',\n ].filter(Boolean);\n\n return {\n kind: OutroKind.Success as const,\n message: 'Successfully installed PostHog!',\n changes,\n docsUrl: config.metadata.docsUrl,\n continueUrl,\n nextSteps: buildWarehouseNextSteps(\n sess,\n credentials.host,\n credentials.projectId,\n ),\n // Set once the agent mirrors the report into a notebook and emits [NOTEBOOK_URL].\n notebookUrl: sess.notebookUrl ?? undefined,\n // No report file — the prompt points at the notebook, when the run captured one.\n handoffPrompt: sess.notebookUrl\n ? buildCodingAgentPrompt(sess.notebookUrl)\n : undefined,\n };\n },\n };\n },\n};\n\nexport { POSTHOG_INTEGRATION_PROGRAM } from './steps.js';\n\n/**\n * Self-contained run step that runs the integration agent. Other programs\n * import this and splice it into their own step list to compose the\n * integration's work as one of their run steps — self-driving sets up PostHog\n * this way before its own run. The host program supplies `show`/`onRunPrep`/\n * `targetDir`; this carries the run.\n */\nexport const integrationRunStep: ProgramStep = {\n id: 'run',\n label: 'Integration',\n screenId: 'run',\n // composed: runs inside the host program (self-driving), so skip the\n // integration's terminal outro + analytics shutdown of the shared client.\n run: (session) =>\n runAgent(posthogIntegrationConfig, session, { composed: true }),\n isComplete: (session) =>\n session.runPhase === RunPhase.Completed ||\n session.runPhase === RunPhase.Error,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,MAAM,sBAAsC,OAAO,QACjD,mBACD,CAAC,KAAK,CAAC,IAAI,aAAa;CAAE;CAAI,MAAM,OAAO,SAAS;CAAM,EAAE;;AAG7D,eAAsB,0BACpB,SACA,SAMiC;AAEjC,QAAO,wBAAwB,SAAS;EACtC,GAAG;EACH,SAAS;EACT,SAAS;EACV,CAAC;;;AAIJ,SAAgB,yBACd,UAC4B;AAC5B,QACE,SAAS,MAAM,MAAM,EAAE,gBAAgB,QAAQ,EAAE,YAAY,KAAK,IAClE,SAAS,MAAM,MAAM,EAAE,YAAY,QAAQ,CAAC,EAAE,WAAW;;;AAc7D,MAAM,YAAY,OAAO,YAAY;AAErC,SAAS,eACP,SACA,aAAsC,EAAE,EAClC;AACN,WAAU,cAAc,qBAAqB;EAAE;EAAS,GAAG;EAAY,CAAC;;;AAI1E,eAAsB,yBACpB,SACe;AAEf,OAAM,aAAa,SAAS,sBAAsB;AAElD,MADc,MAAM,UAAU,sBAAsB,EAAA,kDACe,QAAQ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YAAY,aACZ,YAAY,KACb;AACD,SAAI,UAAU;MACZ,MAAM,iBAAiB,QAAQ,UAAU,qBAAqB;AAC9D,WAAK,iBAAiB,2BAA2B;AACjD,sBAAgB,gBAAgB,sBAAsB,EACpD,MAAM,MACP,CAAC;;;;GAKR,iBAAiB,MAAM,gBAAgB;IACrC,MAAM,UAAU,OAAO,YAAY,WACjC,YAAY,eACZ,YAAY,KAAK,QAClB;IACD,MAAM,WAAW,KAAK,iBAAiB;IACvC,MAAM,cAAc,mBAClB,MACA,YAAY,MACZ,SACD;AASD,WAAO;KACL,MAAA;KACA,SAAS;KACT,SAVc,CACd,GAAG,OAAO,GAAG,gBAAgB,iBAAiB,EAC9C,OAAO,KAAK,QAAQ,CAAC,SAAS,IAC1B,6CACA,GACL,CAAC,OAAO,QAAQ;KAMf,SAAS,OAAO,SAAS;KACzB;KACA,WAAW,wBACT,MACA,YAAY,MACZ,YAAY,UACb;KAED,aAAa,KAAK,eAAe,KAAA;KAEjC,eAAe,KAAK,cAChB,uBAAuB,KAAK,YAAY,GACxC,KAAA;KACL;;GAEJ;;CAEJ;;;;;;;;AAWD,MAAa,qBAAkC;CAC7C,IAAI;CACJ,OAAO;CACP,UAAU;CAGV,MAAM,YACJ,SAAS,0BAA0B,SAAS,EAAE,UAAU,MAAM,CAAC;CACjE,aAAa,YACX,QAAQ,aAAA,eACR,QAAQ,aAAA;CACX"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
2
- import { H as POSTHOG_DEV_CLIENT_ID, Q as POSTHOG_US_CLIENT_ID, W as POSTHOG_EU_CLIENT_ID, pt as WIZARD_USER_AGENT, s as logToFile, ut as WIZARD_PROVISIONING_SCOPES } from "./debug-YQdeZulR.js";
3
- import { n as analytics } from "./analytics-D54mLptm.js";
2
+ import { K as POSTHOG_EU_CLIENT_ID, W as POSTHOG_DEV_CLIENT_ID, dt as WIZARD_PROVISIONING_SCOPES, et as POSTHOG_US_CLIENT_ID, mt as WIZARD_USER_AGENT, s as logToFile } from "./debug-aXxgvtal.js";
3
+ import { n as analytics } from "./analytics-DsMH06jo.js";
4
4
  import axios from "axios";
5
5
  import * as crypto from "node:crypto";
6
6
  import { z } from "zod";
@@ -365,4 +365,4 @@ async function requestDeepLink(accessToken, host, opts) {
365
365
  //#endregion
366
366
  export { detectRegion as a, getIntegrationAuthorizeUrl as c, getUiHostFromHost as d, resolveBaseUrl as f, requestDeepLink as i, getLlmGatewayUrl as l, provisionNewAccount as n, getCloudUrl as o, provisioning_exports as r, getHost as s, ProvisionedAccountUnreadableError as t, getOAuthUrl as u };
367
367
 
368
- //# sourceMappingURL=provisioning-f7lA29tW.js.map
368
+ //# sourceMappingURL=provisioning-94OneD64.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"provisioning-f7lA29tW.js","names":[],"sources":["../src/utils/urls.ts","../src/utils/provisioning.ts"],"sourcesContent":["import axios from 'axios';\nimport { IS_DEV, WIZARD_USER_AGENT } from '@lib/constants';\nimport type { CloudRegion } from './types';\n\n/**\n * Resolve a pinned PostHog base URL from an optional override. When present, it\n * becomes the single source of truth for every PostHog origin — the\n * API/ingestion host, the cloud/app URL, and the OAuth server — bypassing\n * region resolution entirely.\n *\n * The override lives on the session (`session.baseUrl`, set by `--base-url`) and\n * is threaded in by callers, so there is no hidden module-level state. A `--base-url`\n * value wins; otherwise a dev/test build implies `localhost:8010`; otherwise the\n * result is `undefined`, meaning region-based resolution applies.\n *\n * This is the runtime equivalent of the `IS_DEV` localhost routing: `IS_DEV` is a\n * build-time constant that tsdown compiles out of production builds, so it can't\n * point a shipped wizard at a local stack — `--base-url` can. Both feed this one\n * resolver so every URL helper only asks the question once.\n */\nexport const resolveBaseUrl = (override?: string): string | undefined => {\n return override?.trim() || (IS_DEV ? 'http://localhost:8010' : undefined);\n};\n\nexport const getUiHostFromHost = (host: string) => {\n if (host.includes('us.i.posthog.com')) {\n return 'https://us.posthog.com';\n }\n\n if (host.includes('eu.i.posthog.com')) {\n return 'https://eu.posthog.com';\n }\n\n return host;\n};\n\nexport const getHost = (region: CloudRegion, baseUrl?: string) => {\n const override = resolveBaseUrl(baseUrl);\n if (override) {\n return override;\n }\n\n if (region === 'eu') {\n return 'https://eu.i.posthog.com';\n }\n\n return 'https://us.i.posthog.com';\n};\n\nexport const getCloudUrl = (region: CloudRegion, baseUrl?: string) => {\n const override = resolveBaseUrl(baseUrl);\n if (override) {\n return override;\n }\n\n if (region === 'eu') {\n return 'https://eu.posthog.com';\n }\n\n return 'https://us.posthog.com';\n};\n\nexport async function detectRegion(\n accessToken: string,\n baseUrl?: string,\n): Promise<CloudRegion> {\n // With a pinned base URL there is only one instance to talk to — skip the\n // us/eu probe and default the region label to 'us'. (Covers IS_DEV too, via\n // resolveBaseUrl.) The URLs themselves come from the override, not this label.\n if (resolveBaseUrl(baseUrl)) {\n return 'us';\n }\n\n const headers = {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n };\n\n const [usResult, euResult] = await Promise.allSettled([\n axios.get('https://us.posthog.com/api/users/@me/', { headers }),\n axios.get('https://eu.posthog.com/api/users/@me/', { headers }),\n ]);\n\n if (usResult.status === 'fulfilled') return 'us';\n if (euResult.status === 'fulfilled') return 'eu';\n\n throw new Error(\n 'Could not determine cloud region from access token. Please check your PostHog account.',\n );\n}\n\nexport const getLlmGatewayUrl = (host: string) => {\n if (host.includes('host.docker.internal')) {\n return 'http://host.docker.internal:3308/wizard';\n }\n\n if (host.includes('localhost')) {\n return 'http://localhost:3308/wizard';\n }\n\n if (host.includes('eu.posthog.com') || host.includes('eu.i.posthog.com')) {\n return 'https://gateway.eu.posthog.com/wizard';\n }\n\n return 'https://gateway.us.posthog.com/wizard';\n};\n\n/** Region-agnostic prod OAuth server. Resolves to the right region server-side. */\nconst PROD_OAUTH_URL = 'https://oauth.posthog.com';\n\n/**\n * OAuth server URL. Follows the base-URL override (and thus IS_DEV → localhost),\n * otherwise the region-agnostic prod OAuth host.\n */\nexport const getOAuthUrl = (baseUrl?: string): string =>\n resolveBaseUrl(baseUrl) ?? PROD_OAUTH_URL;\n\n/**\n * One-click integration install/authorize deep-link. Opening it in the user's\n * logged-in browser runs the install directly — no settings-page hunting. The\n * one link covers fresh install, link-existing, and re-auth.\n */\nexport const getIntegrationAuthorizeUrl = (\n appHost: string,\n projectId: number,\n kind: string,\n): string =>\n `${appHost.replace(\n /\\/$/,\n '',\n )}/api/environments/${projectId}/integrations/authorize?kind=${kind}`;\n","/**\n * Provisioning API client for creating new PostHog accounts.\n *\n * Uses the agentic provisioning API with PKCE auth:\n * 1. POST /account_requests - create account, get auth code\n * 2. POST /oauth/token - exchange code for tokens (with PKCE)\n * 3. POST /resources - provision project, get API key\n */\n\nimport * as crypto from 'node:crypto';\nimport axios from 'axios';\nimport { z } from 'zod';\nimport {\n POSTHOG_DEV_CLIENT_ID,\n POSTHOG_EU_CLIENT_ID,\n POSTHOG_US_CLIENT_ID,\n WIZARD_PROVISIONING_SCOPES,\n WIZARD_USER_AGENT,\n} from '@lib/constants';\nimport { resolveBaseUrl } from './urls';\nimport { logToFile } from './debug';\nimport { analytics } from './analytics';\nimport type { HostResolution } from '@lib/host-resolution';\n\nconst API_VERSION = '0.1d';\n\n/**\n * Provisioning host. Follows a `--base-url` override (and IS_DEV → localhost),\n * else the prod provisioning host for the target region. Unlike the login OAuth\n * flow (which goes through the region-agnostic `oauth.posthog.com` proxy), the\n * provisioning API is region-specific: an EU account must be created against\n * `eu.posthog.com`, and the subsequent token-exchange / resources calls stay on\n * the same host (they carry the account's bearer token).\n */\nconst getProvisioningBaseUrl = (\n region: 'US' | 'EU',\n baseUrl?: string,\n): string => {\n const override = resolveBaseUrl(baseUrl);\n if (override) return override;\n return region === 'EU' ? 'https://eu.posthog.com' : 'https://us.posthog.com';\n};\n\n/**\n * OAuth client ID for provisioning. A pinned base URL means a dev-seeded stack\n * that registers the dev client; prod uses the client registered for the target\n * region (the wizard OAuth app is registered separately per region).\n *\n * TODO: same assumption as `getOAuthClientId` in oauth.ts — a pinned base URL is\n * treated as a dev-seeded instance. Make configurable if we ever point\n * `--base-url` at a non-dev instance with its own OAuth app.\n */\nconst getProvisioningClientId = (\n region: 'US' | 'EU',\n baseUrl?: string,\n): string => {\n if (resolveBaseUrl(baseUrl)) return POSTHOG_DEV_CLIENT_ID;\n return region === 'EU' ? POSTHOG_EU_CLIENT_ID : POSTHOG_US_CLIENT_ID;\n};\n\nfunction generateCodeVerifier(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\nfunction generateCodeChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n// --- Response schemas ---\n//\n// These schemas validate only the fields the wizard actually reads. The rule is load\n// bearing, not stylistic: the wizard ships to npm and old versions keep running against\n// a provisioning API that moves independently, so a field we require but never consume\n// is a crash we cannot fix in the field. `service_id` was exactly that — required here,\n// read nowhere, and every signup broke the day the API stopped echoing it. Zod strips\n// unknown keys, so fields the API adds are tolerated for free; the only way to break is\n// to demand something back.\n\nconst AccountRequestResponseSchema = z.object({\n id: z.string(),\n type: z.enum(['oauth', 'requires_auth', 'error']),\n oauth: z\n .object({\n code: z.string(),\n })\n .optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n});\n\nconst TokenResponseSchema = z.object({\n token_type: z.string(),\n access_token: z.string(),\n refresh_token: z.string(),\n expires_in: z.number(),\n account: z\n .object({\n id: z.string(),\n })\n .optional(),\n});\n\nconst AccessConfigurationSchema = z.object({\n api_key: z.string(),\n host: z.string(),\n personal_api_key: z.string().optional(),\n});\n\nconst ResourceResponseSchema = z.object({\n status: z.string(),\n id: z.string(),\n complete: z\n .object({\n access_configuration: AccessConfigurationSchema,\n })\n .optional(),\n});\n\n/**\n * Teams the account can reach, from the token exchange. Parsed separately from\n * `TokenResponseSchema` and as loosely as possible: it is only used to recover from a\n * response we already failed to read, so it must never become a new way to fail.\n */\nconst AvailableTeamsSchema = z.array(\n z.object({ id: z.union([z.number(), z.string()]) }),\n);\n\n/**\n * Thrown when the provisioning API completed the work but the wizard could not read the\n * project back out of the response. The account, organization and project exist — callers\n * must not tell the user their account wasn't created.\n */\nexport class ProvisionedAccountUnreadableError extends Error {\n readonly accountCreated = true;\n\n constructor(message: string) {\n super(message);\n this.name = 'ProvisionedAccountUnreadableError';\n }\n}\n\n/** The field paths Zod rejected — never the values, which carry tokens and API keys. */\nfunction issuePaths(error: z.ZodError): string[] {\n return error.issues.map((issue) => issue.path.join('.') || '(root)');\n}\n\n/**\n * Report a response the wizard couldn't read. Silently degrading on a shape mismatch\n * turns the next contract change into a week of guesswork, so the rejected paths go to\n * the debug log and to error tracking before anything else happens.\n */\nfunction reportUnreadableResponse(step: string, error: z.ZodError): Error {\n const paths = issuePaths(error);\n const reported = new Error(\n `Unexpected ${step} response from the provisioning API (missing or invalid: ${paths.join(\n ', ',\n )})`,\n );\n\n logToFile(\n `[provisioning] unexpected ${step} response shape: ${paths.join(', ')}`,\n );\n analytics.captureException(reported, {\n step: `provisioning_${step}`,\n issue_paths: paths,\n });\n\n return reported;\n}\n\nfunction parseOrThrow<T extends z.ZodTypeAny>(\n schema: T,\n data: unknown,\n step: string,\n): z.infer<T> {\n const parsed = schema.safeParse(data);\n if (!parsed.success) {\n throw reportUnreadableResponse(step, parsed.error);\n }\n return parsed.data;\n}\n\ntype ResourceRead =\n | {\n ok: true;\n projectId: string;\n access: z.infer<typeof AccessConfigurationSchema>;\n }\n | { ok: false; reason: 'unreadable' | 'incomplete' };\n\nfunction readResource(data: unknown, step: string): ResourceRead {\n const parsed = ResourceResponseSchema.safeParse(data);\n if (!parsed.success) {\n reportUnreadableResponse(step, parsed.error);\n return { ok: false, reason: 'unreadable' };\n }\n\n if (parsed.data.status !== 'complete' || !parsed.data.complete) {\n logToFile(`[provisioning] ${step} returned status=${parsed.data.status}`);\n return { ok: false, reason: 'incomplete' };\n }\n\n return {\n ok: true,\n projectId: parsed.data.id,\n access: parsed.data.complete.access_configuration,\n };\n}\n\n/**\n * Recover the project after an unreadable `POST /resources` response.\n *\n * By the time that call returns 2xx the account, organization and project exist, so\n * aborting would abandon a provisioned account and leave the user with an orphaned\n * project. `GET /resources/:id` returns the same access configuration, so read it back\n * instead. Best-effort by design: any failure returns null and the caller reports the\n * original drift. The detail endpoint never mints a personal API key, so a recovered\n * result has none — `personalApiKey` is optional for every consumer.\n */\nasync function readBackResource(\n provisioningBaseUrl: string,\n accessToken: string,\n tokenPayload: unknown,\n): Promise<ResourceRead | null> {\n const teams = AvailableTeamsSchema.safeParse(\n (tokenPayload as { account?: { available_teams?: unknown } } | undefined)\n ?.account?.available_teams,\n );\n\n // A freshly provisioned account owns exactly one team. With any other count we can't\n // tell which team the create call made, and guessing would capture into the wrong one.\n if (!teams.success || teams.data.length !== 1) {\n logToFile(\n '[provisioning] no unambiguous team to read the resource back from',\n );\n return null;\n }\n\n const resourceId = String(teams.data[0].id);\n\n try {\n const res = await axios.get(\n `${provisioningBaseUrl}/api/agentic/provisioning/resources/${resourceId}`,\n {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n logToFile(\n `[provisioning] read resource ${resourceId} back after unreadable create`,\n );\n return readResource(res.data, 'resource_readback');\n } catch {\n logToFile(`[provisioning] read-back of resource ${resourceId} failed`);\n return null;\n }\n}\n\nexport interface ProvisioningResult {\n accessToken: string;\n refreshToken: string;\n /** Epoch ms when `accessToken` expires. */\n expiresAt: number;\n /** OAuth client the grant was minted under — refreshes must present the same one. */\n oauthClientId: string;\n projectApiKey: string;\n host: string;\n personalApiKey?: string;\n projectId: string;\n accountId: string;\n}\n\n/**\n * Create a new PostHog account and provision a project via the provisioning API.\n *\n * This is the \"no browser\" signup path: the wizard collects the email,\n * calls the provisioning API to create the account, and gets back\n * credentials without opening a browser.\n */\nexport async function provisionNewAccount(\n email: string,\n name: string,\n region: 'US' | 'EU' = 'US',\n opts?: {\n orgName?: string;\n projectName?: string;\n baseUrl?: string;\n /** Scope list to request; defaults to `WIZARD_PROVISIONING_SCOPES`. */\n scopes?: readonly string[];\n },\n): Promise<ProvisioningResult> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = generateCodeChallenge(codeVerifier);\n const provisioningBaseUrl = getProvisioningBaseUrl(region, opts?.baseUrl);\n const oauthClientId = getProvisioningClientId(region, opts?.baseUrl);\n\n logToFile('[provisioning] starting account creation');\n\n // Step 1: Create account\n const accountRes = await axios.post(\n `${provisioningBaseUrl}/api/agentic/provisioning/account_requests`,\n {\n id: crypto.randomUUID(),\n email,\n name,\n client_id: oauthClientId,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n scopes: opts?.scopes ?? WIZARD_PROVISIONING_SCOPES,\n configuration: {\n region,\n ...(opts?.orgName ? { organization_name: opts.orgName } : {}),\n },\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n const accountData = parseOrThrow(\n AccountRequestResponseSchema,\n accountRes.data,\n 'account_requests',\n );\n\n if (accountData.type === 'error') {\n const msg = accountData.error?.message ?? 'Account creation failed';\n analytics.captureException(new Error(msg), {\n step: 'provisioning_account_request',\n error_code: accountData.error?.code,\n });\n throw new Error(msg);\n }\n\n if (accountData.type === 'requires_auth') {\n throw new Error(\n 'This email is already associated with a PostHog account. Please use the login flow instead.',\n );\n }\n\n const code = accountData.oauth?.code;\n if (!code) {\n throw new Error('No authorization code received from account creation');\n }\n\n logToFile('[provisioning] account created, exchanging code for tokens');\n\n // Step 2: Exchange code for tokens\n const tokenRes = await axios.post(\n `${provisioningBaseUrl}/api/agentic/oauth/token`,\n new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n code_verifier: codeVerifier,\n }).toString(),\n {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n const tokenData = parseOrThrow(\n TokenResponseSchema,\n tokenRes.data,\n 'oauth_token',\n );\n\n logToFile('[provisioning] tokens received, provisioning resources');\n\n // Step 3: Provision resources\n const resourceRes = await axios.post(\n `${provisioningBaseUrl}/api/agentic/provisioning/resources`,\n {\n ...(opts?.projectName\n ? { configuration: { project_name: opts.projectName } }\n : {}),\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${tokenData.access_token}`,\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n // `/resources` is synchronous: it answers `status: \"complete\"` or an error envelope.\n // So an unreadable body means the contract moved, not that provisioning is still\n // running — and the project already exists either way, which is why this recovers\n // instead of aborting.\n let resource = readResource(resourceRes.data, 'resources');\n\n if (!resource.ok && resource.reason === 'unreadable') {\n resource =\n (await readBackResource(\n provisioningBaseUrl,\n tokenData.access_token,\n tokenRes.data,\n )) ?? resource;\n }\n\n if (!resource.ok) {\n if (resource.reason === 'incomplete') {\n throw new Error('Resource provisioning did not complete');\n }\n throw new ProvisionedAccountUnreadableError(\n 'Your PostHog project was created, but the provisioning API returned a response the wizard could not read',\n );\n }\n\n logToFile('[provisioning] resources provisioned successfully');\n\n return {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token,\n expiresAt: Date.now() + tokenData.expires_in * 1000,\n oauthClientId,\n projectApiKey: resource.access.api_key,\n host: resource.access.host,\n personalApiKey: resource.access.personal_api_key,\n projectId: resource.projectId,\n accountId: tokenData.account?.id ?? '',\n };\n}\n\n/**\n * Request a one-time deep link URL that logs the user into PostHog\n * and redirects to their project dashboard — or, when `opts.path` is\n * given, to any safe in-app relative path (e.g. the Signals inbox).\n */\nexport async function requestDeepLink(\n accessToken: string,\n host: HostResolution,\n opts?: { purpose?: string; path?: string },\n): Promise<string | null> {\n try {\n const baseUrl = host.appHost;\n\n const res = await axios.post(\n `${baseUrl}/api/agentic/provisioning/deep_links`,\n {\n purpose: opts?.purpose ?? 'dashboard',\n ...(opts?.path ? { path: opts.path } : {}),\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 10_000,\n },\n );\n\n const url = res.data?.url;\n if (typeof url === 'string') {\n logToFile(`[provisioning] deep link created: ${url}`);\n return url;\n }\n return null;\n } catch {\n logToFile('[provisioning] deep link request failed, skipping');\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,kBAAkB,aAA0C;AACvE,QAAO,UAAU,MAAM,IAAwC,KAAA;;AAGjE,MAAa,qBAAqB,SAAiB;AACjD,KAAI,KAAK,SAAS,mBAAmB,CACnC,QAAO;AAGT,KAAI,KAAK,SAAS,mBAAmB,CACnC,QAAO;AAGT,QAAO;;AAGT,MAAa,WAAW,QAAqB,YAAqB;CAChE,MAAM,WAAW,eAAe,QAAQ;AACxC,KAAI,SACF,QAAO;AAGT,KAAI,WAAW,KACb,QAAO;AAGT,QAAO;;AAGT,MAAa,eAAe,QAAqB,YAAqB;CACpE,MAAM,WAAW,eAAe,QAAQ;AACxC,KAAI,SACF,QAAO;AAGT,KAAI,WAAW,KACb,QAAO;AAGT,QAAO;;AAGT,eAAsB,aACpB,aACA,SACsB;AAItB,KAAI,eAAe,QAAQ,CACzB,QAAO;CAGT,MAAM,UAAU;EACd,eAAe,UAAU;EACzB,cAAc;EACf;CAED,MAAM,CAAC,UAAU,YAAY,MAAM,QAAQ,WAAW,CACpD,MAAM,IAAI,yCAAyC,EAAE,SAAS,CAAC,EAC/D,MAAM,IAAI,yCAAyC,EAAE,SAAS,CAAC,CAChE,CAAC;AAEF,KAAI,SAAS,WAAW,YAAa,QAAO;AAC5C,KAAI,SAAS,WAAW,YAAa,QAAO;AAE5C,OAAM,IAAI,MACR,yFACD;;AAGH,MAAa,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CAAC,SAAS,IAAI;AAChB,MAAI,SAAS,WAAW,aACtB,OAAM,IAAI,MAAM,yCAAyC;AAE3D,QAAM,IAAI,kCACR,2GACD;;AAGH,WAAU,oDAAoD;AAE9D,QAAO;EACL,aAAa,UAAU;EACvB,cAAc,UAAU;EACxB,WAAW,KAAK,KAAK,GAAG,UAAU,aAAa;EAC/C;EACA,eAAe,SAAS,OAAO;EAC/B,MAAM,SAAS,OAAO;EACtB,gBAAgB,SAAS,OAAO;EAChC,WAAW,SAAS;EACpB,WAAW,UAAU,SAAS,MAAM;EACrC;;;;;;;AAQH,eAAsB,gBACpB,aACA,MACA,MACwB;AACxB,KAAI;EACF,MAAM,UAAU,KAAK;EAmBrB,MAAM,OAjBM,MAAM,MAAM,KACtB,GAAG,QAAQ,uCACX;GACE,SAAS,MAAM,WAAW;GAC1B,GAAI,MAAM,OAAO,EAAE,MAAM,KAAK,MAAM,GAAG,EAAE;GAC1C,EACD;GACE,SAAS;IACP,gBAAgB;IAChB,eAAe,UAAU;IACzB,eAAe;IACf,cAAc;IACf;GACD,SAAS;GACV,CACF,EAEe,MAAM;AACtB,MAAI,OAAO,QAAQ,UAAU;AAC3B,aAAU,qCAAqC,MAAM;AACrD,UAAO;;AAET,SAAO;SACD;AACN,YAAU,oDAAoD;AAC9D,SAAO"}
1
+ {"version":3,"file":"provisioning-94OneD64.js","names":[],"sources":["../src/utils/urls.ts","../src/utils/provisioning.ts"],"sourcesContent":["import axios from 'axios';\nimport { IS_DEV, WIZARD_USER_AGENT } from '@lib/constants';\nimport type { CloudRegion } from './types';\n\n/**\n * Resolve a pinned PostHog base URL from an optional override. When present, it\n * becomes the single source of truth for every PostHog origin — the\n * API/ingestion host, the cloud/app URL, and the OAuth server — bypassing\n * region resolution entirely.\n *\n * The override lives on the session (`session.baseUrl`, set by `--base-url`) and\n * is threaded in by callers, so there is no hidden module-level state. A `--base-url`\n * value wins; otherwise a dev/test build implies `localhost:8010`; otherwise the\n * result is `undefined`, meaning region-based resolution applies.\n *\n * This is the runtime equivalent of the `IS_DEV` localhost routing: `IS_DEV` is a\n * build-time constant that tsdown compiles out of production builds, so it can't\n * point a shipped wizard at a local stack — `--base-url` can. Both feed this one\n * resolver so every URL helper only asks the question once.\n */\nexport const resolveBaseUrl = (override?: string): string | undefined => {\n return override?.trim() || (IS_DEV ? 'http://localhost:8010' : undefined);\n};\n\nexport const getUiHostFromHost = (host: string) => {\n if (host.includes('us.i.posthog.com')) {\n return 'https://us.posthog.com';\n }\n\n if (host.includes('eu.i.posthog.com')) {\n return 'https://eu.posthog.com';\n }\n\n return host;\n};\n\nexport const getHost = (region: CloudRegion, baseUrl?: string) => {\n const override = resolveBaseUrl(baseUrl);\n if (override) {\n return override;\n }\n\n if (region === 'eu') {\n return 'https://eu.i.posthog.com';\n }\n\n return 'https://us.i.posthog.com';\n};\n\nexport const getCloudUrl = (region: CloudRegion, baseUrl?: string) => {\n const override = resolveBaseUrl(baseUrl);\n if (override) {\n return override;\n }\n\n if (region === 'eu') {\n return 'https://eu.posthog.com';\n }\n\n return 'https://us.posthog.com';\n};\n\nexport async function detectRegion(\n accessToken: string,\n baseUrl?: string,\n): Promise<CloudRegion> {\n // With a pinned base URL there is only one instance to talk to — skip the\n // us/eu probe and default the region label to 'us'. (Covers IS_DEV too, via\n // resolveBaseUrl.) The URLs themselves come from the override, not this label.\n if (resolveBaseUrl(baseUrl)) {\n return 'us';\n }\n\n const headers = {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n };\n\n const [usResult, euResult] = await Promise.allSettled([\n axios.get('https://us.posthog.com/api/users/@me/', { headers }),\n axios.get('https://eu.posthog.com/api/users/@me/', { headers }),\n ]);\n\n if (usResult.status === 'fulfilled') return 'us';\n if (euResult.status === 'fulfilled') return 'eu';\n\n throw new Error(\n 'Could not determine cloud region from access token. Please check your PostHog account.',\n );\n}\n\nexport const getLlmGatewayUrl = (host: string) => {\n if (host.includes('host.docker.internal')) {\n return 'http://host.docker.internal:3308/wizard';\n }\n\n if (host.includes('localhost')) {\n return 'http://localhost:3308/wizard';\n }\n\n if (host.includes('eu.posthog.com') || host.includes('eu.i.posthog.com')) {\n return 'https://gateway.eu.posthog.com/wizard';\n }\n\n return 'https://gateway.us.posthog.com/wizard';\n};\n\n/** Region-agnostic prod OAuth server. Resolves to the right region server-side. */\nconst PROD_OAUTH_URL = 'https://oauth.posthog.com';\n\n/**\n * OAuth server URL. Follows the base-URL override (and thus IS_DEV → localhost),\n * otherwise the region-agnostic prod OAuth host.\n */\nexport const getOAuthUrl = (baseUrl?: string): string =>\n resolveBaseUrl(baseUrl) ?? PROD_OAUTH_URL;\n\n/**\n * One-click integration install/authorize deep-link. Opening it in the user's\n * logged-in browser runs the install directly — no settings-page hunting. The\n * one link covers fresh install, link-existing, and re-auth.\n */\nexport const getIntegrationAuthorizeUrl = (\n appHost: string,\n projectId: number,\n kind: string,\n): string =>\n `${appHost.replace(\n /\\/$/,\n '',\n )}/api/environments/${projectId}/integrations/authorize?kind=${kind}`;\n","/**\n * Provisioning API client for creating new PostHog accounts.\n *\n * Uses the agentic provisioning API with PKCE auth:\n * 1. POST /account_requests - create account, get auth code\n * 2. POST /oauth/token - exchange code for tokens (with PKCE)\n * 3. POST /resources - provision project, get API key\n */\n\nimport * as crypto from 'node:crypto';\nimport axios from 'axios';\nimport { z } from 'zod';\nimport {\n POSTHOG_DEV_CLIENT_ID,\n POSTHOG_EU_CLIENT_ID,\n POSTHOG_US_CLIENT_ID,\n WIZARD_PROVISIONING_SCOPES,\n WIZARD_USER_AGENT,\n} from '@lib/constants';\nimport { resolveBaseUrl } from './urls';\nimport { logToFile } from './debug';\nimport { analytics } from './analytics';\nimport type { HostResolution } from '@lib/host-resolution';\n\nconst API_VERSION = '0.1d';\n\n/**\n * Provisioning host. Follows a `--base-url` override (and IS_DEV → localhost),\n * else the prod provisioning host for the target region. Unlike the login OAuth\n * flow (which goes through the region-agnostic `oauth.posthog.com` proxy), the\n * provisioning API is region-specific: an EU account must be created against\n * `eu.posthog.com`, and the subsequent token-exchange / resources calls stay on\n * the same host (they carry the account's bearer token).\n */\nconst getProvisioningBaseUrl = (\n region: 'US' | 'EU',\n baseUrl?: string,\n): string => {\n const override = resolveBaseUrl(baseUrl);\n if (override) return override;\n return region === 'EU' ? 'https://eu.posthog.com' : 'https://us.posthog.com';\n};\n\n/**\n * OAuth client ID for provisioning. A pinned base URL means a dev-seeded stack\n * that registers the dev client; prod uses the client registered for the target\n * region (the wizard OAuth app is registered separately per region).\n *\n * TODO: same assumption as `getOAuthClientId` in oauth.ts — a pinned base URL is\n * treated as a dev-seeded instance. Make configurable if we ever point\n * `--base-url` at a non-dev instance with its own OAuth app.\n */\nconst getProvisioningClientId = (\n region: 'US' | 'EU',\n baseUrl?: string,\n): string => {\n if (resolveBaseUrl(baseUrl)) return POSTHOG_DEV_CLIENT_ID;\n return region === 'EU' ? POSTHOG_EU_CLIENT_ID : POSTHOG_US_CLIENT_ID;\n};\n\nfunction generateCodeVerifier(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\nfunction generateCodeChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n// --- Response schemas ---\n//\n// These schemas validate only the fields the wizard actually reads. The rule is load\n// bearing, not stylistic: the wizard ships to npm and old versions keep running against\n// a provisioning API that moves independently, so a field we require but never consume\n// is a crash we cannot fix in the field. `service_id` was exactly that — required here,\n// read nowhere, and every signup broke the day the API stopped echoing it. Zod strips\n// unknown keys, so fields the API adds are tolerated for free; the only way to break is\n// to demand something back.\n\nconst AccountRequestResponseSchema = z.object({\n id: z.string(),\n type: z.enum(['oauth', 'requires_auth', 'error']),\n oauth: z\n .object({\n code: z.string(),\n })\n .optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n});\n\nconst TokenResponseSchema = z.object({\n token_type: z.string(),\n access_token: z.string(),\n refresh_token: z.string(),\n expires_in: z.number(),\n account: z\n .object({\n id: z.string(),\n })\n .optional(),\n});\n\nconst AccessConfigurationSchema = z.object({\n api_key: z.string(),\n host: z.string(),\n personal_api_key: z.string().optional(),\n});\n\nconst ResourceResponseSchema = z.object({\n status: z.string(),\n id: z.string(),\n complete: z\n .object({\n access_configuration: AccessConfigurationSchema,\n })\n .optional(),\n});\n\n/**\n * Teams the account can reach, from the token exchange. Parsed separately from\n * `TokenResponseSchema` and as loosely as possible: it is only used to recover from a\n * response we already failed to read, so it must never become a new way to fail.\n */\nconst AvailableTeamsSchema = z.array(\n z.object({ id: z.union([z.number(), z.string()]) }),\n);\n\n/**\n * Thrown when the provisioning API completed the work but the wizard could not read the\n * project back out of the response. The account, organization and project exist — callers\n * must not tell the user their account wasn't created.\n */\nexport class ProvisionedAccountUnreadableError extends Error {\n readonly accountCreated = true;\n\n constructor(message: string) {\n super(message);\n this.name = 'ProvisionedAccountUnreadableError';\n }\n}\n\n/** The field paths Zod rejected — never the values, which carry tokens and API keys. */\nfunction issuePaths(error: z.ZodError): string[] {\n return error.issues.map((issue) => issue.path.join('.') || '(root)');\n}\n\n/**\n * Report a response the wizard couldn't read. Silently degrading on a shape mismatch\n * turns the next contract change into a week of guesswork, so the rejected paths go to\n * the debug log and to error tracking before anything else happens.\n */\nfunction reportUnreadableResponse(step: string, error: z.ZodError): Error {\n const paths = issuePaths(error);\n const reported = new Error(\n `Unexpected ${step} response from the provisioning API (missing or invalid: ${paths.join(\n ', ',\n )})`,\n );\n\n logToFile(\n `[provisioning] unexpected ${step} response shape: ${paths.join(', ')}`,\n );\n analytics.captureException(reported, {\n step: `provisioning_${step}`,\n issue_paths: paths,\n });\n\n return reported;\n}\n\nfunction parseOrThrow<T extends z.ZodTypeAny>(\n schema: T,\n data: unknown,\n step: string,\n): z.infer<T> {\n const parsed = schema.safeParse(data);\n if (!parsed.success) {\n throw reportUnreadableResponse(step, parsed.error);\n }\n return parsed.data;\n}\n\ntype ResourceRead =\n | {\n ok: true;\n projectId: string;\n access: z.infer<typeof AccessConfigurationSchema>;\n }\n | { ok: false; reason: 'unreadable' | 'incomplete' };\n\nfunction readResource(data: unknown, step: string): ResourceRead {\n const parsed = ResourceResponseSchema.safeParse(data);\n if (!parsed.success) {\n reportUnreadableResponse(step, parsed.error);\n return { ok: false, reason: 'unreadable' };\n }\n\n if (parsed.data.status !== 'complete' || !parsed.data.complete) {\n logToFile(`[provisioning] ${step} returned status=${parsed.data.status}`);\n return { ok: false, reason: 'incomplete' };\n }\n\n return {\n ok: true,\n projectId: parsed.data.id,\n access: parsed.data.complete.access_configuration,\n };\n}\n\n/**\n * Recover the project after an unreadable `POST /resources` response.\n *\n * By the time that call returns 2xx the account, organization and project exist, so\n * aborting would abandon a provisioned account and leave the user with an orphaned\n * project. `GET /resources/:id` returns the same access configuration, so read it back\n * instead. Best-effort by design: any failure returns null and the caller reports the\n * original drift. The detail endpoint never mints a personal API key, so a recovered\n * result has none — `personalApiKey` is optional for every consumer.\n */\nasync function readBackResource(\n provisioningBaseUrl: string,\n accessToken: string,\n tokenPayload: unknown,\n): Promise<ResourceRead | null> {\n const teams = AvailableTeamsSchema.safeParse(\n (tokenPayload as { account?: { available_teams?: unknown } } | undefined)\n ?.account?.available_teams,\n );\n\n // A freshly provisioned account owns exactly one team. With any other count we can't\n // tell which team the create call made, and guessing would capture into the wrong one.\n if (!teams.success || teams.data.length !== 1) {\n logToFile(\n '[provisioning] no unambiguous team to read the resource back from',\n );\n return null;\n }\n\n const resourceId = String(teams.data[0].id);\n\n try {\n const res = await axios.get(\n `${provisioningBaseUrl}/api/agentic/provisioning/resources/${resourceId}`,\n {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n logToFile(\n `[provisioning] read resource ${resourceId} back after unreadable create`,\n );\n return readResource(res.data, 'resource_readback');\n } catch {\n logToFile(`[provisioning] read-back of resource ${resourceId} failed`);\n return null;\n }\n}\n\nexport interface ProvisioningResult {\n accessToken: string;\n refreshToken: string;\n /** Epoch ms when `accessToken` expires. */\n expiresAt: number;\n /** OAuth client the grant was minted under — refreshes must present the same one. */\n oauthClientId: string;\n projectApiKey: string;\n host: string;\n personalApiKey?: string;\n projectId: string;\n accountId: string;\n}\n\n/**\n * Create a new PostHog account and provision a project via the provisioning API.\n *\n * This is the \"no browser\" signup path: the wizard collects the email,\n * calls the provisioning API to create the account, and gets back\n * credentials without opening a browser.\n */\nexport async function provisionNewAccount(\n email: string,\n name: string,\n region: 'US' | 'EU' = 'US',\n opts?: {\n orgName?: string;\n projectName?: string;\n baseUrl?: string;\n /** Scope list to request; defaults to `WIZARD_PROVISIONING_SCOPES`. */\n scopes?: readonly string[];\n },\n): Promise<ProvisioningResult> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = generateCodeChallenge(codeVerifier);\n const provisioningBaseUrl = getProvisioningBaseUrl(region, opts?.baseUrl);\n const oauthClientId = getProvisioningClientId(region, opts?.baseUrl);\n\n logToFile('[provisioning] starting account creation');\n\n // Step 1: Create account\n const accountRes = await axios.post(\n `${provisioningBaseUrl}/api/agentic/provisioning/account_requests`,\n {\n id: crypto.randomUUID(),\n email,\n name,\n client_id: oauthClientId,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n scopes: opts?.scopes ?? WIZARD_PROVISIONING_SCOPES,\n configuration: {\n region,\n ...(opts?.orgName ? { organization_name: opts.orgName } : {}),\n },\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n const accountData = parseOrThrow(\n AccountRequestResponseSchema,\n accountRes.data,\n 'account_requests',\n );\n\n if (accountData.type === 'error') {\n const msg = accountData.error?.message ?? 'Account creation failed';\n analytics.captureException(new Error(msg), {\n step: 'provisioning_account_request',\n error_code: accountData.error?.code,\n });\n throw new Error(msg);\n }\n\n if (accountData.type === 'requires_auth') {\n throw new Error(\n 'This email is already associated with a PostHog account. Please use the login flow instead.',\n );\n }\n\n const code = accountData.oauth?.code;\n if (!code) {\n throw new Error('No authorization code received from account creation');\n }\n\n logToFile('[provisioning] account created, exchanging code for tokens');\n\n // Step 2: Exchange code for tokens\n const tokenRes = await axios.post(\n `${provisioningBaseUrl}/api/agentic/oauth/token`,\n new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n code_verifier: codeVerifier,\n }).toString(),\n {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n const tokenData = parseOrThrow(\n TokenResponseSchema,\n tokenRes.data,\n 'oauth_token',\n );\n\n logToFile('[provisioning] tokens received, provisioning resources');\n\n // Step 3: Provision resources\n const resourceRes = await axios.post(\n `${provisioningBaseUrl}/api/agentic/provisioning/resources`,\n {\n ...(opts?.projectName\n ? { configuration: { project_name: opts.projectName } }\n : {}),\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${tokenData.access_token}`,\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n\n // `/resources` is synchronous: it answers `status: \"complete\"` or an error envelope.\n // So an unreadable body means the contract moved, not that provisioning is still\n // running — and the project already exists either way, which is why this recovers\n // instead of aborting.\n let resource = readResource(resourceRes.data, 'resources');\n\n if (!resource.ok && resource.reason === 'unreadable') {\n resource =\n (await readBackResource(\n provisioningBaseUrl,\n tokenData.access_token,\n tokenRes.data,\n )) ?? resource;\n }\n\n if (!resource.ok) {\n if (resource.reason === 'incomplete') {\n throw new Error('Resource provisioning did not complete');\n }\n throw new ProvisionedAccountUnreadableError(\n 'Your PostHog project was created, but the provisioning API returned a response the wizard could not read',\n );\n }\n\n logToFile('[provisioning] resources provisioned successfully');\n\n return {\n accessToken: tokenData.access_token,\n refreshToken: tokenData.refresh_token,\n expiresAt: Date.now() + tokenData.expires_in * 1000,\n oauthClientId,\n projectApiKey: resource.access.api_key,\n host: resource.access.host,\n personalApiKey: resource.access.personal_api_key,\n projectId: resource.projectId,\n accountId: tokenData.account?.id ?? '',\n };\n}\n\n/**\n * Request a one-time deep link URL that logs the user into PostHog\n * and redirects to their project dashboard — or, when `opts.path` is\n * given, to any safe in-app relative path (e.g. the Signals inbox).\n */\nexport async function requestDeepLink(\n accessToken: string,\n host: HostResolution,\n opts?: { purpose?: string; path?: string },\n): Promise<string | null> {\n try {\n const baseUrl = host.appHost;\n\n const res = await axios.post(\n `${baseUrl}/api/agentic/provisioning/deep_links`,\n {\n purpose: opts?.purpose ?? 'dashboard',\n ...(opts?.path ? { path: opts.path } : {}),\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n 'API-Version': API_VERSION,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 10_000,\n },\n );\n\n const url = res.data?.url;\n if (typeof url === 'string') {\n logToFile(`[provisioning] deep link created: ${url}`);\n return url;\n }\n return null;\n } catch {\n logToFile('[provisioning] deep link request failed, skipping');\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,kBAAkB,aAA0C;AACvE,QAAO,UAAU,MAAM,IAAwC,KAAA;;AAGjE,MAAa,qBAAqB,SAAiB;AACjD,KAAI,KAAK,SAAS,mBAAmB,CACnC,QAAO;AAGT,KAAI,KAAK,SAAS,mBAAmB,CACnC,QAAO;AAGT,QAAO;;AAGT,MAAa,WAAW,QAAqB,YAAqB;CAChE,MAAM,WAAW,eAAe,QAAQ;AACxC,KAAI,SACF,QAAO;AAGT,KAAI,WAAW,KACb,QAAO;AAGT,QAAO;;AAGT,MAAa,eAAe,QAAqB,YAAqB;CACpE,MAAM,WAAW,eAAe,QAAQ;AACxC,KAAI,SACF,QAAO;AAGT,KAAI,WAAW,KACb,QAAO;AAGT,QAAO;;AAGT,eAAsB,aACpB,aACA,SACsB;AAItB,KAAI,eAAe,QAAQ,CAC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5_6_TERRA_MODEL, N as HAIKU_MODEL, P as HAIKU_TRIAGE_MODEL, et as SONNET_5_MODEL, j as GPT5_6_SOL_MODEL } from "./debug-YQdeZulR.js";
2
- import { n as analytics } from "./analytics-D54mLptm.js";
1
+ import { F as HAIKU_MODEL, H as OPUS_MODEL, I as HAIKU_TRIAGE_MODEL, M as GPT5_6_LUNA_MODEL, N as GPT5_6_SOL_MODEL, O as DEFAULT_AGENT_MODEL, P as GPT5_6_TERRA_MODEL, tt as SONNET_5_MODEL } from "./debug-aXxgvtal.js";
2
+ import { n as analytics } from "./analytics-DsMH06jo.js";
3
3
  import * as fs$1 from "fs";
4
4
  import * as path$1 from "path";
5
5
  import { z } from "zod";
6
6
  import { randomUUID } from "crypto";
7
+ //#region src/utils/atomic-ledger.ts
8
+ /**
9
+ * Small shared primitives for on-disk ledgers: an atomic JSON writer and a
10
+ * single-chain async mutex. Used by the audit tools and by the orchestrator
11
+ * queue. Lifted here so both share one implementation.
12
+ */
13
+ /**
14
+ * Atomically write JSON: write to a `.tmp` file then rename over the target. The
15
+ * rename bumps the file's mtime in one step, which is what a file watcher polls.
16
+ */
17
+ function writeJsonAtomic(targetPath, data) {
18
+ const tmpPath = `${targetPath}.tmp`;
19
+ fs$1.writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf8");
20
+ fs$1.renameSync(tmpPath, targetPath);
21
+ }
22
+ /**
23
+ * A single async mutex. Serializes read-modify-write cycles so concurrent callers
24
+ * (parallel task agents, audit tool calls) never interleave a mutation.
25
+ */
26
+ function makeMutex() {
27
+ let chain = Promise.resolve();
28
+ return async function run(fn) {
29
+ const next = chain.then(() => fn());
30
+ chain = next.catch(() => void 0);
31
+ return next;
32
+ };
33
+ }
34
+ //#endregion
7
35
  //#region src/lib/agent/runner/switchboard/models.ts
8
36
  /**
9
37
  * Model capabilities — the traits a harness needs that a bare gateway model id
@@ -97,34 +125,6 @@ function modelCapabilities(modelId, effortOverride) {
97
125
  return caps;
98
126
  }
99
127
  //#endregion
100
- //#region src/utils/atomic-ledger.ts
101
- /**
102
- * Small shared primitives for on-disk ledgers: an atomic JSON writer and a
103
- * single-chain async mutex. Used by the audit tools and by the orchestrator
104
- * queue. Lifted here so both share one implementation.
105
- */
106
- /**
107
- * Atomically write JSON: write to a `.tmp` file then rename over the target. The
108
- * rename bumps the file's mtime in one step, which is what a file watcher polls.
109
- */
110
- function writeJsonAtomic(targetPath, data) {
111
- const tmpPath = `${targetPath}.tmp`;
112
- fs$1.writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf8");
113
- fs$1.renameSync(tmpPath, targetPath);
114
- }
115
- /**
116
- * A single async mutex. Serializes read-modify-write cycles so concurrent callers
117
- * (parallel task agents, audit tool calls) never interleave a mutation.
118
- */
119
- function makeMutex() {
120
- let chain = Promise.resolve();
121
- return async function run(fn) {
122
- const next = chain.then(() => fn());
123
- chain = next.catch(() => void 0);
124
- return next;
125
- };
126
- }
127
- //#endregion
128
128
  //#region src/lib/agent/runner/sequence/orchestrator/queue.ts
129
129
  /**
130
130
  * The orchestrator task queue.
@@ -164,6 +164,33 @@ const SkipReason = {
164
164
  NoticeError: "notice-error",
165
165
  AgentNotNeeded: "agent-not-needed"
166
166
  };
167
+ /**
168
+ * Why the agent itself reported `not needed`.
169
+ *
170
+ * {@link SkipReason.AgentNotNeeded} records who decided the skip, not what they
171
+ * decided. `complete_task` offers `not needed` both for "the step does not
172
+ * apply" and for "you cannot do it", so an agent that never got a credential
173
+ * out of the user lands in the same bucket as one that found nothing to
174
+ * connect — and the bucket is named after the first meaning. For the one step
175
+ * that stops to ask for credentials, that is the difference that matters: a
176
+ * step nobody supplied a password for is not a step that did not apply.
177
+ *
178
+ * A sub-dimension of the skip reason, never a replacement for it, so every
179
+ * existing reason value keeps counting exactly what it counted before.
180
+ */
181
+ const NotNeededReason = {
182
+ NotApplicable: "not-applicable",
183
+ UserDeclined: "user-declined",
184
+ Blocked: "blocked"
185
+ };
186
+ /**
187
+ * Whether a value names a reason. The pi harness hands tool arguments over
188
+ * unvalidated, so an invented value would otherwise reach the analytics
189
+ * dimension as free text — the one thing this step must never emit.
190
+ */
191
+ function isNotNeededReason(value) {
192
+ return Object.values(NotNeededReason).includes(value);
193
+ }
167
194
  const QUEUE_DIR_NAME = ".posthog-wizard-cache";
168
195
  const DEFAULT_MAX_ATTEMPTS = 2;
169
196
  function nowIso() {
@@ -309,10 +336,14 @@ var QueueStore = class {
309
336
  * The reason is required, and sits before the optional handoff for that
310
337
  * reason. A skip carrying no reason is what let a five-minute auto-decline
311
338
  * hide inside the same event as an agent deciding a step did not apply.
339
+ *
340
+ * `notNeededReason` splits the agent-reported reason one level further; only
341
+ * an agent supplies it, and only when it declared one.
312
342
  */
313
- skip(id, reason, handoff) {
343
+ skip(id, reason, handoff, notNeededReason) {
314
344
  const t = this.require(id);
315
345
  t.skipReason = reason;
346
+ if (notNeededReason) t.notNeededReason = notNeededReason;
316
347
  return this.finish(id, TaskStatus.Skipped, handoff);
317
348
  }
318
349
  fail(id, error, handoff) {
@@ -386,6 +417,28 @@ var QueueStore = class {
386
417
  * The guard logic and the apply functions are plain, exported, and unit-tested.
387
418
  * `buildOrchestratorTools` wraps them in the SDK `tool()` shape.
388
419
  */
420
+ /**
421
+ * The `complete_task` `notNeededReason` description, shared by both harnesses'
422
+ * schemas so the ask cannot drift between them.
423
+ *
424
+ * Named per value rather than left to prose: the distinction the flow needs is
425
+ * "the user did not hand over a credential" against "there was nothing here to
426
+ * connect", and an agent asked for that in free text writes it into the handoff
427
+ * — where {@link applyComplete} deliberately cannot forward it, because handoff
428
+ * prose on this step reaches live database passwords.
429
+ */
430
+ const NOT_NEEDED_REASON_ASK = `Required when status is 'not needed': which of these ended the task. '${NotNeededReason.NotApplicable}' — the step genuinely does not apply to this project. '${NotNeededReason.UserDeclined}' — you asked the user and they declined, cancelled, or never answered. '${NotNeededReason.Blocked}' — something outside your and the user's control stopped you (a credential the project does not have, a plan or permission it lacks, an endpoint you could not reach). Ignored for any other status.`;
431
+ /**
432
+ * The `enqueue_task` `model` description, shared by both harnesses' schemas.
433
+ *
434
+ * The field was declared as a bare optional string while
435
+ * {@link checkEnqueueGuards} rejects anything outside {@link VALID_MODELS}, so
436
+ * the allow-list existed only in the rejection message — an agent had to guess
437
+ * a gateway model id, trip the `invalid-model` guard, and spend a turn reading
438
+ * the list back before it could enqueue. Naming the list where the agent picks
439
+ * the value costs nothing and makes the guess unnecessary.
440
+ */
441
+ const ENQUEUE_MODEL_DESCRIPTION = `Optional model override for this task. Omit it to use the task's default, which is almost always right. If you do set it, it must be one of: ${[...VALID_MODELS].join(", ")}.`;
389
442
  /** The per-task remark ask, shared by both harnesses' complete_task schemas. */
390
443
  const REMARK_ASK = "What information or guidance would have been useful to have in the integration prompt or documentation for this task — specifically anything that would have prevented tool failures, erroneous edits, or other wasted turns.";
391
444
  function stableStringify(value) {
@@ -526,7 +579,7 @@ function applyComplete(ctx, args) {
526
579
  type: "self-reported",
527
580
  message: args.handoff.forNextAgent
528
581
  }, args.handoff);
529
- else if (args.status === TaskStatus.Skipped) ctx.store.skip(id, SkipReason.AgentNotNeeded, args.handoff);
582
+ else if (args.status === TaskStatus.Skipped) ctx.store.skip(id, SkipReason.AgentNotNeeded, args.handoff, isNotNeededReason(args.notNeededReason) ? args.notNeededReason : void 0);
530
583
  else ctx.store.complete(id, args.handoff);
531
584
  return { ok: true };
532
585
  }
@@ -569,6 +622,25 @@ const HANDOFF_SHAPE = {
569
622
  conflict: z.string().max(HANDOFF_TEXT_MAX).optional().describe(HANDOFF_FIELDS.conflict),
570
623
  reportSection: z.string().max(HANDOFF_TEXT_MAX).optional().describe(HANDOFF_FIELDS.reportSection)
571
624
  };
625
+ /**
626
+ * `complete_task`'s own arguments, held level with the pi mirror by the same
627
+ * parity test that guards the handoff — a top-level field can go missing on the
628
+ * harness that runs just as easily as a nested one.
629
+ */
630
+ const COMPLETE_SHAPE = {
631
+ status: z.enum([
632
+ "done",
633
+ "failed",
634
+ "not needed"
635
+ ]),
636
+ handoff: z.object(HANDOFF_SHAPE),
637
+ remark: z.string().optional().describe(REMARK_ASK),
638
+ notNeededReason: z.enum([
639
+ NotNeededReason.NotApplicable,
640
+ NotNeededReason.UserDeclined,
641
+ NotNeededReason.Blocked
642
+ ]).optional().describe(NOT_NEEDED_REASON_ASK)
643
+ };
572
644
  function textResult(text, isError = false) {
573
645
  return {
574
646
  isError,
@@ -589,7 +661,7 @@ function buildOrchestratorTools(tool, ctx) {
589
661
  label: z.string().optional().describe("A short label for the UI — the action in a few words (e.g. \"Add the PostHog SDK\", \"Initialize PostHog\"). Leave out file names, class names, and other specifics."),
590
662
  inputs: z.record(z.unknown()).optional(),
591
663
  dependsOn: z.array(z.string()).optional().describe("Task ids that must be done before this task runs."),
592
- model: z.string().optional(),
664
+ model: z.string().optional().describe(ENQUEUE_MODEL_DESCRIPTION),
593
665
  reason: z.string().describe("One line on why this task is needed.")
594
666
  }, ((args) => {
595
667
  const res = applyEnqueue(ctx, args);
@@ -602,15 +674,7 @@ function buildOrchestratorTools(tool, ctx) {
602
674
  }
603
675
  return textResult(JSON.stringify({ id: res.task.id }));
604
676
  })),
605
- tool("complete_task", "Report the outcome of your task. Always call this exactly once when you finish, with a structured handoff for the next agent. Use status 'not needed' when the task does not apply to this project and you cannot do it (say why in the handoff) — not 'done'.", {
606
- status: z.enum([
607
- "done",
608
- "failed",
609
- "not needed"
610
- ]),
611
- handoff: z.object(HANDOFF_SHAPE),
612
- remark: z.string().optional().describe(REMARK_ASK)
613
- }, ((args) => {
677
+ tool("complete_task", "Report the outcome of your task. Always call this exactly once when you finish, with a structured handoff for the next agent. Use status 'not needed' when the task does not apply to this project and you cannot do it (say why in the handoff) — not 'done'.", COMPLETE_SHAPE, ((args) => {
614
678
  const res = applyComplete(ctx, args);
615
679
  if (!res.ok) return textResult(res.message, true);
616
680
  return textResult("ok");
@@ -625,6 +689,6 @@ function buildOrchestratorTools(tool, ctx) {
625
689
  ];
626
690
  }
627
691
  //#endregion
628
- export { modelCapabilities as _, applyReadHandoffs as a, uncoveredBySink as c, SkipReason as d, TaskStatus as f, isValidModel as g, isThinkingLevel as h, applyEnqueue as i, QUEUE_DIR_NAME as l, writeJsonAtomic as m, REMARK_ASK as n, buildOrchestratorTools as o, makeMutex as p, applyComplete as r, dependencyClosure as s, HANDOFF_FIELDS as t, QueueStore as u, requireKnownModel as v, triageModelFor as y };
692
+ export { writeJsonAtomic as S, isValidModel as _, applyComplete as a, triageModelFor as b, buildOrchestratorTools as c, NotNeededReason as d, QUEUE_DIR_NAME as f, isThinkingLevel as g, TaskStatus as h, REMARK_ASK as i, dependencyClosure as l, SkipReason as m, HANDOFF_FIELDS as n, applyEnqueue as o, QueueStore as p, NOT_NEEDED_REASON_ASK as r, applyReadHandoffs as s, ENQUEUE_MODEL_DESCRIPTION as t, uncoveredBySink as u, modelCapabilities as v, makeMutex as x, requireKnownModel as y };
629
693
 
630
- //# sourceMappingURL=queue-tools-DGaHf3n-.js.map
694
+ //# sourceMappingURL=queue-tools--k2v8QYY.js.map