@posthog/wizard 2.79.1 → 2.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +187 -57
  2. package/dist/{PickerMenu-dG5DQCZA.js → PickerMenu-BGGeYqd-.js} +112 -12
  3. package/dist/PickerMenu-BGGeYqd-.js.map +1 -0
  4. package/dist/README.md +9 -6
  5. package/dist/{agent-interface-FkbaBJwz.js → agent-interface-CemBvTAA.js} +130 -324
  6. package/dist/agent-interface-CemBvTAA.js.map +1 -0
  7. package/dist/{agent-prompt-loader-D0weQ-7k.js → agent-prompt-loader-DPnj6SwU.js} +6 -5
  8. package/dist/agent-prompt-loader-DPnj6SwU.js.map +1 -0
  9. package/dist/analytics-B3ROGuIr.js +2 -0
  10. package/dist/analytics-D21z3E5l.js +732 -0
  11. package/dist/analytics-D21z3E5l.js.map +1 -0
  12. package/dist/{api-CrbCIQOz.js → api-DtGIqQ2U.js} +2 -3
  13. package/dist/api-DtGIqQ2U.js.map +1 -0
  14. package/dist/api-IhROOQNv.js +2 -0
  15. package/dist/api-key-login-OEntFvu5.js +2 -0
  16. package/dist/api-key-login-h3E2G3zu.js +55 -0
  17. package/dist/api-key-login-h3E2G3zu.js.map +1 -0
  18. package/dist/bin.js +2 -2
  19. package/dist/bin.js.map +1 -1
  20. package/dist/{bounded-fs-vAq-T-K7.js → bounded-fs-CAsuF6al.js} +3 -3
  21. package/dist/{bounded-fs-vAq-T-K7.js.map → bounded-fs-CAsuF6al.js.map} +1 -1
  22. package/dist/{ci-install-COcV8SY2.js → ci-install-CEYE02t-.js} +22 -26
  23. package/dist/ci-install-CEYE02t-.js.map +1 -0
  24. package/dist/console-log-O828zyiq.js +32 -0
  25. package/dist/console-log-O828zyiq.js.map +1 -0
  26. package/dist/{debug-kAHwWGg7.js → debug-BfQPD2Hg.js} +18 -52
  27. package/dist/debug-BfQPD2Hg.js.map +1 -0
  28. package/dist/{defaults-a9TelDhJ.js → defaults-DDVl3tKN.js} +2 -51
  29. package/dist/defaults-DDVl3tKN.js.map +1 -0
  30. package/dist/{emit-BSetXzDV.js → emit-RfAewcWv.js} +1 -1
  31. package/dist/{emit-BSetXzDV.js.map → emit-RfAewcWv.js.map} +1 -1
  32. package/dist/{errors-C2domSkK.js → errors-CHrJzAZb.js} +4 -4
  33. package/dist/{errors-C2domSkK.js.map → errors-CHrJzAZb.js.map} +1 -1
  34. package/dist/family-picker-BKs-tTyu.js +46 -0
  35. package/dist/family-picker-BKs-tTyu.js.map +1 -0
  36. package/dist/{gateway-C9-GlLO9.js → gateway-D3gIlR6b.js} +122 -11
  37. package/dist/gateway-D3gIlR6b.js.map +1 -0
  38. package/dist/headless-BJjhP0SI.js +10 -0
  39. package/dist/headless-BJjhP0SI.js.map +1 -0
  40. package/dist/headless-DIX68UUA.js +3 -0
  41. package/dist/host-resolution-D8GhEVoX.js +114 -0
  42. package/dist/host-resolution-D8GhEVoX.js.map +1 -0
  43. package/dist/install-Bw8tvDvS.js +2 -0
  44. package/dist/{add-mcp-server-to-clients-DIaTRWMY.js → install-paPCzPHI.js} +34 -100
  45. package/dist/install-paPCzPHI.js.map +1 -0
  46. package/dist/interactive-tdxZKWax.js +11 -0
  47. package/dist/interactive-tdxZKWax.js.map +1 -0
  48. package/dist/{telemetry-B7zJdRmA.js → links-Cyj6v8kg.js} +4 -13
  49. package/dist/links-Cyj6v8kg.js.map +1 -0
  50. package/dist/{main-CgKxbwMP.js → main-0p-YxUNa.js} +233 -490
  51. package/dist/main-0p-YxUNa.js.map +1 -0
  52. package/dist/{mcp-DnAyW0-w.js → mcp-D3Z5MXhA.js} +3 -4
  53. package/dist/{mcp-DnAyW0-w.js.map → mcp-D3Z5MXhA.js.map} +1 -1
  54. package/dist/mcp-install-smoke-test.ts +2 -2
  55. package/dist/{mcp-prompt-streaming-DDWQ-FCA.js → mcp-prompt-streaming-COVbWnHt.js} +12 -12
  56. package/dist/mcp-prompt-streaming-COVbWnHt.js.map +1 -0
  57. package/dist/mode-label-DB3ol_sj.js +9 -0
  58. package/dist/mode-label-DB3ol_sj.js.map +1 -0
  59. package/dist/{models-WcwUnSKb.js → models-D1SnCzvl.js} +2 -2
  60. package/dist/{models-WcwUnSKb.js.map → models-D1SnCzvl.js.map} +1 -1
  61. package/dist/non-interactive-DxRBc73O.js +18 -0
  62. package/dist/non-interactive-DxRBc73O.js.map +1 -0
  63. package/dist/{oauth-session-DYM2Hrl2.js → oauth-session-Dde79Ycm.js} +3 -3
  64. package/dist/{oauth-session-DYM2Hrl2.js.map → oauth-session-Dde79Ycm.js.map} +1 -1
  65. package/dist/{orchestrator-tools-DbgNBFGA.js → orchestrator-tools-BSNhzzkT.js} +3 -3
  66. package/dist/{orchestrator-tools-DbgNBFGA.js.map → orchestrator-tools-BSNhzzkT.js.map} +1 -1
  67. package/dist/{package-json-Atg34fa4.js → package-json-2UrhE6kP.js} +1 -1
  68. package/dist/{package-json-Atg34fa4.js.map → package-json-2UrhE6kP.js.map} +1 -1
  69. package/dist/package-json-Dblip2_X.js +2 -0
  70. package/dist/package-manager-BRXlXo0p.js +105 -0
  71. package/dist/package-manager-BRXlXo0p.js.map +1 -0
  72. package/dist/{pi-8KsYsPmM.js → pi-cM_4Gd_9.js} +19 -20
  73. package/dist/pi-cM_4Gd_9.js.map +1 -0
  74. package/dist/playground-DTKy0XHT.js +12 -0
  75. package/dist/playground-DTKy0XHT.js.map +1 -0
  76. package/dist/posthog-integration-bwHwE87a.js +10291 -0
  77. package/dist/posthog-integration-bwHwE87a.js.map +1 -0
  78. package/dist/programs-BhtyA3lE.js +3 -0
  79. package/dist/programs-SeT1qNik.js +5348 -0
  80. package/dist/programs-SeT1qNik.js.map +1 -0
  81. package/dist/provisioning-BcXfeCMc.js +2 -0
  82. package/dist/{provisioning-Bo2NRxFz.js → provisioning-JbJtq7hq.js} +5 -67
  83. package/dist/provisioning-JbJtq7hq.js.map +1 -0
  84. package/dist/{queue-tools-C8mXOh7e.js → queue-tools-BIZSJyt6.js} +7 -9
  85. package/dist/queue-tools-BIZSJyt6.js.map +1 -0
  86. package/dist/results-DtKICAdz.js +55 -0
  87. package/dist/results-DtKICAdz.js.map +1 -0
  88. package/dist/run-CDurA5tO.js +248 -0
  89. package/dist/run-CDurA5tO.js.map +1 -0
  90. package/dist/run-DDCvLILJ.js +246 -0
  91. package/dist/run-DDCvLILJ.js.map +1 -0
  92. package/dist/run-tool-CTq9OOdT.js +2 -0
  93. package/dist/run-tool-DML8JJvt.js +2420 -0
  94. package/dist/run-tool-DML8JJvt.js.map +1 -0
  95. package/dist/runners-Dhu4pZTN.js +253 -0
  96. package/dist/runners-Dhu4pZTN.js.map +1 -0
  97. package/dist/{security-C71pkwqH.js → security-DEH8Rn0_.js} +5 -5
  98. package/dist/security-DEH8Rn0_.js.map +1 -0
  99. package/dist/setup-utils-C5-WM-hS.js +118 -0
  100. package/dist/setup-utils-C5-WM-hS.js.map +1 -0
  101. package/dist/smoke-test.sh +1 -1
  102. package/dist/{playground-BlYRBMj7.js → start-playground-DL4mVEUx.js} +63 -54
  103. package/dist/start-playground-DL4mVEUx.js.map +1 -0
  104. package/dist/{subagent-D1TrTchE.js → subagent-CnFvAq6E.js} +3 -3
  105. package/dist/{subagent-D1TrTchE.js.map → subagent-CnFvAq6E.js.map} +1 -1
  106. package/dist/{task-DqRlQBfs.js → task-BOScSm4W.js} +17 -18
  107. package/dist/task-BOScSm4W.js.map +1 -0
  108. package/dist/{tasks-ChWufsdO.js → tasks-BfJhVky2.js} +1 -1
  109. package/dist/tasks-BfJhVky2.js.map +1 -0
  110. package/dist/telemetry-CP4rGicd.js +13 -0
  111. package/dist/telemetry-CP4rGicd.js.map +1 -0
  112. package/dist/terminal-J3OD3dN0.js +16162 -0
  113. package/dist/terminal-J3OD3dN0.js.map +1 -0
  114. package/dist/tools-CCMV3DmB.js +544 -0
  115. package/dist/tools-CCMV3DmB.js.map +1 -0
  116. package/dist/{tools-CkJ2y9Wt.js → tools-Cz8tDptL.js} +9 -9
  117. package/dist/tools-Cz8tDptL.js.map +1 -0
  118. package/dist/tui-BUZ2PWqN.js +2 -0
  119. package/dist/tui-Csf7VJxt.js +25 -0
  120. package/dist/tui-Csf7VJxt.js.map +1 -0
  121. package/dist/{steps-BPcg3_3Q.js → upload-step-CEacB2RV.js} +17 -19
  122. package/dist/upload-step-CEacB2RV.js.map +1 -0
  123. package/dist/urls-BDELGZHq.js +67 -0
  124. package/dist/urls-BDELGZHq.js.map +1 -0
  125. package/dist/warlock-smoke-test.ts +1 -2
  126. package/dist/{wizard-abort-BPdv07np.js → wizard-abort-D3-75KyV.js} +41 -32
  127. package/dist/wizard-abort-D3-75KyV.js.map +1 -0
  128. package/dist/yara-hooks-CZ1tKxy_.js +2 -0
  129. package/dist/{yara-hooks-BnxejtXK.js → yara-hooks-D8YDyX7o.js} +283 -21
  130. package/dist/yara-hooks-D8YDyX7o.js.map +1 -0
  131. package/package.json +7 -8
  132. package/dist/PickerMenu-dG5DQCZA.js.map +0 -1
  133. package/dist/add-mcp-server-to-clients-DIaTRWMY.js.map +0 -1
  134. package/dist/add-mcp-server-to-clients-artmN7mz.js +0 -2
  135. package/dist/agent-BEjARD2a.js +0 -6
  136. package/dist/agent-BWFhuLgo.js +0 -3178
  137. package/dist/agent-BWFhuLgo.js.map +0 -1
  138. package/dist/agent-interface-FkbaBJwz.js.map +0 -1
  139. package/dist/agent-prompt-loader-D0weQ-7k.js.map +0 -1
  140. package/dist/analytics-DFtbRjYh.js +0 -2
  141. package/dist/analytics-DXK1gc12.js +0 -301
  142. package/dist/analytics-DXK1gc12.js.map +0 -1
  143. package/dist/api-Cm9UtKZh.js +0 -2
  144. package/dist/api-CrbCIQOz.js.map +0 -1
  145. package/dist/check-screens.tsx +0 -190
  146. package/dist/ci-install-COcV8SY2.js.map +0 -1
  147. package/dist/constants-DHCBSfnx.js +0 -260
  148. package/dist/constants-DHCBSfnx.js.map +0 -1
  149. package/dist/debug-BuYHGr6_.js +0 -2
  150. package/dist/debug-kAHwWGg7.js.map +0 -1
  151. package/dist/defaults-a9TelDhJ.js.map +0 -1
  152. package/dist/endpoints-BVMYm9F4.js +0 -108
  153. package/dist/endpoints-BVMYm9F4.js.map +0 -1
  154. package/dist/env-api-key-BP-NFFXt.js +0 -17
  155. package/dist/env-api-key-BP-NFFXt.js.map +0 -1
  156. package/dist/env-api-key-CaWEDj_9.js +0 -2
  157. package/dist/environment-BATlQxcQ.js +0 -39
  158. package/dist/environment-BATlQxcQ.js.map +0 -1
  159. package/dist/environment-CwD8OPYj.js +0 -2
  160. package/dist/file-C5JMsyR1.js +0 -2
  161. package/dist/file-DcRKycV8.js +0 -60
  162. package/dist/file-DcRKycV8.js.map +0 -1
  163. package/dist/file-watcher-Brq2nnHV.js +0 -123
  164. package/dist/file-watcher-Brq2nnHV.js.map +0 -1
  165. package/dist/gateway-C9-GlLO9.js.map +0 -1
  166. package/dist/headless-ui-CqI2gXlD.js +0 -44
  167. package/dist/headless-ui-CqI2gXlD.js.map +0 -1
  168. package/dist/interactive-B_Ti_CsS.js +0 -11
  169. package/dist/interactive-B_Ti_CsS.js.map +0 -1
  170. package/dist/local-dev-McsurOC-.js +0 -135
  171. package/dist/local-dev-McsurOC-.js.map +0 -1
  172. package/dist/logging-ui-Dza4D0MK.js +0 -226
  173. package/dist/logging-ui-Dza4D0MK.js.map +0 -1
  174. package/dist/main-CgKxbwMP.js.map +0 -1
  175. package/dist/mcp-prompt-streaming-DDWQ-FCA.js.map +0 -1
  176. package/dist/mint-failure-u8xQKNOn.js +0 -6392
  177. package/dist/mint-failure-u8xQKNOn.js.map +0 -1
  178. package/dist/non-interactive-DyVC1AGc.js +0 -18
  179. package/dist/non-interactive-DyVC1AGc.js.map +0 -1
  180. package/dist/package-json-D8Ga03tK.js +0 -2
  181. package/dist/pi-8KsYsPmM.js.map +0 -1
  182. package/dist/playground-BlYRBMj7.js.map +0 -1
  183. package/dist/posthog-Bt0Aplb8.js +0 -124
  184. package/dist/posthog-Bt0Aplb8.js.map +0 -1
  185. package/dist/posthog-CUgCEhH0.js +0 -2
  186. package/dist/provisioning-Bo2NRxFz.js.map +0 -1
  187. package/dist/provisioning-OGFGlzf7.js +0 -2
  188. package/dist/queue-tools-C8mXOh7e.js.map +0 -1
  189. package/dist/registry-C06e_x-p.js +0 -2
  190. package/dist/registry-CD5RQt38.js +0 -3464
  191. package/dist/registry-CD5RQt38.js.map +0 -1
  192. package/dist/run-agent-legacy-ChacZImU.js +0 -2
  193. package/dist/run-agent-legacy-DOlM6DQu.js +0 -3540
  194. package/dist/run-agent-legacy-DOlM6DQu.js.map +0 -1
  195. package/dist/runners-ov3EXF1n.js +0 -834
  196. package/dist/runners-ov3EXF1n.js.map +0 -1
  197. package/dist/security-C71pkwqH.js.map +0 -1
  198. package/dist/setup-utils-B26Lf2yF.js +0 -1512
  199. package/dist/setup-utils-B26Lf2yF.js.map +0 -1
  200. package/dist/setup-utils-CVS86NYR.js +0 -2
  201. package/dist/start-tui-Bo2L0bar.js +0 -6962
  202. package/dist/start-tui-Bo2L0bar.js.map +0 -1
  203. package/dist/steps-BPcg3_3Q.js.map +0 -1
  204. package/dist/store-BTzcvRGT.js +0 -992
  205. package/dist/store-BTzcvRGT.js.map +0 -1
  206. package/dist/store-BpqySPXm.js +0 -5
  207. package/dist/task-DqRlQBfs.js.map +0 -1
  208. package/dist/task-stream-Bw6JaLCX.js +0 -363
  209. package/dist/task-stream-Bw6JaLCX.js.map +0 -1
  210. package/dist/tasks-ChWufsdO.js.map +0 -1
  211. package/dist/telemetry-B7zJdRmA.js.map +0 -1
  212. package/dist/terminal-zgkEfoCL.js +0 -7196
  213. package/dist/terminal-zgkEfoCL.js.map +0 -1
  214. package/dist/tools-CkJ2y9Wt.js.map +0 -1
  215. package/dist/ui-Q6-RvERF.js +0 -15
  216. package/dist/ui-Q6-RvERF.js.map +0 -1
  217. package/dist/version-CHhJjz_H.js +0 -6
  218. package/dist/version-CHhJjz_H.js.map +0 -1
  219. package/dist/wizard-abort-BPdv07np.js.map +0 -1
  220. package/dist/wizard-abort-Br1qMDNa.js +0 -3
  221. package/dist/wizard-session-2w4Ru-Wz.js +0 -131
  222. package/dist/wizard-session-2w4Ru-Wz.js.map +0 -1
  223. package/dist/wizard-session-DGaUHOF3.js +0 -2
  224. package/dist/wizard-ui-DVqrYaOM.js +0 -16
  225. package/dist/wizard-ui-DVqrYaOM.js.map +0 -1
  226. package/dist/yara-hooks-BnxejtXK.js.map +0 -1
  227. package/dist/yara-hooks-DSuExwb4.js +0 -2
@@ -1,992 +0,0 @@
1
- import { s as logToFile } from "./debug-kAHwWGg7.js";
2
- import "./constants-DHCBSfnx.js";
3
- import { n as buildSession } from "./wizard-session-2w4Ru-Wz.js";
4
- import { i as sessionProperties, n as analytics } from "./analytics-DXK1gc12.js";
5
- import { n as isTaskStatus } from "./wizard-ui-DVqrYaOM.js";
6
- import { a as getBlockingServiceKeys } from "./logging-ui-Dza4D0MK.js";
7
- import { a as computeTokenCostUsd } from "./agent-BWFhuLgo.js";
8
- import { p as appendStatus } from "./pi-8KsYsPmM.js";
9
- import { f as createProgramSequence } from "./run-agent-legacy-DOlM6DQu.js";
10
- import { a as PROGRAM_REGISTRY, i as isRunFailure, o as Program, ot as reportWarehouseSourcesDetected, u as getProgramConfig } from "./mint-failure-u8xQKNOn.js";
11
- import { atom, map } from "nanostores";
12
- //#region src/programs/ai-opt-in-gate.ts
13
- /** Step id — also the ScreenId.AiOptIn enum value in screen-sequences. */
14
- const AI_OPT_IN_STEP_ID = "ai-opt-in";
15
- function aiApproved(session) {
16
- return !!session.apiUser?.organization?.is_ai_data_processing_approved;
17
- }
18
- /**
19
- * Returns the program's steps with the AI opt-in gate injected after
20
- * `auth`. Programs with `requiresAi: false` or no auth step pass
21
- * through unchanged — without auth, `apiUser` would never be populated
22
- * for evaluation anyway.
23
- */
24
- function withAiOptInGate(config) {
25
- if (config.requiresAi === false) return config.steps;
26
- const authIdx = config.steps.findIndex((s) => s.id === "auth");
27
- if (authIdx === -1) return config.steps;
28
- const gateStep = {
29
- id: AI_OPT_IN_STEP_ID,
30
- label: "AI opt-in check",
31
- screenId: AI_OPT_IN_STEP_ID,
32
- show: (session) => !session.ci && !session.signup && session.apiUser != null && !aiApproved(session),
33
- isComplete: (session) => session.ci || session.signup || aiApproved(session),
34
- gate: (session) => session.ci || session.signup || aiApproved(session)
35
- };
36
- return [
37
- ...config.steps.slice(0, authIdx + 1),
38
- gateStep,
39
- ...config.steps.slice(authIdx + 1)
40
- ];
41
- }
42
- //#endregion
43
- //#region src/ui/tui/screen-sequences.ts
44
- /** Post-run steps a mint-failure handoff continues through; ends on exit. */
45
- const MINT_HANDOFF_SEQUENCE = [
46
- {
47
- id: "mcp",
48
- isComplete: (s) => s.mcpComplete
49
- },
50
- {
51
- id: "slack-connect",
52
- isComplete: (s) => s.slackStepDismissed
53
- },
54
- {
55
- id: "keep-skills",
56
- isComplete: (s) => s.skillsComplete
57
- },
58
- { id: "exit" }
59
- ];
60
- /** All program screen sequences keyed by program id. */
61
- const PROGRAM_SEQUENCES = Object.fromEntries(PROGRAM_REGISTRY.map((c) => [c.id, createProgramSequence(withAiOptInGate(c))]));
62
- //#endregion
63
- //#region src/ui/tui/router.ts
64
- var WizardRouter = class {
65
- sequence;
66
- programId;
67
- overlays = [];
68
- constructor(programId = Program.PostHogIntegration) {
69
- this.setProgram(programId);
70
- }
71
- /** Point the router at a different program. */
72
- setProgram(programId) {
73
- this.programId = programId;
74
- this.sequence = PROGRAM_SEQUENCES[programId];
75
- this.overlays = [];
76
- }
77
- /**
78
- * Resolve which screen should be active based on session state.
79
- * Walks the program sequence, skipping hidden entries and completed entries,
80
- * returns the first incomplete screen.
81
- */
82
- resolve(session) {
83
- const runFailed = isRunFailure(session);
84
- if (runFailed && session.mintHandoff === "exit") return "exit";
85
- if (runFailed && !session.mintHandoff) return "mint-failure";
86
- if (this.overlays.length > 0) return this.overlays[this.overlays.length - 1];
87
- const sequence = runFailed ? MINT_HANDOFF_SEQUENCE : this.sequence;
88
- for (const entry of sequence) {
89
- if (entry.show && !entry.show(session)) continue;
90
- if (entry.isComplete && entry.isComplete(session)) continue;
91
- if (entry.id === "auth" && session.runPhase === "error" && session.outroData) return "outro";
92
- return entry.id;
93
- }
94
- return sequence[sequence.length - 1].id;
95
- }
96
- /** The screen that should be rendered right now. */
97
- get activeScreen() {
98
- if (this.overlays.length > 0) return this.overlays[this.overlays.length - 1];
99
- return this.sequence[0].id;
100
- }
101
- /** The id of the active program. */
102
- get activeProgram() {
103
- return this.programId;
104
- }
105
- /** Whether an overlay is currently active. */
106
- get hasOverlay() {
107
- return this.overlays.length > 0;
108
- }
109
- /**
110
- * Push an overlay that interrupts the current program.
111
- * The program resumes when the overlay is dismissed via popOverlay().
112
- */
113
- pushOverlay(overlay) {
114
- this.overlays.push(overlay);
115
- }
116
- /**
117
- * Dismiss the topmost overlay. The program screen underneath resumes.
118
- */
119
- popOverlay() {
120
- this.overlays.pop();
121
- }
122
- /**
123
- * Direction hint for screen transitions.
124
- */
125
- _lastDirection = null;
126
- get lastNavDirection() {
127
- return this._lastDirection;
128
- }
129
- /** @internal — called by store wrapper to track direction */
130
- _setDirection(dir) {
131
- this._lastDirection = dir;
132
- }
133
- };
134
- //#endregion
135
- //#region src/ui/tui/store.ts
136
- /**
137
- * WizardStore — Nanostore-backed reactive store for the TUI.
138
- * React components subscribe via useSyncExternalStore.
139
- *
140
- * The active screen is derived from session state — WizardRouter walks
141
- * the flow and shows the first step whose `isComplete` is still false.
142
- *
143
- * Define a step `gate` if your screen needs to await user interactions.
144
- * bin.ts calls `await store.getGate(stepId)` to pause until the gate
145
- * predicate becomes true.
146
- *
147
- * All session mutations that affect screen resolution go through
148
- * explicit setters so emitChange() is always called.
149
- */
150
- const EMPTY_TOKEN_USAGE = {
151
- inputTokens: 0,
152
- outputTokens: 0,
153
- cacheReadTokens: 0,
154
- cacheCreationTokens: 0,
155
- costUsd: 0,
156
- costIsFinal: false
157
- };
158
- /** Total tokens across all counters in a `TokenUsageSnapshot` — used by
159
- * both `TokenCostHud` and `exit-line.ts` to detect "no agent turns yet". */
160
- function totalTokenCount(usage) {
161
- return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheCreationTokens;
162
- }
163
- function captureHealthCheckBlocked(result) {
164
- try {
165
- const health = result.health;
166
- const blockingKeys = getBlockingServiceKeys(health);
167
- const attempts = health.skillsOrigin.rawIndicator?.match(/attempts=(\d+)/);
168
- const retriesUsed = Math.max(0, attempts ? Number(attempts[1]) - 1 : 0);
169
- analytics.wizardCapture("health check blocked", {
170
- decision: "skills-origin-down",
171
- blocking_keys: blockingKeys,
172
- retries_used: retriesUsed
173
- });
174
- } catch (err) {
175
- logToFile(`[health-checks] failed to capture analytics: ${err instanceof Error ? err.message : String(err)}`);
176
- }
177
- }
178
- var WizardStore = class {
179
- $session = map(buildSession({}));
180
- $statusMessages = atom([]);
181
- $statusExpanded = atom(false);
182
- $tasks = atom([]);
183
- $eventPlan = atom([]);
184
- $handoffText = atom(null);
185
- $learnCardBlockIdx = atom(0);
186
- $learnCardComplete = atom(false);
187
- $version = atom(0);
188
- $currentStage = atom(null);
189
- $tokenUsage = atom(EMPTY_TOKEN_USAGE);
190
- $tokenHudVisible = atom(false);
191
- _onTasksChanged = null;
192
- /** Last screen seen — used to detect screen transitions for analytics. */
193
- _lastScreen = null;
194
- /** Hooks run when transitioning onto a screen. */
195
- _enterScreenHooks = /* @__PURE__ */ new Map();
196
- /** Gate promises derived from program step definitions. */
197
- _gates = /* @__PURE__ */ new Map();
198
- version = "";
199
- /** Navigation router — resolves active screen from session state. */
200
- router;
201
- /** Blocks agent execution until the settings-override overlay is dismissed. */
202
- _resolveSettingsOverride = null;
203
- _backupAndFixSettings = null;
204
- /** Blocks the run until an optional step's notice is answered. */
205
- _resolveTaskNotice = null;
206
- /** Blocks OAuth flow until the port-conflict overlay is dismissed. */
207
- _resolvePortConflict = null;
208
- /** Resolves the OAuth flow with a manually-entered authorization code. */
209
- _resolveManualAuthCode = null;
210
- /** Resolves the in-flight wizard_ask request. */
211
- _resolvePendingQuestion = null;
212
- constructor(program = Program.PostHogIntegration) {
213
- this.router = new WizardRouter(program);
214
- this._initFromProgram(program);
215
- }
216
- /**
217
- * Scan program steps for gate predicates and create gate promises.
218
- *
219
- * Steps are wrapped with withAiOptInGate so the injected ai-opt-in
220
- * step's gate registers here — the agent runner awaits it (via
221
- * WizardUI.waitForAiOptIn) before any source leaves the machine.
222
- * Same wrapper screen-sequences.ts uses, so the gate and its screen
223
- * can't drift apart.
224
- */
225
- _initFromProgram(program) {
226
- const steps = withAiOptInGate(getProgramConfig(program));
227
- for (const step of steps) if (step.gate) {
228
- let resolve;
229
- const promise = new Promise((r) => {
230
- resolve = r;
231
- });
232
- this._gates.set(step.id, {
233
- predicate: step.gate,
234
- promise,
235
- resolve,
236
- resolved: false
237
- });
238
- }
239
- }
240
- /**
241
- * Run the program steps' onInit callbacks. startTUI calls this once
242
- * the screens are actually rendering — constructing a store alone
243
- * (tests, playground) must not fire init work like the health-check
244
- * pre-flight, whose probes belong only to flows that show its screen.
245
- */
246
- runInitHooks() {
247
- const steps = getProgramConfig(this.router.activeProgram).steps;
248
- const getSession = () => this.session;
249
- const ctx = {
250
- get session() {
251
- return getSession();
252
- },
253
- setReadinessResult: (r) => this.setReadinessResult(r),
254
- setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),
255
- emitChange: () => this.emitChange()
256
- };
257
- for (const step of steps) step.onInit?.(ctx);
258
- }
259
- /**
260
- * Run all `onReady` hooks declared by the current flow's steps, in
261
- * order. Must be called after `store.session = session` so hooks see
262
- * the real installDir. bin.ts calls this generically — it doesn't
263
- * need to know which program has which pre-flow work.
264
- */
265
- async runReadyHooks() {
266
- const steps = getProgramConfig(this.router.activeProgram).steps;
267
- const ctx = {
268
- session: this.session,
269
- setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),
270
- setFrameworkConfig: (i, c) => this.setFrameworkConfig(i, c),
271
- setDetectedFramework: (l) => this.setDetectedFramework(l),
272
- setPosthogSdkDetected: (d) => this.setPosthogSdkDetected(d),
273
- setSkillId: (id) => this.setSkillId(id),
274
- setUnsupportedVersion: (info) => this.setUnsupportedVersion(info),
275
- addDiscoveredFeature: (f) => this.addDiscoveredFeature(f),
276
- setDetectionComplete: () => this.setDetectionComplete()
277
- };
278
- for (const step of steps) if (step.onReady) await step.onReady(ctx);
279
- }
280
- /**
281
- * Get a gate promise by step ID — the primary blocking checkpoint API
282
- * for bin.ts. `await store.getGate('...')` parks the caller until the
283
- * corresponding program step's gate predicate flips to true (if the
284
- * predicate stays false, the caller stays parked indefinitely — the
285
- * TUI keeps rendering so the user can resolve whatever is blocking).
286
- *
287
- * If the program doesn't define a step with this ID, or the step
288
- * has no `gate` predicate, this returns an already-resolved promise
289
- * so bin.ts flows straight through. This lets programs opt in to
290
- * gates on a per-step basis without bin.ts needing to know which
291
- * gates exist in which flow.
292
- */
293
- getGate(stepId) {
294
- return this._gates.get(stepId)?.promise ?? Promise.resolve();
295
- }
296
- /**
297
- * Resolve once `predicate(session)` is true. Unlike a gate, this is created
298
- * at the await point and evaluated live against the current session, so it
299
- * never latches on a startup value — the orchestrator uses it to wait for a
300
- * decision (a project picked, a handoff acknowledged) without the "true while
301
- * undecided" trap that latched gate predicates have.
302
- */
303
- waitUntil(predicate) {
304
- if (predicate(this.session)) return Promise.resolve();
305
- return new Promise((resolve) => {
306
- const unsub = this.subscribe(() => {
307
- if (predicate(this.session)) {
308
- unsub();
309
- resolve();
310
- }
311
- });
312
- });
313
- }
314
- /**
315
- * Re-evaluate every gate predicate against the current session and
316
- * resolve any whose predicate now returns true. Called after every
317
- * emitChange(), so gates unblock as soon as the session mutation
318
- * that satisfies them lands. Gates only resolve once — a predicate
319
- * that goes true → false → true will NOT re-block a caller that
320
- * already awaited through.
321
- */
322
- _checkGates() {
323
- for (const [, gate] of this._gates) if (!gate.resolved && gate.predicate(this.session)) {
324
- gate.resolved = true;
325
- gate.resolve();
326
- }
327
- }
328
- get session() {
329
- return this.$session.get();
330
- }
331
- set session(value) {
332
- this.$session.set(value);
333
- this.emitChange();
334
- }
335
- get statusMessages() {
336
- return this.$statusMessages.get();
337
- }
338
- get tasks() {
339
- return this.$tasks.get();
340
- }
341
- get eventPlan() {
342
- return this.$eventPlan.get();
343
- }
344
- get handoffText() {
345
- return this.$handoffText.get();
346
- }
347
- get currentStage() {
348
- return this.$currentStage.get();
349
- }
350
- /** No-op when the stage hasn't changed, so `startedAt` survives across
351
- * re-renders and tab switches and measures real stage time. */
352
- setCurrentStage(stage) {
353
- if (this.$currentStage.get()?.stage === stage) return;
354
- this.$currentStage.set({
355
- stage,
356
- startedAt: Date.now()
357
- });
358
- this.emitChange();
359
- }
360
- get statusExpanded() {
361
- return this.$statusExpanded.get();
362
- }
363
- toggleStatusExpanded() {
364
- this.$statusExpanded.set(!this.$statusExpanded.get());
365
- this.emitChange();
366
- }
367
- setStatusExpanded(expanded) {
368
- if (this.$statusExpanded.get() !== expanded) {
369
- this.$statusExpanded.set(expanded);
370
- this.emitChange();
371
- }
372
- }
373
- /** Sets setupConfirmed, and is the point consent becomes final. */
374
- completeSetup() {
375
- this.$session.setKey("setupConfirmed", true);
376
- this._markWarehouseSourcesReportedIfNeeded();
377
- analytics.wizardCapture("setup confirmed", sessionProperties(this.session));
378
- this.emitChange();
379
- }
380
- /**
381
- * Sharing is on: either the user turned it back on in the panel, or they
382
- * pressed Continue without ever touching it. Both are reversible until
383
- * completeSetup() resolves the intro gate and reports.
384
- */
385
- grantSharing() {
386
- this.$session.setKey("scanConsent", "granted");
387
- this.emitChange();
388
- }
389
- /**
390
- * Sharing is off. Suppresses reporting only — local detection still ran and
391
- * the results stay in the session, so the outro suggestion and the warehouse
392
- * task are unaffected; see `scanConsent` on `WizardSession`.
393
- *
394
- * Deliberately does not report. The panel's toggle can come back here, so
395
- * marking the run reported would strand a user who turns sharing off and
396
- * then on again. completeSetup() owns the single report.
397
- */
398
- declineSharing() {
399
- this.$session.setKey("scanConsent", "declined");
400
- this.emitChange();
401
- }
402
- /**
403
- * reportWarehouseSourcesDetected() is the single place scan results turn
404
- * into telemetry; this just supplies its idempotency flag via the normal
405
- * setter path (never mutate session directly). A no-op once
406
- * `warehouseSourcesReported` is set, or for any program that never
407
- * populated a warehouse-scan result in the first place.
408
- */
409
- _markWarehouseSourcesReportedIfNeeded() {
410
- if (reportWarehouseSourcesDetected(this.session)) this.$session.setKey("warehouseSourcesReported", true);
411
- }
412
- setRunPhase(phase) {
413
- this.$session.setKey("runPhase", phase);
414
- analytics.setTag("run_phase", phase);
415
- this.emitChange();
416
- }
417
- setCredentials(credentials) {
418
- this.$session.setKey("credentials", credentials);
419
- if (credentials?.projectId) analytics.setTag("project_id", credentials.projectId);
420
- analytics.wizardCapture("auth complete", { project_id: credentials?.projectId });
421
- this.emitChange();
422
- }
423
- /** Post-refresh credential swap. No `auth complete` — see WizardUI. */
424
- setAccessToken(credentials) {
425
- this.$session.setKey("credentials", credentials);
426
- this.emitChange();
427
- }
428
- setRoleAtOrganization(role) {
429
- this.$session.setKey("roleAtOrganization", role);
430
- this.emitChange();
431
- }
432
- setApiUser(user) {
433
- this.$session.setKey("apiUser", user);
434
- this.emitChange();
435
- }
436
- setFrameworkConfig(integration, config) {
437
- this.$session.setKey("integration", integration);
438
- this.$session.setKey("frameworkConfig", config);
439
- this.$session.setKey("unsupportedVersion", null);
440
- if (integration) analytics.setTag("integration", integration);
441
- this.emitChange();
442
- }
443
- setDetectionComplete() {
444
- this.$session.setKey("detectionComplete", true);
445
- this.emitChange();
446
- }
447
- setDetectedFramework(label) {
448
- this.$session.setKey("detectedFrameworkLabel", label);
449
- analytics.setTag("detected_framework", label);
450
- this.emitChange();
451
- }
452
- setPosthogSdkDetected(detected) {
453
- this.$session.setKey("posthogSdkDetected", detected);
454
- this.emitChange();
455
- }
456
- setSpellbook(spellbook) {
457
- this.$session.setKey("spellbook", spellbook);
458
- this.emitChange();
459
- }
460
- setMintHandoff(action) {
461
- this.cancelPendingQuestion();
462
- if (this.session.taskNotice) this.resolveTaskNotice(false);
463
- this.$session.setKey("mintHandoff", action);
464
- this.emitChange();
465
- }
466
- setSkillId(skillId) {
467
- this.$session.setKey("skillId", skillId);
468
- this.emitChange();
469
- }
470
- setUnsupportedVersion(info) {
471
- this.$session.setKey("unsupportedVersion", info);
472
- this.emitChange();
473
- }
474
- setLoginUrl(url) {
475
- this.$session.setKey("loginUrl", url);
476
- this.emitChange();
477
- }
478
- setAuthorizeUrl(url) {
479
- this.$session.setKey("authorizeUrl", url);
480
- this.emitChange();
481
- }
482
- setReadinessResult(result) {
483
- this.$session.setKey("readinessResult", result);
484
- if (result && result.decision === "no") captureHealthCheckBlocked(result);
485
- this.emitChange();
486
- }
487
- /** User dismissed the blocking outage screen. Gate resolves via _checkGates(). */
488
- dismissOutage() {
489
- logToFile("[health-checks] user dismissed outage screen, continuing");
490
- this.$session.setKey("outageDismissed", true);
491
- this.emitChange();
492
- }
493
- /**
494
- * Push the settings-override overlay and return a promise that blocks
495
- * until the user dismisses it via backupAndFixSettingsOverride().
496
- */
497
- showSettingsOverride(conflicts, backupAndFix) {
498
- const allKeys = conflicts.flatMap((c) => c.keys);
499
- this.$session.setKey("settingsOverrideKeys", allKeys);
500
- this.$session.setKey("settingsConflicts", conflicts);
501
- this._backupAndFixSettings = backupAndFix;
502
- if (conflicts.some((c) => !c.writable)) this.pushOverlay("managed-settings");
503
- else this.pushOverlay("settings-override");
504
- return new Promise((resolve) => {
505
- this._resolveSettingsOverride = resolve;
506
- });
507
- }
508
- /**
509
- * Push the port-conflict overlay and return a promise that blocks
510
- * until the user frees the ports and retries, or exits.
511
- */
512
- showPortConflict(processInfo) {
513
- this.$session.setKey("portConflictProcess", processInfo);
514
- this.pushOverlay("port-conflict");
515
- return new Promise((resolve) => {
516
- this._resolvePortConflict = resolve;
517
- });
518
- }
519
- /** Dismiss the port-conflict overlay and retry the OAuth port loop. */
520
- resolvePortConflict() {
521
- this.$session.setKey("portConflictProcess", null);
522
- this.popOverlay();
523
- this._resolvePortConflict?.();
524
- this._resolvePortConflict = null;
525
- }
526
- /**
527
- * Show an optional step's notice and return whether to keep that step.
528
- * Asked before the step runs, so nobody is surprised by a prompt mid-run.
529
- */
530
- showTaskNotice(notice) {
531
- this.$session.setKey("taskNotice", notice);
532
- this.pushOverlay("task-notice");
533
- return new Promise((resolve) => {
534
- this._resolveTaskNotice = resolve;
535
- });
536
- }
537
- /** Dismiss the notice, keeping (`true`) or skipping (`false`) the step. */
538
- resolveTaskNotice(keep) {
539
- this.$session.setKey("taskNotice", null);
540
- this.popOverlay();
541
- this._resolveTaskNotice?.(keep);
542
- this._resolveTaskNotice = null;
543
- }
544
- /**
545
- * Return a promise that resolves when the user submits a manually-entered
546
- * OAuth code via the paste modal. The OAuth flow races this against the
547
- * local callback server — see `performOAuthFlow`.
548
- */
549
- waitForManualAuthCode() {
550
- return new Promise((resolve) => {
551
- this._resolveManualAuthCode = resolve;
552
- });
553
- }
554
- /** Open the manual OAuth code-entry overlay over the auth screen. */
555
- showManualAuthCode() {
556
- this.pushOverlay("manual-auth-code");
557
- }
558
- /** Dismiss the manual OAuth code overlay without submitting. */
559
- dismissManualAuthCode() {
560
- this.popOverlay();
561
- }
562
- /**
563
- * Submit a manually-entered authorization code: dismiss the overlay and
564
- * resolve the in-flight OAuth flow so it can exchange the code for a token.
565
- */
566
- submitManualAuthCode(code) {
567
- this.popOverlay();
568
- this._resolveManualAuthCode?.(code);
569
- this._resolveManualAuthCode = null;
570
- }
571
- /**
572
- * Open the WizardAsk overlay with a set of questions and return a promise
573
- * that resolves once the user submits answers (or the request is cancelled).
574
- *
575
- * Only one request is in flight at a time — calling this while a request
576
- * is already pending throws.
577
- */
578
- requestQuestion(question) {
579
- if (this._resolvePendingQuestion) throw new Error("requestQuestion called while another wizard_ask request is pending");
580
- this.$session.setKey("pendingQuestion", question);
581
- this.pushOverlay("wizard-ask");
582
- analytics.wizardCapture("wizard_ask shown", {
583
- source: question.source,
584
- question_count: question.questions.length,
585
- kinds: question.questions.map((q) => q.kind)
586
- });
587
- return new Promise((resolve) => {
588
- this._resolvePendingQuestion = resolve;
589
- });
590
- }
591
- /**
592
- * Resolve the in-flight wizard_ask request with the user's answers and
593
- * dismiss the overlay. Answers flow back to the agent as the tool result.
594
- */
595
- resolvePendingQuestion(answers) {
596
- const resolve = this._resolvePendingQuestion;
597
- this._resolvePendingQuestion = null;
598
- this.$session.setKey("pendingQuestion", null);
599
- this.popOverlay();
600
- resolve?.(answers);
601
- }
602
- /**
603
- * Cancel the in-flight wizard_ask request — the bridge sends a sentinel
604
- * answer ("__cancelled__") so the skill can decide how to handle it.
605
- */
606
- cancelPendingQuestion() {
607
- const pending = this.session.pendingQuestion;
608
- if (!pending) return;
609
- const cancelled = {};
610
- for (const q of pending.questions) cancelled[q.id] = "__cancelled__";
611
- this.resolvePendingQuestion(cancelled);
612
- }
613
- /**
614
- * Back up .claude/settings.json. Dismisses the overlay on success.
615
- */
616
- backupAndFixSettingsOverride() {
617
- const ok = this._backupAndFixSettings?.() ?? false;
618
- if (ok) {
619
- this.$session.setKey("settingsOverrideKeys", null);
620
- this.$session.setKey("settingsConflicts", null);
621
- this.popOverlay();
622
- this._resolveSettingsOverride?.();
623
- this._resolveSettingsOverride = null;
624
- this._backupAndFixSettings = null;
625
- }
626
- return ok;
627
- }
628
- /** Push the auth-error overlay (no dismiss — user must exit). */
629
- showAuthError(detail) {
630
- this.$session.setKey("authErrorDetail", detail ?? null);
631
- this.pushOverlay("auth-error");
632
- }
633
- /** Push the session-timeout overlay (no dismiss — user must exit). */
634
- showSessionTimeout() {
635
- this.pushOverlay("session-timeout");
636
- }
637
- addDiscoveredFeature(feature) {
638
- if (!this.session.discoveredFeatures.includes(feature)) {
639
- this.session.discoveredFeatures.push(feature);
640
- this.emitChange();
641
- }
642
- }
643
- setMcpComplete(outcome = "skipped", installedClients = [], featuresSelected, loginCommands = []) {
644
- this.$session.setKey("mcpComplete", true);
645
- this.$session.setKey("mcpOutcome", outcome);
646
- this.$session.setKey("mcpInstalledClients", installedClients);
647
- this.$session.setKey("mcpLoginCommands", loginCommands);
648
- const featuresPayload = outcome === "installed" && featuresSelected !== void 0 ? { mcp_features_selected: featuresSelected } : {};
649
- analytics.wizardCapture("mcp complete", {
650
- mcp_outcome: outcome,
651
- mcp_installed_clients: installedClients,
652
- ...featuresPayload,
653
- ...sessionProperties(this.session)
654
- });
655
- this.emitChange();
656
- }
657
- setSkillsComplete(kept) {
658
- this.$session.setKey("skillsComplete", true);
659
- analytics.wizardCapture("skills complete", {
660
- skills_kept: kept,
661
- ...sessionProperties(this.session)
662
- });
663
- this.emitChange();
664
- }
665
- setMcpSuggestedPromptsDismissed() {
666
- this.$session.setKey("mcpSuggestedPromptsDismissed", true);
667
- this.emitChange();
668
- }
669
- setSlackStepDismissed() {
670
- this.$session.setKey("slackStepDismissed", true);
671
- this.emitChange();
672
- }
673
- setSlackConnected(connected) {
674
- this.$session.setKey("slackConnected", connected);
675
- this.emitChange();
676
- }
677
- setGithubConnected(connected) {
678
- this.$session.setKey("githubConnected", connected);
679
- this.emitChange();
680
- }
681
- /**
682
- * Self-driving GitHub gate declined. Carries the outro the user lands on,
683
- * since declining ends the flow before the agent runs and there is no abort
684
- * case to render one.
685
- */
686
- declineGithub(outroData) {
687
- this.$session.setKey("githubDeclined", true);
688
- this.$session.setKey("outroData", outroData);
689
- this.emitChange();
690
- }
691
- /**
692
- * Self-driving integration-check answer. `true` → integrate the SDK as part
693
- * of this run; `false` → PostHog is already set up, go straight to
694
- * Self-driving. Resolves `session.integrate` from null.
695
- */
696
- setIntegrate(integrate, extra) {
697
- this.$session.setKey("integrate", integrate);
698
- analytics.wizardCapture("self-driving integration check", {
699
- self_driving_integrate: integrate,
700
- ...extra?.via ? { self_driving_integrate_via: extra.via } : {},
701
- ...extra?.path ? { self_driving_integrate_path: extra.path } : {},
702
- ...sessionProperties(this.session)
703
- });
704
- this.emitChange();
705
- }
706
- /**
707
- * Self-driving "no PostHog account" branch of the integration check. The
708
- * project has no SDK, so we always integrate (`integrate = true`); and since
709
- * the user has no account, we flip `signup` and record the `email` / `region`
710
- * collected on the screen so `authenticate` → `getOrAskForProjectData` takes
711
- * the provisioning path (create account + email a login link) instead of
712
- * OAuth. The "yes, I have an account" branch uses `setIntegrate(true)` and
713
- * leaves `signup` false so auth runs the normal OAuth login.
714
- */
715
- chooseProvisionAccount(email, region) {
716
- this.$session.setKey("signup", true);
717
- this.$session.setKey("email", email);
718
- this.$session.setKey("region", region);
719
- this.$session.setKey("integrate", true);
720
- analytics.wizardCapture("self-driving integration check", {
721
- self_driving_integrate: true,
722
- self_driving_has_account: false,
723
- provision_region: region,
724
- ...sessionProperties(this.session)
725
- });
726
- this.emitChange();
727
- }
728
- /**
729
- * Self-driving handoff confirmed — the user acknowledged the post-integration
730
- * screen, so the Self-driving run can begin. Gate resolves via _checkGates().
731
- */
732
- confirmSelfDrivingHandoff() {
733
- this.$session.setKey("selfDrivingHandoffConfirmed", true);
734
- this.emitChange();
735
- }
736
- /**
737
- * Mark a composed run step complete (e.g. self-driving's `integrate-run`).
738
- * Records the step id so its `isComplete` predicate holds, clears the task
739
- * list, and resets run phase to Idle so the next run step starts fresh.
740
- */
741
- completeRunStep(stepId) {
742
- const done = this.session.completedRuns;
743
- if (!done.includes(stepId)) this.$session.setKey("completedRuns", [...done, stepId]);
744
- this.$tasks.set([]);
745
- this.setRunPhase("idle");
746
- }
747
- setOutroDismissed(dismissed = true) {
748
- this.$session.setKey("outroDismissed", dismissed);
749
- this.emitChange();
750
- }
751
- setOutroData(data) {
752
- this.$session.setKey("outroData", data);
753
- this.emitChange();
754
- }
755
- setDashboardUrl(url) {
756
- logToFile(`store.setDashboardUrl: ${url}`);
757
- this.$session.setKey("dashboardUrl", url);
758
- this.emitChange();
759
- }
760
- setNotebookUrl(url) {
761
- logToFile(`store.setNotebookUrl: ${url}`);
762
- this.$session.setKey("notebookUrl", url);
763
- this.emitChange();
764
- }
765
- setFrameworkContext(key, value) {
766
- const ctx = {
767
- ...this.$session.get().frameworkContext,
768
- [key]: value
769
- };
770
- this.$session.setKey("frameworkContext", ctx);
771
- this.emitChange();
772
- }
773
- switchProgram(program) {
774
- if (program === this.router.activeProgram) return;
775
- for (const gate of this._gates.values()) gate.resolve();
776
- this._gates.clear();
777
- this.router.setProgram(program);
778
- this._initFromProgram(program);
779
- analytics.setTag("program_id", program);
780
- const config = getProgramConfig(program);
781
- this.$session.setKey("setupConfirmed", false);
782
- this.$session.setKey("programLabel", config.id);
783
- this.$session.setKey("skillId", config.skillId ?? null);
784
- this.emitChange();
785
- }
786
- /**
787
- * The screen that should be rendered right now.
788
- * Derived from session state via the router.
789
- */
790
- get currentScreen() {
791
- return this.router.resolve(this.session);
792
- }
793
- /** Direction hint for screen transitions. */
794
- get lastNavDirection() {
795
- return this.router.lastNavDirection;
796
- }
797
- getVersion() {
798
- return this.$version.get();
799
- }
800
- /**
801
- * Notify React that state has changed.
802
- * The router re-resolves the active screen on next render.
803
- * Gate predicates are checked and resolved if ready.
804
- */
805
- emitChange() {
806
- this.router._setDirection("push");
807
- this.$version.set(this.$version.get() + 1);
808
- this._checkGates();
809
- this._detectTransition();
810
- }
811
- pushOverlay(overlay) {
812
- this.router._setDirection("push");
813
- this.router.pushOverlay(overlay);
814
- this.$version.set(this.$version.get() + 1);
815
- this._detectTransition();
816
- }
817
- popOverlay() {
818
- this.router._setDirection("pop");
819
- this.router.popOverlay();
820
- this.$version.set(this.$version.get() + 1);
821
- this._detectTransition();
822
- }
823
- /**
824
- * Register a callback to run when transitioning onto the given screen.
825
- * Fires after every transition that lands on this screen.
826
- */
827
- onEnterScreen(screen, fn) {
828
- const list = this._enterScreenHooks.get(screen) ?? [];
829
- list.push(fn);
830
- this._enterScreenHooks.set(screen, list);
831
- }
832
- /**
833
- * The program `screen` reports under — its step's `reportsAsProgramId` if it
834
- * claims one, else the running program (also the fallback for overlays and
835
- * screens with no owning step).
836
- */
837
- _programIdForScreen(screen) {
838
- const program = this.router.activeProgram;
839
- return getProgramConfig(program).steps.find((s) => s.screenId === screen)?.reportsAsProgramId ?? program;
840
- }
841
- /** The program the visible screen reports under; screens stamp this on their
842
- * own events rather than relying on the run-level `program_id` tag. */
843
- get analyticsProgramId() {
844
- return this._programIdForScreen(this.router.resolve(this.session));
845
- }
846
- /**
847
- * Detect screen transitions, run enter-screen hooks, and fire analytics.
848
- * Called at the end of emitChange/pushOverlay/popOverlay.
849
- */
850
- _detectTransition() {
851
- const next = this.router.resolve(this.session);
852
- const prev = this._lastScreen;
853
- if (next !== prev) analytics.setTag("$screen_name", next);
854
- if (prev !== null && next !== prev) {
855
- const hooks = this._enterScreenHooks.get(next);
856
- if (hooks) for (const fn of hooks) fn();
857
- analytics.wizardCapture(`screen ${next}`, {
858
- from_screen: prev,
859
- program_id: this._programIdForScreen(next),
860
- ...sessionProperties(this.session)
861
- });
862
- }
863
- this._lastScreen = next;
864
- }
865
- pushStatus(message) {
866
- const msgs = this.$statusMessages.get();
867
- const next = appendStatus(msgs, message);
868
- if (next === msgs) return;
869
- this.$statusMessages.set(next);
870
- this.emitChange();
871
- }
872
- get tokenUsage() {
873
- return this.$tokenUsage.get();
874
- }
875
- get tokenHudVisible() {
876
- return this.$tokenHudVisible.get();
877
- }
878
- /** Hidden Ctrl+T shortcut — see ScreenContainer. Not registered as a
879
- * keyboard hint, so it never shows in the hints bar. */
880
- toggleTokenHud() {
881
- this.$tokenHudVisible.set(!this.$tokenHudVisible.get());
882
- this.emitChange();
883
- }
884
- /**
885
- * Accumulate one assistant turn's token usage into the running estimate.
886
- * Approximate by design (no dedup for SDK-retried/replayed turns, unlike
887
- * the benchmark middleware's TurnCounterPlugin) — it's a live indicator
888
- * for a hidden debug HUD, not a billing record, and `setFinalTokenCostUsd`
889
- * corrects the total once the run's authoritative cost is known.
890
- */
891
- addTokenUsage(delta) {
892
- const cur = this.$tokenUsage.get();
893
- if (cur.costIsFinal) return;
894
- const deltaCostUsd = computeTokenCostUsd(delta);
895
- this.$tokenUsage.set({
896
- inputTokens: cur.inputTokens + delta.inputTokens,
897
- outputTokens: cur.outputTokens + delta.outputTokens,
898
- cacheReadTokens: cur.cacheReadTokens + delta.cacheReadTokens,
899
- cacheCreationTokens: cur.cacheCreationTokens + delta.cacheCreationTokens,
900
- costUsd: cur.costUsd + deltaCostUsd,
901
- costIsFinal: false
902
- });
903
- this.emitChange();
904
- }
905
- /** Reconcile the running cost estimate to the SDK's authoritative total
906
- * once the agent run completes — same trick the benchmark's
907
- * CostTrackerPlugin.onFinalize uses to correct any per-turn drift. */
908
- setFinalTokenCostUsd(costUsd) {
909
- const cur = this.$tokenUsage.get();
910
- this.$tokenUsage.set({
911
- ...cur,
912
- costUsd,
913
- costIsFinal: true
914
- });
915
- this.emitChange();
916
- }
917
- setTasks(tasks) {
918
- this.$tasks.set(tasks);
919
- this.emitChange();
920
- }
921
- updateTask(index, done) {
922
- const tasks = this.$tasks.get();
923
- if (tasks[index]) {
924
- const updated = [...tasks];
925
- updated[index] = {
926
- ...updated[index],
927
- done,
928
- status: done ? "completed" : "pending"
929
- };
930
- this.$tasks.set(updated);
931
- this.emitChange();
932
- }
933
- }
934
- setEventPlan(events) {
935
- this.$eventPlan.set(events);
936
- this.emitChange();
937
- }
938
- /** No-op on identical text: an emit here means a network push downstream. */
939
- setHandoffText(text) {
940
- if (this.$handoffText.get() === text) return;
941
- logToFile(`store.setHandoffText: ${text.length} chars`);
942
- this.$handoffText.set(text);
943
- this.emitChange();
944
- }
945
- get learnCardBlockIdx() {
946
- return this.$learnCardBlockIdx.get();
947
- }
948
- setLearnCardBlockIdx(idx) {
949
- this.$learnCardBlockIdx.set(idx);
950
- }
951
- get learnCardComplete() {
952
- return this.$learnCardComplete.get();
953
- }
954
- setLearnCardComplete() {
955
- this.$learnCardComplete.set(true);
956
- this.emitChange();
957
- }
958
- syncTodos(todos) {
959
- const incoming = todos.map((t) => {
960
- const status = isTaskStatus(t.status) ? t.status : "pending";
961
- return {
962
- id: t.id,
963
- source: t.source,
964
- sourceStatus: isTaskStatus(t.status) ? void 0 : t.status,
965
- label: t.content,
966
- activeForm: t.activeForm,
967
- status,
968
- done: status === "completed"
969
- };
970
- });
971
- const incomingLabels = new Set(incoming.map((t) => t.label));
972
- const sources = new Set(todos.map((t) => t.source));
973
- const retained = this.$tasks.get().filter((t) => (t.status === "completed" || t.status === "failed" || t.status === "skipped") && (t.source ? !sources.has(t.source) : !incomingLabels.has(t.label)));
974
- this.$tasks.set([...retained, ...incoming]);
975
- this.emitChange();
976
- this._onTasksChanged?.();
977
- }
978
- /** Register a listener for task state changes (e.g. task stream push). */
979
- set onTasksChanged(fn) {
980
- this._onTasksChanged = fn;
981
- }
982
- subscribe(callback) {
983
- return this.$version.listen(() => callback());
984
- }
985
- getSnapshot() {
986
- return this.$version.get();
987
- }
988
- };
989
- //#endregion
990
- export { totalTokenCount as n, WizardStore as t };
991
-
992
- //# sourceMappingURL=store-BTzcvRGT.js.map