@posthog/wizard 2.77.0 → 2.78.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 (173) hide show
  1. package/README.md +30 -15
  2. package/dist/{add-mcp-server-to-clients-BnRyE4pw.js → add-mcp-server-to-clients-JMv8LP-O.js} +6 -5
  3. package/dist/{add-mcp-server-to-clients-BnRyE4pw.js.map → add-mcp-server-to-clients-JMv8LP-O.js.map} +1 -1
  4. package/dist/agent-bCZ3i3fh.js +3085 -0
  5. package/dist/agent-bCZ3i3fh.js.map +1 -0
  6. package/dist/{agent-interface-Avtr_5M5.js → agent-interface-BAOIHuXS.js} +429 -378
  7. package/dist/agent-interface-BAOIHuXS.js.map +1 -0
  8. package/dist/{agent-prompt-loader-CHixNPgY.js → agent-prompt-loader-7Pd4CfZO.js} +6 -6
  9. package/dist/agent-prompt-loader-7Pd4CfZO.js.map +1 -0
  10. package/dist/analytics-BcV-WCM4.js +2 -0
  11. package/dist/{analytics-C67F2vee.js → analytics-CHCZ_qUR.js} +10 -6
  12. package/dist/analytics-CHCZ_qUR.js.map +1 -0
  13. package/dist/{api-Dj1yabTj.js → api-Diy_2fp8.js} +4 -17
  14. package/dist/api-Diy_2fp8.js.map +1 -0
  15. package/dist/bin.js +410 -68
  16. package/dist/bin.js.map +1 -1
  17. package/dist/{bounded-fs-CWRYuLAn.js → bounded-fs-Bx9zTe6m.js} +4 -4
  18. package/dist/bounded-fs-Bx9zTe6m.js.map +1 -0
  19. package/dist/check-screens.tsx +1 -1
  20. package/dist/{ci-install-CvXL5h13.js → ci-install-CDdQYsPe.js} +6 -5
  21. package/dist/ci-install-CDdQYsPe.js.map +1 -0
  22. package/dist/constants-jFI2SaE1.js +260 -0
  23. package/dist/constants-jFI2SaE1.js.map +1 -0
  24. package/dist/debug-Ch4BDOtD.js +171 -0
  25. package/dist/debug-Ch4BDOtD.js.map +1 -0
  26. package/dist/{debug-CziFS0cA.js → debug-M2gV2iDq.js} +1 -1
  27. package/dist/{defaults-4c4YwTmW.js → defaults-C6J7yL4O.js} +1 -1
  28. package/dist/{defaults-4c4YwTmW.js.map → defaults-C6J7yL4O.js.map} +1 -1
  29. package/dist/endpoints-DCVbM06L.js +108 -0
  30. package/dist/endpoints-DCVbM06L.js.map +1 -0
  31. package/dist/{env-api-key-BZ5wE3Y4.js → env-api-key-Qx8NnYHm.js} +3 -3
  32. package/dist/env-api-key-Qx8NnYHm.js.map +1 -0
  33. package/dist/{environment-BEvsey6i.js → environment-B07Bmxae.js} +6 -6
  34. package/dist/environment-B07Bmxae.js.map +1 -0
  35. package/dist/{errors-BoJvrdw8.js → errors-CQ9kttJD.js} +27 -34
  36. package/dist/errors-CQ9kttJD.js.map +1 -0
  37. package/dist/{file-BoD3REGB.js → file-BcLTjU16.js} +2 -2
  38. package/dist/{file-BoD3REGB.js.map → file-BcLTjU16.js.map} +1 -1
  39. package/dist/{file-watcher-BPFazvG_.js → file-watcher-DWc_bTs6.js} +2 -2
  40. package/dist/{file-watcher-BPFazvG_.js.map → file-watcher-DWc_bTs6.js.map} +1 -1
  41. package/dist/{gateway-session-xPFv6p5c.js → gateway-CjoShdLa.js} +175 -20
  42. package/dist/gateway-CjoShdLa.js.map +1 -0
  43. package/dist/generate-version.cjs +1 -1
  44. package/dist/{headless-ui-CsmQrDIl.js → headless-ui-BFFmYC4v.js} +13 -2
  45. package/dist/headless-ui-BFFmYC4v.js.map +1 -0
  46. package/dist/{interactive-Dej-sxvR.js → interactive-D6zV7brJ.js} +2 -2
  47. package/dist/{interactive-Dej-sxvR.js.map → interactive-D6zV7brJ.js.map} +1 -1
  48. package/dist/{local-dev-DPZiIPCK.js → local-dev-McsurOC-.js} +2 -2
  49. package/dist/local-dev-McsurOC-.js.map +1 -0
  50. package/dist/logging-ui-_TwoMNbG.js +226 -0
  51. package/dist/logging-ui-_TwoMNbG.js.map +1 -0
  52. package/dist/mcp-DAgaoGk5.js +97 -0
  53. package/dist/mcp-DAgaoGk5.js.map +1 -0
  54. package/dist/{mcp-prompt-streaming-BU_kuur_.js → mcp-prompt-streaming-I2U_X7BC.js} +7 -6
  55. package/dist/mcp-prompt-streaming-I2U_X7BC.js.map +1 -0
  56. package/dist/{mint-failure-BrleGqMd.js → mint-failure-D4nd2XmZ.js} +82 -25
  57. package/dist/mint-failure-D4nd2XmZ.js.map +1 -0
  58. package/dist/models-DDdBJKwT.js +83 -0
  59. package/dist/models-DDdBJKwT.js.map +1 -0
  60. package/dist/{non-interactive-DcOjH2fw.js → non-interactive-Dzow7YKY.js} +3 -3
  61. package/dist/non-interactive-Dzow7YKY.js.map +1 -0
  62. package/dist/oauth-session-DJ8h6GFa.js +74 -0
  63. package/dist/oauth-session-DJ8h6GFa.js.map +1 -0
  64. package/dist/{orchestrator-tools-DXwr8Sp3.js → orchestrator-tools-szcdscwn.js} +4 -4
  65. package/dist/orchestrator-tools-szcdscwn.js.map +1 -0
  66. package/dist/{package-json-xt3eeyBI.js → package-json-DY70kkNp.js} +2 -2
  67. package/dist/package-json-DY70kkNp.js.map +1 -0
  68. package/dist/{pi-mY8I2XkG.js → pi-D3h5Ok0i.js} +329 -65
  69. package/dist/pi-D3h5Ok0i.js.map +1 -0
  70. package/dist/{playground-CDUUKLkC.js → playground-5AB4WgNF.js} +11 -7
  71. package/dist/playground-5AB4WgNF.js.map +1 -0
  72. package/dist/{posthog-Hc_-9wrr.js → posthog-DNn574nW.js} +8 -3
  73. package/dist/posthog-DNn574nW.js.map +1 -0
  74. package/dist/{provisioning-xfdjhFtA.js → provisioning-B8uSqRZk.js} +6 -5
  75. package/dist/provisioning-B8uSqRZk.js.map +1 -0
  76. package/dist/{queue-tools-C8y_xZJi.js → queue-tools-9OOVx5TE.js} +7 -86
  77. package/dist/queue-tools-9OOVx5TE.js.map +1 -0
  78. package/dist/{registry-DTmREJ-f.js → registry-8YG-kuXk.js} +265 -6
  79. package/dist/registry-8YG-kuXk.js.map +1 -0
  80. package/dist/run-agent-legacy-d7rWlzQR.js +3739 -0
  81. package/dist/run-agent-legacy-d7rWlzQR.js.map +1 -0
  82. package/dist/{security-Dw2oFJjP.js → security-Cg_4a7vB.js} +6 -6
  83. package/dist/security-Cg_4a7vB.js.map +1 -0
  84. package/dist/{setup-utils-fjJTBhaB.js → setup-utils-CmTCTPkX.js} +46 -18
  85. package/dist/setup-utils-CmTCTPkX.js.map +1 -0
  86. package/dist/smoke-test.sh +1 -1
  87. package/dist/{start-tui-UNe2xQ0U.js → start-tui-CB2PZs1x.js} +38 -44
  88. package/dist/start-tui-CB2PZs1x.js.map +1 -0
  89. package/dist/{steps-C2yqOk_h.js → steps-BZcXRJNY.js} +7 -7
  90. package/dist/{steps-C2yqOk_h.js.map → steps-BZcXRJNY.js.map} +1 -1
  91. package/dist/{store-Bic4Cr3L.js → store-UN7c-ASf.js} +18 -28
  92. package/dist/store-UN7c-ASf.js.map +1 -0
  93. package/dist/{subagent-Dz41vV9j.js → subagent-BofIDK-O.js} +8 -3
  94. package/dist/subagent-BofIDK-O.js.map +1 -0
  95. package/dist/{task-5-fw_Vw3.js → task-r9t1UhQP.js} +124 -36
  96. package/dist/task-r9t1UhQP.js.map +1 -0
  97. package/dist/{task-stream-dVzl6b_q.js → task-stream-CMUilu54.js} +45 -15
  98. package/dist/task-stream-CMUilu54.js.map +1 -0
  99. package/dist/{tasks-D1c2z1aw.js → tasks-Bbv_lOBG.js} +17 -13
  100. package/dist/tasks-Bbv_lOBG.js.map +1 -0
  101. package/dist/{telemetry-BRnxBRWK.js → telemetry-D6ruCtnv.js} +5 -5
  102. package/dist/telemetry-D6ruCtnv.js.map +1 -0
  103. package/dist/{terminal-9bvRa4Qt.js → terminal-DrGyci_a.js} +39 -74
  104. package/dist/terminal-DrGyci_a.js.map +1 -0
  105. package/dist/{tools-Dp6i9k70.js → tools-Dyfh9aCD.js} +11 -11
  106. package/dist/tools-Dyfh9aCD.js.map +1 -0
  107. package/dist/ui-BBVuTM1v.js +15 -0
  108. package/dist/ui-BBVuTM1v.js.map +1 -0
  109. package/dist/version-aXxpgRKx.js +6 -0
  110. package/dist/version-aXxpgRKx.js.map +1 -0
  111. package/dist/warlock-smoke-test.ts +2 -2
  112. package/dist/{wizard-abort-lE6umflt.js → wizard-abort-BBkiUxfS.js} +23 -20
  113. package/dist/wizard-abort-BBkiUxfS.js.map +1 -0
  114. package/dist/wizard-abort-BU4aLyvh.js +3 -0
  115. package/dist/{wizard-session-FSJCkTcP.js → wizard-session-2w4Ru-Wz.js} +12 -16
  116. package/dist/wizard-session-2w4Ru-Wz.js.map +1 -0
  117. package/dist/wizard-session-DGaUHOF3.js +2 -0
  118. package/dist/wizard-ui-DoyOZxK8.js +16 -0
  119. package/dist/wizard-ui-DoyOZxK8.js.map +1 -0
  120. package/dist/{yara-hooks-BTNJ6MGW.js → yara-hooks-DCeMDd1o.js} +19 -68
  121. package/dist/yara-hooks-DCeMDd1o.js.map +1 -0
  122. package/dist/yara-hooks-DSGuCU9A.js +2 -0
  123. package/package.json +1 -1
  124. package/dist/agent-interface-Avtr_5M5.js.map +0 -1
  125. package/dist/agent-prompt-loader-CHixNPgY.js.map +0 -1
  126. package/dist/agent-runner-COOIUJCP.js +0 -6188
  127. package/dist/agent-runner-COOIUJCP.js.map +0 -1
  128. package/dist/analytics-C67F2vee.js.map +0 -1
  129. package/dist/analytics-CJA1uLlk.js +0 -2
  130. package/dist/api-Dj1yabTj.js.map +0 -1
  131. package/dist/bounded-fs-CWRYuLAn.js.map +0 -1
  132. package/dist/ci-install-CvXL5h13.js.map +0 -1
  133. package/dist/debug-B4kzIZPi.js +0 -754
  134. package/dist/debug-B4kzIZPi.js.map +0 -1
  135. package/dist/env-api-key-BZ5wE3Y4.js.map +0 -1
  136. package/dist/environment-BEvsey6i.js.map +0 -1
  137. package/dist/errors-BoJvrdw8.js.map +0 -1
  138. package/dist/gateway-session-C118uACz.js +0 -2
  139. package/dist/gateway-session-xPFv6p5c.js.map +0 -1
  140. package/dist/headless-ui-CsmQrDIl.js.map +0 -1
  141. package/dist/local-dev-DPZiIPCK.js.map +0 -1
  142. package/dist/mcp-Cbuw_xss.js +0 -64
  143. package/dist/mcp-Cbuw_xss.js.map +0 -1
  144. package/dist/mcp-prompt-streaming-BU_kuur_.js.map +0 -1
  145. package/dist/mint-failure-BrleGqMd.js.map +0 -1
  146. package/dist/non-interactive-DcOjH2fw.js.map +0 -1
  147. package/dist/orchestrator-tools-DXwr8Sp3.js.map +0 -1
  148. package/dist/package-json-xt3eeyBI.js.map +0 -1
  149. package/dist/package-manager-DR23m5Jg.js +0 -290
  150. package/dist/package-manager-DR23m5Jg.js.map +0 -1
  151. package/dist/pi-mY8I2XkG.js.map +0 -1
  152. package/dist/playground-CDUUKLkC.js.map +0 -1
  153. package/dist/posthog-Hc_-9wrr.js.map +0 -1
  154. package/dist/provisioning-xfdjhFtA.js.map +0 -1
  155. package/dist/queue-tools-C8y_xZJi.js.map +0 -1
  156. package/dist/registry-DTmREJ-f.js.map +0 -1
  157. package/dist/security-Dw2oFJjP.js.map +0 -1
  158. package/dist/setup-utils-fjJTBhaB.js.map +0 -1
  159. package/dist/start-tui-UNe2xQ0U.js.map +0 -1
  160. package/dist/store-Bic4Cr3L.js.map +0 -1
  161. package/dist/subagent-Dz41vV9j.js.map +0 -1
  162. package/dist/task-5-fw_Vw3.js.map +0 -1
  163. package/dist/task-stream-dVzl6b_q.js.map +0 -1
  164. package/dist/tasks-D1c2z1aw.js.map +0 -1
  165. package/dist/telemetry-BRnxBRWK.js.map +0 -1
  166. package/dist/terminal-9bvRa4Qt.js.map +0 -1
  167. package/dist/tools-Dp6i9k70.js.map +0 -1
  168. package/dist/wizard-abort-CAcInAxg.js +0 -2
  169. package/dist/wizard-abort-lE6umflt.js.map +0 -1
  170. package/dist/wizard-session-CYvyYnti.js +0 -2
  171. package/dist/wizard-session-FSJCkTcP.js.map +0 -1
  172. package/dist/yara-hooks-BTNJ6MGW.js.map +0 -1
  173. package/dist/yara-hooks-CFY4pGcW.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"playground-CDUUKLkC.js","names":["path","MOCK_TASKS","getSkillContentBlocks"],"sources":["../src/ui/tui/playground/demos/WelcomeDemo.tsx","../src/ui/tui/playground/demos/LayoutDemo.tsx","../src/ui/tui/playground/demos/InputDemo.tsx","../src/ui/tui/playground/demos/ProgressDemo.tsx","../src/ui/tui/playground/demos/LogDemo.tsx","../src/ui/tui/playground/demos/RunScreenDemo.tsx","../src/ui/tui/playground/demos/HealthCheckDemo.tsx","../src/ui/tui/playground/demos/DoctorReportDemo.tsx","../src/ui/tui/playground/demos/ModalDemo.tsx","../src/ui/tui/playground/demos/McpDemo.tsx","../src/ui/tui/playground/demos/McpSuggestedPromptsDemo.tsx","../src/ui/tui/playground/demos/KeyboardHintsDemo.tsx","../src/ui/tui/playground/demos/AuditChecksDemo.tsx","../src/ui/tui/playground/demos/LearnDeckDemo.tsx","../src/ui/tui/playground/demos/EndScreensDemo.tsx","../src/ui/tui/playground/demos/AiOptInDemo.tsx","../src/ui/tui/playground/demos/AskModalDemo.tsx","../src/ui/tui/playground/demos/ViewportGuardDemo.tsx","../src/ui/tui/playground/PlaygroundApp.tsx","../src/ui/tui/playground/start-playground.ts","../src/commands/basic-integration/playground.ts"],"sourcesContent":["/**\n * WelcomeDemo — Splash screen. Press enter to push the tabbed view.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport type { WizardStore } from '@ui/tui/store';\nimport { Colors, Icons } from '@ui/tui/styles';\n\ninterface WelcomeDemoProps {\n store: WizardStore;\n}\n\nexport const WelcomeDemo = ({ store }: WelcomeDemoProps) => {\n useInput((_input, key) => {\n if (key.return) {\n store.completeSetup();\n }\n });\n\n return (\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n justifyContent=\"center\"\n alignItems=\"center\"\n >\n <Text bold color={Colors.accent}>\n {Icons.diamond} PostHog Setup Wizard layout primitives playground\n </Text>\n <Box height={1} />\n <Text>Layout primitives for the PostHog Setup Wizard TUI.</Text>\n <Text dimColor>\n CardLayout, SplitView, TabContainer, ProgressList, and more.\n </Text>\n <Box height={1} />\n <Text color={Colors.primary}>\n Press enter to continue {Icons.triangleRight}\n </Text>\n </Box>\n );\n};\n","/**\n * LayoutDemo — Demonstrates CardLayout + SplitView.\n * Cycles alignment enums with keyboard shortcuts.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useState } from 'react';\nimport { CardLayout, SplitView, ConfirmButton } from '@ui/tui/primitives/index';\nimport { HAlign, VAlign, Colors } from '@ui/tui/styles';\n\nconst hAligns = [HAlign.Left, HAlign.Center, HAlign.Right];\nconst vAligns = [VAlign.Top, VAlign.Center, VAlign.Bottom];\nconst hLabels = ['Left', 'Center', 'Right'];\nconst vLabels = ['Top', 'Center', 'Bottom'];\n\nexport const LayoutDemo = () => {\n const [hIdx, setHIdx] = useState(0);\n const [vIdx, setVIdx] = useState(0);\n\n useInput((input) => {\n if (input === 'h') setHIdx((i) => (i + 1) % hAligns.length);\n if (input === 'v') setVIdx((i) => (i + 1) % vAligns.length);\n });\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n Layout Demo\n </Text>\n <Text dimColor>\n Press [h] to cycle hAlign ({hLabels[hIdx]}), [v] to cycle vAlign (\n {vLabels[vIdx]})\n </Text>\n <Box height={1} />\n <SplitView\n left={\n <CardLayout hAlign={hAligns[hIdx]} vAlign={vAligns[vIdx]}>\n <Box borderStyle=\"single\" borderColor={Colors.primary} paddingX={1}>\n <Text color={Colors.primary}>Left Pane</Text>\n </Box>\n </CardLayout>\n }\n right={\n <CardLayout hAlign={HAlign.Center} vAlign={VAlign.Center}>\n <Box borderStyle=\"single\" borderColor={Colors.accent} paddingX={1}>\n <Text color={Colors.accent}>Right Pane</Text>\n </Box>\n </CardLayout>\n }\n />\n <Box height={1} />\n <Text dimColor>\n ConfirmButton — the focusable submit target for multi-select menus\n (focused / unfocused):\n </Text>\n <Box gap={2} marginTop={1}>\n <ConfirmButton focused count={3} />\n <ConfirmButton focused={false} />\n </Box>\n </Box>\n );\n};\n","/**\n * InputDemo — Demonstrates PickerMenu (single + multi) and ConfirmationInput.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState } from 'react';\nimport { PickerMenu, ConfirmationInput } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nenum DemoStep {\n Single = 'single',\n Multi = 'multi',\n MultiLong = 'multi-long',\n Confirm = 'confirm',\n Done = 'done',\n}\n\n// A long single-column multi-select — more options than a normal terminal can\n// show at once — so the playground exercises PickerMenu's viewport paging\n// (the \"↑/↓ N more\" indicators and the n/p page keys). Shared with\n// AskModalDemo.\nexport const LONG_OPTIONS = [\n 'None of these',\n 'GitHub Issues',\n 'Linear',\n 'Jira',\n 'GitLab',\n 'Gitea',\n 'Shortcut',\n 'Sentry',\n 'Rollbar',\n 'Bugsnag',\n 'Honeybadger',\n 'Raygun',\n 'Zendesk',\n 'Freshdesk',\n 'Freshservice',\n 'Front',\n 'Gorgias',\n 'Kustomer',\n 'Dixa',\n 'Plain',\n 'pganalyze',\n 'Snyk',\n 'SonarQube',\n 'Semgrep',\n 'Rapid7 InsightVM',\n 'Featurebase',\n 'Frill',\n 'Aha',\n 'UserVoice',\n 'Productboard',\n 'Canny',\n 'AskNicely',\n 'Retently',\n 'Appfigures',\n 'AppFollow',\n 'Judge.me',\n 'Google Search Console',\n].map((label) => ({ label, value: label.toLowerCase().replace(/\\s+/g, '-') }));\n\nexport const InputDemo = () => {\n const [step, setStep] = useState<DemoStep>(DemoStep.Single);\n const [results, setResults] = useState<string[]>([]);\n\n if (step === DemoStep.Single) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Single Select\n </Text>\n <Box height={1} />\n <PickerMenu\n message=\"Pick a color\"\n options={[\n { label: 'Red', value: 'red', hint: 'warm' },\n { label: 'Blue', value: 'blue', hint: 'cool' },\n { label: 'Green', value: 'green', hint: 'natural' },\n ]}\n onSelect={(value) => {\n setResults((prev) => [...prev, `Single: ${value}`]);\n setStep(DemoStep.Multi);\n }}\n />\n </Box>\n );\n }\n\n if (step === DemoStep.Multi) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Multi Select\n </Text>\n <Box height={1} />\n <PickerMenu\n message=\"Pick toppings\"\n mode=\"multi\"\n options={[\n { label: 'Cheese', value: 'cheese' },\n { label: 'Pepperoni', value: 'pepperoni' },\n { label: 'Mushrooms', value: 'mushrooms' },\n { label: 'Onions', value: 'onions' },\n ]}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n setResults((prev) => [...prev, `Multi: ${arr.join(', ')}`]);\n setStep(DemoStep.MultiLong);\n }}\n />\n </Box>\n );\n }\n\n if (step === DemoStep.MultiLong) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Multi Select (long, scrolls)\n </Text>\n <Box height={1} />\n <PickerMenu\n message=\"Which of these do you use? (↑/↓ to scroll)\"\n mode=\"multi\"\n options={LONG_OPTIONS}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n setResults((prev) => [\n ...prev,\n `Multi (long): ${arr.length} picked`,\n ]);\n setStep(DemoStep.Confirm);\n }}\n />\n </Box>\n );\n }\n\n if (step === DemoStep.Confirm) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Confirmation\n </Text>\n <Box height={1} />\n <ConfirmationInput\n message=\"Are you satisfied with your choices?\"\n onConfirm={() => {\n setResults((prev) => [...prev, 'Confirmed: Yes']);\n setStep(DemoStep.Done);\n }}\n onCancel={() => {\n setResults((prev) => [...prev, 'Confirmed: No']);\n setStep(DemoStep.Done);\n }}\n />\n </Box>\n );\n }\n\n // done\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Input Demo — Results\n </Text>\n <Box height={1} />\n {results.map((r, i) => (\n <Text key={i} color={Colors.success}>\n {'\\u2714'} {r}\n </Text>\n ))}\n <Box height={1} />\n <Text dimColor>Switch away from this tab and back to restart.</Text>\n </Box>\n );\n};\n","/**\n * ProgressDemo — Demonstrates ProgressList + LoadingBox.\n * Auto-animates task progression through states.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, useEffect } from 'react';\nimport { ProgressList, LoadingBox } from '@ui/tui/primitives/index';\nimport type { ProgressItem } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nconst INITIAL_ITEMS: ProgressItem[] = [\n {\n label: 'Detect framework',\n activeForm: 'Detecting framework',\n status: 'pending',\n },\n {\n label: 'Install dependencies',\n activeForm: 'Installing dependencies',\n status: 'pending',\n },\n {\n label: 'Configure PostHog',\n activeForm: 'Configuring PostHog',\n status: 'pending',\n },\n {\n label: 'Add analytics provider',\n activeForm: 'Adding analytics provider',\n status: 'pending',\n },\n { label: 'Verify setup', activeForm: 'Verifying setup', status: 'pending' },\n];\n\nexport const ProgressDemo = () => {\n const [items, setItems] = useState<ProgressItem[]>(INITIAL_ITEMS);\n const [tick, setTick] = useState(0);\n\n useEffect(() => {\n const timer = setInterval(() => {\n setTick((t) => t + 1);\n }, 1500);\n return () => clearInterval(timer);\n }, []);\n\n useEffect(() => {\n // Cycle: each tick advances the \"active\" task\n const total = INITIAL_ITEMS.length;\n // After all tasks complete, restart\n const cycle = tick % (total + 2); // +2 for a pause at the end\n\n setItems(\n INITIAL_ITEMS.map((item, i) => {\n if (i < cycle) return { ...item, status: 'completed' as const };\n if (i === cycle) return { ...item, status: 'in_progress' as const };\n return { ...item, status: 'pending' as const };\n }),\n );\n }, [tick]);\n\n const allDone = items.every((i) => i.status === 'completed');\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n Progress Demo\n </Text>\n <Text dimColor>Tasks auto-advance every 1.5s (cycles continuously)</Text>\n <Box height={1} />\n <ProgressList items={items} title=\"Setup in progress:\" />\n <Box height={1} />\n {!allDone && <LoadingBox message=\"Working...\" />}\n {allDone && (\n <Text color={Colors.success} bold>\n {'\\u2714'} All tasks complete! Restarting...\n </Text>\n )}\n </Box>\n );\n};\n","/**\n * LogDemo — Demonstrates LogViewer.\n * Writes demo log lines to a temp file, then tails it.\n */\n\nimport { Box, Text } from 'ink';\nimport { useEffect, useState } from 'react';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { LogViewer } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nconst DEMO_LOG_PATH = path.join(os.tmpdir(), 'posthog-playground.log');\n\nconst LOG_MESSAGES = [\n '[info] Playground started',\n '[info] Initializing demo components...',\n '[debug] Loading primitives barrel export',\n '[info] ScreenContainer mounted',\n '[info] TabContainer initialized with 6 tabs',\n '[debug] LayoutDemo: hAlign=Left, vAlign=Top',\n '[info] NavigationDemo: screenStack depth = 1',\n '[warn] TabDemo: arrow key conflict with outer container',\n '[info] InputDemo: waiting for user selection',\n '[info] ProgressDemo: tick 0, cycling tasks',\n '[debug] LogViewer: watching file for changes',\n '[info] All demos loaded successfully',\n];\n\nexport const LogDemo = () => {\n const [ready, setReady] = useState(false);\n\n useEffect(() => {\n // Write initial log content\n fs.writeFileSync(DEMO_LOG_PATH, LOG_MESSAGES.join('\\n') + '\\n');\n setReady(true);\n\n // Append lines periodically\n let lineNum = LOG_MESSAGES.length;\n const timer = setInterval(() => {\n lineNum++;\n const msg = `[info] Demo log line #${lineNum} — ${new Date().toISOString()}\\n`;\n fs.appendFileSync(DEMO_LOG_PATH, msg);\n }, 2000);\n\n return () => {\n clearInterval(timer);\n try {\n fs.unlinkSync(DEMO_LOG_PATH);\n } catch {\n // ignore\n }\n };\n }, []);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Text bold color={Colors.accent}>\n Log Demo\n </Text>\n <Text dimColor>Tailing {DEMO_LOG_PATH} (new line every 2s)</Text>\n <Box height={1} />\n {ready && <LogViewer filePath={DEMO_LOG_PATH} height={15} />}\n </Box>\n );\n};\n","/**\n * RunScreenDemo — Playground demo for the agent run view.\n *\n * Renders RunScreen's tab panels directly (not RunScreen itself) and owns its\n * own tab navigation, the way HealthCheckDemo renders its components directly —\n * a nested TabContainer would fight the playground's outer one over the arrow\n * keys (Ink delivers every key to every handler), leaving the inner tabs\n * unreachable. So the outer playground keeps the arrows and this demo uses:\n *\n * n / p switch run-screen tab (Status, Event plan, Tail logs, Visualizer, HN)\n *\n * Tasks auto-advance every 1.5s and the visualizer stage cycles on its own.\n * Discovered features (Stripe, LLM) are pre-populated so conditional tips appear.\n */\n\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { Box, Text, useInput } from 'ink';\nimport { WizardStore, TaskStatus } from '@ui/tui/store';\nimport { DiscoveredFeature } from '@lib/wizard-session';\nimport { AgentPhase } from '@lib/agent/agent-phase';\nimport {\n SplitView,\n ProgressList,\n LogViewer,\n EventPlanViewer,\n HNViewer,\n} from '@ui/tui/primitives/index';\nimport type { ProgressItem, TabDefinition } from '@ui/tui/primitives/index';\nimport { LearnCard } from '@ui/tui/components/LearnCard';\nimport { TipsCard } from '@ui/tui/components/TipsCard';\nimport { VisualizerTab } from '@ui/tui/components/PhaseVisuals';\nimport { getProgramConfig } from '@lib/programs/program-registry';\nimport { getContentBlocks as getSkillContentBlocks } from '@lib/programs/agent-skill/content/index';\nimport { Colors } from '@ui/tui/styles';\nimport { WIZARD_LOG_FILE } from '@utils/paths';\n\nconst STAGE_CYCLE: AgentPhase[] = [\n AgentPhase.CodebaseScan,\n AgentPhase.SkillInstall,\n AgentPhase.DepInstall,\n AgentPhase.CodeEdits,\n AgentPhase.EnvSetup,\n AgentPhase.Dashboards,\n];\n\nconst MOCK_TASKS = [\n {\n label: 'Checking project structure and finding files for event tracking',\n activeForm: 'Checking project structure',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Load skill menu and install integration-nextjs-app-router skill',\n activeForm: 'Picking the right skill',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Verify PostHog dependencies',\n activeForm: 'Verifying PostHog dependencies',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Generate events plan (.posthog-events.json)',\n activeForm: 'Generating events plan',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Install posthog-js and posthog-node packages',\n activeForm: 'Installing packages',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Set up environment variables',\n activeForm: 'Setting up environment variables',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Create instrumentation-client.ts',\n activeForm: 'Creating instrumentation-client.ts',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Update next.config with rewrites',\n activeForm: 'Updating next.config',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Create posthog-server.ts',\n activeForm: 'Creating posthog-server.ts',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Add PostHog capture events to project files',\n activeForm: 'Adding capture events',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Create onboarding dashboard and insight',\n activeForm: 'Building dashboard',\n status: TaskStatus.Pending,\n done: false,\n },\n {\n label: 'Verify $pageview and $autocapture are arriving',\n activeForm: 'Watching events arrive',\n status: TaskStatus.Pending,\n done: false,\n },\n];\n\nconst MOCK_EVENTS = [\n { name: 'page_viewed', description: 'Fires when a user views any page' },\n {\n name: 'button_clicked',\n description: 'Fires when the CTA button is clicked',\n },\n {\n name: 'form_submitted',\n description: 'Fires when the contact form is submitted',\n },\n {\n name: 'signup_started',\n description: 'Fires when a user begins the signup flow',\n },\n];\n\ninterface RunScreenDemoProps {\n store: WizardStore;\n}\n\nexport const RunScreenDemo = ({ store }: RunScreenDemoProps) => {\n const tickRef = useRef(0);\n const lastStatusRef = useRef('');\n const [activeTab, setActiveTab] = useState(0);\n\n // Re-render whenever the mock timers mutate the store (tasks, stage, etc.).\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n // Seed the store with mock data on mount\n useEffect(() => {\n store.addDiscoveredFeature(DiscoveredFeature.Stripe);\n store.addDiscoveredFeature(DiscoveredFeature.LLM);\n store.setEventPlan(MOCK_EVENTS);\n store.pushStatus('Checking project structure.');\n lastStatusRef.current = 'Checking project structure.';\n\n // Set initial tasks\n const initial = MOCK_TASKS.map((t, i) =>\n i === 0 ? { ...t, status: TaskStatus.InProgress } : t,\n );\n store.setTasks(initial);\n }, []);\n\n // Auto-advance tasks every 1.5s\n useEffect(() => {\n const timer = setInterval(() => {\n tickRef.current += 1;\n const tick = tickRef.current;\n const total = MOCK_TASKS.length;\n const cycle = tick % (total + 3); // +3 for pause at end before restart\n\n const tasks = MOCK_TASKS.map((t, i) => {\n if (i < cycle)\n return { ...t, status: TaskStatus.Completed, done: true };\n if (i === cycle)\n return { ...t, status: TaskStatus.InProgress, done: false };\n return { ...t, status: TaskStatus.Pending, done: false };\n });\n\n store.setTasks(tasks);\n\n // Only push status when the message actually changes\n if (cycle < total) {\n const msg = MOCK_TASKS[cycle].activeForm + '...';\n if (msg !== lastStatusRef.current) {\n store.pushStatus(msg);\n lastStatusRef.current = msg;\n }\n }\n }, 1500);\n\n return () => clearInterval(timer);\n }, []);\n\n // Cycle through every Visualizer stage on a faster timer so the playground\n // exercises each ASCII visual without needing the real agent loop.\n useEffect(() => {\n let i = 0;\n store.setCurrentStage(STAGE_CYCLE[0]);\n const timer = setInterval(() => {\n i = (i + 1) % STAGE_CYCLE.length;\n store.setCurrentStage(STAGE_CYCLE[i]);\n }, 4000);\n return () => clearInterval(timer);\n }, [store]);\n\n // Mirror RunScreen's tab panels (built here so the demo can drive them with\n // n/p instead of the arrow keys the outer playground TabContainer owns).\n const progressItems: ProgressItem[] = store.tasks.map((t) => ({\n label: t.label,\n activeForm: t.activeForm,\n status: t.status,\n }));\n\n const learnBlocks = useMemo(() => {\n const getBlocks =\n getProgramConfig(store.router.activeProgram).getContentBlocks ??\n getSkillContentBlocks;\n return getBlocks(store);\n }, [store]);\n\n const leftPane = store.learnCardComplete ? (\n <TipsCard store={store} />\n ) : (\n <LearnCard\n store={store}\n blocks={learnBlocks}\n onComplete={() => store.setLearnCardComplete()}\n />\n );\n\n const tabs: TabDefinition[] = [\n {\n id: 'status',\n label: 'Status',\n component: (\n <SplitView\n left={leftPane}\n right={<ProgressList items={progressItems} title=\"Tasks\" />}\n />\n ),\n },\n ...(store.eventPlan.length > 0\n ? [\n {\n id: 'events',\n label: 'Event plan',\n component: <EventPlanViewer events={store.eventPlan} />,\n },\n ]\n : []),\n {\n id: 'logs',\n label: 'Tail logs',\n component: <LogViewer filePath={WIZARD_LOG_FILE} />,\n },\n {\n id: 'visualizer',\n label: 'Visualizer',\n component: <VisualizerTab store={store} />,\n },\n { id: 'hn', label: 'HN', component: <HNViewer /> },\n ];\n\n // The outer playground TabContainer owns the arrow keys, so navigate with n/p.\n useInput((input) => {\n if (input === 'n') {\n setActiveTab((i) => Math.min(tabs.length - 1, i + 1));\n } else if (input === 'p') {\n setActiveTab((i) => Math.max(0, i - 1));\n }\n });\n\n const current = tabs[Math.min(activeTab, tabs.length - 1)];\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Box flexDirection=\"column\" flexGrow={1} flexShrink={1} overflow=\"hidden\">\n {current?.component}\n </Box>\n\n <Box height={1} />\n <Box gap={1} paddingX={1}>\n {tabs.map((tab, i) => (\n <Text\n key={tab.id}\n inverse={i === activeTab}\n color={i === activeTab ? Colors.accent : Colors.muted}\n bold={i === activeTab}\n >\n {` ${tab.label} `}\n </Text>\n ))}\n </Box>\n <Box paddingX={1}>\n <Text dimColor>n/p switch tab</Text>\n </Box>\n </Box>\n );\n};\n","// Preview the skills health-check states without handling input.\n\nimport { useEffect, useState } from 'react';\nimport { Box, Text } from 'ink';\nimport { LoadingBox, ModalOverlay } from '@ui/tui/primitives/index';\nimport { Icons } from '@ui/tui/styles';\nimport { ServiceHealthList } from '@ui/tui/components/ServiceHealthList';\nimport { getBlockingServiceKeys } from '@lib/health-checks/readiness';\nimport { ServiceHealthStatus } from '@lib/health-checks/types';\nimport type { AllServicesHealth } from '@lib/health-checks/types';\n\nconst MOCK_CONFIRMED_OUTAGE: AllServicesHealth = {\n skillsOrigin: { status: ServiceHealthStatus.Down },\n};\n\nconst MOCK_NO_CONNECTION: AllServicesHealth = {\n skillsOrigin: { status: ServiceHealthStatus.NoConnection },\n};\n\ntype Phase = 'checking' | 'confirmed' | 'no-connection';\n\nexport const HealthCheckDemo = () => {\n const [phase, setPhase] = useState<Phase>('checking');\n\n useEffect(() => {\n const t1 = setTimeout(() => setPhase('confirmed'), 2000);\n const t2 = setTimeout(() => setPhase('no-connection'), 7000);\n const t3 = setTimeout(() => setPhase('checking'), 12000);\n return () => {\n clearTimeout(t1);\n clearTimeout(t2);\n clearTimeout(t3);\n };\n }, [phase]);\n\n if (phase === 'checking') {\n return (\n <Box\n flexDirection=\"column\"\n flexGrow={1}\n alignItems=\"center\"\n justifyContent=\"center\"\n >\n <LoadingBox message=\"Checking service status...\" />\n </Box>\n );\n }\n\n const health =\n phase === 'confirmed' ? MOCK_CONFIRMED_OUTAGE : MOCK_NO_CONNECTION;\n const blockingKeys = getBlockingServiceKeys(health);\n const isNoConnection = phase === 'no-connection';\n\n return (\n <ModalOverlay\n borderColor={isNoConnection ? 'yellow' : 'red'}\n title={\n isNoConnection\n ? \"Couldn't reach skill downloads\"\n : `${Icons.warning} Skill downloads unavailable`\n }\n width={72}\n footer={\n <Box marginLeft={2}>\n <Text dimColor>Exit [Esc] (disabled in playground)</Text>\n </Box>\n }\n >\n <Box flexDirection=\"column\" marginBottom={1}>\n <Box marginBottom={1}>\n <Text>\n <Text color=\"red\">{Icons.squareFilled}</Text>\n <Text dimColor> Down </Text>\n <Text color=\"#DC9300\">{Icons.squareFilled}</Text>\n <Text dimColor> Degraded </Text>\n <Text color=\"gray\">{Icons.squareFilled}</Text>\n <Text dimColor> No connection</Text>\n </Text>\n </Box>\n\n <ServiceHealthList\n health={health}\n filterKeys={blockingKeys}\n showHealthy={false}\n />\n </Box>\n\n <Text dimColor>\n {isNoConnection\n ? \"We couldn't reach either skills source. Check your connection and try again.\"\n : 'Neither GitHub Releases nor the AWS mirror is available.'}\n </Text>\n </ModalOverlay>\n );\n};\n","import { Box, Text } from 'ink';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { IssueTable } from '@ui/tui/screens/doctor/IssueTable';\nimport type { HealthIssue } from '@lib/programs/posthog-doctor/index';\n\nconst NOW = '2026-04-27T15:00:00Z';\n\nconst MOCK_ISSUES: HealthIssue[] = [\n mock('1', 'ingestion_lag', 'critical'),\n mock('2', 'ingestion_warning', 'critical'),\n mock('3', 'materialized_view_failure', 'critical'),\n mock('4', 'sdk_outdated', 'warning'),\n mock('5', 'no_pageleave_events', 'warning'),\n mock('6', 'scroll_depth', 'warning'),\n mock('7', 'web_vitals', 'warning'),\n mock('8', 'reverse_proxy', 'info'),\n mock('9', 'authorized_urls', 'info'),\n mock('10', 'unrecognised_kind_with_a_long_slug_that_should_truncate', 'info'),\n];\n\nfunction mock(\n id: string,\n kind: string,\n severity: HealthIssue['severity'],\n): HealthIssue {\n return {\n id,\n kind,\n severity,\n status: 'active',\n dismissed: false,\n created_at: NOW,\n updated_at: NOW,\n };\n}\n\nexport const DoctorReportDemo = () => {\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n PostHog Doctor Report\n </Text>\n <Text dimColor>\n Project 12345 {Icons.bullet} https://us.i.posthog.com\n </Text>\n <Box marginTop={1}>\n <Text>\n {MOCK_ISSUES.length} active issues: 3 critical, 4 warning, 3 info\n </Text>\n </Box>\n <IssueTable issues={MOCK_ISSUES} />\n </Box>\n );\n};\n","/**\n * ModalDemo — Playground demo for the ModalOverlay primitive.\n *\n * Shows several modal variants: info, warning, error, and one with feedback text.\n */\n\nimport { Box, Text } from 'ink';\nimport { ModalOverlay } from '@ui/tui/primitives/index';\nimport { Icons } from '@ui/tui/styles';\n\nexport const ModalDemo = () => {\n return (\n <Box flexDirection=\"column\" gap={1} flexGrow={1}>\n <ModalOverlay borderColor=\"cyan\" title=\"Info Modal\" width={60}>\n <Text>A simple informational modal with default styling.</Text>\n </ModalOverlay>\n\n <ModalOverlay\n borderColor=\"#DC9300\"\n title={`${Icons.warning} Warning Modal`}\n width={60}\n feedback=\"Something needs your attention.\"\n >\n <Text>This modal includes a feedback message shown in yellow.</Text>\n </ModalOverlay>\n\n <ModalOverlay\n borderColor=\"red\"\n title={`${Icons.warning} Error Modal`}\n width={60}\n footer={\n <Box marginLeft={2}>\n <Text dimColor>\n Continue [Enter] / Exit [Esc] (disabled in playground)\n </Text>\n </Box>\n }\n >\n <Text>This modal has a footer section below a divider.</Text>\n </ModalOverlay>\n </Box>\n );\n};\n","/**\n * McpDemo — Playground demo for the MCP client selection screen.\n *\n * Uses a mock McpInstaller that simulates detecting three editors,\n * a short install delay, and a successful result.\n */\n\nimport { WizardStore } from '@ui/tui/store';\nimport { McpScreen } from '@ui/tui/screens/McpScreen';\nimport type {\n McpInstaller,\n McpClientInfo,\n} from '@ui/tui/services/mcp-installer';\nimport { McpClientStatus } from '@steps/add-mcp-server-to-clients/results';\n\nconst MOCK_CLIENTS: McpClientInfo[] = [\n { name: 'Claude Code', supportsPlugin: true, pluginBundlesMcp: false },\n { name: 'Cursor', supportsPlugin: true, pluginBundlesMcp: false },\n { name: 'VS Code', supportsPlugin: false, pluginBundlesMcp: false },\n {\n name: 'Claude Desktop/Web',\n supportsPlugin: false,\n pluginBundlesMcp: false,\n finish: {\n url: 'https://claude.ai/directory/connectors/posthog',\n instruction: 'Sign in and click \"Connect\" to finish.',\n },\n },\n];\n\nfunction createMockInstaller(): McpInstaller {\n return {\n async detectClients() {\n await new Promise((r) => setTimeout(r, 800));\n return MOCK_CLIENTS;\n },\n async install(clientNames) {\n await new Promise((r) => setTimeout(r, 1500));\n // Mixed outcomes so the demo shows every Done-phase section.\n return clientNames.map((name, i) => ({\n name,\n status: i === 1 ? McpClientStatus.Unchanged : McpClientStatus.Changed,\n }));\n },\n async installPlugins(clientNames) {\n await new Promise((r) => setTimeout(r, 800));\n return clientNames\n .filter(\n (name) => MOCK_CLIENTS.find((c) => c.name === name)?.supportsPlugin,\n )\n .map((name) => ({ name, status: McpClientStatus.Changed }));\n },\n async remove() {\n await new Promise((r) => setTimeout(r, 1000));\n // Mixed outcomes so the demo shows the removal failure copy too.\n return MOCK_CLIENTS.map((c, i) =>\n i === 2\n ? {\n name: c.name,\n status: McpClientStatus.Failed,\n detail: 'EACCES: permission denied',\n }\n : { name: c.name, status: McpClientStatus.Changed },\n );\n },\n };\n}\n\ninterface McpDemoProps {\n store: WizardStore;\n}\n\nexport const McpDemo = ({ store }: McpDemoProps) => {\n return (\n <McpScreen store={store} installer={createMockInstaller()} mode=\"install\" />\n );\n};\n","/**\n * McpSuggestedPromptsDemo — Playground demo for the post-MCP\n * suggested-prompts screen.\n *\n * Mounts the real McpSuggestedPromptsScreen with mock services so every\n * phase (Choose → Authenticating → Scouting → [SeedOffer → Seeding] →\n * Greeting → PromptPicker → Running → FollowUp → Goodbye) can be previewed\n * without touching the network. The Greeting phase auto-advances; FollowUp\n * re-enters Running when a follow-up is picked, building a conversation\n * tree up to MAX_PROMPT_RUNS deep.\n *\n * R cycle role (null → founder → product → ... → data → null)\n * F cycle framework (null → nextjs → vue → swift → django → null)\n * T cycle data tier (rich → sparse → empty) — drives the scout:\n * rich → generated quests from real events;\n * empty → seed-offer fork; sparse → safe read.\n * X remount the screen (useful after Exit)\n *\n * O OAuth outcome: success | error\n * L login delay: 0ms (skip UI) | 2000ms | 6000ms\n * S stream script: short-text | with-tools | mid-stream-error\n * C chunk delay: 50ms | 200ms | 800ms\n *\n * Tips:\n * - Set T to \"empty\" to walk the seed-events fork (SeedOffer → Seeding),\n * which lands on a rich seeded profile.\n * - Switch S to \"with-tools\" and the FollowUp picker after the run will\n * show context-aware suggestions based on the last tool. The mock\n * calls are CLI-mode `exec` chunks (`mcp__posthog-wizard__exec` + a\n * `call <tool> …` command), so they exercise getFollowUps' inner-tool\n * extraction.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\nimport { McpSuggestedPromptsScreen } from '@ui/tui/screens/McpSuggestedPromptsScreen';\nimport { Colors } from '@ui/tui/styles';\nimport { Integration } from '@lib/constants';\nimport { McpOutcome } from '@lib/wizard-session';\nimport { HostResolution } from '@lib/host-resolution';\nimport { TAILORED_ROLES } from '@lib/mcp-role-prompts';\nimport {\n assembleProfile,\n type ProjectDataProfile,\n} from '@lib/mcp-project-profile';\nimport { seededProfile } from '@lib/mcp-seed-events';\nimport type {\n AgentChunk,\n McpSuggestedPromptsServices,\n} from '@ui/tui/services/mcp-suggested-prompts-services';\n\n// One Integration per framework family so cycling exercises every\n// override bucket in mcp-role-prompts.ts.\nconst FAMILY_INTEGRATIONS: Array<Integration | null> = [\n null,\n Integration.nextjs, // fullstack\n Integration.vue, // frontend-web\n Integration.swift, // mobile\n Integration.django, // backend\n];\n\nconst ROLE_CYCLE: Array<string | null> = [null, ...TAILORED_ROLES];\n\nconst LOGIN_DELAYS_MS = [0, 2000, 6000] as const;\nconst CHUNK_DELAYS_MS = [50, 200, 800] as const;\n\n// Canned scout outcomes. 'rich' → generated quests from real events;\n// 'sparse' → safe read + a generated quest; 'empty' → seed-offer fork.\nconst PROBE_TIER_CYCLE = ['rich', 'sparse', 'empty'] as const;\ntype ProbeTier = (typeof PROBE_TIER_CYCLE)[number];\n\n// Every product absent, so activation cross-sells are eligible in the demo.\nconst NO_PRODUCTS = {\n sessionReplay: false,\n surveys: false,\n featureFlags: false,\n experiments: false,\n dataWarehouse: false,\n} as const;\n\nfunction mockProfile(tier: ProbeTier): ProjectDataProfile {\n if (tier === 'empty') {\n return assembleProfile([], NO_PRODUCTS);\n }\n if (tier === 'sparse') {\n return assembleProfile(\n [\n { name: '$pageview', count: 12 },\n { name: 'clicked', count: 5 },\n ],\n NO_PRODUCTS,\n );\n }\n return assembleProfile(\n [\n { name: '$pageview', count: 100 },\n { name: 'feature_used', count: 21 },\n { name: 'signed_up', count: 10 },\n { name: 'activated', count: 7 },\n { name: 'upgraded_to_paid', count: 3 },\n ],\n NO_PRODUCTS,\n );\n}\n\ntype LoginOutcome = 'success' | 'error';\ntype StreamScript = 'short-text' | 'with-tools' | 'mid-stream-error';\nconst LOGIN_OUTCOMES: LoginOutcome[] = ['success', 'error'];\nconst STREAM_SCRIPTS: StreamScript[] = [\n 'short-text',\n 'with-tools',\n 'mid-stream-error',\n];\n\nconst SCRIPTS: Record<StreamScript, AgentChunk[]> = {\n 'short-text': [\n { kind: 'text', text: 'Looking at your project…' },\n { kind: 'text', text: ' here is a quick read of the last 24 hours.' },\n {\n kind: 'text',\n text: ' You had 12,308 events from 2,144 distinct users.',\n },\n { kind: 'text', text: '\\n\\nNothing unusual stood out.' },\n { kind: 'done', sessionId: 'mock-session-aaa' },\n ],\n 'with-tools': [\n { kind: 'text', text: 'Looking up your project…' },\n {\n kind: 'tool-call',\n toolName: 'mcp__posthog-wizard__exec',\n detail: 'call query-trends { event: \"signup\", interval: \"day\" }',\n command:\n 'call query-trends {\"event\":\"signup\",\"interval\":\"day\",\"window\":\"7d\"}',\n },\n {\n kind: 'tool-result',\n toolName: 'mcp__posthog-wizard__exec',\n detail: '{ rows: 7, total: 482, change: +8.4% }',\n },\n {\n kind: 'text',\n text: '\\nSignups are up 8.4% week-over-week — 482 over the last 7 days.',\n },\n {\n kind: 'tool-call',\n toolName: 'mcp__posthog-wizard__exec',\n detail: 'call create-insight { name: \"Weekly signups\", save: true }',\n command:\n 'call create-insight {\"name\":\"Weekly signups\",\"query\":\"<trends>\",\"save\":true}',\n },\n {\n kind: 'tool-result',\n toolName: 'mcp__posthog-wizard__exec',\n detail:\n '{ id: \"ins_abc123\", url: \"https://app.posthog.com/i/ins_abc123\" }',\n },\n {\n kind: 'text',\n text: '\\nInsight saved as \"Weekly signups\" — pinned to your team dashboard.',\n },\n { kind: 'done', sessionId: 'mock-session-aaa' },\n ],\n 'mid-stream-error': [\n { kind: 'text', text: 'Looking at the most recent errors…' },\n {\n kind: 'tool-call',\n toolName: 'mcp__posthog-wizard__exec',\n detail: 'call query-error-tracking-issue { window: \"7d\", limit: 5 }',\n command: 'call query-error-tracking-issue {\"window\":\"7d\",\"limit\":5}',\n },\n {\n kind: 'error',\n text: 'MCP server returned 503 — try again in a moment.',\n },\n ],\n};\n\ninterface MockConfig {\n role: string | null;\n tier: ProbeTier;\n loginOutcome: LoginOutcome;\n loginDelayMs: number;\n script: StreamScript;\n chunkDelayMs: number;\n}\n\ninterface McpSuggestedPromptsDemoProps {\n store: WizardStore;\n}\n\nconst delay = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Returns a McpSuggestedPromptsServices instance whose behavior is read\n * fresh from `configRef` on every call. Hotkey changes take effect on\n * the *next* invocation without remounting the screen.\n */\nfunction createMockServices(\n store: WizardStore,\n configRef: { current: MockConfig },\n): McpSuggestedPromptsServices {\n return {\n performLogin: async () => {\n const cfg = configRef.current;\n store.setLoginUrl('https://app.posthog.com/oauth/playground-mock');\n await delay(cfg.loginDelayMs);\n store.setLoginUrl(null);\n\n if (cfg.loginOutcome === 'error') {\n throw new Error('Mock OAuth rejected — exercising error path.');\n }\n\n return {\n credentials: {\n accessToken: 'phx_mock',\n projectApiKey: 'phc_mock',\n host: HostResolution.fromApiHost('http://127.0.0.1:1'),\n projectId: 1,\n },\n roleAtOrganization: cfg.role,\n user: {\n distinct_id: 'demo-distinct-id',\n uuid: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',\n id: 1,\n email: 'joe@demo.example.com',\n first_name: 'Joe',\n last_name: 'Demo',\n role_at_organization: cfg.role,\n team: {\n id: 1,\n uuid: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',\n organization: 'cccccccc-cccc-cccc-cccc-cccccccccccc',\n api_token: 'phc_mock',\n project_id: 1,\n name: 'Demo team',\n timezone: 'UTC',\n },\n organization: {\n id: 'cccccccc-cccc-cccc-cccc-cccccccccccc',\n name: 'Demo org',\n slug: 'demo-org',\n membership_level: 1,\n },\n organizations: [\n {\n id: 'cccccccc-cccc-cccc-cccc-cccccccccccc',\n name: 'Demo org',\n membership_level: 1,\n },\n ],\n },\n };\n },\n\n runPromptStreaming: ({ signal }) => mockStream(configRef, signal),\n\n probeProjectData: async () => {\n // Brief delay so the Scouting spinner is visible.\n await delay(800);\n return mockProfile(configRef.current.tier);\n },\n\n seedDemoEvents: async ({ baseProfile }) => {\n // No real ingestion in the playground — just show the spinner and\n // return the same seeded profile the production seeder would yield.\n await delay(1500);\n return seededProfile(baseProfile, new Date());\n },\n };\n}\n\nasync function* mockStream(\n configRef: { current: MockConfig },\n signal: AbortSignal,\n): AsyncIterable<AgentChunk> {\n const cfg = configRef.current;\n const chunks = SCRIPTS[cfg.script];\n for (const chunk of chunks) {\n if (signal.aborted) return;\n await delay(cfg.chunkDelayMs);\n if (signal.aborted) return;\n yield chunk;\n }\n}\n\nexport const McpSuggestedPromptsDemo = ({\n store,\n}: McpSuggestedPromptsDemoProps) => {\n const [roleIdx, setRoleIdx] = useState(2); // 'product' — has overrides\n const [familyIdx, setFamilyIdx] = useState(1); // nextjs (fullstack)\n const [tierIdx, setTierIdx] = useState(0); // 'rich' — shows generated quests\n const [resetKey, setResetKey] = useState(0);\n const [loginOutcomeIdx, setLoginOutcomeIdx] = useState(0);\n const [loginDelayIdx, setLoginDelayIdx] = useState(1); // 2000ms default\n const [scriptIdx, setScriptIdx] = useState(1); // 'with-tools' default\n const [chunkDelayIdx, setChunkDelayIdx] = useState(1); // 200ms default\n\n const role = ROLE_CYCLE[roleIdx];\n const integration = FAMILY_INTEGRATIONS[familyIdx];\n const tier = PROBE_TIER_CYCLE[tierIdx];\n const loginOutcome = LOGIN_OUTCOMES[loginOutcomeIdx];\n const loginDelayMs = LOGIN_DELAYS_MS[loginDelayIdx];\n const script = STREAM_SCRIPTS[scriptIdx];\n const chunkDelayMs = CHUNK_DELAYS_MS[chunkDelayIdx];\n\n // Ref-based config so hotkeys can update behavior without remounting.\n const configRef = useRef<MockConfig>({\n role,\n tier,\n loginOutcome,\n loginDelayMs,\n script,\n chunkDelayMs,\n });\n configRef.current = {\n role,\n tier,\n loginOutcome,\n loginDelayMs,\n script,\n chunkDelayMs,\n };\n\n // Stable services instance — reads from configRef each call.\n const services = useMemo(() => createMockServices(store, configRef), [store]);\n\n // Seed framework + a fake \"installed\" MCP state. setMcpComplete here\n // is harmless — production would have set it from the McpScreen step\n // before this screen mounts.\n useEffect(() => {\n store.setMcpComplete(McpOutcome.Installed, ['Claude Code']);\n store.setFrameworkConfig(integration ?? null, null);\n }, [store, integration]);\n\n useInput((input) => {\n if (input === 'R' || input === 'r') {\n setRoleIdx((i) => (i + 1) % ROLE_CYCLE.length);\n setResetKey((k) => k + 1);\n } else if (input === 'F' || input === 'f') {\n setFamilyIdx((i) => (i + 1) % FAMILY_INTEGRATIONS.length);\n setResetKey((k) => k + 1);\n } else if (input === 'T' || input === 't') {\n // Remount so the new tier is re-probed from the Scouting phase.\n setTierIdx((i) => (i + 1) % PROBE_TIER_CYCLE.length);\n setResetKey((k) => k + 1);\n } else if (input === 'X' || input === 'x') {\n store.setCredentials(null);\n store.setRoleAtOrganization(null);\n setResetKey((k) => k + 1);\n } else if (input === 'O' || input === 'o') {\n setLoginOutcomeIdx((i) => (i + 1) % LOGIN_OUTCOMES.length);\n } else if (input === 'L' || input === 'l') {\n setLoginDelayIdx((i) => (i + 1) % LOGIN_DELAYS_MS.length);\n } else if (input === 'S' || input === 's') {\n setScriptIdx((i) => (i + 1) % STREAM_SCRIPTS.length);\n } else if (input === 'C' || input === 'c') {\n setChunkDelayIdx((i) => (i + 1) % CHUNK_DELAYS_MS.length);\n }\n });\n\n const familyLabel = integration ?? 'unknown';\n\n return (\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <Text dimColor>\n R role · F framework · T data-tier · X reset · O oauth · L login-delay ·\n S script · C chunk-delay\n </Text>\n <Text dimColor>\n role={String(role)} · integration={familyLabel} · tier={tier} · login=\n {loginOutcome}/{loginDelayMs}ms · script={script}/{chunkDelayMs}ms\n </Text>\n <Box marginTop={1} flexDirection=\"column\" flexGrow={1}>\n <McpSuggestedPromptsScreen\n key={resetKey}\n store={store}\n services={services}\n />\n </Box>\n <Box marginTop={1}>\n <Text color={Colors.muted} dimColor>\n (mock services — no real OAuth, no real LLM. Press R/F to preview\n different prompt kits; O/L/S/C to flip mock outcomes.)\n </Text>\n </Box>\n </Box>\n );\n};\n","/**\n * KeyboardHintsDemo — Demonstrates the KeyboardHintsBar with all input types.\n *\n * Cycles through SinglePicker, MultiPicker, GroupedPicker, and Confirmation\n * so the user can see the hints bar update automatically for each component.\n * The bar appears at the bottom of the screen and stays visible, updating to\n * match the active component.\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, type ReactNode } from 'react';\nimport {\n PickerMenu,\n GroupedPickerMenu,\n ConfirmationInput,\n} from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\n\nenum DemoStep {\n SingleSelect = 'single',\n MultiSelect = 'multi',\n GroupedSelect = 'grouped',\n Confirmation = 'confirm',\n Done = 'done',\n}\n\nconst STEP_LABELS: Record<DemoStep, string> = {\n [DemoStep.SingleSelect]: 'Single Select — hints: ↑↓ navigate, enter select',\n [DemoStep.MultiSelect]:\n 'Multi Select — hints: ↑↓ navigate, enter select, arrow to Confirm + enter to submit',\n [DemoStep.GroupedSelect]:\n 'Grouped Select — hints: ↑↓ navigate, enter select, a toggle all, arrow to Confirm + enter to submit',\n [DemoStep.Confirmation]:\n 'Confirmation — hints: ←→ switch, enter confirm, esc cancel',\n [DemoStep.Done]: 'Done',\n};\n\nexport const KeyboardHintsDemo = () => {\n const [step, setStep] = useState<DemoStep>(DemoStep.SingleSelect);\n const [log, setLog] = useState<string[]>([]);\n\n const addLog = (msg: string) => setLog((prev) => [...prev.slice(-4), msg]);\n\n if (step === DemoStep.SingleSelect) {\n return (\n <Wrapper step={step} log={log}>\n <PickerMenu\n message=\"Pick a framework\"\n options={[\n { label: 'Next.js', value: 'next' },\n { label: 'React', value: 'react' },\n { label: 'Vue', value: 'vue' },\n { label: 'Svelte', value: 'svelte' },\n ]}\n columns={2}\n onSelect={(v) => {\n addLog(`Single: ${String(v)}`);\n setStep(DemoStep.MultiSelect);\n }}\n />\n </Wrapper>\n );\n }\n\n if (step === DemoStep.MultiSelect) {\n return (\n <Wrapper step={step} log={log}>\n <PickerMenu\n message=\"Pick features to enable\"\n mode=\"multi\"\n options={[\n { label: 'Analytics', value: 'analytics' },\n { label: 'Session Replay', value: 'replay' },\n { label: 'Feature Flags', value: 'flags' },\n { label: 'Surveys', value: 'surveys' },\n ]}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n addLog(`Multi: ${arr.join(', ')}`);\n setStep(DemoStep.GroupedSelect);\n }}\n />\n </Wrapper>\n );\n }\n\n if (step === DemoStep.GroupedSelect) {\n return (\n <Wrapper step={step} log={log}>\n <GroupedPickerMenu\n message=\"Select integrations\"\n groups={{\n Frontend: [\n { label: 'React SDK', value: 'react-sdk' },\n { label: 'Web Analytics', value: 'web-analytics' },\n ],\n Backend: [\n { label: 'Node SDK', value: 'node-sdk' },\n { label: 'Python SDK', value: 'python-sdk' },\n ],\n Tooling: [\n { label: 'MCP Server', value: 'mcp' },\n { label: 'CLI', value: 'cli' },\n ],\n }}\n onSelect={(values) => {\n addLog(`Grouped: ${values.join(', ')}`);\n setStep(DemoStep.Confirmation);\n }}\n />\n </Wrapper>\n );\n }\n\n if (step === DemoStep.Confirmation) {\n return (\n <Wrapper step={step} log={log}>\n <ConfirmationInput\n message=\"Apply these settings?\"\n onConfirm={() => {\n addLog('Confirmed!');\n setStep(DemoStep.Done);\n }}\n onCancel={() => {\n addLog('Cancelled');\n setStep(DemoStep.Done);\n }}\n />\n </Wrapper>\n );\n }\n\n return (\n <Wrapper step={step} log={log}>\n <Text dimColor>\n All steps complete. Switch away from this tab and back to restart.\n </Text>\n </Wrapper>\n );\n};\n\nconst Wrapper = ({\n step,\n log,\n children,\n}: {\n step: DemoStep;\n log: string[];\n children: ReactNode;\n}) => (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Keyboard Hints Demo\n </Text>\n <Text dimColor>{STEP_LABELS[step]}</Text>\n <Box height={1} />\n {children}\n {log.length > 0 && (\n <>\n <Box height={1} />\n <Text dimColor>Log:</Text>\n {log.map((entry, i) => (\n <Text key={i} color={Colors.muted}>\n {' '}\n {entry}\n </Text>\n ))}\n </>\n )}\n </Box>\n);\n","/**\n * AuditChecksDemo — renders the AuditChecksViewer against a mock ledger so\n * the scroll/expand/sort behavior can be verified in the playground without\n * running the actual audit agent.\n */\n\nimport { Box } from 'ink';\nimport type { AuditCheck } from '@lib/programs/audit/types';\nimport { AuditChecksViewer } from '@ui/tui/screens/audit/AuditChecksViewer/AuditChecksViewer';\n\nconst MOCK_CHECKS: AuditCheck[] = [\n {\n id: 'sdk-installed',\n area: 'Installation',\n label: 'PostHog SDK installed',\n status: 'pass',\n file: 'package.json',\n details: 'posthog-js@1.260.0 found in dependencies.',\n },\n {\n id: 'sdk-up-to-date',\n area: 'Installation',\n label: 'SDK version up to date',\n status: 'warning',\n details: 'installed 1.260.0, latest 1.372.6 — more than one minor behind.',\n },\n {\n id: 'init-correct',\n area: 'Installation',\n label: 'Initialization is correct',\n status: 'warning',\n file: 'index.js:12',\n details:\n 'Init runs at module load with no singleton guard; calling posthog.init() multiple times can cause duplicate events.',\n },\n {\n id: 'identify-stable-distinct-id',\n area: 'Identification',\n label: 'Stable distinct_id (not session UUID)',\n status: 'error',\n file: 'index.js:18',\n details:\n 'distinct_id is crypto.randomUUID() — a per-session ephemeral UUID that resets on every page load. Replace with an authenticated user id.',\n },\n {\n id: 'identify-not-late',\n area: 'Identification',\n label: 'identify() called before captures / flag evals',\n status: 'pass',\n file: 'index.js:18',\n details:\n 'posthog.identify() is called before any posthog.capture() calls in this module.',\n },\n {\n id: 'cross-runtime-distinct-id',\n area: 'Identification',\n label: 'Same distinct_id across client and server',\n status: 'pass',\n details: 'Single runtime — no cross-runtime check needed.',\n },\n {\n id: 'identify-reset-on-logout',\n area: 'Identification',\n label: 'reset() called on logout / account switch',\n status: 'error',\n file: 'auth.ts:44',\n details:\n 'signOut() clears app auth state but never calls posthog.reset(), so the next identify() on this device can merge into the prior user profile.',\n },\n {\n id: 'capture-event-names-static',\n area: 'Event Capture',\n label: 'Event names are static and consistent',\n status: 'pass',\n file: 'index.js:21',\n details:\n \"All posthog.capture() calls use static string literals ('pageview', 'cta_clicked'); no template literals or dynamic variables found.\",\n },\n {\n id: 'capture-uses-proxy',\n area: 'Event Capture',\n label: 'Captures route through a reverse proxy',\n status: 'warning',\n file: 'index.js:13',\n details:\n 'api_host is set to the default PostHog US ingest host (https://us.i.posthog.com) rather than a first-party reverse proxy — ad/tracking blockers can silently drop these events.',\n },\n {\n id: 'capture-growth-events',\n area: 'Event Capture',\n label: 'Key activation events captured',\n status: 'pending',\n },\n];\n\nexport const AuditChecksDemo = () => (\n <Box flexDirection=\"column\" flexGrow={1}>\n <AuditChecksViewer checks={MOCK_CHECKS} />\n </Box>\n);\n","/**\n * LearnDeckDemo — flip through every program's content deck one block at\n * a time so wording, pauses, and visual blocks can be reviewed without\n * waiting for the auto-advance timer.\n *\n * n / p step block (next / previous)\n * [ / ] switch deck\n * r replay current block (re-runs the reveal animation)\n *\n * Arrow keys are reserved for the playground's tab switcher, so this demo\n * uses letter keys.\n *\n * Decks are pulled from `PROGRAM_REGISTRY` so every program that ships a\n * deck is reviewable here. Migration also gets per-variant entries (one\n * per `--product=<id>` choice) so the variant composer in\n * `migration/content/index.tsx` can be exercised side-by-side with the\n * generic deck.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useMemo, useState } from 'react';\nimport {\n ContentSequencer,\n ProgressList,\n SplitView,\n TextRevealMode,\n} from '@ui/tui/primitives/index';\nimport type { ContentBlock, ProgressItem } from '@ui/tui/primitives/index';\nimport { Colors } from '@ui/tui/styles';\nimport type { WizardStore } from '@ui/tui/store';\nimport { PROGRAM_REGISTRY } from '@lib/programs/program-registry';\nimport { AUDIT_AREA_SLIDES } from '@ui/tui/screens/audit/slides/index';\nimport type { AreaSlide } from '@ui/tui/screens/audit/slides/shared';\n\ninterface Deck {\n id: string;\n label: string;\n blocks: ContentBlock[];\n}\n\n/**\n * Fake task list to fill the right-hand pane so the SplitView layout matches\n * what operators actually see during a real run. Mix of statuses so the\n * spinner glyph, the in-progress row, and completed rows all render.\n */\nconst MOCK_TASKS: ProgressItem[] = [\n {\n label: 'Confirm Statsig is in use',\n activeForm: 'Confirming Statsig is in use',\n status: 'completed',\n },\n {\n label: 'Install PostHog',\n activeForm: 'Installing PostHog',\n status: 'completed',\n },\n {\n label: 'Plan call site replacements',\n activeForm: 'Planning call site replacements',\n status: 'in_progress',\n },\n {\n label: 'Rewrite call sites',\n activeForm: 'Rewriting call sites',\n status: 'pending',\n },\n {\n label: 'Remove Statsig',\n activeForm: 'Removing Statsig',\n status: 'pending',\n },\n {\n label: 'Verify the project still builds',\n activeForm: 'Verifying the build',\n status: 'pending',\n },\n {\n label: 'Write migration report',\n activeForm: 'Writing migration report',\n status: 'pending',\n },\n];\n\ninterface LearnDeckDemoProps {\n store: WizardStore;\n}\n\nexport const LearnDeckDemo = ({ store }: LearnDeckDemoProps) => {\n const decks: Deck[] = useMemo(() => {\n const all: Deck[] = [];\n\n // Every program in the registry that ships a deck. Seed the store's\n // skillId from the program config so decks that template the skill\n // name (e.g. agent-skill's \"Running the <skill> skill...\") render the\n // real value instead of \"unknown\".\n for (const program of PROGRAM_REGISTRY) {\n if (!program.getContentBlocks) continue;\n const stub = program.skillId\n ? withSessionOverride(store, { skillId: program.skillId })\n : store;\n all.push({\n id: `program:${program.id}`,\n label: `${program.id} (${program.command ?? 'default'})${\n program.skillId ? ` · skill: ${program.skillId}` : ''\n }`,\n blocks: program.getContentBlocks(stub),\n });\n }\n\n // Audit ships its own per-area slide model (not the ContentBlock deck\n // most programs use). Adapt each AreaSlide into a flat ContentBlock\n // list so the flipper can review them the same way.\n all.push({\n id: 'audit:area-slides',\n label: 'audit · area slides',\n blocks: areaSlidesToBlocks(AUDIT_AREA_SLIDES),\n });\n\n return all;\n }, [store]);\n\n const [deckIdx, setDeckIdx] = useState(0);\n const [blockIdx, setBlockIdx] = useState(0);\n const [replayKey, setReplayKey] = useState(0);\n\n const deck = decks[deckIdx];\n const block = deck.blocks[blockIdx];\n\n useInput((input) => {\n if (input === 'p') {\n setBlockIdx((i) => Math.max(0, i - 1));\n } else if (input === 'n') {\n setBlockIdx((i) => Math.min(deck.blocks.length - 1, i + 1));\n } else if (input === '[') {\n setDeckIdx((i) => (i - 1 + decks.length) % decks.length);\n setBlockIdx(0);\n } else if (input === ']') {\n setDeckIdx((i) => (i + 1) % decks.length);\n setBlockIdx(0);\n } else if (input === 'r') {\n setReplayKey((k) => k + 1);\n }\n });\n\n const pauseMs =\n typeof block === 'object' && 'pause' in block ? block.pause : '—';\n const blockKind = describeBlockKind(block);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <Text bold color={Colors.accent}>\n Learn deck flipper\n </Text>\n <Text dimColor>n/p step block · [ ] switch deck · r replay</Text>\n <Box height={1} />\n\n <Text>\n <Text bold>Deck:</Text> {deck.label}{' '}\n <Text dimColor>\n ({deckIdx + 1}/{decks.length})\n </Text>\n </Text>\n <Text>\n <Text bold>Block:</Text> {blockIdx + 1}/{deck.blocks.length}{' '}\n <Text dimColor>\n · kind: {blockKind} · pause: {String(pauseMs)}ms\n </Text>\n </Text>\n <Box height={1} />\n\n <Box flexGrow={1}>\n <SplitView\n left={\n <ContentSequencer\n key={`${deck.id}-${blockIdx}-${replayKey}`}\n blocks={deck.blocks.slice(0, blockIdx + 1)}\n mode={TextRevealMode.SentenceBySentence}\n startDelay={0}\n initialBlockIdx={blockIdx}\n />\n }\n right={<ProgressList items={MOCK_TASKS} title=\"Tasks\" />}\n />\n </Box>\n </Box>\n );\n};\n\n/**\n * Build a store proxy that exposes an overridden `session` while keeping\n * every prototype method (e.g. `setStatusExpanded`) and atom reference\n * intact. A plain `{...store, session: ...}` spread would drop the\n * prototype, so anything that called a store method on the result would\n * crash at render time.\n */\nfunction withSessionOverride(\n store: WizardStore,\n patch: Partial<WizardStore['session']>,\n): WizardStore {\n const stub = Object.create(Object.getPrototypeOf(store)) as WizardStore;\n Object.assign(stub, store);\n Object.defineProperty(stub, 'session', {\n value: { ...store.session, ...patch },\n writable: false,\n configurable: true,\n });\n return stub;\n}\n\n/**\n * Adapter: turn each audit AreaSlide into a sequence of ContentBlocks so it\n * fits the flipper's renderer. One block per intro paragraph, one for the\n * visual when present. Each slide is preceded by a heading block naming the\n * area so flipping between areas is obvious.\n */\nfunction areaSlidesToBlocks(slides: AreaSlide[]): ContentBlock[] {\n const out: ContentBlock[] = [];\n for (const slide of slides) {\n out.push({\n content: (\n <Text bold color={Colors.accent}>\n {slide.area}\n </Text>\n ),\n pause: 3000,\n });\n for (const paragraph of slide.intro) {\n out.push({ content: paragraph, pause: 5000 });\n }\n if (slide.visual) {\n out.push({\n content: slide.visual,\n pause: 8000,\n persist: true,\n });\n }\n out.push({ type: 'clear', pause: 1000 });\n }\n return out;\n}\n\nfunction describeBlockKind(block: ContentBlock): string {\n if (typeof block === 'string') return 'string';\n if (typeof block === 'object' && block !== null) {\n if ('type' in block && block.type === 'clear') return 'clear';\n if ('type' in block && block.type === 'lines') return 'lines';\n if ('content' in block) {\n return typeof block.content === 'string' ? 'text' : 'jsx';\n }\n }\n return 'unknown';\n}\n","/**\n * EndScreensDemo — Playground demo for the screens shown at the end of\n * a wizard run.\n *\n * Mounts the real SlackConnectScreen and OutroScreen against the shared\n * playground store so every variant can be previewed without a run:\n *\n * V switch view (slack-connect → outro)\n * K toggle Slack state (connected ↔ not connected) — simulates the\n * poll flipping the screen when the user finishes the browser OAuth\n * O cycle outro kind (success → error → cancel)\n *\n * The playground credentials are re-pointed at a localhost dead-end\n * while this demo is mounted, so SlackConnectScreen's poll fails fast\n * without real network traffic; `K` drives `session.slackConnected`\n * directly, which is the same store key the poll writes.\n *\n * KeepSkillsScreen is intentionally absent — it reads the install dir's\n * .claude/skills/ from disk and calls process.exit() when none are\n * found, which would kill the playground.\n */\n\nimport { Box, Text, useInput } from 'ink';\nimport { useEffect, useState, useSyncExternalStore } from 'react';\nimport type { WizardStore } from '@ui/tui/store';\nimport { SlackConnectScreen } from '@ui/tui/screens/SlackConnectScreen';\nimport { OutroScreen } from '@ui/tui/screens/OutroScreen';\nimport { Colors } from '@ui/tui/styles';\nimport { OutroKind, type OutroData } from '@lib/wizard-session';\nimport { HostResolution } from '@lib/host-resolution';\n\nconst VIEWS = ['slack-connect', 'outro'] as const;\ntype View = (typeof VIEWS)[number];\n\nconst OUTRO_KINDS = [OutroKind.Success, OutroKind.Error, OutroKind.Cancel];\n\nconst OUTRO_FIXTURES: Record<OutroKind, OutroData> = {\n [OutroKind.Success]: {\n kind: OutroKind.Success,\n message: 'PostHog is set up!',\n changes: [\n 'Installed posthog-js and wired the provider',\n 'Added pageview + pageleave capture',\n 'Instrumented 4 product events',\n ],\n reportFile: 'posthog-setup-report.md',\n dashboardUrl: 'https://us.posthog.com/project/1/dashboard/42',\n notebookUrl: 'https://us.posthog.com/project/1/notebooks/demo',\n docsUrl: 'https://posthog.com/docs/libraries/next-js',\n },\n [OutroKind.Error]: {\n kind: OutroKind.Error,\n message: 'The agent hit an error',\n body: 'The integration step failed before any files were changed.\\nRe-run the wizard to try again.',\n docsUrl: 'https://posthog.com/docs/ai-engineering/ai-wizard',\n },\n [OutroKind.Cancel]: {\n kind: OutroKind.Cancel,\n message: 'Cancelled — no changes were made',\n },\n};\n\ninterface EndScreensDemoProps {\n store: WizardStore;\n}\n\nexport const EndScreensDemo = ({ store }: EndScreensDemoProps) => {\n useSyncExternalStore(\n (cb) => store.subscribe(cb),\n () => store.getSnapshot(),\n );\n\n const [viewIdx, setViewIdx] = useState(0);\n const [outroKindIdx, setOutroKindIdx] = useState(0);\n\n const view: View = VIEWS[viewIdx];\n const outroKind = OUTRO_KINDS[outroKindIdx];\n\n // The playground pre-seeds fake credentials pointed at the real\n // PostHog host, which SlackConnectScreen's poll would hit. Swap the\n // host for a localhost dead-end while this demo is mounted (restore\n // on unmount — tab switches unmount). The credentials must stay\n // non-null: the router derives the active screen from session state,\n // and nulling them drops the playground out of the 'run' screen,\n // unmounting the tab bar and resetting it to the first tab.\n useEffect(() => {\n const previous = store.session.credentials;\n store.setCredentials({\n accessToken: 'playground',\n projectApiKey: 'playground',\n host: HostResolution.fromApiHost('http://127.0.0.1:9'),\n projectId: 0,\n });\n return () => {\n store.setCredentials(previous);\n };\n }, [store]);\n\n // Seed the outro fixture each screen reads. slackConnected starts\n // null (unknown) so the first paint shows the nudge variant, exactly\n // like a wizard run before the poll's first response.\n useEffect(() => {\n store.setOutroData(OUTRO_FIXTURES[outroKind]);\n }, [store, outroKind]);\n\n useInput((input) => {\n if (input === 'V' || input === 'v') {\n setViewIdx((i) => (i + 1) % VIEWS.length);\n } else if (input === 'K' || input === 'k') {\n store.setSlackConnected(store.session.slackConnected !== true);\n } else if (input === 'O' || input === 'o') {\n setOutroKindIdx((i) => (i + 1) % OUTRO_KINDS.length);\n }\n });\n\n const slackState =\n store.session.slackConnected === true ? 'connected' : 'not-connected';\n\n return (\n <Box flexDirection=\"column\" flexGrow={1} paddingX={1}>\n <Text dimColor>V view · K slack state · O outro kind</Text>\n <Text dimColor>\n view={view} · slack={slackState} · outro={outroKind}\n </Text>\n <Box marginTop={1} flexDirection=\"column\" flexGrow={1}>\n {view === 'slack-connect' ? (\n <SlackConnectScreen store={store} />\n ) : (\n <OutroScreen store={store} />\n )}\n </Box>\n <Box marginTop={1}>\n <Text color={Colors.muted} dimColor>\n (session-driven previews — the Slack poll points at a localhost\n dead-end; K flips the same store key the poll writes.)\n </Text>\n </Box>\n </Box>\n );\n};\n","/**\n * AiOptInDemo — Playground demo for AiOptInRequiredScreen.\n *\n * Mounts the real screen with a synthetic store pre-populated with an\n * apiUser whose org has `is_ai_data_processing_approved: false`.\n * Variant selection is driven by `membership_level` — admin (>= 8) vs\n * non-admin (< 8), matching what the screen reads in production.\n *\n * One demo function, used by two PlaygroundApp tabs. ⚠ keybindings on\n * the screen are LIVE — [E] exits the playground, [O] opens a real\n * browser URL, [R] fires a network request (which will fail with the\n * fake token, but won't be destructive).\n */\n\nimport { useEffect, useState } from 'react';\nimport { Box, Text } from 'ink';\nimport { WizardStore } from '@ui/tui/store';\nimport { AiOptInRequiredScreen } from '@ui/tui/screens/AiOptInRequiredScreen';\nimport { HostResolution } from '@lib/host-resolution';\n\ntype Variant = 'admin' | 'non-admin';\n\ninterface AiOptInDemoProps {\n variant: Variant;\n}\n\nexport const AiOptInDemo = ({ variant }: AiOptInDemoProps) => {\n const [store] = useState(() => {\n const s = new WizardStore();\n s.setCredentials({\n accessToken: 'demo-fake-token',\n projectApiKey: 'demo-fake-project-key',\n host: HostResolution.fromApiHost('https://us.posthog.com'),\n projectId: 0,\n });\n return s;\n });\n\n useEffect(() => {\n store.session.region = 'us';\n store.setApiUser({\n distinct_id: 'demo-distinct-id',\n email: 'sarah@example.com',\n organization: {\n id: '00000000-0000-0000-0000-000000000000',\n name: 'Demo Org',\n membership_level: variant === 'admin' ? 8 : 1,\n is_ai_data_processing_approved: false,\n } as never,\n organizations: [],\n team: {\n id: 0,\n organization: '00000000-0000-0000-0000-000000000000',\n } as never,\n } as never);\n }, [variant, store]);\n\n return (\n <Box flexDirection=\"column\" flexGrow={1}>\n <Box marginBottom={1}>\n <Text dimColor>\n Playground —{' '}\n <Text bold>\n AiOptInRequiredScreen ({variant === 'admin' ? 'Admin' : 'Non-admin'}\n )\n </Text>\n . Keys are live: [E] exits the playground.\n </Text>\n </Box>\n <AiOptInRequiredScreen store={store} />\n </Box>\n );\n};\n","/**\n * AskModalDemo — Pickers rendered inside an ask-style ModalOverlay, the way\n * WizardAskScreen composes them: prompt paragraph in the modal body, then a\n * label-less PickerMenu. Exercises the viewport height cap (MAX_LIST_ROWS)\n * and the no-label spacing (no stray blank lines under the paragraph).\n */\n\nimport { Box, Text } from 'ink';\nimport { useState, type ReactNode } from 'react';\nimport {\n ModalOverlay,\n PickerMenu,\n GroupedPickerMenu,\n} from '@ui/tui/primitives/index';\nimport { Colors, Icons } from '@ui/tui/styles';\nimport { LONG_OPTIONS } from './InputDemo.js';\n\nenum DemoStep {\n ScoutRepro = 'scout-repro',\n CountLabel100 = 'count-label-100',\n CountLabel10 = 'count-label-10',\n CountLabel2 = 'count-label-2',\n CountLabel1 = 'count-label-1',\n CountDesc100 = 'count-desc-100',\n CountDesc10 = 'count-desc-10',\n CountDesc2 = 'count-desc-2',\n CountDesc1 = 'count-desc-1',\n MultiLong = 'multi-long',\n MultiDescriptions = 'multi-descriptions',\n Single = 'single',\n Grouped = 'grouped',\n Done = 'done',\n}\n\n/** Label-only options at a given count, e.g. \"Option 1\" ... \"Option 100\". */\nconst countLabelOptions = (n: number) =>\n Array.from({ length: n }, (_, i) => ({\n label: `Option ${i + 1}`,\n value: `opt-${i + 1}`,\n }));\n\n/** Options at a given count, each with a wrapping description so rows are tall. */\nconst countDescOptions = (n: number) =>\n Array.from({ length: n }, (_, i) => ({\n label: `Option ${i + 1}`,\n value: `opt-${i + 1}`,\n description:\n 'A longer description that wraps onto multiple lines so each option row costs several terminal rows, exercising the viewport cap and the paging math at small counts.',\n }));\n\n/** Repro of the scout-proposal ask that paged 3 tall described options one per page. */\nconst SCOUT_REPRO_OPTIONS = [\n {\n label: 'None — keep the built-in troop',\n value: 'none',\n description:\n 'Skip custom scouts; the built-in troop already covers this project well enough, and adding more scheduled checks would mostly duplicate the coverage you already get out of the box.',\n },\n {\n label: 'Playground snapshot drift scout',\n value: 'snapshot-drift',\n description:\n 'Watches CI snapshot runs and flags visual drift in the playground demos before it reaches a release, so a rendering regression in a picker or overlay never ships to users unnoticed.',\n },\n {\n label: 'Benchmark regression scout',\n value: 'benchmark',\n description:\n 'Tracks wizard-benchmark timings week over week and opens an issue when a run regresses past the recorded baseline, catching slow drift in agent latency before customers feel it.',\n },\n];\n\nconst DESCRIBED_OPTIONS = [\n {\n label: 'Session replay',\n value: 'replay',\n description:\n 'Record and replay real user sessions to see exactly what happened before an error or a rage click.',\n },\n {\n label: 'Feature flags',\n value: 'flags',\n description:\n 'Roll features out gradually, target by cohort, and kill misbehaving code paths without a deploy.',\n },\n {\n label: 'Error tracking',\n value: 'errors',\n description: 'Capture exceptions with stack traces and source maps.',\n },\n];\n\nconst GROUPED = {\n 'Issue trackers': [\n { label: 'GitHub Issues', value: 'github' },\n { label: 'Linear', value: 'linear' },\n { label: 'Jira', value: 'jira' },\n { label: 'Shortcut', value: 'shortcut' },\n ],\n 'Error monitoring': [\n { label: 'Sentry', value: 'sentry' },\n { label: 'Rollbar', value: 'rollbar' },\n { label: 'Bugsnag', value: 'bugsnag' },\n { label: 'Honeybadger', value: 'honeybadger' },\n ],\n 'Support desks': [\n { label: 'Zendesk', value: 'zendesk' },\n { label: 'Freshdesk', value: 'freshdesk' },\n { label: 'Front', value: 'front' },\n { label: 'Intercom', value: 'intercom' },\n ],\n Observability: [\n { label: 'Datadog', value: 'datadog' },\n { label: 'New Relic', value: 'newrelic' },\n { label: 'Grafana', value: 'grafana' },\n { label: 'Splunk', value: 'splunk' },\n ],\n};\n\n/** Mirrors WizardAskScreen's shape: paragraph body, then a label-less input. */\nconst AskModal = ({\n prompt,\n children,\n}: {\n prompt: string;\n children: ReactNode;\n}) => (\n <ModalOverlay\n borderColor={Colors.accent}\n title={`${Icons.diamond} self-driving-setup`}\n titleColor={Colors.accent}\n width={72}\n >\n <Box flexDirection=\"column\">\n <Text>{prompt}</Text>\n </Box>\n <Box marginTop={1}>{children}</Box>\n </ModalOverlay>\n);\n\nexport const AskModalDemo = () => {\n const [step, setStep] = useState<DemoStep>(DemoStep.ScoutRepro);\n const [results, setResults] = useState<string[]>([]);\n\n const advance = (result: string, next: DemoStep) => {\n setResults((prev) => [...prev, result]);\n setStep(next);\n };\n\n const countLabelSteps: Partial<\n Record<DemoStep, { next: DemoStep; count: number }>\n > = {\n [DemoStep.CountLabel100]: {\n next: DemoStep.CountLabel10,\n count: 100,\n },\n [DemoStep.CountLabel10]: { next: DemoStep.CountLabel2, count: 10 },\n [DemoStep.CountLabel2]: { next: DemoStep.CountLabel1, count: 2 },\n [DemoStep.CountLabel1]: { next: DemoStep.CountDesc100, count: 1 },\n };\n\n const countDescSteps: Partial<\n Record<DemoStep, { next: DemoStep; count: number }>\n > = {\n [DemoStep.CountDesc100]: { next: DemoStep.CountDesc10, count: 100 },\n [DemoStep.CountDesc10]: { next: DemoStep.CountDesc2, count: 10 },\n [DemoStep.CountDesc2]: { next: DemoStep.CountDesc1, count: 2 },\n [DemoStep.CountDesc1]: { next: DemoStep.MultiLong, count: 1 },\n };\n\n if (step === DemoStep.ScoutRepro) {\n return (\n <AskModal prompt=\"Scouts are scheduled checks that watch your data and flag issues for your inbox. Based on your repo I found two gaps the built-in troop doesn't cover — add one, both, or none. (Repro: 3 described options must stay on ONE page even in a short terminal.)\">\n <PickerMenu\n key={step}\n mode=\"multi\"\n optionMarginBottom={1}\n options={SCOUT_REPRO_OPTIONS}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n advance(\n `Scout repro: ${arr.length} picked`,\n DemoStep.CountLabel100,\n );\n }}\n />\n </AskModal>\n );\n }\n\n const labelStep = countLabelSteps[step];\n if (labelStep) {\n const { count, next } = labelStep;\n return (\n <AskModal\n prompt={`Multi-select — ${count} label-only option${\n count === 1 ? '' : 's'\n }. Watch whether ${\n count <= 2 ? 'this tiny list still pages' : 'paging kicks in'\n }.`}\n >\n <PickerMenu\n key={step}\n mode=\"multi\"\n options={countLabelOptions(count)}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n advance(`Count label (${count}): ${arr.length} picked`, next);\n }}\n />\n </AskModal>\n );\n }\n\n const descStep = countDescSteps[step];\n if (descStep) {\n const { count, next } = descStep;\n return (\n <AskModal\n prompt={`Multi-select — ${count} option${\n count === 1 ? '' : 's'\n } with wrapping descriptions (tall rows). ${\n count <= 2\n ? 'This is where a tiny list can still split into multiple pages.'\n : ''\n }`}\n >\n <PickerMenu\n key={step}\n mode=\"multi\"\n optionMarginBottom={1}\n options={countDescOptions(count)}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n advance(`Count desc (${count}): ${arr.length} picked`, next);\n }}\n />\n </AskModal>\n );\n }\n\n if (step === DemoStep.MultiLong) {\n return (\n <AskModal prompt=\"Self-driving can also watch your other tools and investigate and fix the problems they surface. Which of these do you use?\">\n <PickerMenu\n key={step}\n mode=\"multi\"\n options={LONG_OPTIONS}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n advance(\n `Multi (long): ${arr.length} picked`,\n DemoStep.MultiDescriptions,\n );\n }}\n />\n </AskModal>\n );\n }\n\n if (step === DemoStep.MultiDescriptions) {\n return (\n <AskModal prompt=\"Besides analytics, which PostHog products should the agent set up while it's in the codebase?\">\n <PickerMenu\n key={step}\n mode=\"multi\"\n optionMarginBottom={1}\n options={DESCRIBED_OPTIONS}\n onSelect={(values) => {\n const arr = Array.isArray(values) ? values : [values];\n advance(\n `Multi (descriptions): ${arr.join(', ') || 'none'}`,\n DemoStep.Single,\n );\n }}\n />\n </AskModal>\n );\n }\n\n if (step === DemoStep.Single) {\n return (\n <AskModal prompt=\"Your project has both an app and a marketing site. Which one should the agent instrument first?\">\n <PickerMenu<string>\n options={[\n { label: 'The app', value: 'app', hint: 'src/app' },\n { label: 'The marketing site', value: 'marketing', hint: 'www/' },\n { label: 'Both, app first', value: 'both' },\n ]}\n onSelect={(value) => {\n advance(`Single: ${String(value)}`, DemoStep.Grouped);\n }}\n />\n </AskModal>\n );\n }\n\n if (step === DemoStep.Grouped) {\n return (\n <AskModal prompt=\"Grouped variant of the same ask — categories with headers, everything pre-selected:\">\n <GroupedPickerMenu\n groups={GROUPED}\n onSelect={(values) => {\n advance(`Grouped: ${values.length} kept`, DemoStep.Done);\n }}\n />\n </AskModal>\n );\n }\n\n return (\n <Box flexDirection=\"column\">\n <Text bold color={Colors.accent}>\n Ask Modal Demo — Results\n </Text>\n <Box height={1} />\n {results.map((r, i) => (\n <Text key={i} color={Colors.success}>\n {'✔'} {r}\n </Text>\n ))}\n <Box height={1} />\n <Text dimColor>Switch away from this tab and back to restart.</Text>\n </Box>\n );\n};\n","/**\n * ViewportGuardDemo — Playground demo for the ViewportTooSmall primitive.\n *\n * The real thing only appears when the terminal drops below the minimum, at\n * which point the playground itself is hidden behind it — so render it here at\n * a couple of fake sizes to see the copy and the wrapping.\n */\n\nimport { Box, Text } from 'ink';\nimport {\n ViewportTooSmall,\n MIN_VIEWPORT_COLUMNS,\n MIN_VIEWPORT_ROWS,\n} from '@ui/tui/primitives/index';\n\nconst SAMPLES: Array<[number, number]> = [\n [70, 8],\n [40, 7],\n];\n\nexport const ViewportGuardDemo = () => {\n return (\n <Box flexDirection=\"column\" gap={1} flexGrow={1}>\n <Text dimColor>\n {`Shown full-screen whenever the terminal is under ${MIN_VIEWPORT_COLUMNS}×${MIN_VIEWPORT_ROWS} — shrink this window to see it for real.`}\n </Text>\n {SAMPLES.map(([columns, rows]) => (\n <Box key={`${columns}x${rows}`} flexDirection=\"column\">\n <Text dimColor>{`at ${columns}×${rows}:`}</Text>\n <ViewportTooSmall columns={columns} rows={rows} />\n </Box>\n ))}\n </Box>\n );\n};\n","/**\n * PlaygroundApp — Root component for the primitives playground.\n *\n * Two screens mirroring the real wizard flow:\n * intro → (press enter) → run (tabbed demo view)\n */\n\nimport { ScreenContainer, TabContainer } from '@ui/tui/primitives/index';\nimport type { WizardStore } from '@ui/tui/store';\nimport { WelcomeDemo } from './demos/WelcomeDemo.js';\nimport { LayoutDemo } from './demos/LayoutDemo.js';\nimport { InputDemo } from './demos/InputDemo.js';\nimport { ProgressDemo } from './demos/ProgressDemo.js';\nimport { LogDemo } from './demos/LogDemo.js';\nimport { RunScreenDemo } from './demos/RunScreenDemo.js';\nimport { HealthCheckDemo } from './demos/HealthCheckDemo.js';\nimport { DoctorReportDemo } from './demos/DoctorReportDemo.js';\nimport { ModalDemo } from './demos/ModalDemo.js';\nimport { McpDemo } from './demos/McpDemo.js';\nimport { McpSuggestedPromptsDemo } from './demos/McpSuggestedPromptsDemo.js';\nimport { KeyboardHintsDemo } from './demos/KeyboardHintsDemo.js';\nimport { AuditChecksDemo } from './demos/AuditChecksDemo.js';\nimport { LearnDeckDemo } from './demos/LearnDeckDemo.js';\nimport { EndScreensDemo } from './demos/EndScreensDemo.js';\nimport { AiOptInDemo } from './demos/AiOptInDemo.js';\nimport { AskModalDemo } from './demos/AskModalDemo.js';\nimport { ViewportGuardDemo } from './demos/ViewportGuardDemo.js';\n\ninterface PlaygroundAppProps {\n store: WizardStore;\n}\n\nexport const PlaygroundApp = ({ store }: PlaygroundAppProps) => {\n const tabs = [\n { id: 'layout', label: 'Layout', component: <LayoutDemo /> },\n { id: 'input', label: 'Input', component: <InputDemo /> },\n { id: 'ask-modal', label: 'Ask modal', component: <AskModalDemo /> },\n { id: 'progress', label: 'Progress', component: <ProgressDemo /> },\n { id: 'logs', label: 'Logs', component: <LogDemo /> },\n {\n id: 'run',\n label: 'RunScreen',\n component: <RunScreenDemo store={store} />,\n },\n {\n id: 'health',\n label: 'HealthCheck',\n component: <HealthCheckDemo />,\n },\n {\n id: 'doctor',\n label: 'Doctor',\n component: <DoctorReportDemo />,\n },\n {\n id: 'modal',\n label: 'Modal',\n component: <ModalDemo />,\n },\n {\n id: 'mcp',\n label: 'MCP',\n component: <McpDemo store={store} />,\n },\n {\n id: 'mcp-tutorial',\n label: 'MCP tutorial',\n component: <McpSuggestedPromptsDemo store={store} />,\n },\n {\n id: 'hints',\n label: 'KeyHints',\n component: <KeyboardHintsDemo />,\n },\n {\n id: 'audit-checks',\n label: 'Audit checks',\n component: <AuditChecksDemo />,\n },\n {\n id: 'learn-deck',\n label: 'Learn deck',\n component: <LearnDeckDemo store={store} />,\n },\n {\n id: 'end-screens',\n label: 'End screens',\n component: <EndScreensDemo store={store} />,\n },\n {\n id: 'ai-opt-in-admin',\n label: 'AI opt-in (admin)',\n component: <AiOptInDemo variant=\"admin\" />,\n },\n {\n id: 'ai-opt-in-nonadmin',\n label: 'AI opt-in (non-admin)',\n component: <AiOptInDemo variant=\"non-admin\" />,\n },\n {\n id: 'viewport-guard',\n label: 'Viewport guard',\n component: <ViewportGuardDemo />,\n },\n ];\n\n return (\n <ScreenContainer\n store={store}\n screens={{\n intro: <WelcomeDemo store={store} />,\n run: (\n <TabContainer\n tabs={tabs}\n statusMessage=\"Primitives Playground — use arrow keys to switch tabs\"\n />\n ),\n }}\n />\n );\n};\n","/**\n * start-playground.ts — Launches the TUI primitives playground.\n */\n\nimport { render } from 'ink';\nimport { createElement } from 'react';\nimport { WizardStore } from '@ui/tui/store';\nimport { PlaygroundApp } from './PlaygroundApp.js';\nimport { HostResolution } from '@lib/host-resolution';\nimport { WizardReadiness } from '@lib/health-checks/readiness';\nimport { enterDarkTerminal, releaseTerminal } from '../terminal.js';\n\nexport function startPlayground(version: string): void {\n enterDarkTerminal();\n\n const store = new WizardStore();\n store.version = version;\n\n // Pre-fill session so the router skips health-check, auth, and setup,\n // landing on 'run' after the intro screen.\n // dismissOutage() guards against the onInit health-check async result\n // overwriting this with WizardReadiness.No before the user presses enter.\n store.setReadinessResult({\n decision: WizardReadiness.Yes,\n health: {} as never,\n reasons: [],\n });\n store.dismissOutage();\n store.setCredentials({\n accessToken: 'fake',\n projectApiKey: 'fake',\n host: HostResolution.fromApiHost('https://app.posthog.com'),\n projectId: 0,\n });\n\n const { unmount, waitUntilExit } = render(\n createElement(PlaygroundApp, { store }),\n );\n\n void waitUntilExit().then(() => {\n unmount();\n releaseTerminal();\n process.exit(0);\n });\n}\n","import { VERSION } from '@lib/version';\nimport { startPlayground } from '@ui/tui/playground/start-playground';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Hc_-9wrr.js","names":[],"sources":["../src/lib/task-stream/destinations/posthog.ts"],"sourcesContent":["/**\n * PostHog destination — pushes wizard run state to the PostHog backend\n * via `POST /api/projects/{project_id}/wizard/sessions/`.\n *\n * The endpoint is an upsert keyed by `(team, session_id)`: 201 means\n * the row was created, 200 means it was updated. Both are success.\n *\n * Failure handling is fail-silent: never throws to the caller, never\n * writes to stdout/stderr, never blocks the agent. Errors flow through\n * the optional `onError` callback for the wizard's debug log.\n *\n * Retry policy:\n * 5xx / network → exponential backoff base 500ms cap 8s, max 3 attempts\n * 429 → honour `Retry-After` (seconds), single retry\n * 401 / 403 → disable for the rest of the run, no further pushes\n * 400 → give up for this push, do not disable\n * other 4xx → give up for this push, do not disable\n */\n\nimport type {\n TaskStreamDestination,\n TaskStreamUpdate,\n StreamEvent,\n} from '@lib/task-stream/types';\nimport type { Credentials } from '@lib/wizard-session';\nimport { logToFile } from '@utils/debug';\n\nexport interface PostHogDestinationOptions {\n /**\n * Lazy credential resolver — called on every send. Returns null\n * before authentication has completed; in that case the send is a\n * no-op (no HTTP request).\n */\n getCredentials: () => Credentials | null;\n /** Receives every error for the wizard's internal logfile. */\n onError?: (err: Error) => void;\n /** Override for tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /** Override for tests. Defaults to setTimeout. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nconst MAX_ATTEMPTS = 3;\nconst BASE_BACKOFF_MS = 500;\nconst MAX_BACKOFF_MS = 8000;\nconst DEFAULT_RETRY_AFTER_MS = 1000;\n// setTimeout silently clamps anything above 2^31-1 ms to fire\n// immediately, so any Retry-After-derived sleep must be capped.\nconst MAX_RETRY_AFTER_MS = 60_000;\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfter(value: string | null): number {\n if (!value) return DEFAULT_RETRY_AFTER_MS;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return Math.min(Math.ceil(seconds * 1000), MAX_RETRY_AFTER_MS);\n }\n // HTTP-date form — best-effort.\n const date = Date.parse(value);\n if (Number.isFinite(date)) {\n return Math.min(Math.max(0, date - Date.now()), MAX_RETRY_AFTER_MS);\n }\n return DEFAULT_RETRY_AFTER_MS;\n}\n\n/**\n * Strip the internal-only `timestamp` field before sending. The\n * backend schema in the RFC does not define it.\n */\nfunction toWirePayload(\n payload: TaskStreamUpdate,\n): Omit<TaskStreamUpdate, 'timestamp'> {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { timestamp: _unused, ...rest } = payload;\n return rest;\n}\n\nexport class PostHogDestination implements TaskStreamDestination {\n readonly name = 'posthog';\n\n private readonly getCredentials: () => Credentials | null;\n private readonly onError: (err: Error) => void;\n private readonly fetchImpl: typeof fetch;\n private readonly sleep: (ms: number) => Promise<void>;\n\n private disabled = false;\n\n constructor(opts: PostHogDestinationOptions) {\n this.getCredentials = opts.getCredentials;\n this.onError = opts.onError ?? (() => undefined);\n this.fetchImpl = opts.fetchImpl ?? ((...args) => fetch(...args));\n this.sleep = opts.sleep ?? defaultSleep;\n }\n\n async send(_event: StreamEvent, payload: TaskStreamUpdate): Promise<void> {\n if (this.disabled) return;\n const creds = this.getCredentials();\n if (!creds) return;\n\n await this.postWithRetry(creds, toWirePayload(payload));\n }\n\n private buildRequest(\n creds: Credentials,\n body: object,\n ): { url: string; init: Parameters<typeof fetch>[1] } {\n const url = `${creds.host.apiHost.replace(/\\/$/, '')}/api/projects/${\n creds.projectId\n }/wizard/sessions/`;\n return {\n url,\n init: {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${creds.accessToken}`,\n },\n body: JSON.stringify(body),\n },\n };\n }\n\n private async postWithRetry(creds: Credentials, body: object): Promise<void> {\n const { url, init } = this.buildRequest(creds, body);\n let attempt = 0;\n let backoff = BASE_BACKOFF_MS;\n let retriedAfter429 = false;\n\n while (attempt < MAX_ATTEMPTS) {\n attempt += 1;\n let response: Response;\n try {\n response = await this.fetchImpl(url, init);\n } catch (err) {\n if (attempt >= MAX_ATTEMPTS) {\n this.onError(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n await this.sleep(backoff);\n backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);\n continue;\n }\n\n if (response.ok) {\n logToFile(`[task-stream] wizard/sessions push ok: ${response.status}`);\n return;\n }\n\n const status = response.status;\n\n if (status === 401 || status === 403) {\n this.disabled = true;\n this.onError(new Error(`wizard/sessions auth failed: ${status}`));\n return;\n }\n\n if (status === 429) {\n if (retriedAfter429) {\n this.onError(new Error('wizard/sessions rate limited'));\n return;\n }\n retriedAfter429 = true;\n const wait = parseRetryAfter(response.headers.get('Retry-After'));\n await this.sleep(wait);\n // Don't count this against the 5xx attempt budget.\n attempt -= 1;\n continue;\n }\n\n if (status >= 500) {\n if (attempt >= MAX_ATTEMPTS) {\n this.onError(new Error(`wizard/sessions server error: ${status}`));\n return;\n }\n await this.sleep(backoff);\n backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);\n continue;\n }\n\n if (status === 400) {\n let detail = '';\n try {\n detail = await response.text();\n } catch {\n // ignore\n }\n this.onError(new Error(`wizard/sessions bad request (400): ${detail}`));\n return;\n }\n\n this.onError(new Error(`wizard/sessions unexpected status: ${status}`));\n return;\n }\n }\n}\n"],"mappings":";;AA0CA,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,yBAAyB;AAG/B,MAAM,qBAAqB;AAE3B,SAAS,aAAa,IAA2B;AAC/C,QAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;AAG1D,SAAS,gBAAgB,OAA8B;AACrD,KAAI,CAAC,MAAO,QAAO;CACnB,MAAM,UAAU,OAAO,MAAM;AAC7B,KAAI,OAAO,SAAS,QAAQ,IAAI,WAAW,EACzC,QAAO,KAAK,IAAI,KAAK,KAAK,UAAU,IAAK,EAAE,mBAAmB;CAGhE,MAAM,OAAO,KAA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C,CAAC;AACjE;;AAEF,UAAM,KAAK,MAAM,QAAQ;AACzB,cAAU,KAAK,IAAI,UAAU,GAAG,eAAe;AAC/C;;AAGF,OAAI,SAAS,IAAI;AACf,cAAU,0CAA0C,SAAS,SAAS;AACtE;;GAGF,MAAM,SAAS,SAAS;AAExB,OAAI,WAAW,OAAO,WAAW,KAAK;AACpC,SAAK,WAAW;AAChB,SAAK,wBAAQ,IAAI,MAAM,gCAAgC,SAAS,CAAC;AACjE;;AAGF,OAAI,WAAW,KAAK;AAClB,QAAI,iBAAiB;AACnB,UAAK,wBAAQ,IAAI,MAAM,+BAA+B,CAAC;AACvD;;AAEF,sBAAkB;IAClB,MAAM,OAAO,gBAAgB,SAAS,QAAQ,IAAI,cAAc,CAAC;AACjE,UAAM,KAAK,MAAM,KAAK;AAEtB,eAAW;AACX;;AAGF,OAAI,UAAU,KAAK;AACjB,QAAI,WAAW,cAAc;AAC3B,UAAK,wBAAQ,IAAI,MAAM,iCAAiC,SAAS,CAAC;AAClE;;AAEF,UAAM,KAAK,MAAM,QAAQ;AACzB,cAAU,KAAK,IAAI,UAAU,GAAG,eAAe;AAC/C;;AAGF,OAAI,WAAW,KAAK;IAClB,IAAI,SAAS;AACb,QAAI;AACF,cAAS,MAAM,SAAS,MAAM;YACxB;AAGR,SAAK,wBAAQ,IAAI,MAAM,sCAAsC,SAAS,CAAC;AACvE;;AAGF,QAAK,wBAAQ,IAAI,MAAM,sCAAsC,SAAS,CAAC;AACvE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"provisioning-xfdjhFtA.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\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,M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AAGV,KAAI,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 +0,0 @@
1
- {"version":3,"file":"queue-tools-C8y_xZJi.js","names":["path"],"sources":["../src/utils/atomic-ledger.ts","../src/lib/agent/runner/switchboard/models.ts","../src/lib/agent/runner/sequence/orchestrator/queue.ts","../src/lib/agent/runner/sequence/orchestrator/queue-tools.ts"],"sourcesContent":["/**\n * Small shared primitives for on-disk ledgers: an atomic JSON writer and a\n * single-chain async mutex. Used by the audit tools and by the orchestrator\n * queue. Lifted here so both share one implementation.\n */\nimport * as fs from 'fs';\n\n/**\n * Atomically write JSON: write to a `.tmp` file then rename over the target. The\n * rename bumps the file's mtime in one step, which is what a file watcher polls.\n */\nexport function writeJsonAtomic(targetPath: string, data: unknown): void {\n const tmpPath = `${targetPath}.tmp`;\n fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8');\n fs.renameSync(tmpPath, targetPath);\n}\n\n/**\n * A single async mutex. Serializes read-modify-write cycles so concurrent callers\n * (parallel task agents, audit tool calls) never interleave a mutation.\n */\nexport function makeMutex() {\n let chain: Promise<unknown> = Promise.resolve();\n return async function run<T>(fn: () => Promise<T> | T): Promise<T> {\n const next = chain.then(() => fn());\n chain = next.catch(() => undefined);\n return next;\n };\n}\n","// Local capabilities inform transport parameters; gateway policy independently admits models and efforts.\nimport {\n SONNET_5_MODEL,\n HAIKU_MODEL,\n GPT5_6_LUNA_MODEL,\n GPT5_6_SOL_MODEL,\n GPT5_6_TERRA_MODEL,\n HAIKU_TRIAGE_MODEL,\n Harness,\n} from '@lib/constants';\n\n/** Reasoning effort, mapped by each harness to its provider transport. */\nconst THINKING_LEVELS = [\n 'off',\n 'minimal',\n 'low',\n 'medium',\n 'high',\n 'xhigh',\n] as const;\nexport type ThinkingLevel = (typeof THINKING_LEVELS)[number];\n\n/** Whether a value (e.g. remote prompt frontmatter) names a valid effort. */\nexport function isThinkingLevel(value: unknown): value is ThinkingLevel {\n return (THINKING_LEVELS as readonly unknown[]).includes(value);\n}\n\n/**\n * An effort *override* is always a positive level — `'off'` is a model trait\n * (`reasoning: false`), not something a flag may force onto a reasoning model.\n */\nexport type EffortLevel = Exclude<ThinkingLevel, 'off'>;\n\nexport interface ModelCapabilities {\n /** Model supports reasoning; safe to request reasoning effort. */\n reasoning: boolean;\n /** Effort to request when reasoning. Omit for the harness/provider default. */\n thinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Explicit per-model traits. Anything absent falls back to `defaultCaps`.\n *\n * A reasoning model without a `thinkingLevel` leaves the effort to the harness,\n * and the mint pins effort per model (posthog `WIZARD_MODEL_ALLOWLIST`), so an\n * unpinned reasoning model is refused with no tool calls. Every level below is\n * one the mint allows for that model.\n */\nexport const MODEL_CAPABILITIES: Record<string, ModelCapabilities> = {\n // The mint takes sonnet 5 at `none` or `high`; high is the only level it\n // serves once reasoning is on.\n [SONNET_5_MODEL]: { reasoning: true, thinkingLevel: 'high' },\n // The mint takes haiku with no effort parameter at all, which is `off`.\n [HAIKU_MODEL]: { reasoning: true, thinkingLevel: 'off' },\n // The openai 5.6 line; all reasoning models, so they must opt in past the\n // openai-completions default (reasoning off). Luna stays low for cheap,\n // short-context mechanical work; terra runs medium as the sonnet-tier parallel\n // — enough reasoning depth for the judgment tasks without high's latency blowup.\n [GPT5_6_LUNA_MODEL]: { reasoning: true, thinkingLevel: 'low' },\n [GPT5_6_TERRA_MODEL]: { reasoning: true, thinkingLevel: 'medium' },\n [GPT5_6_SOL_MODEL]: { reasoning: true, thinkingLevel: 'medium' },\n};\n\n/**\n * The mint's per-model effort pin, mirrored from posthog\n * `WIZARD_MODEL_ALLOWLIST`. `'off'` is the CLI's spelling of the mint's\n * `\"none\"` — a call carrying no effort parameter.\n */\nexport const MINT_ALLOWED_EFFORTS: Record<string, readonly ThinkingLevel[]> = {\n [SONNET_5_MODEL]: ['off', 'high'],\n [HAIKU_MODEL]: ['off'],\n [GPT5_6_LUNA_MODEL]: ['low'],\n [GPT5_6_SOL_MODEL]: ['medium'],\n [GPT5_6_TERRA_MODEL]: ['low', 'medium', 'high'],\n};\n\n// Local model choices; gateway admission also requires allowed models, efforts, and prompt compatibility.\nexport const VALID_MODELS: ReadonlySet<string> = new Set(\n Object.keys(MODEL_CAPABILITIES),\n);\n\n/** Whether the value is an allow-listed model. */\nexport function isValidModel(model: unknown): model is string {\n return typeof model === 'string' && VALID_MODELS.has(model);\n}\n\n/** First allow-listed candidate, else throw so a bad id fails loud. */\nexport function requireKnownModel(\n ...candidates: (string | undefined)[]\n): string {\n for (const c of candidates) if (isValidModel(c)) return c;\n throw new Error(\n `No valid model to dispatch on (tried ${JSON.stringify(candidates)}). ` +\n `Allowed: ${[...VALID_MODELS].join(', ')}.`,\n );\n}\n\n// Unknown Anthropic models default to reasoning; OpenAI models must opt in through the local table.\nfunction defaultCaps(modelId: string): ModelCapabilities {\n return { reasoning: !modelId.startsWith('openai/') };\n}\n\n// Triage requests must satisfy gateway safety policy and preserve Warlock’s classifier format.\nexport const TRIAGE_MODELS: Record<Harness, string> = {\n [Harness.anthropic]: HAIKU_TRIAGE_MODEL,\n [Harness.pi]: GPT5_6_LUNA_MODEL,\n};\n\nexport function triageModelFor(harness: Harness): string {\n return TRIAGE_MODELS[harness];\n}\n\n/**\n * Capabilities for a gateway model id, table override then transport default.\n * `effortOverride` is a switchboard-resolved effort (e.g. from a pi effort\n * flag); it applies only when the model reasons at all — a non-reasoning model\n * rejects reasoning effort, so the override is dropped.\n */\nexport function modelCapabilities(\n modelId: string,\n effortOverride?: EffortLevel,\n): ModelCapabilities {\n const caps = MODEL_CAPABILITIES[modelId] ?? defaultCaps(modelId);\n if (caps.reasoning && effortOverride) {\n return { ...caps, thinkingLevel: effortOverride };\n }\n return caps;\n}\n","/**\n * The orchestrator task queue.\n *\n * In memory, synchronous, single-owner: one Node process drives the run, so\n * there is no locking. The queue imposes no execution policy — `nextRunnable`\n * returns every pending task whose dependencies are satisfied, and how many of\n * those run at once is decided by the task graph, not the queue.\n *\n * Every transition rewrites `<installDir>/.posthog-wizard-cache/queue.json`, a\n * small file holding the whole queue, handoffs included. It is the run's log\n * and the report's source. The whole cache folder is run-scoped and wiped when\n * the run ends.\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { randomUUID } from 'crypto';\nimport { writeJsonAtomic } from '@utils/atomic-ledger';\nimport { analytics } from '@utils/analytics';\n\nexport const TaskStatus = {\n Pending: 'pending',\n Running: 'running',\n Done: 'done',\n Skipped: 'not needed',\n Failed: 'failed',\n} as const;\n\nexport type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus];\n\n/**\n * Why a task ended as skipped.\n *\n * A skip has several causes that look identical from outside: an agent finding\n * the step does not apply, a user declining it, and an offer nobody answered.\n * They mean opposite things — the first is a no-op, the last two are the user\n * telling us something — and telling them apart needs the reason recorded at\n * the moment of the skip, not inferred later from timings.\n *\n * Recorded on the task like `error` is on a failed one, so it reaches the\n * skipped-task event and the run's queue.json alike.\n */\nexport const SkipReason = {\n /** The user answered the step's notice with Skip. */\n UserDeclined: 'user-declined',\n /** The notice went unanswered until it timed out. */\n NoticeTimeout: 'notice-timeout',\n /** The notice could not be shown at all, so consent failed closed. */\n NoticeError: 'notice-error',\n /** The task agent reported `not needed`. See {@link NotNeededReason} for why. */\n AgentNotNeeded: 'agent-not-needed',\n} as const;\n\nexport type SkipReason = (typeof SkipReason)[keyof typeof SkipReason];\n\n/**\n * Why the agent itself reported `not needed`.\n *\n * {@link SkipReason.AgentNotNeeded} records who decided the skip, not what they\n * decided. `complete_task` offers `not needed` both for \"the step does not\n * apply\" and for \"you cannot do it\", so an agent that never got a credential\n * out of the user lands in the same bucket as one that found nothing to\n * connect — and the bucket is named after the first meaning. For the one step\n * that stops to ask for credentials, that is the difference that matters: a\n * step nobody supplied a password for is not a step that did not apply.\n *\n * A sub-dimension of the skip reason, never a replacement for it, so every\n * existing reason value keeps counting exactly what it counted before.\n */\nexport const NotNeededReason = {\n /** Nothing to do: the step genuinely does not apply to this project. */\n NotApplicable: 'not-applicable',\n /** The user was asked and declined, or left the prompts unanswered. */\n UserDeclined: 'user-declined',\n /** Something outside the run stopped it — a credential, plan, or endpoint. */\n Blocked: 'blocked',\n} as const;\n\nexport type NotNeededReason =\n (typeof NotNeededReason)[keyof typeof NotNeededReason];\n\n/**\n * Whether a value names a reason. The pi harness hands tool arguments over\n * unvalidated, so an invented value would otherwise reach the analytics\n * dimension as free text — the one thing this step must never emit.\n */\nexport function isNotNeededReason(value: unknown): value is NotNeededReason {\n return (Object.values(NotNeededReason) as unknown[]).includes(value);\n}\n\nexport interface QueuedTask {\n id: string;\n type: string;\n /** Human-readable label for the TUI, set by the enqueuing agent. */\n label?: string;\n status: TaskStatus;\n /**\n * Ids of tasks that must finish before this one runs. Ids are generated at\n * enqueue, so a task can only depend on tasks created before it — the graph is\n * a DAG by construction, cycles cannot form. Unknown ids are rejected by the\n * enqueue_task guard.\n *\n * One sanctioned exception: {@link QueueStore.addDependencies} adds edges to a\n * still-pending task, for a runner-seeded task that was queued before the\n * planner ran and so could not name its dependencies then. It is additive,\n * pending-only, and cycle-checked per edge, so the DAG property above still\n * holds. Nothing else mutates this field.\n */\n dependsOn: string[];\n inputs: Record<string, unknown>;\n model?: string;\n attempts: number;\n maxAttempts: number;\n /** The structured handoff the task reported on completion. */\n handoff?: TaskHandoff;\n /** 'orchestrator' for seeded tasks, or the id of the task that enqueued this one. */\n enqueuedBy: string;\n /** Terminal failure unblocks dependents and never fails the run. */\n optional?: boolean;\n createdAt: string;\n startedAt?: string;\n finishedAt?: string;\n error?: { type: string; message: string };\n /** Set when `status` is `not needed`: why. The failed-task `error` of a skip. */\n skipReason?: SkipReason;\n /** Set only for an agent-reported skip, and only when the agent declared it. */\n notNeededReason?: NotNeededReason;\n}\n\nexport interface QueueFile {\n version: 1;\n runId: string;\n tasks: QueuedTask[];\n}\n\n/** Session frameworkContext key holding the drained queue's final outcomes —\n * written by the runner before the cache wipe, read by the e2e harness. */\nexport const TASK_OUTCOMES_KEY = 'orchestrator-task-outcomes';\n\nexport interface TaskOutcome {\n type: string;\n status: TaskStatus;\n optional: boolean;\n}\n\n/** The structured handoff a task leaves for the next agent. */\nexport interface TaskHandoff {\n goals: string;\n did: string;\n forNextAgent: string;\n filesTouched?: string[];\n /** How the agent knows it worked — what it ran or observed. */\n evidence?: string;\n /** What the agent assumed about the app and could not verify. */\n assumptions?: string;\n /** A one-line summary of any unresolved conflict, surfaced in the outro. */\n conflict?: string;\n /** A finished section for the run's report, written by the task that owns the subject. */\n reportSection?: string;\n}\n\nexport interface EnqueueInput {\n type: string;\n label?: string;\n inputs?: Record<string, unknown>;\n dependsOn?: string[];\n model?: string;\n maxAttempts?: number;\n enqueuedBy?: string;\n optional?: boolean;\n}\n\nexport const QUEUE_DIR_NAME = '.posthog-wizard-cache';\nconst DEFAULT_MAX_ATTEMPTS = 2;\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\n/** Dropped in the cache folder so an orphaned copy explains itself. */\nconst DELETE_ME_FILE = '.DELETE-ME.md';\nconst DELETE_ME_BODY = `# Safe to delete\n\nThis folder contains run artifacts from the PostHog Wizard. This should have\nbeen deleted if the Wizard has finished running. If this wasn't deleted for\nsome reason, you can safely delete the entire \\`${QUEUE_DIR_NAME}/\\` folder.\n`;\n\n/** Every queue transition, in the order it is reflected. */\nexport type TransitionEvent =\n | 'enqueue'\n | 'start'\n | 'complete'\n | 'skip'\n | 'fail'\n | 'requeue';\n\nexport interface QueueStoreOptions {\n /**\n * Called on every transition with the task's post-transition state. The\n * runner uses it for telemetry; the store itself stays analytics-free.\n * Listener errors are reported but cannot break a transition.\n */\n onTransition?: (event: TransitionEvent, task: QueuedTask) => void;\n}\n\nexport class QueueStore {\n private tasks: QueuedTask[] = [];\n private readonly onTransition?: (\n event: TransitionEvent,\n task: QueuedTask,\n ) => void;\n\n readonly runId: string;\n readonly queuePath: string;\n\n constructor(installDir: string, runId: string, opts?: QueueStoreOptions) {\n this.onTransition = opts?.onTransition;\n this.runId = runId;\n const dir = path.join(installDir, QUEUE_DIR_NAME);\n this.queuePath = path.join(dir, 'queue.json');\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(path.join(dir, DELETE_ME_FILE), DELETE_ME_BODY);\n }\n\n // ── Reads ───────────────────────────────────────────────────────────\n\n list(): readonly QueuedTask[] {\n return this.tasks;\n }\n\n get(id: string): QueuedTask | undefined {\n return this.tasks.find((t) => t.id === id);\n }\n\n /**\n * Every pending task whose dependencies are all satisfied (`done` or\n * `skipped`). A skipped dependency does not block downstream work.\n */\n nextRunnable(): QueuedTask[] {\n // A TERMINALLY failed optional dep satisfies like skipped; retryable failure still blocks.\n const doneIds = new Set(\n this.tasks\n .filter(\n (t) =>\n t.status === TaskStatus.Done ||\n t.status === TaskStatus.Skipped ||\n (t.status === TaskStatus.Failed &&\n t.optional === true &&\n t.attempts >= t.maxAttempts),\n )\n .map((t) => t.id),\n );\n return this.tasks.filter(\n (t) =>\n t.status === TaskStatus.Pending &&\n t.dependsOn.every((d) => doneIds.has(d)),\n );\n }\n\n /**\n * True when no task is running and none can be started. Either everything\n * is terminal, or the only pending tasks are blocked by a failed dependency.\n */\n isDrained(): boolean {\n if (this.tasks.some((t) => t.status === TaskStatus.Running)) return false;\n return this.nextRunnable().length === 0;\n }\n\n summary(): Record<TaskStatus, number> & { total: number } {\n const counts: Record<TaskStatus, number> = {\n [TaskStatus.Pending]: 0,\n [TaskStatus.Running]: 0,\n [TaskStatus.Done]: 0,\n [TaskStatus.Skipped]: 0,\n [TaskStatus.Failed]: 0,\n };\n for (const t of this.tasks) counts[t.status] += 1;\n return { ...counts, total: this.tasks.length };\n }\n\n readHandoff(id: string): TaskHandoff | null {\n return this.get(id)?.handoff ?? null;\n }\n\n /** Handoffs of completed tasks of a given type, oldest first. */\n readHandoffsByType(type: string): TaskHandoff[] {\n return this.tasks\n .filter((t) => t.type === type && t.handoff)\n .map((t) => t.handoff as TaskHandoff);\n }\n\n // ── Transitions (each one reflected to queue.json) ──────────────────\n\n enqueue(input: EnqueueInput): QueuedTask {\n const task: QueuedTask = {\n id: randomUUID(),\n type: input.type,\n label: input.label,\n status: TaskStatus.Pending,\n dependsOn: input.dependsOn ?? [],\n inputs: input.inputs ?? {},\n model: input.model,\n attempts: 0,\n maxAttempts: input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n enqueuedBy: input.enqueuedBy ?? 'orchestrator',\n optional: input.optional,\n createdAt: nowIso(),\n };\n this.tasks.push(task);\n this.reflect();\n this.notify('enqueue', task);\n return task;\n }\n\n /**\n * Add dependency edges to a pending task — the one sanctioned exception to\n * `dependsOn` being immutable (see the field's doc).\n *\n * A runner-seeded task is enqueued before the planner runs, so the tasks it\n * should wait for do not exist yet and it cannot name them. This closes that\n * gap once, between planning and the drain.\n *\n * Three rules keep the graph a DAG: additive only (never removes an edge),\n * pending only (a task that already started keeps the graph it ran under), and\n * every edge cycle-checked — a dep that already reaches this task through its\n * own chain is refused. Refusals come back in the result rather than throwing:\n * one bad edge is a bug worth reporting, not a reason to end a run that is\n * otherwise fine.\n */\n addDependencies(\n id: string,\n depIds: readonly string[],\n ): { added: string[]; refused: string[] } {\n const task = this.require(id);\n if (task.status !== TaskStatus.Pending) {\n return { added: [], refused: [...depIds] };\n }\n\n const added: string[] = [];\n const refused: string[] = [];\n for (const depId of depIds) {\n // Already an edge, or a self-loop: nothing to do and nothing wrong.\n if (depId === id || task.dependsOn.includes(depId)) continue;\n // Checked against the graph as it stands, so two edges added in one call\n // cannot together form a cycle the first check missed.\n if (!this.get(depId) || this.reaches(depId, id)) {\n refused.push(depId);\n continue;\n }\n task.dependsOn.push(depId);\n added.push(depId);\n }\n if (added.length > 0) this.reflect();\n return { added, refused };\n }\n\n start(id: string): QueuedTask {\n const t = this.require(id);\n t.status = TaskStatus.Running;\n t.startedAt = nowIso();\n t.attempts += 1;\n this.reflect();\n this.notify('start', t);\n return t;\n }\n\n complete(id: string, handoff?: TaskHandoff): QueuedTask {\n return this.finish(id, TaskStatus.Done, handoff);\n }\n\n /**\n * Terminal: the task was not done, and that is not a failure.\n *\n * The reason is required, and sits before the optional handoff for that\n * reason. A skip carrying no reason is what let a five-minute auto-decline\n * hide inside the same event as an agent deciding a step did not apply.\n *\n * `notNeededReason` splits the agent-reported reason one level further; only\n * an agent supplies it, and only when it declared one.\n */\n skip(\n id: string,\n reason: SkipReason,\n handoff?: TaskHandoff,\n notNeededReason?: NotNeededReason,\n ): QueuedTask {\n const t = this.require(id);\n t.skipReason = reason;\n if (notNeededReason) t.notNeededReason = notNeededReason;\n return this.finish(id, TaskStatus.Skipped, handoff);\n }\n\n fail(\n id: string,\n error: { type: string; message: string },\n handoff?: TaskHandoff,\n ): QueuedTask {\n const t = this.require(id);\n t.error = error;\n return this.finish(id, TaskStatus.Failed, handoff);\n }\n\n /** Put a failed/running task back to pending for a retry within the run. */\n requeue(id: string): QueuedTask {\n const t = this.require(id);\n t.status = TaskStatus.Pending;\n t.startedAt = undefined;\n t.finishedAt = undefined;\n this.reflect();\n this.notify('requeue', t);\n return t;\n }\n\n // ── Internals ───────────────────────────────────────────────────────\n\n private finish(\n id: string,\n status: 'done' | 'not needed' | 'failed',\n handoff?: TaskHandoff,\n ): QueuedTask {\n const t = this.require(id);\n if (handoff) t.handoff = handoff;\n t.status = status;\n t.finishedAt = nowIso();\n this.reflect();\n this.notify(\n status === TaskStatus.Done\n ? 'complete'\n : status === TaskStatus.Skipped\n ? 'skip'\n : 'fail',\n t,\n );\n return t;\n }\n\n private reflect(): void {\n const file: QueueFile = {\n version: 1,\n runId: this.runId,\n tasks: this.tasks,\n };\n writeJsonAtomic(this.queuePath, file);\n }\n\n private notify(event: TransitionEvent, task: QueuedTask): void {\n try {\n this.onTransition?.(event, task);\n } catch (error) {\n // A listener must never break a transition, but its failure is a bug.\n analytics.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'orchestrator_queue_listener', event },\n );\n }\n }\n\n /** Whether `fromId` reaches `targetId` by following dependsOn edges. */\n private reaches(fromId: string, targetId: string): boolean {\n const seen = new Set<string>();\n const stack = [fromId];\n while (stack.length > 0) {\n const current = stack.pop() as string;\n if (current === targetId) return true;\n if (seen.has(current)) continue;\n seen.add(current);\n stack.push(...(this.get(current)?.dependsOn ?? []));\n }\n return false;\n }\n\n private require(id: string): QueuedTask {\n const t = this.get(id);\n if (!t) throw new Error(`No task ${id} in the queue`);\n return t;\n }\n}\n","/**\n * Orchestrator MCP tools, registered into the existing `wizard-tools` server when\n * a queue is present. They let the orchestrator agent and task agents grow the\n * queue, report completion with a structured handoff, and read prior handoffs.\n *\n * The guard logic and the apply functions are plain, exported, and unit-tested.\n * `buildOrchestratorTools` wraps them in the SDK `tool()` shape.\n */\nimport { z } from 'zod';\nimport { analytics } from '@utils/analytics';\nimport {\n isValidModel,\n VALID_MODELS,\n} from '@lib/agent/runner/switchboard/models';\nimport {\n isNotNeededReason,\n NotNeededReason,\n SkipReason,\n TaskStatus,\n type QueueStore,\n type QueuedTask,\n type TaskHandoff,\n} from './queue';\n\n/**\n * The `complete_task` `notNeededReason` description, shared by both harnesses'\n * schemas so the ask cannot drift between them.\n *\n * Named per value rather than left to prose: the distinction the flow needs is\n * \"the user did not hand over a credential\" against \"there was nothing here to\n * connect\", and an agent asked for that in free text writes it into the handoff\n * — where {@link applyComplete} deliberately cannot forward it, because handoff\n * prose on this step reaches live database passwords.\n */\nexport 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.`;\n\n/**\n * The `enqueue_task` `model` description, shared by both harnesses' schemas.\n *\n * The field was declared as a bare optional string while\n * {@link checkEnqueueGuards} rejects anything outside {@link VALID_MODELS}, so\n * the allow-list existed only in the rejection message — an agent had to guess\n * a gateway model id, trip the `invalid-model` guard, and spend a turn reading\n * the list back before it could enqueue. Naming the list where the agent picks\n * the value costs nothing and makes the guess unnecessary.\n */\nexport 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: ${[\n ...VALID_MODELS,\n].join(', ')}.`;\n\n/**\n * The `complete_task` tool description, shared by both harnesses' schemas so\n * the outcome contract cannot drift — the same discipline {@link HANDOFF_FIELDS}\n * applies to the fields inside the handoff.\n *\n * The closing sentence names the nesting because agents kept learning it from a\n * rejection instead: a first call with `goals`/`did`/`forNextAgent` at the top\n * level fails schema validation, and reading that error back was the only place\n * the shape was stated. Naming it where the agent fills the call in costs\n * nothing, the same reasoning as {@link ENQUEUE_MODEL_DESCRIPTION}.\n */\nexport const COMPLETE_TASK_DESCRIPTION =\n 'Report the outcome of your task. Always call this exactly once when you finish, with a structured handoff for the next agent. ' +\n \"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'. \" +\n 'The handoff is one nested object: put `goals`, `did` and `forNextAgent` — all three required — inside `handoff`, along with any optional fields, never at the top level.';\n\n/** The per-task remark ask, shared by both harnesses' complete_task schemas. */\nexport const REMARK_ASK =\n '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.';\n\nexport interface OrchestratorToolsContext {\n store: QueueStore;\n /** Task types the registry knows about. enqueue_task rejects anything else. */\n validTypes: readonly string[];\n /**\n * Types marked `sink: true` — the ones that run last and must therefore\n * depend, transitively, on every other task in the queue. Enqueuing one with\n * an incomplete closure is rejected, so a task the runner seeded before the\n * planner ran can never be left un-awaited.\n */\n sinkTypes?: readonly string[];\n /**\n * Types the wizard queues itself, before the planner runs. They are deferred\n * to the end of the drain and may stop to ask the user for input, so the edge\n * to them is one-way: the sink depends on them, nothing else may. See\n * {@link seededDepViolations}.\n */\n runnerSeededTypes?: readonly string[];\n /**\n * Types marked `optional: true` in their frontmatter. Enqueue stamps the flag\n * from this list — the task's definition decides, never the enqueuing agent —\n * so terminal failure of such a task unblocks dependents and never fails the\n * run.\n */\n optionalTypes?: readonly string[];\n /**\n * The id of the task this tool server is bound to. Each task agent gets its\n * own wizard-tools server, so attribution holds when independent tasks run\n * in parallel. Absent for the seed, which is not a task.\n */\n currentTaskId?: string;\n}\n\nexport interface EnqueueArgs {\n type: string;\n label?: string;\n inputs?: Record<string, unknown>;\n dependsOn?: string[];\n model?: string;\n reason: string;\n}\n\nexport type GuardResult =\n | { ok: true }\n | { ok: false; guard: string; message: string };\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>).sort(\n ([a], [b]) => a.localeCompare(b),\n );\n return `{${entries\n .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)\n .join(',')}}`;\n}\n\nfunction dedupKey(type: string, inputs: Record<string, unknown>): string {\n return `${type}::${stableStringify(inputs)}`;\n}\n\n/**\n * A backstop on total queue size. Tasks can enqueue tasks, so a misbehaving\n * type could grow the queue without bound. Keeping the graph small is the job\n * of good agent and skill design, not this number — it only stops a runaway.\n * The real flow is ~9 tasks, so this sits well clear of it.\n */\nconst MAX_QUEUE_TASKS = 30;\n\n/** Every task id reachable from `roots` through dependsOn edges, roots included. */\nexport function dependencyClosure(\n store: QueueStore,\n roots: readonly string[],\n): Set<string> {\n const seen = new Set<string>();\n const visit = (id: string): void => {\n if (seen.has(id)) return;\n seen.add(id);\n for (const dep of store.get(id)?.dependsOn ?? []) visit(dep);\n };\n for (const id of roots) visit(id);\n return seen;\n}\n\n/**\n * Tasks a sink would fail to wait for. A sink runs last by definition, so any\n * queued task outside its dependency closure is work whose handoff the sink\n * would miss — the exact failure mode of a task seeded before the planner ran.\n * Empty for a non-sink type, and for a sink that covers everything.\n */\nexport function uncoveredBySink(\n ctx: OrchestratorToolsContext,\n args: Pick<EnqueueArgs, 'type' | 'dependsOn'>,\n): QueuedTask[] {\n if (!ctx.sinkTypes?.includes(args.type)) return [];\n const covered = dependencyClosure(ctx.store, args.dependsOn ?? []);\n return ctx.store.list().filter((t) => !covered.has(t.id));\n}\n\n/**\n * Runner-seeded tasks a non-sink task would end up waiting for.\n *\n * The edge to a runner-seeded task is one-way. Such a task is deferred to the\n * end of the drain and may stop to ask the user for input, so anything that\n * waits on it inherits that wait — a coding step gated on someone typing a\n * database password. The sink is the sole exception: it runs last by\n * definition and must depend on every task, this one included.\n *\n * The whole closure is checked, not just direct dependencies, so the rule\n * cannot be reached through an intermediate hop.\n *\n * Empty for a sink, and for any task that does not reach a seeded task.\n */\nexport function seededDepViolations(\n ctx: OrchestratorToolsContext,\n args: Pick<EnqueueArgs, 'type' | 'dependsOn'>,\n): QueuedTask[] {\n const seeded = ctx.runnerSeededTypes ?? [];\n if (seeded.length === 0) return [];\n if (ctx.sinkTypes?.includes(args.type)) return [];\n const reached = dependencyClosure(ctx.store, args.dependsOn ?? []);\n return ctx.store\n .list()\n .filter((t) => reached.has(t.id) && seeded.includes(t.type));\n}\n\n/**\n * Validate an enqueue. Structural checks only — a real type, real dependencies,\n * a sink that waits for everything, no non-sink task waiting on a runner-seeded\n * one, not a literal duplicate, and not past the runaway backstop. How much\n * runs, and in what shape, is the task graph's business, not a knob's.\n */\nexport function checkEnqueueGuards(\n ctx: OrchestratorToolsContext,\n args: EnqueueArgs,\n): GuardResult {\n const tasks = ctx.store.list();\n\n if (tasks.length >= MAX_QUEUE_TASKS) {\n return {\n ok: false,\n guard: 'queue-full',\n message: `The queue already holds ${tasks.length} tasks (cap ${MAX_QUEUE_TASKS}). Refine the existing tasks rather than adding more.`,\n };\n }\n\n if (!ctx.validTypes.includes(args.type)) {\n return {\n ok: false,\n guard: 'unknown-type',\n message: `Unknown task type \"${\n args.type\n }\". Valid types: ${ctx.validTypes.join(', ')}.`,\n };\n }\n\n // Reject an agent pinning a task to a non-allow-listed model.\n if (args.model !== undefined && !isValidModel(args.model)) {\n return {\n ok: false,\n guard: 'invalid-model',\n message: `Model \"${\n args.model\n }\" is not allowed. Omit model to use the task default, or pick one of: ${[\n ...VALID_MODELS,\n ].join(', ')}.`,\n };\n }\n\n for (const dep of args.dependsOn ?? []) {\n if (!ctx.store.get(dep)) {\n return {\n ok: false,\n guard: 'unknown-dep',\n message: `Dependency \"${dep}\" is not a known task id.`,\n };\n }\n }\n\n const seededDeps = seededDepViolations(ctx, args);\n if (seededDeps.length > 0) {\n return {\n ok: false,\n guard: 'seeded-dep',\n message: `A \"${args.type}\" task must not wait for ${seededDeps\n .map((t) => `${t.type} (${t.id})`)\n .join(\n ', ',\n )} — directly or through its dependencies. The wizard placed those, runs them at the end, and they stop to ask the user for input, so anything waiting on one waits on a person. Remove them from dependsOn and enqueue it again; only the final reporting task may depend on them.`,\n };\n }\n\n const uncovered = uncoveredBySink(ctx, args);\n if (uncovered.length > 0) {\n const seededUncovered = uncovered.filter((t) =>\n (ctx.runnerSeededTypes ?? []).includes(t.type),\n );\n // \"Or to a task already in dependsOn\" is the right advice for an ordinary\n // task and exactly wrong for a runner-seeded one — routing it through an\n // intermediate satisfies the closure while breaking the one-way rule above.\n // So a seeded task is named with the only placement that is legal for it.\n const how =\n seededUncovered.length === uncovered.length\n ? \"Add them to this task's own dependsOn — for a task the wizard placed, that is the only legal spot — and enqueue it again.\"\n : 'Add them to dependsOn, or to a task already in dependsOn, and enqueue it again.';\n return {\n ok: false,\n guard: 'sink-closure',\n message: `A \"${\n args.type\n }\" task runs last, so it must depend on every other task — directly or through its dependencies. These are not covered: ${uncovered\n .map((t) => `${t.type} (${t.id})`)\n .join(', ')}. ${how}`,\n };\n }\n\n const key = dedupKey(args.type, args.inputs ?? {});\n if (\n tasks.some(\n (t) =>\n t.status !== TaskStatus.Failed && dedupKey(t.type, t.inputs) === key,\n )\n ) {\n return {\n ok: false,\n guard: 'dedup',\n message: `A \"${args.type}\" task with these inputs already exists.`,\n };\n }\n\n return { ok: true };\n}\n\nexport type EnqueueResult =\n | { ok: true; task: QueuedTask }\n | { ok: false; guard: string; message: string };\n\nexport function applyEnqueue(\n ctx: OrchestratorToolsContext,\n args: EnqueueArgs,\n): EnqueueResult {\n const guard = checkEnqueueGuards(ctx, args);\n if (!guard.ok) return guard;\n\n const task = ctx.store.enqueue({\n type: args.type,\n label: args.label,\n inputs: args.inputs ?? {},\n dependsOn: args.dependsOn ?? [],\n model: args.model,\n optional: (ctx.optionalTypes ?? []).includes(args.type) || undefined,\n enqueuedBy: ctx.currentTaskId ?? 'orchestrator',\n });\n return { ok: true, task };\n}\n\nexport type CompleteResult = { ok: true } | { ok: false; message: string };\n\nexport type CompleteArgs = {\n status: 'done' | 'failed' | 'not needed';\n handoff: TaskHandoff;\n remark?: string;\n notNeededReason?: NotNeededReason;\n};\n\nexport function applyComplete(\n ctx: OrchestratorToolsContext,\n args: CompleteArgs,\n): CompleteResult {\n const id = ctx.currentTaskId;\n if (!id) {\n return {\n ok: false,\n message: 'complete_task can only be called by a running task agent.',\n };\n }\n if (args.remark) {\n analytics.wizardCapture('orchestrator remark', {\n task_type: ctx.store.get(id)?.type,\n remark: args.remark,\n });\n }\n if (args.status === TaskStatus.Failed) {\n ctx.store.fail(\n id,\n { type: 'self-reported', message: args.handoff.forNextAgent },\n args.handoff,\n );\n } else if (args.status === TaskStatus.Skipped) {\n // The agent's own words stay in the handoff and out of telemetry. This flow\n // reaches live database and API credentials, and the repo has no redaction\n // pass for handoff prose, so the event carries the task type, the reason,\n // and the closed set of `notNeededReason` values — enough to separate an\n // agent no-op from a user decline from a blocked step, with no free text.\n ctx.store.skip(\n id,\n SkipReason.AgentNotNeeded,\n args.handoff,\n isNotNeededReason(args.notNeededReason)\n ? args.notNeededReason\n : undefined,\n );\n } else {\n ctx.store.complete(id, args.handoff);\n }\n return { ok: true };\n}\n\nexport function applyReadHandoffs(\n ctx: OrchestratorToolsContext,\n args: { type?: string; taskId?: string },\n): TaskHandoff[] {\n if (args.taskId) {\n const h = ctx.store.readHandoff(args.taskId);\n return h ? [h] : [];\n }\n if (args.type) {\n return ctx.store.readHandoffsByType(args.type);\n }\n // No filter: every handoff of a dependency of the current task.\n const currentId = ctx.currentTaskId;\n const current = currentId ? ctx.store.get(currentId) : undefined;\n if (!current) return [];\n return current.dependsOn\n .map((depId) => ctx.store.readHandoff(depId))\n .filter((h): h is TaskHandoff => h !== null);\n}\n\n// Caps each LLM-authored free-text field; queue.json rewrites whole per transition.\nconst HANDOFF_TEXT_MAX = 8_000;\n\n/**\n * The one description of every handoff field, shared by both harnesses'\n * `complete_task` schemas — the zod shape below and the typebox mirror in\n * `harness/pi/orchestrator-tools.ts`. A field an agent cannot see is a field it\n * cannot fill, so the two drifting silently drops whatever the missing field\n * carried; `__tests__/handoff-schema-parity.test.ts` holds them level.\n */\nexport const HANDOFF_FIELDS = {\n goals: 'What this task was asked to achieve.',\n did: 'What you actually did — for each file you edited: the change, the intention behind it, and the analytics it should feed (the insight, funnel, or dashboard tile it becomes part of).',\n forNextAgent: 'What the next agent should know.',\n filesTouched: 'Paths of every file you edited.',\n evidence:\n 'How you know it worked — what you ran or observed, not what you expect.',\n assumptions: 'What you assumed about the app and could not verify.',\n conflict:\n 'A one-line summary of any conflict you could not cleanly resolve (e.g. a dependency or build conflict). Put full detail in your work; this line is surfaced to the user.',\n reportSection:\n 'A finished markdown section about your work for the run report, written only when your task instructions ask for one. The reporting task includes it as its own section instead of rewriting it.',\n} as const satisfies Record<keyof Required<TaskHandoff>, string>;\n\nconst HANDOFF_SHAPE = {\n goals: z.string().max(HANDOFF_TEXT_MAX).describe(HANDOFF_FIELDS.goals),\n did: z.string().max(HANDOFF_TEXT_MAX).describe(HANDOFF_FIELDS.did),\n forNextAgent: z\n .string()\n .max(HANDOFF_TEXT_MAX)\n .describe(HANDOFF_FIELDS.forNextAgent),\n filesTouched: z\n .array(z.string().max(1_000))\n .max(200)\n .optional()\n .describe(HANDOFF_FIELDS.filesTouched),\n evidence: z\n .string()\n .max(HANDOFF_TEXT_MAX)\n .optional()\n .describe(HANDOFF_FIELDS.evidence),\n assumptions: z\n .string()\n .max(HANDOFF_TEXT_MAX)\n .optional()\n .describe(HANDOFF_FIELDS.assumptions),\n conflict: z\n .string()\n .max(HANDOFF_TEXT_MAX)\n .optional()\n .describe(HANDOFF_FIELDS.conflict),\n reportSection: z\n .string()\n .max(HANDOFF_TEXT_MAX)\n .optional()\n .describe(HANDOFF_FIELDS.reportSection),\n};\n\n/** Exported so the parity test can compare both harnesses' field sets. */\nexport const HANDOFF_SHAPE_KEYS: readonly string[] = Object.keys(HANDOFF_SHAPE);\n\n/**\n * `complete_task`'s own arguments, held level with the pi mirror by the same\n * parity test that guards the handoff — a top-level field can go missing on the\n * harness that runs just as easily as a nested one.\n */\nconst COMPLETE_SHAPE = {\n status: z.enum(['done', 'failed', 'not needed']),\n handoff: z.object(HANDOFF_SHAPE),\n remark: z.string().optional().describe(REMARK_ASK),\n notNeededReason: z\n .enum([\n NotNeededReason.NotApplicable,\n NotNeededReason.UserDeclined,\n NotNeededReason.Blocked,\n ])\n .optional()\n .describe(NOT_NEEDED_REASON_ASK),\n};\n\n/** Exported so the parity test can compare both harnesses' field sets. */\nexport const COMPLETE_SHAPE_KEYS: readonly string[] =\n Object.keys(COMPLETE_SHAPE);\n\ntype SdkTool = (\n name: string,\n description: string,\n // The SDK accepts a plain object of zod fields as the schema.\n schema: Record<string, z.ZodTypeAny>,\n handler: (args: never) => unknown,\n) => unknown;\n\nfunction textResult(text: string, isError = false) {\n return { isError, content: [{ type: 'text' as const, text }] };\n}\n\n/**\n * Build the orchestrator tools in the SDK `tool()` shape. Called from\n * createWizardToolsServer only when a queue context is present.\n */\nexport function buildOrchestratorTools(\n tool: SdkTool,\n ctx: OrchestratorToolsContext,\n): unknown[] {\n const enqueueTask = tool(\n 'enqueue_task',\n 'Add a task to the orchestrator queue. Use it to seed work and to enqueue follow-up work you discover. Keep tasks small and discrete.',\n {\n type: z\n .string()\n .describe(`The task type. One of: ${ctx.validTypes.join(', ')}.`),\n label: z\n .string()\n .optional()\n .describe(\n '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.',\n ),\n inputs: z.record(z.unknown()).optional(),\n dependsOn: z\n .array(z.string())\n .optional()\n .describe('Task ids that must be done before this task runs.'),\n model: z.string().optional().describe(ENQUEUE_MODEL_DESCRIPTION),\n reason: z.string().describe('One line on why this task is needed.'),\n },\n ((args: EnqueueArgs) => {\n const res = applyEnqueue(ctx, args);\n if (!res.ok) {\n analytics.wizardCapture('orchestrator guard tripped', {\n guard: res.guard,\n type: args.type,\n });\n return textResult(res.message, true);\n }\n return textResult(JSON.stringify({ id: res.task.id }));\n }) as (args: never) => unknown,\n );\n\n const completeTask = tool(\n 'complete_task',\n COMPLETE_TASK_DESCRIPTION,\n COMPLETE_SHAPE,\n ((args: CompleteArgs) => {\n const res = applyComplete(ctx, args);\n if (!res.ok) return textResult(res.message, true);\n return textResult('ok');\n }) as (args: never) => unknown,\n );\n\n const readHandoffs = tool(\n 'read_handoffs',\n 'Read structured handoffs from earlier tasks. With no argument, returns the handoffs of your dependencies.',\n {\n type: z.string().optional(),\n taskId: z.string().optional(),\n },\n ((args: { type?: string; taskId?: string }) => {\n const handoffs = applyReadHandoffs(ctx, args);\n return textResult(JSON.stringify(handoffs, null, 2));\n }) as (args: never) => unknown,\n );\n\n return [enqueueTask, completeTask, readHandoffs];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,SAAgB,gBAAgB,YAAoB,MAAqB;CACvE,MAAM,UAAU,GAAG,WAAW;AAC9B,MAAG,cAAc,SAAS,KAAK,UAAU,MAAM,MAAM,EAAE,EAAE,OAAO;AAChE,MAAG,WAAW,SAAS,WAAW;;;;;;AAOpC,SAAgB,YAAY;CAC1B,IAAI,QAA0B,QAAQ,SAAS;AAC/C,QAAO,eAAe,IAAO,IAAsC;EACjE,MAAM,OAAO,MAAM,WAAW,IAAI,CAAC;AACnC,UAAQ,KAAK,YAAY,KAAA,EAAU;AACnC,SAAO;;;;;;ACdX,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACD;;AAID,SAAgB,gBAAgB,OAAwC;AACtE,QAAQ,gBAAuC,SAAS,MAAM;;;;;;;;;;AAwBhE,MAAa,qBAAwD;EAGlE,iBAAiB;EAAE,WAAW;EAAM,eAAe;EAAQ;EAE3D,cAAc;EAAE,WAAW;EAAM,eAAe;EAAO;EAKvD,oBAAoB;EAAE,WAAW;EAAM,eAAe;EAAO;EAC7D,qBAAqB;EAAE,WAAW;EAAM,eAAe;EAAU;EACjE,mBAAmB;EAAE,WAAW;EAAM,eAAe;EAAU;CACjE;AAgBD,MAAa,eAA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