@posthog/wizard 2.79.0 → 2.80.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 (186) hide show
  1. package/dist/PickerMenu-m4CCPX4f.js +758 -0
  2. package/dist/PickerMenu-m4CCPX4f.js.map +1 -0
  3. package/dist/{agent-CNrEC-9v.js → agent-BkBbVuNq.js} +50 -45
  4. package/dist/agent-BkBbVuNq.js.map +1 -0
  5. package/dist/agent-QGK2YzlX.js +6 -0
  6. package/dist/{agent-interface-BXvmAm4c.js → agent-interface-CzyCmp7q.js} +87 -38
  7. package/dist/agent-interface-CzyCmp7q.js.map +1 -0
  8. package/dist/{agent-prompt-loader-DiKUbhi_.js → agent-prompt-loader-4wMxlYSX.js} +5 -5
  9. package/dist/{agent-prompt-loader-DiKUbhi_.js.map → agent-prompt-loader-4wMxlYSX.js.map} +1 -1
  10. package/dist/{analytics-VRYdebXW.js → analytics-B6q5PN7a.js} +5 -5
  11. package/dist/analytics-B6q5PN7a.js.map +1 -0
  12. package/dist/analytics-BXtfK9o7.js +2 -0
  13. package/dist/{api-DGuJTzjr.js → api-C3Dc4LFl.js} +4 -16
  14. package/dist/{api-DGuJTzjr.js.map → api-C3Dc4LFl.js.map} +1 -1
  15. package/dist/api-yNjrfZs2.js +2 -0
  16. package/dist/bin.js +5 -2960
  17. package/dist/bin.js.map +1 -1
  18. package/dist/{bounded-fs-Cpn129A4.js → bounded-fs-CC_NDtoP.js} +3 -3
  19. package/dist/{bounded-fs-Cpn129A4.js.map → bounded-fs-CC_NDtoP.js.map} +1 -1
  20. package/dist/check-screens.tsx +5 -5
  21. package/dist/{ci-install-BPA6gzEq.js → ci-install-DfcAMhlu.js} +9 -8
  22. package/dist/ci-install-DfcAMhlu.js.map +1 -0
  23. package/dist/{constants-CuJfQEcC.js → constants-DO4X70po.js} +3 -3
  24. package/dist/{constants-CuJfQEcC.js.map → constants-DO4X70po.js.map} +1 -1
  25. package/dist/{debug-B9k4ideV.js → debug-BueK5mRR.js} +1 -1
  26. package/dist/{debug-Cj-8vfXY.js → debug-DyARf5TF.js} +3 -3
  27. package/dist/debug-DyARf5TF.js.map +1 -0
  28. package/dist/{defaults-C6J7yL4O.js → defaults-DpfMnH2q.js} +2 -2
  29. package/dist/defaults-DpfMnH2q.js.map +1 -0
  30. package/dist/emit-BSetXzDV.js +69 -0
  31. package/dist/emit-BSetXzDV.js.map +1 -0
  32. package/dist/{endpoints-DnIX0pZH.js → endpoints-D-4KxZiB.js} +3 -3
  33. package/dist/{endpoints-DnIX0pZH.js.map → endpoints-D-4KxZiB.js.map} +1 -1
  34. package/dist/env-api-key-CHGLe0iz.js +2 -0
  35. package/dist/{env-api-key-BWdKpGEr.js → env-api-key-COf0U-Au.js} +3 -5
  36. package/dist/{env-api-key-BWdKpGEr.js.map → env-api-key-COf0U-Au.js.map} +1 -1
  37. package/dist/{environment-DZYUSCpV.js → environment-DrLaSsA8.js} +5 -10
  38. package/dist/{environment-DZYUSCpV.js.map → environment-DrLaSsA8.js.map} +1 -1
  39. package/dist/environment-hBj7ngmO.js +2 -0
  40. package/dist/{errors-ddDE6MbA.js → errors-C2domSkK.js} +3 -67
  41. package/dist/errors-C2domSkK.js.map +1 -0
  42. package/dist/{file-dEhr-l3n.js → file-CVA9ocIC.js} +4 -4
  43. package/dist/file-CVA9ocIC.js.map +1 -0
  44. package/dist/file-CmoKK_Pp.js +2 -0
  45. package/dist/{file-watcher-CPM-Nn9L.js → file-watcher-C3Su8vXm.js} +3 -3
  46. package/dist/file-watcher-C3Su8vXm.js.map +1 -0
  47. package/dist/{gateway-CVU1G0H3.js → gateway-BmjYUSua.js} +8 -7
  48. package/dist/{gateway-CVU1G0H3.js.map → gateway-BmjYUSua.js.map} +1 -1
  49. package/dist/{headless-ui-pY2xB5ug.js → headless-ui-CUbv12Yx.js} +3 -3
  50. package/dist/headless-ui-CUbv12Yx.js.map +1 -0
  51. package/dist/host-resolution-DVSb7kXb.js +114 -0
  52. package/dist/host-resolution-DVSb7kXb.js.map +1 -0
  53. package/dist/{add-mcp-server-to-clients-amlJWW7W.js → install-Bk5TNk27.js} +16 -26
  54. package/dist/install-Bk5TNk27.js.map +1 -0
  55. package/dist/install-F4wm3RSl.js +2 -0
  56. package/dist/interactive-C5LNvDj6.js +11 -0
  57. package/dist/interactive-C5LNvDj6.js.map +1 -0
  58. package/dist/{telemetry-Bpv-Mh5B.js → links-9LWZPSCq.js} +4 -13
  59. package/dist/links-9LWZPSCq.js.map +1 -0
  60. package/dist/{logging-ui-CUxNYF2t.js → logging-ui-p6XKVmTx.js} +6 -6
  61. package/dist/logging-ui-p6XKVmTx.js.map +1 -0
  62. package/dist/main-DKPjFHEV.js +1404 -0
  63. package/dist/main-DKPjFHEV.js.map +1 -0
  64. package/dist/{mcp-JcsBBnWv.js → mcp-Co8VRF62.js} +4 -4
  65. package/dist/{mcp-JcsBBnWv.js.map → mcp-Co8VRF62.js.map} +1 -1
  66. package/dist/mcp-install-smoke-test.ts +1 -1
  67. package/dist/{mcp-prompt-streaming-B-p_Pvb2.js → mcp-prompt-streaming-ljCVoQ9I.js} +6 -6
  68. package/dist/{mcp-prompt-streaming-B-p_Pvb2.js.map → mcp-prompt-streaming-ljCVoQ9I.js.map} +1 -1
  69. package/dist/{mint-failure-CZFZpHpW.js → mint-failure-C0HyvEwO.js} +105 -93
  70. package/dist/mint-failure-C0HyvEwO.js.map +1 -0
  71. package/dist/{models-DnAY67Lg.js → models-Dba8ITeo.js} +2 -2
  72. package/dist/{models-DnAY67Lg.js.map → models-Dba8ITeo.js.map} +1 -1
  73. package/dist/{non-interactive-DR1CWXY1.js → non-interactive-CLMJrj_7.js} +5 -4
  74. package/dist/non-interactive-CLMJrj_7.js.map +1 -0
  75. package/dist/{oauth-session-CQTFOk-I.js → oauth-session-D-RfcVmr.js} +2 -2
  76. package/dist/{oauth-session-CQTFOk-I.js.map → oauth-session-D-RfcVmr.js.map} +1 -1
  77. package/dist/{orchestrator-tools-CBdt-SXO.js → orchestrator-tools-CVJ1F9Ub.js} +3 -3
  78. package/dist/{orchestrator-tools-CBdt-SXO.js.map → orchestrator-tools-CVJ1F9Ub.js.map} +1 -1
  79. package/dist/package-json--ppioh2F.js +2 -0
  80. package/dist/{package-json-DY70kkNp.js → package-json-Cowya9-3.js} +2 -8
  81. package/dist/{package-json-DY70kkNp.js.map → package-json-Cowya9-3.js.map} +1 -1
  82. package/dist/{pi-BtqcLX3y.js → pi-B5YTBRDv.js} +20 -18
  83. package/dist/pi-B5YTBRDv.js.map +1 -0
  84. package/dist/{playground-Dz-ZVjBk.js → playground-BLsCfHmQ.js} +33 -33
  85. package/dist/playground-BLsCfHmQ.js.map +1 -0
  86. package/dist/posthog-B2E0hpZt.js +2 -0
  87. package/dist/{posthog-6Uqw_Eux.js → posthog-B42rt_1S.js} +4 -9
  88. package/dist/posthog-B42rt_1S.js.map +1 -0
  89. package/dist/project-data--L-WZyvj.js +2 -0
  90. package/dist/{setup-utils-dCViCC6s.js → project-data-BO9IXn9y.js} +566 -957
  91. package/dist/project-data-BO9IXn9y.js.map +1 -0
  92. package/dist/provisioning-C01REIU2.js +2 -0
  93. package/dist/{provisioning-Zf7yPcEs.js → provisioning-CLhuKqXH.js} +6 -73
  94. package/dist/provisioning-CLhuKqXH.js.map +1 -0
  95. package/dist/{queue-tools-B7_aCyd-.js → queue-tools-knnPQP0e.js} +4 -4
  96. package/dist/{queue-tools-B7_aCyd-.js.map → queue-tools-knnPQP0e.js.map} +1 -1
  97. package/dist/{registry-B6iLGorH.js → registry-B3rC5U4b.js} +7 -9
  98. package/dist/{registry-B6iLGorH.js.map → registry-B3rC5U4b.js.map} +1 -1
  99. package/dist/registry-BamsM7J9.js +2 -0
  100. package/dist/run-agent-legacy-CwUmPfQF.js +2 -0
  101. package/dist/{run-agent-legacy-6WcYMaR9.js → run-agent-legacy-DWBajsMh.js} +40 -114
  102. package/dist/run-agent-legacy-DWBajsMh.js.map +1 -0
  103. package/dist/runners-D1PqqpjA.js +834 -0
  104. package/dist/runners-D1PqqpjA.js.map +1 -0
  105. package/dist/{security-lkBwWbrK.js → security-BvdSFDuM.js} +5 -5
  106. package/dist/{security-lkBwWbrK.js.map → security-BvdSFDuM.js.map} +1 -1
  107. package/dist/setup-utils-ChXXTi1m.js +301 -0
  108. package/dist/setup-utils-ChXXTi1m.js.map +1 -0
  109. package/dist/{start-tui-oCWMgsDP.js → start-tui-DicLfgsj.js} +95 -91
  110. package/dist/start-tui-DicLfgsj.js.map +1 -0
  111. package/dist/{steps-gx0Pq4I4.js → steps-Hc28zVc_.js} +10 -10
  112. package/dist/steps-Hc28zVc_.js.map +1 -0
  113. package/dist/store-COCO6U0P.js +5 -0
  114. package/dist/{store-xYy_6Ruv.js → store-D3509G87.js} +67 -35
  115. package/dist/store-D3509G87.js.map +1 -0
  116. package/dist/{subagent-Bfy0sfhU.js → subagent-D_Sqak94.js} +3 -3
  117. package/dist/{subagent-Bfy0sfhU.js.map → subagent-D_Sqak94.js.map} +1 -1
  118. package/dist/{task-BOfw7GPc.js → task-DiTI6Sak.js} +19 -17
  119. package/dist/task-DiTI6Sak.js.map +1 -0
  120. package/dist/{wizard-ui-DoyOZxK8.js → task-status-CmrrR7zo.js} +2 -2
  121. package/dist/task-status-CmrrR7zo.js.map +1 -0
  122. package/dist/{task-stream-kYlm9qd0.js → task-stream-BckhG_cB.js} +11 -11
  123. package/dist/task-stream-BckhG_cB.js.map +1 -0
  124. package/dist/{tasks-Bbv_lOBG.js → tasks-ChZ_F1YP.js} +1 -1
  125. package/dist/{tasks-Bbv_lOBG.js.map → tasks-ChZ_F1YP.js.map} +1 -1
  126. package/dist/telemetry-BNKsDxNS.js +13 -0
  127. package/dist/telemetry-BNKsDxNS.js.map +1 -0
  128. package/dist/{terminal-D07EQ2y0.js → terminal-PK9bCLRi.js} +123 -97
  129. package/dist/terminal-PK9bCLRi.js.map +1 -0
  130. package/dist/{tools-Cc41af5W.js → tools-C8LQ8QFz.js} +9 -9
  131. package/dist/tools-C8LQ8QFz.js.map +1 -0
  132. package/dist/{ui-CGXtC7Vn.js → ui-tPNpM6vj.js} +3 -3
  133. package/dist/ui-tPNpM6vj.js.map +1 -0
  134. package/dist/urls-BI4kJ4qQ.js +67 -0
  135. package/dist/urls-BI4kJ4qQ.js.map +1 -0
  136. package/dist/{version-Cadof0Z_.js → version-5_ydHkM6.js} +2 -2
  137. package/dist/{version-Cadof0Z_.js.map → version-5_ydHkM6.js.map} +1 -1
  138. package/dist/wizard-abort-BVjqLyeA.js +3 -0
  139. package/dist/{wizard-abort-HDbP3YcS.js → wizard-abort-DBKtfnBR.js} +20 -17
  140. package/dist/wizard-abort-DBKtfnBR.js.map +1 -0
  141. package/dist/wizard-session-B7BHnay0.js +2 -0
  142. package/dist/{wizard-session-2w4Ru-Wz.js → wizard-session-BYw6LzpS.js} +30 -28
  143. package/dist/wizard-session-BYw6LzpS.js.map +1 -0
  144. package/dist/{yara-hooks-DCfROpZt.js → yara-hooks-C3L6lBij.js} +5 -5
  145. package/dist/{yara-hooks-DCfROpZt.js.map → yara-hooks-C3L6lBij.js.map} +1 -1
  146. package/dist/yara-hooks-CF_IsoaA.js +2 -0
  147. package/package.json +2 -3
  148. package/dist/add-mcp-server-to-clients-amlJWW7W.js.map +0 -1
  149. package/dist/agent-CNrEC-9v.js.map +0 -1
  150. package/dist/agent-interface-BXvmAm4c.js.map +0 -1
  151. package/dist/analytics-DxwRi2Hf.js +0 -2
  152. package/dist/analytics-VRYdebXW.js.map +0 -1
  153. package/dist/ci-install-BPA6gzEq.js.map +0 -1
  154. package/dist/debug-Cj-8vfXY.js.map +0 -1
  155. package/dist/defaults-C6J7yL4O.js.map +0 -1
  156. package/dist/errors-ddDE6MbA.js.map +0 -1
  157. package/dist/file-dEhr-l3n.js.map +0 -1
  158. package/dist/file-watcher-CPM-Nn9L.js.map +0 -1
  159. package/dist/headless-ui-pY2xB5ug.js.map +0 -1
  160. package/dist/interactive-BOGlinZe.js +0 -11
  161. package/dist/interactive-BOGlinZe.js.map +0 -1
  162. package/dist/logging-ui-CUxNYF2t.js.map +0 -1
  163. package/dist/mint-failure-CZFZpHpW.js.map +0 -1
  164. package/dist/non-interactive-DR1CWXY1.js.map +0 -1
  165. package/dist/pi-BtqcLX3y.js.map +0 -1
  166. package/dist/playground-Dz-ZVjBk.js.map +0 -1
  167. package/dist/posthog-6Uqw_Eux.js.map +0 -1
  168. package/dist/provisioning-Zf7yPcEs.js.map +0 -1
  169. package/dist/rolldown-runtime-B_-DWIq7.js +0 -15
  170. package/dist/run-agent-legacy-6WcYMaR9.js.map +0 -1
  171. package/dist/setup-utils-dCViCC6s.js.map +0 -1
  172. package/dist/start-tui-oCWMgsDP.js.map +0 -1
  173. package/dist/steps-gx0Pq4I4.js.map +0 -1
  174. package/dist/store-xYy_6Ruv.js.map +0 -1
  175. package/dist/task-BOfw7GPc.js.map +0 -1
  176. package/dist/task-stream-kYlm9qd0.js.map +0 -1
  177. package/dist/telemetry-Bpv-Mh5B.js.map +0 -1
  178. package/dist/terminal-D07EQ2y0.js.map +0 -1
  179. package/dist/tools-Cc41af5W.js.map +0 -1
  180. package/dist/ui-CGXtC7Vn.js.map +0 -1
  181. package/dist/wizard-abort-HDbP3YcS.js.map +0 -1
  182. package/dist/wizard-abort-Y-Ip2K4z.js +0 -3
  183. package/dist/wizard-session-2w4Ru-Wz.js.map +0 -1
  184. package/dist/wizard-session-DGaUHOF3.js +0 -2
  185. package/dist/wizard-ui-DoyOZxK8.js.map +0 -1
  186. package/dist/yara-hooks-B49RIk5d.js +0 -2
@@ -1,13 +1,8 @@
1
- import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
2
- import "./constants-CuJfQEcC.js";
3
- import "./bounded-fs-Cpn129A4.js";
4
- import "./setup-utils-dCViCC6s.js";
1
+ import "./constants-DO4X70po.js";
2
+ import "./bounded-fs-CC_NDtoP.js";
3
+ import "./setup-utils-ChXXTi1m.js";
5
4
  import readEnvModule from "read-env";
6
5
  //#region src/shared/utils/environment.ts
7
- var environment_exports = /* @__PURE__ */ __exportAll({
8
- isNonInteractiveEnvironment: () => isNonInteractiveEnvironment,
9
- readEnvironment: () => readEnvironment
10
- });
11
6
  const readEnv = typeof readEnvModule === "function" ? readEnvModule : readEnvModule.default;
12
7
  function isNonInteractiveEnvironment() {
13
8
  if (!process.stdout.isTTY || !process.stderr.isTTY) return true;
@@ -39,6 +34,6 @@ function readEnvironment() {
39
34
  return result;
40
35
  }
41
36
  //#endregion
42
- export { isNonInteractiveEnvironment as n, environment_exports as t };
37
+ export { readEnvironment as n, isNonInteractiveEnvironment as t };
43
38
 
44
- //# sourceMappingURL=environment-DZYUSCpV.js.map
39
+ //# sourceMappingURL=environment-DrLaSsA8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"environment-DZYUSCpV.js","names":[],"sources":["../src/shared/utils/environment.ts"],"sourcesContent":["import readEnvModule from 'read-env';\n\nconst readEnv =\n typeof readEnvModule === 'function'\n ? readEnvModule\n : (readEnvModule as any).default;\nimport { tryGetPackageJson } from './setup-utils';\nimport type { WizardRunOptions } from './types';\nimport { boundedGlob } from './bounded-fs';\nimport { IS_DEV } from '@shared/constants';\n\nexport function isNonInteractiveEnvironment(): boolean {\n if (IS_DEV) {\n return false;\n }\n\n if (!process.stdout.isTTY || !process.stderr.isTTY) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Session fields the environment must never set, matched case-insensitively\n * against the camel-cased key `read-env` produces.\n *\n * `e2eAsk` re-wires the `wizard_ask` bridge in an otherwise non-interactive\n * run. Only the e2e TUI host may set it: a real `--ci` run has nobody to answer,\n * so every question would stall for the bridge timeout instead of failing fast\n * with an actionable error. See `shouldDisableAsk`.\n */\nconst NEVER_FROM_ENV = ['e2eAsk', 'runId'];\n\n/**\n * Session args from the `POSTHOG_WIZARD_*` environment variables.\n *\n * `read-env` camel-cases every prefixed variable into a key, and the CI runner\n * spreads the whole bag into `buildSession` — so adding a field to the session\n * silently adds an environment variable that sets it. Most of them are meant to\n * work that way (`POSTHOG_WIZARD_DEBUG` → `debug`); the ones in\n * {@link NEVER_FROM_ENV} are not, and are dropped here rather than at the call\n * site, so a second caller cannot reopen the door.\n */\nexport function readEnvironment(): Record<string, unknown> {\n const result = readEnv('POSTHOG_WIZARD') as Record<string, unknown>;\n\n for (const key of Object.keys(result)) {\n if (NEVER_FROM_ENV.some((k) => k.toLowerCase() === key.toLowerCase())) {\n delete result[key];\n }\n }\n\n return result;\n}\n\nexport async function detectEnvVarPrefix(\n options: WizardRunOptions,\n): Promise<string> {\n const packageJson = await tryGetPackageJson(options);\n if (!packageJson) return 'VITE_PUBLIC_';\n\n const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };\n const has = (name: string) => name in deps;\n // O(1) matches per probe: one config file existing anywhere answers it.\n const hasAnyFile = async (patterns: string[]) => {\n const matches = await boundedGlob(patterns, {\n cwd: options.installDir,\n limit: 1,\n });\n return matches.length > 0;\n };\n\n // --- Next.js\n if (has('next') || (await hasAnyFile(['**/next.config.{js,ts,mjs,cjs}']))) {\n return 'NEXT_PUBLIC_';\n }\n\n // --- Create React App\n if (\n has('react-scripts') ||\n has('create-react-app') ||\n (await hasAnyFile(['**/config-overrides.js']))\n ) {\n return 'REACT_APP_';\n }\n\n // --- Vite (vanilla, TanStack, Solid, etc.)\n // Note: Vite does not need PUBLIC_ but we use it to follow the docs, to improve the chances of an LLM getting it right.\n if (has('vite') || (await hasAnyFile(['**/vite.config.{js,ts,mjs,cjs}']))) {\n return 'VITE_PUBLIC_';\n }\n\n // --- SvelteKit\n if (\n has('@sveltejs/kit') ||\n (await hasAnyFile(['**/svelte.config.{js,ts}']))\n ) {\n return 'PUBLIC_';\n }\n\n // --- TanStack Start (uses Vite)\n if (\n has('@tanstack/start') ||\n (await hasAnyFile(['**/tanstack.config.{js,ts}']))\n ) {\n return 'VITE_PUBLIC_';\n }\n\n // --- SolidStart (uses Vite)\n if (has('solid-start') || (await hasAnyFile(['**/solid.config.{js,ts}']))) {\n return 'VITE_PUBLIC_';\n }\n\n // --- Astro\n if (has('astro') || (await hasAnyFile(['**/astro.config.{js,ts,mjs}']))) {\n return 'PUBLIC_';\n }\n\n // We default to Vite if we can't detect a specific framework, since it's the most commonly used.\n return 'VITE_PUBLIC_';\n}\n"],"mappings":";;;;;;;;;;AAEA,MAAM,UACJ,OAAO,kBAAkB,aACrB,gBACC,cAAsB;AAM7B,SAAgB,8BAAuC;AAKrD,KAAI,CAAC,QAAQ,OAAO,SAAS,CAAC,QAAQ,OAAO,MAC3C,QAAO;AAGT,QAAO;;;;;;;;;;;AAYT,MAAM,iBAAiB,CAAC,UAAU,QAAQ;;;;;;;;;;;AAY1C,SAAgB,kBAA2C;CACzD,MAAM,SAAS,QAAQ,iBAAiB;AAExC,MAAK,MAAM,OAAO,OAAO,KAAK,OAAO,CACnC,KAAI,eAAe,MAAM,MAAM,EAAE,aAAa,KAAK,IAAI,aAAa,CAAC,CACnE,QAAO,OAAO;AAIlB,QAAO"}
1
+ {"version":3,"file":"environment-DrLaSsA8.js","names":[],"sources":["../src/shared/utils/environment.ts"],"sourcesContent":["import readEnvModule from 'read-env';\n\nconst readEnv =\n typeof readEnvModule === 'function'\n ? readEnvModule\n : (readEnvModule as any).default;\nimport { tryGetPackageJson } from './setup-utils';\nimport type { WizardRunOptions } from './types';\nimport { boundedGlob } from './bounded-fs';\nimport { IS_DEV } from '@shared/constants';\n\nexport function isNonInteractiveEnvironment(): boolean {\n if (IS_DEV) {\n return false;\n }\n\n if (!process.stdout.isTTY || !process.stderr.isTTY) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Session fields the environment must never set, matched case-insensitively\n * against the camel-cased key `read-env` produces.\n *\n * `e2eAsk` re-wires the `wizard_ask` bridge in an otherwise non-interactive\n * run. Only the e2e TUI host may set it: a real `--ci` run has nobody to answer,\n * so every question would stall for the bridge timeout instead of failing fast\n * with an actionable error. See `shouldDisableAsk`.\n */\nconst NEVER_FROM_ENV = ['e2eAsk', 'runId'];\n\n/**\n * Session args from the `POSTHOG_WIZARD_*` environment variables.\n *\n * `read-env` camel-cases every prefixed variable into a key, and the CI runner\n * spreads the whole bag into `buildSession` — so adding a field to the session\n * silently adds an environment variable that sets it. Most of them are meant to\n * work that way (`POSTHOG_WIZARD_DEBUG` → `debug`); the ones in\n * {@link NEVER_FROM_ENV} are not, and are dropped here rather than at the call\n * site, so a second caller cannot reopen the door.\n */\nexport function readEnvironment(): Record<string, unknown> {\n const result = readEnv('POSTHOG_WIZARD') as Record<string, unknown>;\n\n for (const key of Object.keys(result)) {\n if (NEVER_FROM_ENV.some((k) => k.toLowerCase() === key.toLowerCase())) {\n delete result[key];\n }\n }\n\n return result;\n}\n\nexport async function detectEnvVarPrefix(\n options: WizardRunOptions,\n): Promise<string> {\n const packageJson = await tryGetPackageJson(options);\n if (!packageJson) return 'VITE_PUBLIC_';\n\n const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };\n const has = (name: string) => name in deps;\n // O(1) matches per probe: one config file existing anywhere answers it.\n const hasAnyFile = async (patterns: string[]) => {\n const matches = await boundedGlob(patterns, {\n cwd: options.installDir,\n limit: 1,\n });\n return matches.length > 0;\n };\n\n // --- Next.js\n if (has('next') || (await hasAnyFile(['**/next.config.{js,ts,mjs,cjs}']))) {\n return 'NEXT_PUBLIC_';\n }\n\n // --- Create React App\n if (\n has('react-scripts') ||\n has('create-react-app') ||\n (await hasAnyFile(['**/config-overrides.js']))\n ) {\n return 'REACT_APP_';\n }\n\n // --- Vite (vanilla, TanStack, Solid, etc.)\n // Note: Vite does not need PUBLIC_ but we use it to follow the docs, to improve the chances of an LLM getting it right.\n if (has('vite') || (await hasAnyFile(['**/vite.config.{js,ts,mjs,cjs}']))) {\n return 'VITE_PUBLIC_';\n }\n\n // --- SvelteKit\n if (\n has('@sveltejs/kit') ||\n (await hasAnyFile(['**/svelte.config.{js,ts}']))\n ) {\n return 'PUBLIC_';\n }\n\n // --- TanStack Start (uses Vite)\n if (\n has('@tanstack/start') ||\n (await hasAnyFile(['**/tanstack.config.{js,ts}']))\n ) {\n return 'VITE_PUBLIC_';\n }\n\n // --- SolidStart (uses Vite)\n if (has('solid-start') || (await hasAnyFile(['**/solid.config.{js,ts}']))) {\n return 'VITE_PUBLIC_';\n }\n\n // --- Astro\n if (has('astro') || (await hasAnyFile(['**/astro.config.{js,ts,mjs}']))) {\n return 'PUBLIC_';\n }\n\n // We default to Vite if we can't detect a specific framework, since it's the most commonly used.\n return 'VITE_PUBLIC_';\n}\n"],"mappings":";;;;;AAEA,MAAM,UACJ,OAAO,kBAAkB,aACrB,gBACC,cAAsB;AAM7B,SAAgB,8BAAuC;AAKrD,KAAI,CAAC,QAAQ,OAAO,SAAS,CAAC,QAAQ,OAAO,MAC3C,QAAO;AAGT,QAAO;;;;;;;;;;;AAYT,MAAM,iBAAiB,CAAC,UAAU,QAAQ;;;;;;;;;;;AAY1C,SAAgB,kBAA2C;CACzD,MAAM,SAAS,QAAQ,iBAAiB;AAExC,MAAK,MAAM,OAAO,OAAO,KAAK,OAAO,CACnC,KAAI,eAAe,MAAM,MAAM,EAAE,aAAa,KAAK,IAAI,aAAa,CAAC,CACnE,QAAO,OAAO;AAIlB,QAAO"}
@@ -0,0 +1,2 @@
1
+ import { n as readEnvironment } from "./environment-DrLaSsA8.js";
2
+ export { readEnvironment };
@@ -1,68 +1,4 @@
1
- //#region src/shared/errors/codes.ts
2
- const ErrorCodes = {
3
- CliNodeVersion: "PHW_CLI_NODE_VERSION",
4
- CliBadArgs: "PHW_CLI_BAD_ARGS",
5
- CliFlagUnavailable: "PHW_CLI_FLAG_UNAVAILABLE",
6
- CliInteractiveRequired: "PHW_CLI_INTERACTIVE_REQUIRED",
7
- ArgsMissingApiKey: "PHW_ARGS_MISSING_API_KEY",
8
- ArgsMissingInstallDir: "PHW_ARGS_MISSING_INSTALL_DIR",
9
- ArgsMissingEmail: "PHW_ARGS_MISSING_EMAIL",
10
- ArgsSignupProvisionFailed: "PHW_ARGS_SIGNUP_PROVISION_FAILED",
11
- AuthKeyType: "PHW_AUTH_KEY_TYPE",
12
- AuthMissingScope: "PHW_AUTH_MISSING_SCOPE",
13
- AuthRegionMismatch: "PHW_AUTH_REGION_MISMATCH",
14
- AuthInvalidOrExpired: "PHW_AUTH_INVALID_OR_EXPIRED",
15
- AuthSessionExpired: "PHW_AUTH_SESSION_EXPIRED",
16
- AuthSettingsConflict: "PHW_AUTH_SETTINGS_CONFLICT",
17
- AuthStoredLoginConflict: "PHW_AUTH_STORED_LOGIN_CONFLICT",
18
- AuthProjectFetchFailed: "PHW_AUTH_PROJECT_FETCH_FAILED",
19
- EnvLocalServicesDown: "PHW_ENV_LOCAL_SERVICES_DOWN",
20
- EnvServiceOutage: "PHW_ENV_SERVICE_OUTAGE",
21
- DetectBadDirectory: "PHW_DETECT_BAD_DIRECTORY",
22
- DetectNoFramework: "PHW_DETECT_NO_FRAMEWORK",
23
- DetectUnsupportedVersion: "PHW_DETECT_UNSUPPORTED_VERSION",
24
- DetectUnsupportedPlatform: "PHW_DETECT_UNSUPPORTED_PLATFORM",
25
- DetectNoPosthogSdk: "PHW_DETECT_NO_POSTHOG_SDK",
26
- DetectNoProjectFiles: "PHW_DETECT_NO_PROJECT_FILES",
27
- DetectNoSources: "PHW_DETECT_NO_SOURCES",
28
- DetectNoPackageJson: "PHW_DETECT_NO_PACKAGE_JSON",
29
- DetectNoSdks: "PHW_DETECT_NO_SDKS",
30
- DetectMissingStripe: "PHW_DETECT_MISSING_STRIPE",
31
- DetectUnclassified: "PHW_DETECT_UNCLASSIFIED",
32
- SkillMenuFetchFailed: "PHW_SKILL_MENU_FETCH_FAILED",
33
- SkillNotFound: "PHW_SKILL_NOT_FOUND",
34
- SkillDownloadFailed: "PHW_SKILL_DOWNLOAD_FAILED",
35
- AgentAbort: "PHW_AGENT_ABORT",
36
- AgenticDetectionTimeout: "PHW_AGENTIC_DETECTION_TIMEOUT",
37
- AgentMcpMissing: "PHW_AGENT_MCP_MISSING",
38
- AgentResourceMissing: "PHW_AGENT_RESOURCE_MISSING",
39
- AgentRateLimit: "PHW_AGENT_RATE_LIMIT",
40
- AgentApiError: "PHW_AGENT_API_ERROR",
41
- AgentYaraViolation: "PHW_AGENT_YARA_VIOLATION",
42
- AgentNoProgress: "PHW_AGENT_NO_PROGRESS",
43
- AgentInvalidStructuredOutput: "PHW_AGENT_INVALID_STRUCTURED_OUTPUT",
44
- AgentIncompleteTasks: "PHW_AGENT_INCOMPLETE_TASKS",
45
- AgentOrchestratorSkillVariantMissing: "PHW_AGENT_ORCHESTRATOR_SKILL_VARIANT_MISSING",
46
- AgentOrchestratorTasksFailed: "PHW_AGENT_ORCHESTRATOR_TASKS_FAILED",
47
- AgentOrchestratorHollowRun: "PHW_AGENT_ORCHESTRATOR_HOLLOW_RUN",
48
- AgentOrchestratorSinkInvariant: "PHW_AGENT_ORCHESTRATOR_SINK_INVARIANT",
49
- GatewayMintRefused: "PHW_GATEWAY_MINT_REFUSED",
50
- GatewayMintFailed: "PHW_GATEWAY_MINT_FAILED",
51
- SettingsUnfixableConflict: "PHW_SETTINGS_UNFIXABLE_CONFLICT",
52
- InternalUnhandled: "PHW_INTERNAL_UNHANDLED"
53
- };
54
- function isErrorCode(value) {
55
- return Object.values(ErrorCodes).includes(value);
56
- }
57
- //#endregion
58
- //#region src/shared/errors/emit.ts
59
- const PHW_ERROR_PREFIX = "phw-error:";
60
- function formatWizardErrorLine(line) {
61
- return `${PHW_ERROR_PREFIX} ${JSON.stringify(line)}`;
62
- }
63
- function emitWizardError(line) {
64
- process.stderr.write(`${formatWizardErrorLine(line)}\n`);
65
- }
1
+ import { n as ErrorCodes, r as isErrorCode } from "./emit-BSetXzDV.js";
66
2
  ErrorCodes.CliNodeVersion, ErrorCodes.CliBadArgs, ErrorCodes.CliFlagUnavailable, ErrorCodes.CliInteractiveRequired, ErrorCodes.ArgsMissingApiKey, ErrorCodes.ArgsMissingInstallDir, ErrorCodes.ArgsMissingEmail, ErrorCodes.ArgsSignupProvisionFailed, ErrorCodes.AuthKeyType, ErrorCodes.AuthInvalidOrExpired, ErrorCodes.AuthSessionExpired, ErrorCodes.AuthMissingScope, ErrorCodes.AuthRegionMismatch, ErrorCodes.AuthSettingsConflict, ErrorCodes.AuthStoredLoginConflict, ErrorCodes.AuthProjectFetchFailed, ErrorCodes.EnvLocalServicesDown, ErrorCodes.EnvServiceOutage, ErrorCodes.DetectBadDirectory, ErrorCodes.DetectNoFramework, ErrorCodes.DetectUnsupportedVersion, ErrorCodes.DetectUnsupportedPlatform, ErrorCodes.DetectNoPosthogSdk, ErrorCodes.DetectNoProjectFiles, ErrorCodes.DetectNoSources, ErrorCodes.DetectNoPackageJson, ErrorCodes.DetectNoSdks, ErrorCodes.DetectMissingStripe, ErrorCodes.DetectUnclassified, ErrorCodes.SkillMenuFetchFailed, ErrorCodes.SkillNotFound, ErrorCodes.SkillDownloadFailed, ErrorCodes.AgentAbort, ErrorCodes.AgenticDetectionTimeout, ErrorCodes.AgentMcpMissing, ErrorCodes.AgentResourceMissing, ErrorCodes.AgentRateLimit, ErrorCodes.AgentApiError, ErrorCodes.AgentYaraViolation, ErrorCodes.AgentNoProgress, ErrorCodes.AgentInvalidStructuredOutput, ErrorCodes.AgentIncompleteTasks, ErrorCodes.AgentOrchestratorSkillVariantMissing, ErrorCodes.AgentOrchestratorTasksFailed, ErrorCodes.AgentOrchestratorHollowRun, ErrorCodes.AgentOrchestratorSinkInvariant, ErrorCodes.GatewayMintRefused, ErrorCodes.GatewayMintFailed, ErrorCodes.SettingsUnfixableConflict, ErrorCodes.InternalUnhandled;
67
3
  //#endregion
68
4
  //#region src/shared/errors/wizard-error.ts
@@ -138,6 +74,6 @@ function classifyRunFailure(err) {
138
74
  };
139
75
  }
140
76
  //#endregion
141
- export { WizardError as a, classifyAuthFailure as i, sanitizeErrorDetail as n, emitWizardError as o, skillErrorCode as r, ErrorCodes as s, classifyRunFailure as t };
77
+ export { WizardError as a, classifyAuthFailure as i, sanitizeErrorDetail as n, skillErrorCode as r, classifyRunFailure as t };
142
78
 
143
- //# sourceMappingURL=errors-ddDE6MbA.js.map
79
+ //# sourceMappingURL=errors-C2domSkK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-C2domSkK.js","names":[],"sources":["../src/shared/errors/catalog.ts","../src/shared/errors/wizard-error.ts","../src/shared/errors/auth.ts","../src/shared/errors/skill-map.ts","../src/shared/errors/sanitize.ts","../src/shared/errors/run-failure.ts"],"sourcesContent":["import { ErrorCodes, type ErrorCode } from './codes';\nimport type { ErrorCatalogEntry } from './types';\n\nexport const ERROR_CATALOG: Record<ErrorCode, ErrorCatalogEntry> = {\n [ErrorCodes.CliNodeVersion]: {\n group: 'cli',\n retry: 'no',\n description: 'Node.js runtime is older than the required range.',\n },\n [ErrorCodes.CliBadArgs]: {\n group: 'cli',\n retry: 'no',\n description: 'Unrecognized command or option.',\n },\n [ErrorCodes.CliFlagUnavailable]: {\n group: 'cli',\n retry: 'no',\n description: 'A dev-only flag or env var was passed to a published build.',\n },\n [ErrorCodes.CliInteractiveRequired]: {\n group: 'cli',\n retry: 'no',\n description:\n 'The command requires an interactive terminal and has no non-interactive fallback.',\n },\n [ErrorCodes.ArgsMissingApiKey]: {\n group: 'args',\n retry: 'no',\n description: 'Non-interactive run without --api-key.',\n },\n [ErrorCodes.ArgsMissingInstallDir]: {\n group: 'args',\n retry: 'no',\n description: 'Non-interactive run without --install-dir.',\n },\n [ErrorCodes.ArgsMissingEmail]: {\n group: 'args',\n retry: 'no',\n description: 'Signup run without --email.',\n },\n [ErrorCodes.ArgsSignupProvisionFailed]: {\n group: 'args',\n retry: 'yes',\n description: 'Account provisioning for --signup failed.',\n },\n [ErrorCodes.AuthKeyType]: {\n group: 'auth',\n retry: 'no',\n description: 'The API key has the wrong type or prefix for this mode.',\n },\n [ErrorCodes.AuthInvalidOrExpired]: {\n group: 'auth',\n retry: 'no',\n description: 'The credential was rejected by the LLM gateway or API.',\n },\n [ErrorCodes.AuthSessionExpired]: {\n group: 'auth',\n // Retryable, unlike its neighbours: a new run means a new login.\n retry: 'yes',\n description: 'The OAuth grant expired or was revoked mid-run.',\n },\n [ErrorCodes.AuthMissingScope]: {\n group: 'auth',\n retry: 'no',\n description: 'The personal API key lacks a scope the run requires.',\n },\n [ErrorCodes.AuthRegionMismatch]: {\n group: 'auth',\n retry: 'no',\n description: 'The resolved region does not match the credential.',\n },\n [ErrorCodes.AuthSettingsConflict]: {\n group: 'auth',\n retry: 'no',\n description: 'A Claude settings file overrides the gateway credential.',\n },\n [ErrorCodes.AuthStoredLoginConflict]: {\n group: 'auth',\n retry: 'no',\n description:\n 'The agent SDK used a stored Claude login instead of the gateway token.',\n },\n [ErrorCodes.AuthProjectFetchFailed]: {\n group: 'auth',\n retry: 'yes',\n description: 'Fetching user or project data from the PostHog API failed.',\n },\n [ErrorCodes.EnvLocalServicesDown]: {\n group: 'env',\n retry: 'yes',\n description: 'A local dev target service is not running.',\n },\n [ErrorCodes.EnvServiceOutage]: {\n group: 'env',\n retry: 'yes',\n description: 'Blocking external services are down.',\n },\n [ErrorCodes.DetectBadDirectory]: {\n group: 'detect',\n retry: 'no',\n description:\n 'The install directory is missing, not a directory, or unreadable.',\n },\n [ErrorCodes.DetectNoFramework]: {\n group: 'detect',\n retry: 'no',\n description: 'Framework auto-detection found no supported framework.',\n },\n [ErrorCodes.DetectUnsupportedVersion]: {\n group: 'detect',\n retry: 'no',\n description:\n 'The detected framework version is below the supported minimum.',\n },\n [ErrorCodes.DetectUnsupportedPlatform]: {\n group: 'detect',\n retry: 'no',\n description: 'The project platform has no matching skill variant.',\n },\n [ErrorCodes.DetectNoPosthogSdk]: {\n group: 'detect',\n retry: 'no',\n description:\n 'The program requires an installed PostHog SDK and none was found.',\n },\n [ErrorCodes.DetectNoProjectFiles]: {\n group: 'detect',\n retry: 'no',\n description: 'The project has no files for the program to work on.',\n },\n [ErrorCodes.DetectNoSources]: {\n group: 'detect',\n retry: 'no',\n description: 'No data warehouse sources were found.',\n },\n [ErrorCodes.DetectNoPackageJson]: {\n group: 'detect',\n retry: 'no',\n description: 'The project has no package.json for the program to scan.',\n },\n [ErrorCodes.DetectNoSdks]: {\n group: 'detect',\n retry: 'no',\n description: 'None of the SDKs the program needs are installed.',\n },\n [ErrorCodes.DetectMissingStripe]: {\n group: 'detect',\n retry: 'no',\n description: 'Revenue analytics requires a Stripe SDK and none was found.',\n },\n [ErrorCodes.DetectUnclassified]: {\n group: 'detect',\n // A detect step reported a precondition failure we have no code for yet.\n // Every known cause is a property of the user's project, so retrying can\n // only burn budget — fail closed rather than inheriting `internal`'s 'yes'.\n retry: 'no',\n description: 'A detect step failed with a kind absent from the catalog.',\n },\n [ErrorCodes.SkillMenuFetchFailed]: {\n group: 'skill',\n retry: 'yes',\n description: 'The context-mill skill menu could not be fetched.',\n },\n [ErrorCodes.SkillNotFound]: {\n group: 'skill',\n retry: 'no',\n description: 'The skill id is absent from the context-mill menu.',\n },\n [ErrorCodes.SkillDownloadFailed]: {\n group: 'skill',\n retry: 'yes',\n description: 'The skill download or extraction failed.',\n },\n [ErrorCodes.AgentAbort]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The agent emitted an [ABORT] signal with a reason.',\n },\n [ErrorCodes.AgenticDetectionTimeout]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent run exceeded its configured time limit.',\n },\n [ErrorCodes.AgentMcpMissing]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent could not reach the PostHog MCP server.',\n },\n [ErrorCodes.AgentResourceMissing]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent could not access a setup resource.',\n },\n [ErrorCodes.AgentRateLimit]: {\n group: 'agent',\n retry: 'yes',\n description: 'The LLM gateway rate-limited the run.',\n },\n [ErrorCodes.AgentApiError]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent hit an API error other than a rate limit.',\n },\n [ErrorCodes.AgentYaraViolation]: {\n group: 'agent',\n retry: 'no',\n description: 'The security scanner terminated the run.',\n },\n [ErrorCodes.AgentNoProgress]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The agent ended without a single tool call.',\n },\n [ErrorCodes.AgentInvalidStructuredOutput]: {\n group: 'agent',\n retry: 'yes',\n description:\n 'The agent ended a schema-bound run without output matching the schema.',\n },\n [ErrorCodes.AgentIncompleteTasks]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The agent stopped with planned tasks still open.',\n },\n [ErrorCodes.AgentOrchestratorSkillVariantMissing]: {\n group: 'agent',\n retry: 'yes',\n description: 'The orchestrator could not download a needed skill variant.',\n },\n [ErrorCodes.AgentOrchestratorTasksFailed]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The orchestrator queue drained with failed or blocked tasks.',\n },\n [ErrorCodes.AgentOrchestratorHollowRun]: {\n group: 'agent',\n retry: 'yes',\n description:\n 'The orchestrator drained with zero tasks — the seed step got no usable model output.',\n },\n [ErrorCodes.AgentOrchestratorSinkInvariant]: {\n group: 'agent',\n retry: 'no',\n description: 'The orchestrator plan failed the sink coverage invariant.',\n },\n [ErrorCodes.GatewayMintRefused]: {\n group: 'gateway',\n // 429 clears with the daily window, 401 with a fresh login, 403 never.\n retry: 'case-by-case',\n description:\n 'The PostHog backend refused to mint a gateway token for this run.',\n },\n [ErrorCodes.GatewayMintFailed]: {\n group: 'gateway',\n retry: 'yes',\n description:\n 'The PostHog backend could not mint a gateway token: unreachable, a 5xx, or an unusable response.',\n },\n [ErrorCodes.SettingsUnfixableConflict]: {\n group: 'settings',\n retry: 'no',\n description:\n 'A Claude settings conflict cannot be neutralized automatically.',\n },\n [ErrorCodes.InternalUnhandled]: {\n group: 'internal',\n retry: 'yes',\n description: 'An unexpected error escaped the pipeline.',\n },\n};\n","import type { ErrorCode } from './codes';\n\n/**\n * Structured error data for analytics and the machine-readable error line.\n *\n * A data carrier: the agent returns it inside a failure and the legacy adapter\n * hands it to `wizardAbort()`, which captures it. Never thrown by the wizard.\n */\nexport class WizardError extends Error {\n readonly code?: ErrorCode;\n\n constructor(\n message: string,\n public readonly context?: Record<string, unknown>,\n code?: ErrorCode,\n ) {\n super(message);\n this.name = 'WizardError';\n this.code = code;\n }\n}\n","import { ErrorCodes, type ErrorCode } from './codes';\n\nexport interface AuthFailureInput {\n hasSettingsConflict?: boolean;\n usingManagedLogin?: boolean;\n /** A pre-run token refresh already failed on a dead grant this run. */\n sessionExpired?: boolean;\n apiKey?: string;\n missingScopes?: readonly string[];\n gatewayRegion?: 'us' | 'eu' | 'local';\n sessionRegion?: 'us' | 'eu';\n}\n\nexport function classifyAuthFailure(input: AuthFailureInput): ErrorCode {\n // First: the only branch backed by a server verdict rather than inference.\n // The token endpoint already told us the grant is dead, so every heuristic\n // below would be guessing at a cause we know.\n if (input.sessionExpired) return ErrorCodes.AuthSessionExpired;\n if (input.usingManagedLogin) return ErrorCodes.AuthStoredLoginConflict;\n if (input.hasSettingsConflict) return ErrorCodes.AuthSettingsConflict;\n if (\n input.apiKey &&\n !input.apiKey.startsWith('phx_') &&\n !input.apiKey.startsWith('pha_')\n ) {\n return ErrorCodes.AuthKeyType;\n }\n if (input.missingScopes && input.missingScopes.length > 0) {\n return ErrorCodes.AuthMissingScope;\n }\n if (\n input.gatewayRegion &&\n input.sessionRegion &&\n input.gatewayRegion !== 'local' &&\n input.gatewayRegion !== input.sessionRegion\n ) {\n return ErrorCodes.AuthRegionMismatch;\n }\n return ErrorCodes.AuthInvalidOrExpired;\n}\n","import { ErrorCodes, type ErrorCode } from './codes';\nimport type { InstallSkillResult } from '@agent/types';\n\nconst SKILL_CODES: Record<\n Exclude<InstallSkillResult['kind'], 'ok'>,\n ErrorCode\n> = {\n 'menu-fetch-failed': ErrorCodes.SkillMenuFetchFailed,\n 'skill-not-found': ErrorCodes.SkillNotFound,\n 'download-failed': ErrorCodes.SkillDownloadFailed,\n};\n\nexport function skillErrorCode(result: InstallSkillResult): ErrorCode | null {\n if (result.kind === 'ok') return null;\n return SKILL_CODES[result.kind];\n}\n","const DETAIL_ALLOWLIST = ['reason', 'detected', 'platform'] as const;\n\nexport function sanitizeErrorDetail(\n detail: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!detail) return undefined;\n const safe: Record<string, unknown> = {};\n for (const key of DETAIL_ALLOWLIST) {\n if (detail[key] !== undefined) safe[key] = detail[key];\n }\n return Object.keys(safe).length > 0 ? safe : undefined;\n}\n","import { ErrorCodes, isErrorCode, type ErrorCode } from './codes';\n\nexport interface RunFailure {\n code: ErrorCode;\n message: string;\n /** True when the error carried its own code: a decision, not a crash. */\n coded: boolean;\n}\n\n/**\n * How a run's terminal error is reported. A coded WizardError (a mint refusal,\n * say) keeps its own message and code; anything else is unhandled and gets the\n * generic framing. Duck-typed on `code` so callers need not load wizard-abort.\n */\nexport function classifyRunFailure(err: unknown): RunFailure {\n const message = err instanceof Error ? err.message : String(err);\n const code =\n err instanceof Error ? (err as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && isErrorCode(code)) {\n return { code, message, coded: true };\n }\n return { code: ErrorCodes.InternalUnhandled, message, coded: false };\n}\n"],"mappings":";AAIG,WAAW,gBAKX,WAAW,YAKX,WAAW,oBAKX,WAAW,wBAMX,WAAW,mBAKX,WAAW,uBAKX,WAAW,kBAKX,WAAW,2BAKX,WAAW,aAKX,WAAW,sBAKX,WAAW,oBAMX,WAAW,kBAKX,WAAW,oBAKX,WAAW,sBAKX,WAAW,yBAMX,WAAW,wBAKX,WAAW,sBAKX,WAAW,kBAKX,WAAW,oBAMX,WAAW,mBAKX,WAAW,0BAMX,WAAW,2BAKX,WAAW,oBAMX,WAAW,sBAKX,WAAW,iBAKX,WAAW,qBAKX,WAAW,cAKX,WAAW,qBAKX,WAAW,oBAQX,WAAW,sBAKX,WAAW,eAKX,WAAW,qBAKX,WAAW,YAKX,WAAW,yBAKX,WAAW,iBAKX,WAAW,sBAKX,WAAW,gBAKX,WAAW,eAKX,WAAW,oBAKX,WAAW,iBAKX,WAAW,8BAMX,WAAW,sBAKX,WAAW,sCAKX,WAAW,8BAKX,WAAW,4BAMX,WAAW,gCAK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AA;AAC5D,KAAI,OAAO,SAAS,YAAY,YAAY,KAAK,CAC/C,QAAO;EAAE;EAAM;EAAS,OAAO;EAAM;AAEvC,QAAO;EAAE,MAAM,WAAW;EAAmB;EAAS,OAAO;EAAO"}
@@ -1,7 +1,7 @@
1
- import { d as WIZARD_TASK_STREAM_FILE, s as logToFile } from "./debug-Cj-8vfXY.js";
1
+ import { d as WIZARD_TASK_STREAM_FILE, s as logToFile } from "./debug-DyARf5TF.js";
2
2
  import { dirname, isAbsolute, resolve } from "node:path";
3
3
  import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
4
- //#region src/programs/task-stream/destinations/file.ts
4
+ //#region src/programs/session/task-stream/destinations/file.ts
5
5
  /**
6
6
  * Dumps every *attempted* sync to a local JSONL file, one line per push. A line
7
7
  * means the run published that payload, not that a backend accepted it — `--ci`
@@ -55,6 +55,6 @@ function createFileDestination(value, opts = {}) {
55
55
  return new FileDestination({ path });
56
56
  }
57
57
  //#endregion
58
- export { FileDestination, createFileDestination };
58
+ export { createFileDestination as n, FileDestination as t };
59
59
 
60
- //# sourceMappingURL=file-dEhr-l3n.js.map
60
+ //# sourceMappingURL=file-CVA9ocIC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-CVA9ocIC.js","names":[],"sources":["../src/programs/session/task-stream/destinations/file.ts"],"sourcesContent":["/**\n * Dumps every *attempted* sync to a local JSONL file, one line per push. A line\n * means the run published that payload, not that a backend accepted it — `--ci`\n * swaps the PostHog destination for this one, so a synthetic run never creates a\n * session row in a real project.\n *\n * Dev builds only: the payload holds the run's handoff report.\n */\n\nimport { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { IS_PRODUCTION_BUILD } from '@env';\nimport { WIZARD_TASK_STREAM_FILE } from '@utils/paths';\nimport { logToFile } from '@utils/debug';\nimport type {\n StreamEvent,\n TaskStreamDestination,\n TaskStreamUpdate,\n} from '@programs/session/task-stream/types';\n\nexport interface FileDestinationOptions {\n path: string;\n /** Override for tests. */\n now?: () => string;\n}\n\nexport class FileDestination implements TaskStreamDestination {\n readonly name = 'file';\n readonly path: string;\n\n private readonly now: () => string;\n private disabled = false;\n\n constructor(opts: FileDestinationOptions) {\n this.path = opts.path;\n this.now = opts.now ?? (() => new Date().toISOString());\n // Truncate up front: one run, one file.\n this.write(() => writeFileSync(this.path, '', { mode: 0o600 }));\n }\n\n send(event: StreamEvent, payload: TaskStreamUpdate): Promise<void> {\n if (!this.disabled) {\n const line = `${JSON.stringify({ at: this.now(), event, payload })}\\n`;\n this.write(() => appendFileSync(this.path, line, { mode: 0o600 }));\n }\n return Promise.resolve();\n }\n\n /** Never throws, never writes to stdio; the first failure ends the dump. */\n private write(op: () => void): void {\n try {\n mkdirSync(dirname(this.path), { recursive: true });\n op();\n } catch (err) {\n this.disabled = true;\n logToFile(\n `[task-stream] file destination disabled (${\n err instanceof Error ? err.message : String(err)\n }): ${this.path}`,\n );\n }\n }\n}\n\n/**\n * Resolve a `--task-stream-log` value, or null when the run did not ask for a\n * dump. `''` and `true` mean the default path — how `--ci` asks for one.\n */\nexport function createFileDestination(\n value: unknown,\n opts: { productionBuild?: boolean; cwd?: string } = {},\n): FileDestination | null {\n if (opts.productionBuild ?? IS_PRODUCTION_BUILD) return null;\n if (value === undefined || value === null || value === false) return null;\n\n const raw = typeof value === 'string' ? value.trim() : '';\n const path =\n raw === ''\n ? WIZARD_TASK_STREAM_FILE\n : isAbsolute(raw)\n ? raw\n : resolve(opts.cwd ?? process.cwd(), raw);\n\n logToFile(`[task-stream] file destination enabled: ${path}`);\n return new FileDestination({ path });\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,IAAa,kBAAb,MAA8D;CAC5D,OAAgB;CAChB;CAEA;CACA,WAAmB;CAEnB,YAAY,MAA8B;AACxC,OAAK,OAAO,KAAK;AACjB,OAAK,MAAM,KAAK,+BAAc,IAAI,MAAM,EAAC,aAAa;AAEtD,OAAK,YAAY,cAAc,KAAK,MAAM,IAAI,EAAE,MAAM,KAAO,CAAC,CAAC;;CAGjE,KAAK,OAAoB,SAA0C;AACjE,MAAI,CAAC,KAAK,UAAU;GAClB,MAAM,OAAO,GAAG,KAAK,UAAU;IAAE,IAAI,KAAK,KAAK;IAAE;IAAO;IAAS,CAAC,CAAC;AACnE,QAAK,YAAY,eAAe,KAAK,MAAM,MAAM,EAAE,MAAM,KAAO,CAAC,CAAC;;AAEpE,SAAO,QAAQ,SAAS;;;CAI1B,MAAc,IAAsB;AAClC,MAAI;AACF,aAAU,QAAQ,KAAK,KAAK,EAAE,EAAE,WAAW,MAAM,CAAC;AAClD,OAAI;WACG,KAAK;AACZ,QAAK,WAAW;AAChB,aACE,4CACE,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,CACjD,KAAK,KAAK,OACZ;;;;;;;;AASP,SAAgB,sBACd,OACA,OAAoD,EAAE,EAC9B;AACxB,KAAI,KAAK,mBAAA,KAAwC,QAAO;AACxD,KAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,MAAO,QAAO;CAErE,MAAM,MAAM,OAAO,UAAU,WAAW,MAAM,MAAM,GAAG;CACvD,MAAM,OACJ,QAAQ,KACJ,0BACA,WAAW,IAAI,GACf,MACA,QAAQ,KAAK,OAAO,QAAQ,KAAK,EAAE,IAAI;AAE7C,WAAU,2CAA2C,OAAO;AAC5D,QAAO,IAAI,gBAAgB,EAAE,MAAM,CAAC"}
@@ -0,0 +1,2 @@
1
+ import { n as createFileDestination } from "./file-CVA9ocIC.js";
2
+ export { createFileDestination };
@@ -1,7 +1,7 @@
1
- import { s as logToFile } from "./debug-Cj-8vfXY.js";
1
+ import { s as logToFile } from "./debug-DyARf5TF.js";
2
2
  import * as fs$1 from "fs";
3
3
  import { basename, dirname } from "node:path";
4
- //#region src/lib/file-watcher.ts
4
+ //#region src/shared/utils/file-watcher.ts
5
5
  /**
6
6
  * JSON file watcher shared by runner and UI machinery.
7
7
  *
@@ -120,4 +120,4 @@ function startFileWatcher(path, onUpdate, options = {}) {
120
120
  //#endregion
121
121
  export { startFileWatcher as t };
122
122
 
123
- //# sourceMappingURL=file-watcher-CPM-Nn9L.js.map
123
+ //# sourceMappingURL=file-watcher-C3Su8vXm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-watcher-C3Su8vXm.js","names":["fs"],"sources":["../src/shared/utils/file-watcher.ts"],"sourcesContent":["/**\n * JSON file watcher shared by runner and UI machinery.\n *\n * `fs.watch` alone is unreliable for atomic-rename writes, so the watcher\n * pairs it with a continuous mtime-polled re-read. The poll catches missed\n * events; the watch keeps latency low when it does fire.\n */\n\nimport * as fs from 'fs';\nimport { basename, dirname } from 'node:path';\nimport { logToFile } from '@utils/debug';\n\nconst DEFAULT_POLL_INTERVAL_MS = 5000;\nconst DEFAULT_ATTACH_RETRY_INTERVAL_MS = 1000;\nconst DEFAULT_WATCH_DEBOUNCE_MS = 25;\n\nexport interface FileWatcherHandle {\n refresh(): void;\n stop(): void;\n}\n\nexport interface FileWatcherOptions {\n /** ms between mtime checks once the file exists. */\n pollIntervalMs?: number;\n /** ms between attach attempts while waiting for the file to appear. */\n attachRetryIntervalMs?: number;\n /** ms to coalesce duplicate filesystem events. */\n watchDebounceMs?: number;\n /** Ignore the file that exists when the watcher starts until it changes. */\n ignoreInitialFile?: boolean;\n /** Refuse to read files larger than this many bytes. */\n maxFileSizeBytes?: number;\n}\n\n/** Watch `path` for JSON updates and call `onUpdate(parsed)` whenever the\n * file's mtime changes and the contents are valid JSON. Caller must invoke\n * `handle.stop()` to release the watcher. */\nexport function startFileWatcher(\n path: string,\n onUpdate: (parsed: unknown) => void,\n options: FileWatcherOptions = {},\n): FileWatcherHandle {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const attachRetryIntervalMs =\n options.attachRetryIntervalMs ?? DEFAULT_ATTACH_RETRY_INTERVAL_MS;\n const watchDebounceMs = options.watchDebounceMs ?? DEFAULT_WATCH_DEBOUNCE_MS;\n\n const watchers: fs.FSWatcher[] = [];\n const intervals: Array<ReturnType<typeof setInterval>> = [];\n const targetDir = dirname(path);\n const targetName = basename(path);\n let lastMtimeMs = 0;\n let ignoredInitialSignature: string | null = null;\n let watchDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n let lastReadErrorSignature: string | null = null;\n let stopped = false;\n\n const signature = (stat: fs.Stats): string =>\n `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;\n\n if (options.ignoreInitialFile) {\n try {\n const stat = fs.lstatSync(path);\n if (stat.isFile() && !stat.isSymbolicLink()) {\n ignoredInitialSignature = signature(stat);\n }\n } catch {\n // No initial file to ignore.\n }\n }\n\n const logReadError = (errorSignature: string, message: string) => {\n if (lastReadErrorSignature === errorSignature) return;\n lastReadErrorSignature = errorSignature;\n logToFile(`[file-watcher] ${message}: ${path}`);\n };\n\n const read = (force = false) => {\n let stat: fs.Stats;\n try {\n stat = fs.lstatSync(path);\n } catch {\n return;\n }\n\n if (!stat.isFile() || stat.isSymbolicLink()) return;\n const fileSignature = signature(stat);\n\n try {\n if (ignoredInitialSignature) {\n if (fileSignature === ignoredInitialSignature) return;\n ignoredInitialSignature = null;\n }\n if (\n options.maxFileSizeBytes !== undefined &&\n stat.size > options.maxFileSizeBytes\n ) {\n logReadError(\n `oversized:${fileSignature}`,\n `refusing oversized JSON file (${stat.size} bytes, limit ${options.maxFileSizeBytes} bytes)`,\n );\n return;\n }\n if (!force && stat.mtimeMs === lastMtimeMs) return;\n lastMtimeMs = stat.mtimeMs;\n const parsed: unknown = JSON.parse(fs.readFileSync(path, 'utf-8'));\n lastReadErrorSignature = null;\n onUpdate(parsed);\n } catch (error) {\n logReadError(\n `invalid:${fileSignature}:${String(error)}`,\n `could not read valid JSON (${String(error)})`,\n );\n }\n };\n\n const scheduleRead = () => {\n if (stopped) return;\n if (watchDebounceTimer) clearTimeout(watchDebounceTimer);\n watchDebounceTimer = setTimeout(() => {\n watchDebounceTimer = null;\n read(true);\n }, watchDebounceMs);\n };\n\n const attachWatch = () => {\n watchers.push(\n fs.watch(targetDir, (_eventType, filename) => {\n if (filename == null || filename.toString() === targetName) {\n scheduleRead();\n }\n }),\n );\n };\n\n intervals.push(setInterval(() => read(), pollIntervalMs));\n\n try {\n attachWatch();\n // Defer the initial callback until the caller has received the handle, so\n // callbacks that stop their watcher cannot race handle assignment.\n queueMicrotask(() => {\n if (!stopped) read(true);\n });\n } catch {\n // Parent directory does not exist yet. Polling still covers a later file;\n // retry attaching the low-latency directory watcher until it appears.\n const attachInterval = setInterval(() => {\n try {\n fs.accessSync(targetDir);\n clearInterval(attachInterval);\n const idx = intervals.indexOf(attachInterval);\n if (idx >= 0) intervals.splice(idx, 1);\n attachWatch();\n read(true);\n } catch {\n // Still waiting.\n }\n }, attachRetryIntervalMs);\n intervals.push(attachInterval);\n }\n\n return {\n refresh() {\n if (stopped) return;\n if (watchDebounceTimer) {\n clearTimeout(watchDebounceTimer);\n watchDebounceTimer = null;\n }\n read(true);\n },\n stop() {\n stopped = true;\n if (watchDebounceTimer) {\n clearTimeout(watchDebounceTimer);\n watchDebounceTimer = null;\n }\n for (const watcher of watchers) watcher.close();\n for (const interval of intervals) clearInterval(interval);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,2BAA2B;AACjC,MAAM,mCAAmC;AACzC,MAAM,4BAA4B;;;;AAuBlC,SAAgB,iBACd,MACA,UACA,UAA8B,EAAE,EACb;CACnB,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,wBACJ,QAAQ,yBAAyB;CACnC,MAAM,kBAAkB,QAAQ,mBAAmB;CAEnD,MAAM,WAA2B,EAAE;CACnC,MAAM,YAAmD,EAAE;CAC3D,MAAM,YAAY,QAAQ,KAAK;CAC/B,MAAM,aAAa,SAAS,KAAK;CACjC,IAAI,cAAc;CAClB,IAAI,0BAAyC;CAC7C,IAAI,qBAA2D;CAC/D,IAAI,yBAAwC;CAC5C,IAA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WAAS,KACPA,KAAG,MAAM,YAAY,YAAY,aAAa;AAC5C,OAAI,YAAY,QAAQ,SAAS,UAAU,KAAK,WAC9C,eAAc;IAEhB,CACH;;AAGH,WAAU,KAAK,kBAAkB,MAAM,EAAE,eAAe,CAAC;AAEzD,KAAI;AACF,eAAa;AAGb,uBAAqB;AACnB,OAAI,CAAC,QAAS,MAAK,KAAK;IACxB;SACI;EAGN,MAAM,iBAAiB,kBAAkB;AACvC,OAAI;AACF,SAAG,WAAW,UAAU;AACxB,kBAAc,eAAe;IAC7B,MAAM,MAAM,UAAU,QAAQ,eAAe;AAC7C,QAAI,OAAO,EAAG,WAAU,OAAO,KAAK,EAAE;AACtC,iBAAa;AACb,SAAK,KAAK;WACJ;KAGP,sBAAsB;AACzB,YAAU,KAAK,eAAe;;AAGhC,QAAO;EACL,UAAU;AACR,OAAI,QAAS;AACb,OAAI,oBAAoB;AACtB,iBAAa,mBAAmB;AAChC,yBAAqB;;AAEvB,QAAK,KAAK;;EAEZ,OAAO;AACL,aAAU;AACV,OAAI,oBAAoB;AACtB,iBAAa,mBAAmB;AAChC,yBAAqB;;AAEvB,QAAK,MAAM,WAAW,SAAU,SAAQ,OAAO;AAC/C,QAAK,MAAM,YAAY,UAAW,eAAc,SAAS;;EAE5D"}
@@ -1,9 +1,10 @@
1
- import { a as WizardError, s as ErrorCodes } from "./errors-ddDE6MbA.js";
2
- import { s as logToFile } from "./debug-Cj-8vfXY.js";
3
- import { n as analytics } from "./analytics-VRYdebXW.js";
4
- import { t as checkLlmGatewayHealth } from "./endpoints-DnIX0pZH.js";
5
- import { a as oauthLoginKey } from "./oauth-session-CQTFOk-I.js";
6
- import { i as modelCapabilities } from "./models-DnAY67Lg.js";
1
+ import { n as ErrorCodes } from "./emit-BSetXzDV.js";
2
+ import { s as logToFile } from "./debug-DyARf5TF.js";
3
+ import { n as analytics } from "./analytics-B6q5PN7a.js";
4
+ import { a as WizardError } from "./errors-C2domSkK.js";
5
+ import { t as checkLlmGatewayHealth } from "./endpoints-D-4KxZiB.js";
6
+ import { a as oauthLoginKey } from "./oauth-session-D-RfcVmr.js";
7
+ import { i as modelCapabilities } from "./models-Dba8ITeo.js";
7
8
  import "node:fs";
8
9
  //#region src/agent/gateway-session.ts
9
10
  /**
@@ -453,4 +454,4 @@ function withGatewayRemint(opts) {
453
454
  //#endregion
454
455
  export { gatewayTerminalFailure as a, REMARK_INSTRUCTION as c, configureGatewayFromCIEnvironment as d, gatewayAuth as f, gatewayApiFor as i, RESUME_INSTRUCTION as l, buildGatewayModel as n, withGatewayRemint as o, isPastRefresh as p, buildGatewayProvider as r, AgentSignals as s, GATEWAY_PROVIDER as t, buildWizardPropertiesBlob as u };
455
456
 
456
- //# sourceMappingURL=gateway-CVU1G0H3.js.map
457
+ //# sourceMappingURL=gateway-BmjYUSua.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gateway-CVU1G0H3.js","names":[],"sources":["../src/agent/gateway-session.ts","../src/agent/signals.ts","../src/agent/runner/harness/pi/gateway.ts"],"sourcesContent":["/**\n * Gateway auth for a wizard run: a `phe_` scoped token the backend mints, with\n * pinned attribution, a spend cap and an expiry.\n *\n * Every mint failure throws: a silent downgrade would spend uncapped,\n * unattributed money to hide an outage.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport { ErrorCodes, WizardError } from '@shared/errors';\nimport type { HostResolution } from '@shared/host-resolution';\nimport { oauthLoginKey } from '@shared/oauth-session';\nimport { checkLlmGatewayHealth } from '@shared/health-checks/endpoints';\nimport { ServiceHealthStatus } from '@shared/health-checks/types';\nimport { IS_PRODUCTION_BUILD, runtimeEnv } from '@env';\nimport type { CloudRegion } from '@utils/types';\n\nexport interface GatewayAuth {\n /** Base URL for model calls (no `/v1`; transports append their route). */\n gatewayUrl: string;\n /** Gateway bearer, minted normally or supplied directly by CI. */\n token: string;\n /** Team verified by the mint, or explicitly supplied for CI attribution. */\n teamId?: number;\n /**\n * Instant past which a 401 on this bearer is age rather than a bad\n * credential: the cache re-mints past it, and a session still holding the\n * old bearer may re-mint once. Before it the mint has to be trusted.\n */\n refreshAtMs: number;\n}\n\ninterface CachedAuth {\n key: string;\n auth: GatewayAuth;\n /** Re-resolve once past this instant. */\n staleAtMs: number;\n}\n\nlet cached: CachedAuth | null = null;\n/**\n * Shared so concurrent callers mint once. The orchestrator starts every runnable\n * task at once, and each would otherwise take its own token and its own cap.\n */\nlet inFlight: { key: string; promise: Promise<GatewayAuth> } | null = null;\nlet ciAuth: GatewayAuth | null = null;\n\n// Snapshot CI supplies a gateway bearer without minting or re-minting.\nexport function configureGatewayCredentialsForCI(\n token: string,\n projectId: number,\n gatewayUrl: string,\n): void {\n if (IS_PRODUCTION_BUILD)\n throw new Error('CI gateway auth requires a non-production build');\n if (!token.trim() || !Number.isSafeInteger(projectId) || projectId <= 0) {\n throw new Error('CI gateway auth requires a token and valid project ID');\n }\n if (\n !/^https?:\\/\\//.test(gatewayUrl) ||\n !isTrustedGatewayUrl(gatewayUrl, '')\n ) {\n throw new Error('CI gateway auth requires a trusted gateway origin');\n }\n resetGatewaySession();\n ciAuth = {\n token: token.trim(),\n teamId: projectId,\n gatewayUrl: gatewayUrl.replace(/\\/+$/, ''),\n refreshAtMs: Infinity,\n };\n}\n\n// TODO: CI credential loading belongs outside the agent. It leaves with the rest\n// of this module once RunInput carries resolved inference auth, later in the\n// refactor.\nexport function configureGatewayFromCIEnvironment(\n projectId: number,\n region: CloudRegion,\n): void {\n if (IS_PRODUCTION_BUILD)\n throw new Error('CI gateway auth requires a non-production build');\n const path = runtimeEnv('WIZARD_CI_GATEWAY_TOKEN_FILE');\n if (!path) throw new Error('WIZARD_CI_GATEWAY_TOKEN_FILE is required for CI');\n const token = readFileSync(path, 'utf8');\n delete process.env.WIZARD_CI_GATEWAY_TOKEN_FILE;\n configureGatewayCredentialsForCI(\n token,\n projectId,\n runtimeEnv('WIZARD_CI_GATEWAY_URL') ||\n `https://ai-gateway.${region}.posthog.com`,\n );\n}\n\n/**\n * Adoption floor. The anthropic subprocess holds its credential until a 401\n * forces a re-mint, so a token below this would churn mints.\n */\nconst MIN_USABLE_TTL_MS = 2 * 60 * 1000;\n/** Re-resolve at this fraction of the token's life, leaving a usable remainder. */\nconst REFRESH_AT_FRACTION = 0.8;\n// Exceeds the backend's own 10s gateway timeout: a slow mint that lands after the\n// CLI hangs up spends a daily mint and orphans a live token.\nconst MINT_TIMEOUT_MS = 20_000;\n/** Longer than any refusal the mint writes; a body past this is not a message. */\nconst MAX_REFUSAL_DETAIL_LENGTH = 500;\n/** Outcomes are short snake_case labels; anything longer is not one. */\nconst MAX_REFUSAL_OUTCOME_LENGTH = 64;\n\n/** Resolve this run's gateway auth, minting and re-minting near expiry. */\nexport async function gatewayAuth(\n host: HostResolution,\n accessToken: string,\n program: string | undefined,\n): Promise<GatewayAuth> {\n if (ciAuth) return ciAuth;\n // Keyed by program: a token pins `wizard:<program>`, so reusing one across\n // programs bills the wrong budget. Keyed by login rather than OAuth token:\n // the token rotates mid-run, and each new one would spend a weekly mint.\n const key = `${host.apiHost}\\n${oauthLoginKey(accessToken)}\\n${\n program ?? ''\n }`;\n if (cached && cached.key === key && Date.now() < cached.staleAtMs) {\n return cached.auth;\n }\n if (inFlight && inFlight.key === key) return inFlight.promise;\n const promise = resolveGatewayAuth(host, accessToken, key, program);\n inFlight = { key, promise };\n try {\n return await promise;\n } finally {\n if (inFlight?.promise === promise) inFlight = null;\n }\n}\n\nasync function resolveGatewayAuth(\n host: HostResolution,\n accessToken: string,\n key: string,\n program: string | undefined,\n): Promise<GatewayAuth> {\n if (!program) {\n // Every run has one; absent means a caller was not wired, and the spend would\n // be unattributable.\n logToFile('[gateway] run has no program id; failing the run');\n throw new GatewayMintFailed(\n 'this run has no program to attribute its spend to',\n );\n }\n const minted = await mintGatewayToken(host, accessToken, program);\n const health = await checkLlmGatewayHealth(minted.gatewayUrl);\n if (health.status !== ServiceHealthStatus.Healthy) {\n throw new WizardError(\n 'The PostHog AI gateway is unavailable. Please try again later.',\n undefined,\n ErrorCodes.EnvServiceOutage,\n );\n }\n const expiresAtMs = Date.parse(minted.expiresAt);\n const ttlMs = expiresAtMs - Date.now();\n if (!Number.isFinite(expiresAtMs) || ttlMs < MIN_USABLE_TTL_MS) {\n // Expired, unreadable, or too short to serve a session. Adopting it would\n // 401 mid-run, and downgrading would spend the rest of the run uncapped.\n logToFile(\n `[gateway] mint returned a token with ${ttlMs}ms of life; failing the run`,\n );\n throw new GatewayMintFailed(\n `the PostHog gateway issued a token with ${ttlMs}ms of life`,\n );\n }\n const staleAtMs = Date.now() + ttlMs * REFRESH_AT_FRACTION;\n // Only failures are logged otherwise, so a successful run leaves no\n // local trace. Never log the token itself.\n logToFile(\n `[gateway] minted a scoped token: program=${program} team=${\n minted.teamId ?? 'unknown'\n } ttl=${Math.round(ttlMs / 1000)}s url=${minted.gatewayUrl}`,\n );\n const auth: GatewayAuth = {\n gatewayUrl: minted.gatewayUrl,\n token: minted.token,\n teamId: minted.teamId,\n refreshAtMs: staleAtMs,\n };\n cached = { key, auth, staleAtMs };\n return auth;\n}\n\n/** Test hook: drop the cached auth so the next call re-resolves. */\nexport function resetGatewaySession(): void {\n cached = null;\n inFlight = null;\n ciAuth = null;\n}\n\n/** Whether a 401 on this bearer may be age (past its refresh instant) rather than a bad credential. */\nexport function isPastRefresh(auth: GatewayAuth, now = Date.now()): boolean {\n return now >= auth.refreshAtMs;\n}\n\n/**\n * Whether a server-supplied origin may receive a bearer and prompt content:\n * https (loopback excepted), and either a current cloud gateway or the host the run\n * authenticated against.\n */\nexport function isTrustedGatewayUrl(value: string, apiHost: string): boolean {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n // Consumers append routes to this value, so anything beyond an origin\n // (path, query, fragment, userinfo) would build a malformed endpoint.\n if (\n url.pathname !== '/' ||\n url.search ||\n url.hash ||\n url.username ||\n url.password\n ) {\n return false;\n }\n const localhost =\n url.hostname === 'localhost' ||\n url.hostname === '127.0.0.1' ||\n url.hostname === 'host.docker.internal';\n // Loopback is the dev gateway, and is the one case allowed over http.\n if (localhost) return true;\n if (url.protocol !== 'https:') return false;\n if (url.hostname.endsWith('.posthog.com')) {\n return (\n url.origin === 'https://ai-gateway.us.posthog.com' ||\n url.origin === 'https://ai-gateway.eu.posthog.com'\n );\n }\n try {\n return url.hostname === new URL(apiHost).hostname;\n } catch {\n return false;\n }\n}\n\ninterface MintedToken {\n token: string;\n expiresAt: string;\n gatewayUrl: string;\n teamId?: number;\n}\n\n/**\n * A deliberate refusal from the mint endpoint, as opposed to the mint being\n * unavailable. Thrown so the run stops instead of proceeding without the\n * controls the refusal was enforcing. A WizardError, so the runners print its\n * message as-is and `wizardAbort` resolves its code.\n */\nexport class GatewayMintRefused extends WizardError {\n readonly status: number;\n /** The backend's refusal outcome (`blocked`, `throttled`, ...), when it sent one. */\n readonly outcome?: string;\n\n constructor(status: number, message: string, outcome?: string) {\n super(message, { status, outcome }, ErrorCodes.GatewayMintRefused);\n this.name = 'GatewayMintRefused';\n this.status = status;\n this.outcome = outcome;\n }\n}\n\n/**\n * The mint could not produce a usable credential: unreachable, a 5xx, or a\n * response the client cannot use.\n */\nexport class GatewayMintFailed extends WizardError {\n constructor(message: string) {\n super(message, undefined, ErrorCodes.GatewayMintFailed);\n this.name = 'GatewayMintFailed';\n }\n}\n\n/**\n * Whether a mint status means \"refused this run\" rather than \"not available\".\n * 429 the daily run limit, 403 revoked project access, 400 a login covering\n * more than one project, 401 a credential the mint does not accept, 404 an\n * instance without the mint endpoint.\n */\nfunction isMintRefusal(status: number): boolean {\n return (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 429\n );\n}\n\ninterface MintRefusal {\n detail?: string;\n outcome?: string;\n}\n\n/**\n * The server's own reason for a refusal, when it sent one. DRF answers every\n * refusal as `{\"detail\": \"...\", \"code\": \"<outcome>\"}`; the blocklist's detail\n * names the contact address, which the fixed messages below cannot. `code` is\n * the backend's own label for the refusal (`outcome` on older backends) and\n * rides the client event.\n */\nfunction cleanRefusalText(value: unknown): string {\n if (typeof value !== 'string') return '';\n // Not because the server sends escapes, but because this string is printed\n // straight to a terminal: sanitizing at the boundary means no later message\n // can move the cursor or repaint the screen.\n // eslint-disable-next-line no-control-regex\n return value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, ' ').trim();\n}\n\nasync function readRefusal(resp: Response): Promise<MintRefusal> {\n try {\n const body = (await resp.json()) as {\n detail?: unknown;\n code?: unknown;\n outcome?: unknown;\n };\n const detail = cleanRefusalText(body?.detail);\n // The DRF handler flattens a dict detail, so the outcome rides as `code`.\n // A `code` that cleans to nothing does not shadow a usable `outcome`.\n const outcome =\n cleanRefusalText(body?.code) || cleanRefusalText(body?.outcome);\n return {\n detail:\n detail.length > 0 && detail.length <= MAX_REFUSAL_DETAIL_LENGTH\n ? detail\n : undefined,\n outcome:\n outcome.length > 0 && outcome.length <= MAX_REFUSAL_OUTCOME_LENGTH\n ? outcome\n : undefined,\n };\n } catch {\n return {};\n }\n}\n\nfunction mintRefusalMessage(status: number, detail?: string): string {\n if (detail) return detail;\n switch (status) {\n case 429:\n return 'This wizard program has used its daily run limit. Try again tomorrow.';\n case 403:\n return 'Your access to this project has changed. Re-authenticate and try again.';\n case 400:\n // The only 400 the mint answers is the exactly-one-project check.\n return 'Your PostHog login must cover exactly one project. Re-authenticate and try again.';\n case 401:\n return 'PostHog did not accept this login. Re-authenticate with `npx @posthog/wizard@latest`.';\n case 404:\n return 'This PostHog instance does not issue gateway tokens. Upgrade with `npx @posthog/wizard@latest` and try again.';\n default:\n return 'The PostHog gateway refused this run.';\n }\n}\n\nasync function mintGatewayToken(\n host: HostResolution,\n accessToken: string,\n program: string,\n): Promise<MintedToken> {\n try {\n const resp = await fetch(`${host.apiHost}/api/wizard/gateway_token/`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n },\n // The flag tells the server this build reads a refusal, so it may answer\n // with the reason. A build that omits it gets a 404, which is its signal\n // to fall back to the legacy gateway.\n body: JSON.stringify({ program, reads_refusal_reason: true }),\n signal: AbortSignal.timeout(MINT_TIMEOUT_MS),\n });\n if (!resp.ok) {\n if (isMintRefusal(resp.status)) {\n const refusal = await readRefusal(resp);\n logToFile(\n `[gateway] mint refused with HTTP ${resp.status} (${\n refusal.outcome ?? 'no outcome'\n }); failing the run`,\n );\n // The terminal denial event for this run. The backend's own event has\n // no run id, so this is what joins a refusal to the session.\n analytics.wizardCapture('gateway mint refused', {\n status: resp.status,\n outcome: refusal.outcome,\n program,\n });\n throw new GatewayMintRefused(\n resp.status,\n mintRefusalMessage(resp.status, refusal.detail),\n refusal.outcome,\n );\n }\n logToFile(\n `[gateway] mint failed with HTTP ${resp.status}; failing the run`,\n );\n throw new GatewayMintFailed(\n `the PostHog gateway could not issue a token (HTTP ${resp.status})`,\n );\n }\n const body = (await resp.json()) as {\n token?: string;\n expires_at?: string;\n gateway_url?: string;\n team_id?: number;\n };\n // Checked one at a time, not in a loop, so each clause narrows the optional\n // field for the return below and each names itself in the failure.\n if (!body.token) {\n logToFile('[gateway] mint response omitted token; failing the run');\n throw new GatewayMintFailed('mint response omitted token');\n }\n if (!body.expires_at) {\n logToFile('[gateway] mint response omitted expires_at; failing the run');\n throw new GatewayMintFailed('mint response omitted expires_at');\n }\n if (!body.gateway_url) {\n logToFile('[gateway] mint response omitted gateway_url; failing the run');\n throw new GatewayMintFailed('mint response omitted gateway_url');\n }\n if (!isTrustedGatewayUrl(body.gateway_url, host.apiHost)) {\n logToFile(\n '[gateway] mint returned an untrusted gateway url; failing the run',\n );\n throw new GatewayMintFailed('mint returned an untrusted gateway url');\n }\n const gatewayUrl = new URL(body.gateway_url);\n if (\n ['localhost', '127.0.0.1'].includes(new URL(host.apiHost).hostname) &&\n gatewayUrl.hostname === 'host.docker.internal'\n ) {\n gatewayUrl.hostname = 'localhost';\n }\n return {\n token: body.token,\n expiresAt: body.expires_at,\n gatewayUrl: gatewayUrl.origin,\n teamId: body.team_id,\n };\n } catch (e) {\n // Decisions and failures both pass through: this catch exists for transport\n // errors, and folding the others into it would lose the reason.\n if (e instanceof GatewayMintRefused || e instanceof GatewayMintFailed)\n throw e;\n logToFile(\n `[gateway] mint transport failure (${String(e)}); failing the run`,\n );\n throw new GatewayMintFailed(\n `could not reach the PostHog gateway (${String(e)})`,\n );\n }\n}\n\n/**\n * The v2 run-metadata carrier: one JSON blob for the `X-PostHog-Properties`\n * header. Plain keys only, since the gateway strips `$`-prefixed keys as reserved,\n * so feature-flag variants land as `wizard_flag_<key>` instead of the legacy\n * `$feature/<key>` (dashboards keying on `$feature/wizard-*` read the new key\n * post-cutover).\n */\nexport function buildWizardPropertiesBlob(\n wizardMetadata: Record<string, string>,\n wizardFlags: Record<string, string>,\n teamId?: number,\n): string {\n // The gateway pins `$ai_product` to `wizard:<program>`, and rejects a legacy\n // product override on a scoped token, so the unprefixed key every cost and\n // error consumer reads is only present if this blob declares it.\n const props: Record<string, string | number> = { ai_product: 'wizard' };\n if (teamId !== undefined) props.team_id = teamId;\n for (const [key, value] of Object.entries(wizardMetadata)) {\n props[stripPropertyPrefix(key)] = value;\n }\n for (const [flagKey, variant] of Object.entries(wizardFlags)) {\n if (!flagKey.toLowerCase().startsWith('wizard')) continue;\n props[`wizard_flag_${flagKey.toLowerCase()}`] = variant;\n }\n return JSON.stringify(props);\n}\n\nconst LEGACY_PROPERTY_PREFIX = 'X-POSTHOG-PROPERTY-';\n\nfunction stripPropertyPrefix(key: string): string {\n return key.toUpperCase().startsWith(LEGACY_PROPERTY_PREFIX)\n ? key.slice(LEGACY_PROPERTY_PREFIX.length).toLowerCase()\n : key;\n}\n","/**\n * Agent signal vocabulary — the marker strings the agent emits and the error\n * taxonomy the runner returns. Kept as a dependency-free leaf module so both\n * `agent-interface.ts` and `output-signals.ts` can import it without a cycle.\n */\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the PostHog MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n /**\n * Signal emitted when `install_skill` failed and the agent is continuing\n * the integration WITHOUT the skill (best-effort from its own knowledge).\n * Format: \"[SKILL-INSTALL-FAILED] <skill id — reason>\". Non-fatal by\n * design: a freestyled integration beats an outright failure, but the run\n * must be measurable — the runner captures it as an analytics event.\n */\n SKILL_INSTALL_FAILED: '[SKILL-INSTALL-FAILED]',\n /**\n * Signal emitted when the agent cannot complete the program and is\n * aborting intentionally (distinct from errors). Format: \"[ABORT] <reason>\".\n * Programs can declare an onAbort handler to render a custom screen.\n */\n ABORT: '[ABORT]',\n /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\n /** Signal prefix for benchmark logging */\n BENCHMARK: '[BENCHMARK]',\n /**\n * Signal emitted when the agent has created a PostHog dashboard for the\n * user. Format: `[DASHBOARD_URL] <full https url>`. The URL is captured\n * onto `session.dashboardUrl` and surfaced by programs in their outro.\n */\n DASHBOARD_URL: '[DASHBOARD_URL]',\n /**\n * Signal emitted when the agent has uploaded a report to a PostHog\n * notebook. Format: `[NOTEBOOK_URL] <full https url>`. The URL is captured\n * onto `session.notebookUrl` and surfaced by programs in their outro.\n */\n NOTEBOOK_URL: '[NOTEBOOK_URL]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/**\n * End-of-run reflection ask, shared by both harnesses so remarks are\n * comparable. The format clause comes FIRST and nothing trails the marker —\n * literal models (gpt-5-mini) echo whatever text follows it. The parser also\n * drops remarks that quote this instruction (see AgentOutputSignals.remark).\n */\nexport const REMARK_INSTRUCTION = `Reply with a single line that starts with ${AgentSignals.WIZARD_REMARK} and no other lines. In that line, state briefly what information or guidance would have been useful to have in the integration prompt or documentation for this run — specifically anything that would have prevented tool failures, erroneous edits, or other wasted turns.`;\n\n/**\n * First prompt of a session resumed after a mid-run re-mint. The transcript\n * carries the work so far; the model only needs to pick it up.\n */\nexport const RESUME_INSTRUCTION =\n 'Your previous request failed with a transient gateway authentication error that has since been fixed. Continue the task from where you left off.';\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** The configured run deadline elapsed and the SDK query was aborted */\n AGENTIC_DETECTION_TIMEOUT = 'WIZARD_AGENTIC_DETECTION_TIMEOUT',\n /** Agent could not access the PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n /** YARA scanner detected a security violation */\n YARA_VIOLATION = 'WIZARD_YARA_VIOLATION',\n /** Agent intentionally aborted the program (emitted [ABORT] <reason>) */\n ABORT = 'WIZARD_ABORT',\n /** Agent ended without making a single tool call — a no-op run that did no work */\n NO_PROGRESS = 'WIZARD_NO_PROGRESS',\n /** A schema-bound run ended without output matching its schema */\n INVALID_STRUCTURED_OUTPUT = 'WIZARD_INVALID_STRUCTURED_OUTPUT',\n /** Agent acted but stopped short — planned tasks left open and/or no skill installed */\n INCOMPLETE_TASKS = 'WIZARD_INCOMPLETE_TASKS',\n}\n","/**\n * PostHog AI gateway provider spec for pi sessions, shared by the linear run\n * and the orchestrator's per-task runs so both speak to the gateway\n * identically: bearer auth, the wizard properties header, transport shape\n * inferred from the model id. The caller registers the spec on its own\n * (lazily imported, properly typed) pi ModelRegistry.\n */\n\nimport {\n buildWizardPropertiesBlob,\n isPastRefresh,\n type GatewayAuth,\n} from '@agent/gateway-session';\nimport {\n modelCapabilities,\n type ThinkingLevel,\n} from '../../switchboard/models';\nimport { AgentErrorType } from '@agent/signals';\n\n/** Provider registered on the in-memory registry for this run. */\nexport const GATEWAY_PROVIDER = 'posthog-gateway';\n\n/** The pi transports the gateway serves. */\nexport type GatewayApi =\n | 'anthropic-messages'\n | 'openai-completions'\n | 'openai-responses';\n\n/**\n * The gateway speaks two shapes on two endpoints: Anthropic models over\n * `anthropic-messages` (the SDK appends `/v1/messages`, so the base URL has no\n * `/v1`), and OpenAI-class models (`openai/gpt-5`, …) over an OpenAI shape at\n * `/v1/responses` or `/v1/chat/completions` (base URL keeps `/v1`). Infer the\n * shape from the model id so a pair's model selects the right transport.\n *\n * OpenAI models take the Responses API because OpenAI rejects function tools\n * combined with `reasoning_effort` on chat completions and every task sends both.\n */\nexport function gatewayApiFor(modelId: string): GatewayApi {\n return modelId.startsWith('openai/')\n ? 'openai-responses'\n : 'anthropic-messages';\n}\n\n/**\n * Gateway HTTP headers, mirroring `buildAgentEnv` on the anthropic path: one\n * `X-PostHog-Properties` JSON blob (Bedrock fallback is native, so no opt-in)\n * plus the 1M context beta, since pi otherwise runs at 200k and overflows on\n * larger projects (the post-run compaction failures).\n */\nexport function buildGatewayHeaders(\n wizardMetadata: Record<string, string>,\n wizardFlags: Record<string, string>,\n teamId?: number,\n): Record<string, string> {\n return {\n 'anthropic-beta': 'context-1m-2025-08-07',\n 'X-PostHog-Properties': buildWizardPropertiesBlob(\n wizardMetadata,\n wizardFlags,\n teamId,\n ),\n };\n}\n\nexport interface GatewayProviderInputs {\n gatewayUrl: string;\n accessToken: string;\n /** Customer team for the properties blob (from the mint response). */\n teamId?: number;\n wizardMetadata: Record<string, string>;\n wizardFlags: Record<string, string>;\n modelId: string;\n // Resolved effort override — the switchboard's flag/payload pick on linear\n // runs, the prompt-frontmatter effort on per-task agents. Overrides the\n // table default for a reasoning model when set.\n effort?: ThinkingLevel;\n}\n\n/**\n * One gateway model spec — the single description of how to reach a model on\n * the gateway. The provider spec below wraps it for pi's registry; one-shot\n * callers (scan triage) hand it straight to `completeSimple`.\n */\nexport function buildGatewayModel(inputs: GatewayProviderInputs) {\n const { gatewayUrl, wizardMetadata, wizardFlags, modelId, teamId } = inputs;\n const api = gatewayApiFor(modelId);\n return {\n id: modelId,\n name: `${modelId} (PostHog Gateway)`,\n api,\n provider: GATEWAY_PROVIDER,\n // Anthropic drops /v1 (the SDK appends /v1/messages); the OpenAI shape keeps it.\n baseUrl: api === 'anthropic-messages' ? gatewayUrl : `${gatewayUrl}/v1`,\n // A model trait resolved by the switchboard, not a harness guess:\n // non-reasoning openai models reject `reasoning_effort` (gpt-4o → gateway\n // UnsupportedParamsError → the run no-ops).\n reasoning: modelCapabilities(modelId).reasoning,\n input: ['text' as const],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 1_000_000,\n maxTokens: 64_000,\n headers: buildGatewayHeaders(wizardMetadata, wizardFlags, teamId),\n };\n}\n\n/**\n * The provider object for `registry.registerProvider(GATEWAY_PROVIDER, …)`,\n * plus the derived traits the session setup needs (`caps.thinkingLevel`).\n */\nexport function buildGatewayProvider(inputs: GatewayProviderInputs): {\n provider: Record<string, unknown>;\n api: GatewayApi;\n caps: ReturnType<typeof modelCapabilities>;\n gatewayUrl: string;\n baseUrl: string;\n} {\n const { gatewayUrl, accessToken, modelId, effort } = inputs;\n const api = gatewayApiFor(modelId);\n // One resolution point for the model's traits and the run's effort override.\n // pi clamps whatever comes out of here against the levels this spec declares,\n // so a level the spec doesn't carry is silently reduced by the session.\n const tableCaps = modelCapabilities(modelId);\n const caps =\n effort && effort !== 'off' && tableCaps.reasoning\n ? modelCapabilities(modelId, effort)\n : effort === 'off' && tableCaps.reasoning\n ? { ...tableCaps, thinkingLevel: 'off' as const }\n : tableCaps;\n\n const model = buildGatewayModel(inputs);\n const provider = {\n name: 'PostHog Gateway',\n baseUrl: model.baseUrl,\n apiKey: accessToken,\n authHeader: true,\n api,\n headers: model.headers,\n models: [model],\n };\n return { provider, api, caps, gatewayUrl, baseUrl: model.baseUrl };\n}\n\n/** The part of a pi assistant turn that says why it failed. */\nexport interface GatewayTurnError {\n errorMessage?: string;\n diagnostics?: { error?: { name?: string; code?: string | number } }[];\n}\n\nexport type GatewayTerminalFailure = {\n classification:\n | AgentErrorType.API_ERROR\n | AgentErrorType.RATE_LIMIT\n | AgentErrorType.ABORT;\n message: string;\n status?: number;\n};\n\nexport function gatewayTerminalFailure(\n turn: ({ stopReason?: string } & GatewayTurnError) | undefined,\n): GatewayTerminalFailure | undefined {\n if (!turn || (turn.stopReason !== 'error' && turn.stopReason !== 'aborted'))\n return undefined;\n const message =\n turn.errorMessage ||\n (turn.stopReason === 'aborted'\n ? 'Agent turn aborted'\n : 'Gateway request failed');\n if (turn.stopReason === 'aborted') {\n return { classification: AgentErrorType.ABORT, message };\n }\n const codes =\n turn.diagnostics\n ?.map((d) => d.error?.code)\n .filter((code) => code !== undefined) ?? [];\n const structuredStatus = codes\n .map(Number)\n .find((code) => Number.isInteger(code) && code >= 400 && code < 600);\n const rateLimited =\n structuredStatus !== undefined\n ? structuredStatus === 429\n : /\\b429\\b|rate limit/i.test(message);\n return {\n classification: rateLimited\n ? AgentErrorType.RATE_LIMIT\n : AgentErrorType.API_ERROR,\n message,\n status:\n structuredStatus ?? (isGatewayAuthRejection(turn) ? 401 : undefined),\n };\n}\n\n/**\n * Whether a turn's error is the gateway rejecting the bearer. pi attaches the\n * SDK's own error to `diagnostics`, so its code decides when one is present.\n * The message match is the fallback for a turn that failed before pi built a\n * diagnostic, where the status survives only as prose.\n */\nexport function isGatewayAuthRejection(\n turn: GatewayTurnError | string | undefined,\n): boolean {\n const { errorMessage, diagnostics } =\n typeof turn === 'string'\n ? { errorMessage: turn, diagnostics: undefined }\n : turn ?? {};\n const structuredStatus = (diagnostics ?? [])\n .map((diagnostic) => Number(diagnostic.error?.code))\n .find((code) => Number.isInteger(code) && code >= 400 && code < 600);\n if (structuredStatus !== undefined) return structuredStatus === 401;\n for (const diagnostic of diagnostics ?? []) {\n const code = diagnostic.error?.code;\n if (code === 401 || code === '401') return true;\n if (/^authentication_?error$/i.test(diagnostic.error?.name ?? ''))\n return true;\n }\n return /\\b401\\b|authentication_error|unauthorized/i.test(errorMessage ?? '');\n}\n\nexport interface GatewayRemintOptions {\n signal?: AbortSignal;\n session: { prompt(text: string): Promise<void> };\n registry: { registerProvider(providerName: string, config: never): void };\n auth: GatewayAuth;\n /** The cache: the same token while fresh, a new mint past the refresh point. */\n refreshAuth: () => Promise<GatewayAuth>;\n providerInputs: (auth: GatewayAuth) => GatewayProviderInputs;\n /** The prompt that resumes the work after a re-mint. */\n continueText: string | (() => string);\n onRemint?: () => void;\n}\n\n/**\n * Wraps a pi session's prompt(): when a turn ends on a 401 from a bearer past\n * its refresh instant, mint once, re-register the provider with the new\n * bearer (pi resolves the apiKey per request), and continue. A 401 on a fresh\n * bearer, or a second one, is left to the harness's normal failure path.\n */\nexport function withGatewayRemint(opts: GatewayRemintOptions): {\n prompt(text: string): Promise<void>;\n /** Feed every assistant `message_end`; the last turn decides. */\n noteAssistantTurn(message: unknown): void;\n terminalFailure(): GatewayTerminalFailure | undefined;\n} {\n let auth = opts.auth;\n let rejected = false;\n let reminted = false;\n let lastTurn: ({ stopReason?: string } & GatewayTurnError) | undefined;\n return {\n noteAssistantTurn(message) {\n lastTurn = message as\n | ({ stopReason?: string } & GatewayTurnError)\n | undefined;\n rejected =\n lastTurn?.stopReason === 'error' && isGatewayAuthRejection(lastTurn);\n },\n terminalFailure: () => gatewayTerminalFailure(lastTurn),\n async prompt(text) {\n if (opts.signal?.aborted) return;\n rejected = false;\n lastTurn = undefined;\n await opts.session.prompt(text);\n if (opts.signal?.aborted || !rejected || reminted || !isPastRefresh(auth))\n return;\n reminted = true;\n auth = await opts.refreshAuth();\n if (opts.signal?.aborted) return;\n opts.registry.registerProvider(\n GATEWAY_PROVIDER,\n buildGatewayProvider(opts.providerInputs(auth)).provider as never,\n );\n opts.onRemint?.();\n rejected = false;\n lastTurn = undefined;\n const next = opts.continueText;\n if (opts.signal?.aborted) return;\n await opts.session.prompt(typeof next ===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qBAAqB,KAAA,EAAW,QAAO,qBAAqB;AAChE,MAAK,MAAM,cAAc,eAAe,EAAE,EAAE;EAC1C,MAAM,OAAO,WAAW,OAAO;AAC/B,MAAI,SAAS,OAAO,SAAS,MAAO,QAAO;AAC3C,MAAI,2BAA2B,KAAK,WAAW,OAAO,QAAQ,GAAG,CAC/D,QAAO;;AAEX,QAAO,6CAA6C,KAAK,gBAAgB,GAAG;;;;;;;;AAsB9E,SAAgB,kBAAkB,MAKhC;CACA,IAAI,OAAO,KAAK;CAChB,IAAI,WAAW;CACf,IAAI,WAAW;CACf,IAAI;AACJ,QAAO;EACL,kBAAkB,SAAS;AACzB,cAAW;AAGX,cACE,UAAU,eAAe,WAAW,uBAAuB,SAAS;;EAExE,uBAAuB,uBAAuB,SAAS;EACvD,MAAM,OAAO,MAAM;AACjB,OAAI,KAAK,QAAQ,QAAS;AAC1B,cAAW;AACX,cAAW,KAAA;AACX,SAAM,KAAK,QAAQ,OAAO,KAAK;AAC/B,OAAI,KAAK,QAAQ,WAAW,CAAC,YAAY,YAAY,CAAC,cAAc,KAAK,CACvE;AACF,cAAW;AACX,UAAO,MAAM,KAAK,aAAa;AAC/B,OAAI,KAAK,QAAQ,QAAS;AAC1B,QAAK,SAAS,iBACZ,kBACA,qBAAqB,KAAK,eAAe,KAAK,CAAC,CAAC,SACjD;AACD,QAAK,YAAY;AACjB,cAAW;AACX,cAAW,KAAA;GACX,MAAM,OAAO,KAAK;AAClB,OAAI,KAAK,QAAQ,QAAS;AAC1B,SAAM,KAAK,QAAQ,OAAO,OAAO,SAAS,aAAa,MAAM,GAAG,KAAK;;EAExE"}
1
+ {"version":3,"file":"gateway-BmjYUSua.js","names":[],"sources":["../src/agent/gateway-session.ts","../src/agent/signals.ts","../src/agent/runner/harness/pi/gateway.ts"],"sourcesContent":["/**\n * Gateway auth for a wizard run: a `phe_` scoped token the backend mints, with\n * pinned attribution, a spend cap and an expiry.\n *\n * Every mint failure throws: a silent downgrade would spend uncapped,\n * unattributed money to hide an outage.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport { ErrorCodes, WizardError } from '@shared/errors';\nimport type { HostResolution } from '@shared/host-resolution';\nimport { oauthLoginKey } from '@shared/oauth-session';\nimport { checkLlmGatewayHealth } from '@shared/health-checks/endpoints';\nimport { ServiceHealthStatus } from '@shared/health-checks/types';\nimport { IS_PRODUCTION_BUILD, runtimeEnv } from '@env';\nimport type { CloudRegion } from '@utils/types';\n\nexport interface GatewayAuth {\n /** Base URL for model calls (no `/v1`; transports append their route). */\n gatewayUrl: string;\n /** Gateway bearer, minted normally or supplied directly by CI. */\n token: string;\n /** Team verified by the mint, or explicitly supplied for CI attribution. */\n teamId?: number;\n /**\n * Instant past which a 401 on this bearer is age rather than a bad\n * credential: the cache re-mints past it, and a session still holding the\n * old bearer may re-mint once. Before it the mint has to be trusted.\n */\n refreshAtMs: number;\n}\n\ninterface CachedAuth {\n key: string;\n auth: GatewayAuth;\n /** Re-resolve once past this instant. */\n staleAtMs: number;\n}\n\nlet cached: CachedAuth | null = null;\n/**\n * Shared so concurrent callers mint once. The orchestrator starts every runnable\n * task at once, and each would otherwise take its own token and its own cap.\n */\nlet inFlight: { key: string; promise: Promise<GatewayAuth> } | null = null;\nlet ciAuth: GatewayAuth | null = null;\n\n// Snapshot CI supplies a gateway bearer without minting or re-minting.\nexport function configureGatewayCredentialsForCI(\n token: string,\n projectId: number,\n gatewayUrl: string,\n): void {\n if (IS_PRODUCTION_BUILD)\n throw new Error('CI gateway auth requires a non-production build');\n if (!token.trim() || !Number.isSafeInteger(projectId) || projectId <= 0) {\n throw new Error('CI gateway auth requires a token and valid project ID');\n }\n if (\n !/^https?:\\/\\//.test(gatewayUrl) ||\n !isTrustedGatewayUrl(gatewayUrl, '')\n ) {\n throw new Error('CI gateway auth requires a trusted gateway origin');\n }\n resetGatewaySession();\n ciAuth = {\n token: token.trim(),\n teamId: projectId,\n gatewayUrl: gatewayUrl.replace(/\\/+$/, ''),\n refreshAtMs: Infinity,\n };\n}\n\n// TODO: CI credential loading belongs outside the agent. It leaves with the rest\n// of this module once RunInput carries resolved inference auth, later in the\n// refactor.\nexport function configureGatewayFromCIEnvironment(\n projectId: number,\n region: CloudRegion,\n): void {\n if (IS_PRODUCTION_BUILD)\n throw new Error('CI gateway auth requires a non-production build');\n const path = runtimeEnv('WIZARD_CI_GATEWAY_TOKEN_FILE');\n if (!path) throw new Error('WIZARD_CI_GATEWAY_TOKEN_FILE is required for CI');\n const token = readFileSync(path, 'utf8');\n delete process.env.WIZARD_CI_GATEWAY_TOKEN_FILE;\n configureGatewayCredentialsForCI(\n token,\n projectId,\n runtimeEnv('WIZARD_CI_GATEWAY_URL') ||\n `https://ai-gateway.${region}.posthog.com`,\n );\n}\n\n/**\n * Adoption floor. The anthropic subprocess holds its credential until a 401\n * forces a re-mint, so a token below this would churn mints.\n */\nconst MIN_USABLE_TTL_MS = 2 * 60 * 1000;\n/** Re-resolve at this fraction of the token's life, leaving a usable remainder. */\nconst REFRESH_AT_FRACTION = 0.8;\n// Exceeds the backend's own 10s gateway timeout: a slow mint that lands after the\n// CLI hangs up spends a daily mint and orphans a live token.\nconst MINT_TIMEOUT_MS = 20_000;\n/** Longer than any refusal the mint writes; a body past this is not a message. */\nconst MAX_REFUSAL_DETAIL_LENGTH = 500;\n/** Outcomes are short snake_case labels; anything longer is not one. */\nconst MAX_REFUSAL_OUTCOME_LENGTH = 64;\n\n/** Resolve this run's gateway auth, minting and re-minting near expiry. */\nexport async function gatewayAuth(\n host: HostResolution,\n accessToken: string,\n program: string | undefined,\n): Promise<GatewayAuth> {\n if (ciAuth) return ciAuth;\n // Keyed by program: a token pins `wizard:<program>`, so reusing one across\n // programs bills the wrong budget. Keyed by login rather than OAuth token:\n // the token rotates mid-run, and each new one would spend a weekly mint.\n const key = `${host.apiHost}\\n${oauthLoginKey(accessToken)}\\n${\n program ?? ''\n }`;\n if (cached && cached.key === key && Date.now() < cached.staleAtMs) {\n return cached.auth;\n }\n if (inFlight && inFlight.key === key) return inFlight.promise;\n const promise = resolveGatewayAuth(host, accessToken, key, program);\n inFlight = { key, promise };\n try {\n return await promise;\n } finally {\n if (inFlight?.promise === promise) inFlight = null;\n }\n}\n\nasync function resolveGatewayAuth(\n host: HostResolution,\n accessToken: string,\n key: string,\n program: string | undefined,\n): Promise<GatewayAuth> {\n if (!program) {\n // Every run has one; absent means a caller was not wired, and the spend would\n // be unattributable.\n logToFile('[gateway] run has no program id; failing the run');\n throw new GatewayMintFailed(\n 'this run has no program to attribute its spend to',\n );\n }\n const minted = await mintGatewayToken(host, accessToken, program);\n const health = await checkLlmGatewayHealth(minted.gatewayUrl);\n if (health.status !== ServiceHealthStatus.Healthy) {\n throw new WizardError(\n 'The PostHog AI gateway is unavailable. Please try again later.',\n undefined,\n ErrorCodes.EnvServiceOutage,\n );\n }\n const expiresAtMs = Date.parse(minted.expiresAt);\n const ttlMs = expiresAtMs - Date.now();\n if (!Number.isFinite(expiresAtMs) || ttlMs < MIN_USABLE_TTL_MS) {\n // Expired, unreadable, or too short to serve a session. Adopting it would\n // 401 mid-run, and downgrading would spend the rest of the run uncapped.\n logToFile(\n `[gateway] mint returned a token with ${ttlMs}ms of life; failing the run`,\n );\n throw new GatewayMintFailed(\n `the PostHog gateway issued a token with ${ttlMs}ms of life`,\n );\n }\n const staleAtMs = Date.now() + ttlMs * REFRESH_AT_FRACTION;\n // Only failures are logged otherwise, so a successful run leaves no\n // local trace. Never log the token itself.\n logToFile(\n `[gateway] minted a scoped token: program=${program} team=${\n minted.teamId ?? 'unknown'\n } ttl=${Math.round(ttlMs / 1000)}s url=${minted.gatewayUrl}`,\n );\n const auth: GatewayAuth = {\n gatewayUrl: minted.gatewayUrl,\n token: minted.token,\n teamId: minted.teamId,\n refreshAtMs: staleAtMs,\n };\n cached = { key, auth, staleAtMs };\n return auth;\n}\n\n/** Test hook: drop the cached auth so the next call re-resolves. */\nexport function resetGatewaySession(): void {\n cached = null;\n inFlight = null;\n ciAuth = null;\n}\n\n/** Whether a 401 on this bearer may be age (past its refresh instant) rather than a bad credential. */\nexport function isPastRefresh(auth: GatewayAuth, now = Date.now()): boolean {\n return now >= auth.refreshAtMs;\n}\n\n/**\n * Whether a server-supplied origin may receive a bearer and prompt content:\n * https (loopback excepted), and either a current cloud gateway or the host the run\n * authenticated against.\n */\nexport function isTrustedGatewayUrl(value: string, apiHost: string): boolean {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n // Consumers append routes to this value, so anything beyond an origin\n // (path, query, fragment, userinfo) would build a malformed endpoint.\n if (\n url.pathname !== '/' ||\n url.search ||\n url.hash ||\n url.username ||\n url.password\n ) {\n return false;\n }\n const localhost =\n url.hostname === 'localhost' ||\n url.hostname === '127.0.0.1' ||\n url.hostname === 'host.docker.internal';\n // Loopback is the dev gateway, and is the one case allowed over http.\n if (localhost) return true;\n if (url.protocol !== 'https:') return false;\n if (url.hostname.endsWith('.posthog.com')) {\n return (\n url.origin === 'https://ai-gateway.us.posthog.com' ||\n url.origin === 'https://ai-gateway.eu.posthog.com'\n );\n }\n try {\n return url.hostname === new URL(apiHost).hostname;\n } catch {\n return false;\n }\n}\n\ninterface MintedToken {\n token: string;\n expiresAt: string;\n gatewayUrl: string;\n teamId?: number;\n}\n\n/**\n * A deliberate refusal from the mint endpoint, as opposed to the mint being\n * unavailable. Thrown so the run stops instead of proceeding without the\n * controls the refusal was enforcing. A WizardError, so the runners print its\n * message as-is and `wizardAbort` resolves its code.\n */\nexport class GatewayMintRefused extends WizardError {\n readonly status: number;\n /** The backend's refusal outcome (`blocked`, `throttled`, ...), when it sent one. */\n readonly outcome?: string;\n\n constructor(status: number, message: string, outcome?: string) {\n super(message, { status, outcome }, ErrorCodes.GatewayMintRefused);\n this.name = 'GatewayMintRefused';\n this.status = status;\n this.outcome = outcome;\n }\n}\n\n/**\n * The mint could not produce a usable credential: unreachable, a 5xx, or a\n * response the client cannot use.\n */\nexport class GatewayMintFailed extends WizardError {\n constructor(message: string) {\n super(message, undefined, ErrorCodes.GatewayMintFailed);\n this.name = 'GatewayMintFailed';\n }\n}\n\n/**\n * Whether a mint status means \"refused this run\" rather than \"not available\".\n * 429 the daily run limit, 403 revoked project access, 400 a login covering\n * more than one project, 401 a credential the mint does not accept, 404 an\n * instance without the mint endpoint.\n */\nfunction isMintRefusal(status: number): boolean {\n return (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 429\n );\n}\n\ninterface MintRefusal {\n detail?: string;\n outcome?: string;\n}\n\n/**\n * The server's own reason for a refusal, when it sent one. DRF answers every\n * refusal as `{\"detail\": \"...\", \"code\": \"<outcome>\"}`; the blocklist's detail\n * names the contact address, which the fixed messages below cannot. `code` is\n * the backend's own label for the refusal (`outcome` on older backends) and\n * rides the client event.\n */\nfunction cleanRefusalText(value: unknown): string {\n if (typeof value !== 'string') return '';\n // Not because the server sends escapes, but because this string is printed\n // straight to a terminal: sanitizing at the boundary means no later message\n // can move the cursor or repaint the screen.\n // eslint-disable-next-line no-control-regex\n return value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, ' ').trim();\n}\n\nasync function readRefusal(resp: Response): Promise<MintRefusal> {\n try {\n const body = (await resp.json()) as {\n detail?: unknown;\n code?: unknown;\n outcome?: unknown;\n };\n const detail = cleanRefusalText(body?.detail);\n // The DRF handler flattens a dict detail, so the outcome rides as `code`.\n // A `code` that cleans to nothing does not shadow a usable `outcome`.\n const outcome =\n cleanRefusalText(body?.code) || cleanRefusalText(body?.outcome);\n return {\n detail:\n detail.length > 0 && detail.length <= MAX_REFUSAL_DETAIL_LENGTH\n ? detail\n : undefined,\n outcome:\n outcome.length > 0 && outcome.length <= MAX_REFUSAL_OUTCOME_LENGTH\n ? outcome\n : undefined,\n };\n } catch {\n return {};\n }\n}\n\nfunction mintRefusalMessage(status: number, detail?: string): string {\n if (detail) return detail;\n switch (status) {\n case 429:\n return 'This wizard program has used its daily run limit. Try again tomorrow.';\n case 403:\n return 'Your access to this project has changed. Re-authenticate and try again.';\n case 400:\n // The only 400 the mint answers is the exactly-one-project check.\n return 'Your PostHog login must cover exactly one project. Re-authenticate and try again.';\n case 401:\n return 'PostHog did not accept this login. Re-authenticate with `npx @posthog/wizard@latest`.';\n case 404:\n return 'This PostHog instance does not issue gateway tokens. Upgrade with `npx @posthog/wizard@latest` and try again.';\n default:\n return 'The PostHog gateway refused this run.';\n }\n}\n\nasync function mintGatewayToken(\n host: HostResolution,\n accessToken: string,\n program: string,\n): Promise<MintedToken> {\n try {\n const resp = await fetch(`${host.apiHost}/api/wizard/gateway_token/`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n },\n // The flag tells the server this build reads a refusal, so it may answer\n // with the reason. A build that omits it gets a 404, which is its signal\n // to fall back to the legacy gateway.\n body: JSON.stringify({ program, reads_refusal_reason: true }),\n signal: AbortSignal.timeout(MINT_TIMEOUT_MS),\n });\n if (!resp.ok) {\n if (isMintRefusal(resp.status)) {\n const refusal = await readRefusal(resp);\n logToFile(\n `[gateway] mint refused with HTTP ${resp.status} (${\n refusal.outcome ?? 'no outcome'\n }); failing the run`,\n );\n // The terminal denial event for this run. The backend's own event has\n // no run id, so this is what joins a refusal to the session.\n analytics.wizardCapture('gateway mint refused', {\n status: resp.status,\n outcome: refusal.outcome,\n program,\n });\n throw new GatewayMintRefused(\n resp.status,\n mintRefusalMessage(resp.status, refusal.detail),\n refusal.outcome,\n );\n }\n logToFile(\n `[gateway] mint failed with HTTP ${resp.status}; failing the run`,\n );\n throw new GatewayMintFailed(\n `the PostHog gateway could not issue a token (HTTP ${resp.status})`,\n );\n }\n const body = (await resp.json()) as {\n token?: string;\n expires_at?: string;\n gateway_url?: string;\n team_id?: number;\n };\n // Checked one at a time, not in a loop, so each clause narrows the optional\n // field for the return below and each names itself in the failure.\n if (!body.token) {\n logToFile('[gateway] mint response omitted token; failing the run');\n throw new GatewayMintFailed('mint response omitted token');\n }\n if (!body.expires_at) {\n logToFile('[gateway] mint response omitted expires_at; failing the run');\n throw new GatewayMintFailed('mint response omitted expires_at');\n }\n if (!body.gateway_url) {\n logToFile('[gateway] mint response omitted gateway_url; failing the run');\n throw new GatewayMintFailed('mint response omitted gateway_url');\n }\n if (!isTrustedGatewayUrl(body.gateway_url, host.apiHost)) {\n logToFile(\n '[gateway] mint returned an untrusted gateway url; failing the run',\n );\n throw new GatewayMintFailed('mint returned an untrusted gateway url');\n }\n const gatewayUrl = new URL(body.gateway_url);\n if (\n ['localhost', '127.0.0.1'].includes(new URL(host.apiHost).hostname) &&\n gatewayUrl.hostname === 'host.docker.internal'\n ) {\n gatewayUrl.hostname = 'localhost';\n }\n return {\n token: body.token,\n expiresAt: body.expires_at,\n gatewayUrl: gatewayUrl.origin,\n teamId: body.team_id,\n };\n } catch (e) {\n // Decisions and failures both pass through: this catch exists for transport\n // errors, and folding the others into it would lose the reason.\n if (e instanceof GatewayMintRefused || e instanceof GatewayMintFailed)\n throw e;\n logToFile(\n `[gateway] mint transport failure (${String(e)}); failing the run`,\n );\n throw new GatewayMintFailed(\n `could not reach the PostHog gateway (${String(e)})`,\n );\n }\n}\n\n/**\n * The v2 run-metadata carrier: one JSON blob for the `X-PostHog-Properties`\n * header. Plain keys only, since the gateway strips `$`-prefixed keys as reserved,\n * so feature-flag variants land as `wizard_flag_<key>` instead of the legacy\n * `$feature/<key>` (dashboards keying on `$feature/wizard-*` read the new key\n * post-cutover).\n */\nexport function buildWizardPropertiesBlob(\n wizardMetadata: Record<string, string>,\n wizardFlags: Record<string, string>,\n teamId?: number,\n): string {\n // The gateway pins `$ai_product` to `wizard:<program>`, and rejects a legacy\n // product override on a scoped token, so the unprefixed key every cost and\n // error consumer reads is only present if this blob declares it.\n const props: Record<string, string | number> = { ai_product: 'wizard' };\n if (teamId !== undefined) props.team_id = teamId;\n for (const [key, value] of Object.entries(wizardMetadata)) {\n props[stripPropertyPrefix(key)] = value;\n }\n for (const [flagKey, variant] of Object.entries(wizardFlags)) {\n if (!flagKey.toLowerCase().startsWith('wizard')) continue;\n props[`wizard_flag_${flagKey.toLowerCase()}`] = variant;\n }\n return JSON.stringify(props);\n}\n\nconst LEGACY_PROPERTY_PREFIX = 'X-POSTHOG-PROPERTY-';\n\nfunction stripPropertyPrefix(key: string): string {\n return key.toUpperCase().startsWith(LEGACY_PROPERTY_PREFIX)\n ? key.slice(LEGACY_PROPERTY_PREFIX.length).toLowerCase()\n : key;\n}\n","/**\n * Agent signal vocabulary — the marker strings the agent emits and the error\n * taxonomy the runner returns. Kept as a dependency-free leaf module so both\n * `agent-interface.ts` and `output-signals.ts` can import it without a cycle.\n */\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the PostHog MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n /**\n * Signal emitted when `install_skill` failed and the agent is continuing\n * the integration WITHOUT the skill (best-effort from its own knowledge).\n * Format: \"[SKILL-INSTALL-FAILED] <skill id — reason>\". Non-fatal by\n * design: a freestyled integration beats an outright failure, but the run\n * must be measurable — the runner captures it as an analytics event.\n */\n SKILL_INSTALL_FAILED: '[SKILL-INSTALL-FAILED]',\n /**\n * Signal emitted when the agent cannot complete the program and is\n * aborting intentionally (distinct from errors). Format: \"[ABORT] <reason>\".\n * Programs can declare an onAbort handler to render a custom screen.\n */\n ABORT: '[ABORT]',\n /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\n /** Signal prefix for benchmark logging */\n BENCHMARK: '[BENCHMARK]',\n /**\n * Signal emitted when the agent has created a PostHog dashboard for the\n * user. Format: `[DASHBOARD_URL] <full https url>`. The URL is captured\n * onto `session.dashboardUrl` and surfaced by programs in their outro.\n */\n DASHBOARD_URL: '[DASHBOARD_URL]',\n /**\n * Signal emitted when the agent has uploaded a report to a PostHog\n * notebook. Format: `[NOTEBOOK_URL] <full https url>`. The URL is captured\n * onto `session.notebookUrl` and surfaced by programs in their outro.\n */\n NOTEBOOK_URL: '[NOTEBOOK_URL]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/**\n * End-of-run reflection ask, shared by both harnesses so remarks are\n * comparable. The format clause comes FIRST and nothing trails the marker —\n * literal models (gpt-5-mini) echo whatever text follows it. The parser also\n * drops remarks that quote this instruction (see AgentOutputSignals.remark).\n */\nexport const REMARK_INSTRUCTION = `Reply with a single line that starts with ${AgentSignals.WIZARD_REMARK} and no other lines. In that line, state briefly what information or guidance would have been useful to have in the integration prompt or documentation for this run — specifically anything that would have prevented tool failures, erroneous edits, or other wasted turns.`;\n\n/**\n * First prompt of a session resumed after a mid-run re-mint. The transcript\n * carries the work so far; the model only needs to pick it up.\n */\nexport const RESUME_INSTRUCTION =\n 'Your previous request failed with a transient gateway authentication error that has since been fixed. Continue the task from where you left off.';\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** The configured run deadline elapsed and the SDK query was aborted */\n AGENTIC_DETECTION_TIMEOUT = 'WIZARD_AGENTIC_DETECTION_TIMEOUT',\n /** Agent could not access the PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n /** YARA scanner detected a security violation */\n YARA_VIOLATION = 'WIZARD_YARA_VIOLATION',\n /** Agent intentionally aborted the program (emitted [ABORT] <reason>) */\n ABORT = 'WIZARD_ABORT',\n /** Agent ended without making a single tool call — a no-op run that did no work */\n NO_PROGRESS = 'WIZARD_NO_PROGRESS',\n /** A schema-bound run ended without output matching its schema */\n INVALID_STRUCTURED_OUTPUT = 'WIZARD_INVALID_STRUCTURED_OUTPUT',\n /** Agent acted but stopped short — planned tasks left open and/or no skill installed */\n INCOMPLETE_TASKS = 'WIZARD_INCOMPLETE_TASKS',\n}\n","/**\n * PostHog AI gateway provider spec for pi sessions, shared by the linear run\n * and the orchestrator's per-task runs so both speak to the gateway\n * identically: bearer auth, the wizard properties header, transport shape\n * inferred from the model id. The caller registers the spec on its own\n * (lazily imported, properly typed) pi ModelRegistry.\n */\n\nimport {\n buildWizardPropertiesBlob,\n isPastRefresh,\n type GatewayAuth,\n} from '@agent/gateway-session';\nimport {\n modelCapabilities,\n type ThinkingLevel,\n} from '../../switchboard/models';\nimport { AgentErrorType } from '@agent/signals';\n\n/** Provider registered on the in-memory registry for this run. */\nexport const GATEWAY_PROVIDER = 'posthog-gateway';\n\n/** The pi transports the gateway serves. */\nexport type GatewayApi =\n | 'anthropic-messages'\n | 'openai-completions'\n | 'openai-responses';\n\n/**\n * The gateway speaks two shapes on two endpoints: Anthropic models over\n * `anthropic-messages` (the SDK appends `/v1/messages`, so the base URL has no\n * `/v1`), and OpenAI-class models (`openai/gpt-5`, …) over an OpenAI shape at\n * `/v1/responses` or `/v1/chat/completions` (base URL keeps `/v1`). Infer the\n * shape from the model id so a pair's model selects the right transport.\n *\n * OpenAI models take the Responses API because OpenAI rejects function tools\n * combined with `reasoning_effort` on chat completions and every task sends both.\n */\nexport function gatewayApiFor(modelId: string): GatewayApi {\n return modelId.startsWith('openai/')\n ? 'openai-responses'\n : 'anthropic-messages';\n}\n\n/**\n * Gateway HTTP headers, mirroring `buildAgentEnv` on the anthropic path: one\n * `X-PostHog-Properties` JSON blob (Bedrock fallback is native, so no opt-in)\n * plus the 1M context beta, since pi otherwise runs at 200k and overflows on\n * larger projects (the post-run compaction failures).\n */\nexport function buildGatewayHeaders(\n wizardMetadata: Record<string, string>,\n wizardFlags: Record<string, string>,\n teamId?: number,\n): Record<string, string> {\n return {\n 'anthropic-beta': 'context-1m-2025-08-07',\n 'X-PostHog-Properties': buildWizardPropertiesBlob(\n wizardMetadata,\n wizardFlags,\n teamId,\n ),\n };\n}\n\nexport interface GatewayProviderInputs {\n gatewayUrl: string;\n accessToken: string;\n /** Customer team for the properties blob (from the mint response). */\n teamId?: number;\n wizardMetadata: Record<string, string>;\n wizardFlags: Record<string, string>;\n modelId: string;\n // Resolved effort override — the switchboard's flag/payload pick on linear\n // runs, the prompt-frontmatter effort on per-task agents. Overrides the\n // table default for a reasoning model when set.\n effort?: ThinkingLevel;\n}\n\n/**\n * One gateway model spec — the single description of how to reach a model on\n * the gateway. The provider spec below wraps it for pi's registry; one-shot\n * callers (scan triage) hand it straight to `completeSimple`.\n */\nexport function buildGatewayModel(inputs: GatewayProviderInputs) {\n const { gatewayUrl, wizardMetadata, wizardFlags, modelId, teamId } = inputs;\n const api = gatewayApiFor(modelId);\n return {\n id: modelId,\n name: `${modelId} (PostHog Gateway)`,\n api,\n provider: GATEWAY_PROVIDER,\n // Anthropic drops /v1 (the SDK appends /v1/messages); the OpenAI shape keeps it.\n baseUrl: api === 'anthropic-messages' ? gatewayUrl : `${gatewayUrl}/v1`,\n // A model trait resolved by the switchboard, not a harness guess:\n // non-reasoning openai models reject `reasoning_effort` (gpt-4o → gateway\n // UnsupportedParamsError → the run no-ops).\n reasoning: modelCapabilities(modelId).reasoning,\n input: ['text' as const],\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n contextWindow: 1_000_000,\n maxTokens: 64_000,\n headers: buildGatewayHeaders(wizardMetadata, wizardFlags, teamId),\n };\n}\n\n/**\n * The provider object for `registry.registerProvider(GATEWAY_PROVIDER, …)`,\n * plus the derived traits the session setup needs (`caps.thinkingLevel`).\n */\nexport function buildGatewayProvider(inputs: GatewayProviderInputs): {\n provider: Record<string, unknown>;\n api: GatewayApi;\n caps: ReturnType<typeof modelCapabilities>;\n gatewayUrl: string;\n baseUrl: string;\n} {\n const { gatewayUrl, accessToken, modelId, effort } = inputs;\n const api = gatewayApiFor(modelId);\n // One resolution point for the model's traits and the run's effort override.\n // pi clamps whatever comes out of here against the levels this spec declares,\n // so a level the spec doesn't carry is silently reduced by the session.\n const tableCaps = modelCapabilities(modelId);\n const caps =\n effort && effort !== 'off' && tableCaps.reasoning\n ? modelCapabilities(modelId, effort)\n : effort === 'off' && tableCaps.reasoning\n ? { ...tableCaps, thinkingLevel: 'off' as const }\n : tableCaps;\n\n const model = buildGatewayModel(inputs);\n const provider = {\n name: 'PostHog Gateway',\n baseUrl: model.baseUrl,\n apiKey: accessToken,\n authHeader: true,\n api,\n headers: model.headers,\n models: [model],\n };\n return { provider, api, caps, gatewayUrl, baseUrl: model.baseUrl };\n}\n\n/** The part of a pi assistant turn that says why it failed. */\nexport interface GatewayTurnError {\n errorMessage?: string;\n diagnostics?: { error?: { name?: string; code?: string | number } }[];\n}\n\nexport type GatewayTerminalFailure = {\n classification:\n | AgentErrorType.API_ERROR\n | AgentErrorType.RATE_LIMIT\n | AgentErrorType.ABORT;\n message: string;\n status?: number;\n};\n\nexport function gatewayTerminalFailure(\n turn: ({ stopReason?: string } & GatewayTurnError) | undefined,\n): GatewayTerminalFailure | undefined {\n if (!turn || (turn.stopReason !== 'error' && turn.stopReason !== 'aborted'))\n return undefined;\n const message =\n turn.errorMessage ||\n (turn.stopReason === 'aborted'\n ? 'Agent turn aborted'\n : 'Gateway request failed');\n if (turn.stopReason === 'aborted') {\n return { classification: AgentErrorType.ABORT, message };\n }\n const codes =\n turn.diagnostics\n ?.map((d) => d.error?.code)\n .filter((code) => code !== undefined) ?? [];\n const structuredStatus = codes\n .map(Number)\n .find((code) => Number.isInteger(code) && code >= 400 && code < 600);\n const rateLimited =\n structuredStatus !== undefined\n ? structuredStatus === 429\n : /\\b429\\b|rate limit/i.test(message);\n return {\n classification: rateLimited\n ? AgentErrorType.RATE_LIMIT\n : AgentErrorType.API_ERROR,\n message,\n status:\n structuredStatus ?? (isGatewayAuthRejection(turn) ? 401 : undefined),\n };\n}\n\n/**\n * Whether a turn's error is the gateway rejecting the bearer. pi attaches the\n * SDK's own error to `diagnostics`, so its code decides when one is present.\n * The message match is the fallback for a turn that failed before pi built a\n * diagnostic, where the status survives only as prose.\n */\nexport function isGatewayAuthRejection(\n turn: GatewayTurnError | string | undefined,\n): boolean {\n const { errorMessage, diagnostics } =\n typeof turn === 'string'\n ? { errorMessage: turn, diagnostics: undefined }\n : turn ?? {};\n const structuredStatus = (diagnostics ?? [])\n .map((diagnostic) => Number(diagnostic.error?.code))\n .find((code) => Number.isInteger(code) && code >= 400 && code < 600);\n if (structuredStatus !== undefined) return structuredStatus === 401;\n for (const diagnostic of diagnostics ?? []) {\n const code = diagnostic.error?.code;\n if (code === 401 || code === '401') return true;\n if (/^authentication_?error$/i.test(diagnostic.error?.name ?? ''))\n return true;\n }\n return /\\b401\\b|authentication_error|unauthorized/i.test(errorMessage ?? '');\n}\n\nexport interface GatewayRemintOptions {\n signal?: AbortSignal;\n session: { prompt(text: string): Promise<void> };\n registry: { registerProvider(providerName: string, config: never): void };\n auth: GatewayAuth;\n /** The cache: the same token while fresh, a new mint past the refresh point. */\n refreshAuth: () => Promise<GatewayAuth>;\n providerInputs: (auth: GatewayAuth) => GatewayProviderInputs;\n /** The prompt that resumes the work after a re-mint. */\n continueText: string | (() => string);\n onRemint?: () => void;\n}\n\n/**\n * Wraps a pi session's prompt(): when a turn ends on a 401 from a bearer past\n * its refresh instant, mint once, re-register the provider with the new\n * bearer (pi resolves the apiKey per request), and continue. A 401 on a fresh\n * bearer, or a second one, is left to the harness's normal failure path.\n */\nexport function withGatewayRemint(opts: GatewayRemintOptions): {\n prompt(text: string): Promise<void>;\n /** Feed every assistant `message_end`; the last turn decides. */\n noteAssistantTurn(message: unknown): void;\n terminalFailure(): GatewayTerminalFailure | undefined;\n} {\n let auth = opts.auth;\n let rejected = false;\n let reminted = false;\n let lastTurn: ({ stopReason?: string } & GatewayTurnError) | undefined;\n return {\n noteAssistantTurn(message) {\n lastTurn = message as\n | ({ stopReason?: string } & GatewayTurnError)\n | undefined;\n rejected =\n lastTurn?.stopReason === 'error' && isGatewayAuthRejection(lastTurn);\n },\n terminalFailure: () => gatewayTerminalFailure(lastTurn),\n async prompt(text) {\n if (opts.signal?.aborted) return;\n rejected = false;\n lastTurn = undefined;\n await opts.session.prompt(text);\n if (opts.signal?.aborted || !rejected || reminted || !isPastRefresh(auth))\n return;\n reminted = true;\n auth = await opts.refreshAuth();\n if (opts.signal?.aborted) return;\n opts.registry.registerProvider(\n GATEWAY_PROVIDER,\n buildGatewayProvider(opts.providerInputs(auth)).provider as never,\n );\n opts.onRemint?.();\n rejected = false;\n lastTurn = undefined;\n const next = opts.continueText;\n if (opts.signal?.aborted) return;\n await opts.session.prompt(typeof next === 'function' ? next() : next);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,IAAI,SAA4B;;;;;AAKhC,IAAI,WAAkE;AAgCtE,SAAgB,kCACd,WACA,QACM;AAEJ,OAAM,IAAI,MAAM,kDAAkD;;;;;;AAiBtE,MAAM,oBAAoB,MAAS;;AAEnC,MAAM,sBAAsB;AAG5B,MAAM,kBAAkB;;AAExB,MAAM,4BAA4B;;AAElC,MAAM,6BAA6B;;AAGnC,eAAsB,YACpB,MACA,aACA,SACsB;CAKtB,MAAM,MAAM,GAAG,KAAK,QAAQ,IAAI,cAAc,YAAY,CAAC,IACzD,WAAW;AAEb,KAAI,UAAU,OAAO,QAAQ,OAAO,KAAK,KAAK,GAAG,OAAO,UACtD,QAAO,OAAO;AAEhB,KAAI,YAAY,SAAS,QAAQ,IAAK,QAAO,SAAS;CACtD,MAAM,UAAU,mBAAmB,MAAM,aAAa,KAAK,QAAQ;AACnE,YAAW;EAAE;EAAK;EAAS;AAC3B,KAAI;AACF,SAAO,MAAM;WACL;AACR,MAAI,UAAU,YAAY,QAAS,YAAW;;;AAIlD,eAAe,mBACb,MACA,aACA,KACA,SACsB;AACtB,KAAI,CAAC,SAAS;AAG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AS;AAC1B,QAAK,SAAS,iBACZ,kBACA,qBAAqB,KAAK,eAAe,KAAK,CAAC,CAAC,SACjD;AACD,QAAK,YAAY;AACjB,cAAW;AACX,cAAW,KAAA;GACX,MAAM,OAAO,KAAK;AAClB,OAAI,KAAK,QAAQ,QAAS;AAC1B,SAAM,KAAK,QAAQ,OAAO,OAAO,SAAS,aAAa,MAAM,GAAG,KAAK;;EAExE"}
@@ -1,5 +1,5 @@
1
- import "./wizard-session-2w4Ru-Wz.js";
2
- import { t as LoggingUI } from "./logging-ui-CUxNYF2t.js";
1
+ import "./wizard-session-BYw6LzpS.js";
2
+ import { t as LoggingUI } from "./logging-ui-p6XKVmTx.js";
3
3
  //#region src/ui/headless-ui.ts
4
4
  /**
5
5
  * `LoggingUI` plus it feeds run state into a `WizardStore` so the background
@@ -41,4 +41,4 @@ var HeadlessUI = class extends LoggingUI {
41
41
  //#endregion
42
42
  export { HeadlessUI };
43
43
 
44
- //# sourceMappingURL=headless-ui-pY2xB5ug.js.map
44
+ //# sourceMappingURL=headless-ui-CUbv12Yx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headless-ui-CUbv12Yx.js","names":[],"sources":["../src/ui/headless-ui.ts"],"sourcesContent":["import { RunPhase, type Credentials } from '@programs/session/wizard-session';\nimport { LoggingUI } from '../headless/renderers/logging-ui';\nimport type { WizardStore } from '../tui/store';\n\n/**\n * `LoggingUI` plus it feeds run state into a `WizardStore` so the background\n * wizard-session sync (`TaskStreamPush`) can observe a headless run. We extend\n * `LoggingUI` (not `InkUI`) because its blocking/gate methods would wait on a\n * TUI that never renders; the runner drives phase transitions on the store\n * directly, so only UI-originated per-run updates tee through here. The audit\n * ledger arrives through `setFrameworkContext`, the seam every UI implements.\n */\nexport class HeadlessUI extends LoggingUI {\n constructor(private readonly store: WizardStore) {\n super();\n }\n\n startRun(): void {\n super.startRun();\n this.store.setRunPhase(RunPhase.Running);\n }\n\n setCredentials(credentials: Credentials): void {\n this.store.setAccessToken(credentials);\n }\n\n setAccessToken(credentials: Credentials): void {\n this.store.setAccessToken(credentials);\n }\n\n syncTodos(\n todos: Array<{\n id?: string;\n source?: string;\n content: string;\n status: string;\n activeForm?: string;\n }>,\n ): void {\n super.syncTodos(todos);\n this.store.syncTodos(todos);\n }\n\n setHandoffText(text: string): void {\n this.store.setHandoffText(text);\n }\n\n setFrameworkContext(key: string, value: unknown): void {\n this.store.setFrameworkContext(key, value);\n }\n\n getFrameworkContext(key: string): unknown {\n return this.store.session.frameworkContext[key];\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,aAAb,cAAgC,UAAU;CACxC,YAAY,OAAqC;AAC/C,SAAO;AADoB,OAAA,QAAA;;CAI7B,WAAiB;AACf,QAAM,UAAU;AAChB,OAAK,MAAM,YAAA,UAA6B;;CAG1C,eAAe,aAAgC;AAC7C,OAAK,MAAM,eAAe,YAAY;;CAGxC,eAAe,aAAgC;AAC7C,OAAK,MAAM,eAAe,YAAY;;CAGxC,UACE,OAOM;AACN,QAAM,UAAU,MAAM;AACtB,OAAK,MAAM,UAAU,MAAM;;CAG7B,eAAe,MAAoB;AACjC,OAAK,MAAM,eAAe,KAAK;;CAGjC,oBAAoB,KAAa,OAAsB;AACrD,OAAK,MAAM,oBAAoB,KAAK,MAAM;;CAG5C,oBAAoB,KAAsB;AACxC,SAAO,KAAK,MAAM,QAAQ,iBAAiB"}
@@ -0,0 +1,114 @@
1
+ import "./debug-DyARf5TF.js";
2
+ import { n as MCP_LOCAL_URL } from "./local-dev-McsurOC-.js";
3
+ import { n as getCloudUrl, o as getUiHostFromHost, r as getHost, s as resolveBaseUrl, t as detectRegion } from "./urls-BI4kJ4qQ.js";
4
+ //#region src/shared/host-resolution.ts
5
+ /**
6
+ * HostResolution — the single, immutable snapshot of where the wizard talks to
7
+ * PostHog for one run.
8
+ *
9
+ * One cloud region (or a pinned `--base-url`) implies a whole family of hosts:
10
+ * the event-ingestion/API host, the user-facing web app host, the CDN asset
11
+ * host, the LLM gateway, and the MCP server. Rather than re-deriving each of
12
+ * these at every call site and threading `region` + `baseUrl` around as loose
13
+ * params, resolve once at auth time and pass this frozen object around — read
14
+ * the property you need.
15
+ *
16
+ * The actual region→URL math (and the `--base-url` override) lives in
17
+ * `@utils/urls`; this class is a thin, immutable façade over those resolvers so
18
+ * the override flows through every field without callers having to know about
19
+ * it. The OAuth-server URL stays in `@utils/urls` (`getOAuthUrl`) because it is
20
+ * needed *before* a region is known, so it can't come from this post-auth object.
21
+ */
22
+ const MCP_PROD_URL = "https://mcp.posthog.com/mcp";
23
+ function assetHostFor(region, baseUrl) {
24
+ const override = resolveBaseUrl(baseUrl);
25
+ if (override) return override;
26
+ return region === "eu" ? "https://eu-assets.i.posthog.com" : "https://us-assets.i.posthog.com";
27
+ }
28
+ function assetHostFromApiHost(apiHost) {
29
+ if (apiHost.includes("us.i.posthog.com")) return "https://us-assets.i.posthog.com";
30
+ if (apiHost.includes("eu.i.posthog.com")) return "https://eu-assets.i.posthog.com";
31
+ return apiHost;
32
+ }
33
+ /**
34
+ * Dev/CI only: the env override (see env.ts) wins even under --local-mcp;
35
+ * published builds strip the read. Don't name that env var in comments here —
36
+ * smoke-test.sh greps dist/*.js for it, and JSDoc survives bundling.
37
+ */
38
+ function mcpUrlFor(localMcp) {
39
+ return localMcp ? MCP_LOCAL_URL : MCP_PROD_URL;
40
+ }
41
+ var HostResolution = class HostResolution {
42
+ /** The resolved cloud region. `'us'` when a base URL is pinned. */
43
+ region;
44
+ /**
45
+ * Event-ingestion / REST API host (e.g. `https://us.i.posthog.com`, or the
46
+ * pinned `--base-url`). The SDK `host` written into the user's `.env`, the
47
+ * base for the wizard-session REST calls, and the host shown to the agent.
48
+ */
49
+ apiHost;
50
+ /**
51
+ * User-facing web app host (e.g. `https://us.posthog.com`). Use for any link
52
+ * we hand to the user or open in their browser (dashboards, settings, inbox,
53
+ * deep-link base).
54
+ */
55
+ appHost;
56
+ /** CDN asset host (e.g. `https://us-assets.i.posthog.com`). */
57
+ assetHost;
58
+ /**
59
+ * PostHog MCP server URL the agent connects to. Region-independent — the
60
+ * server resolves the user's region from the bearer token — so this is driven
61
+ * only by `--local-mcp` / `--local-dev` and the dev env override, not by
62
+ * region/base-url.
63
+ */
64
+ mcpUrl;
65
+ constructor(fields) {
66
+ this.region = fields.region;
67
+ this.apiHost = fields.apiHost;
68
+ this.appHost = fields.appHost;
69
+ this.assetHost = fields.assetHost;
70
+ this.mcpUrl = fields.mcpUrl;
71
+ Object.freeze(this);
72
+ }
73
+ /**
74
+ * Canonical path: build the host family from a resolved region. A pinned
75
+ * `--base-url` (via `opts.baseUrl`) wins for every origin; otherwise the
76
+ * region's standard hosts are used. Honors IS_DEV through `resolveBaseUrl`.
77
+ */
78
+ static fromRegion(region, opts = {}) {
79
+ return new HostResolution({
80
+ region,
81
+ apiHost: getHost(region, opts.baseUrl),
82
+ appHost: getCloudUrl(region, opts.baseUrl),
83
+ assetHost: assetHostFor(region, opts.baseUrl),
84
+ mcpUrl: mcpUrlFor(opts.localMcp ?? false)
85
+ });
86
+ }
87
+ /**
88
+ * Build from an ingestion host string (the provisioning API returns one). The
89
+ * given host is preserved verbatim as `apiHost`; the region and the derived
90
+ * app/asset/gateway hosts are inferred from it.
91
+ */
92
+ static fromApiHost(apiHost, opts = {}) {
93
+ return new HostResolution({
94
+ region: apiHost.includes("eu.") ? "eu" : "us",
95
+ apiHost,
96
+ appHost: getUiHostFromHost(apiHost),
97
+ assetHost: assetHostFromApiHost(apiHost),
98
+ mcpUrl: mcpUrlFor(opts.localMcp ?? false)
99
+ });
100
+ }
101
+ /**
102
+ * Resolve the region from an access token (the us/eu probe, skipped when a
103
+ * base URL is pinned), then build the host family. Used after OAuth and after
104
+ * CI-mode API-key auth.
105
+ */
106
+ static async fromAccessToken(accessToken, opts = {}) {
107
+ const region = opts.region ?? await detectRegion(accessToken, opts.baseUrl);
108
+ return HostResolution.fromRegion(region, opts);
109
+ }
110
+ };
111
+ //#endregion
112
+ export { mcpUrlFor as n, HostResolution as t };
113
+
114
+ //# sourceMappingURL=host-resolution-DVSb7kXb.js.map