@posthog/wizard 2.77.0 → 2.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +30 -15
  2. package/dist/{add-mcp-server-to-clients-BnRyE4pw.js → add-mcp-server-to-clients-JMv8LP-O.js} +6 -5
  3. package/dist/{add-mcp-server-to-clients-BnRyE4pw.js.map → add-mcp-server-to-clients-JMv8LP-O.js.map} +1 -1
  4. package/dist/agent-bCZ3i3fh.js +3085 -0
  5. package/dist/agent-bCZ3i3fh.js.map +1 -0
  6. package/dist/{agent-interface-Avtr_5M5.js → agent-interface-BAOIHuXS.js} +429 -378
  7. package/dist/agent-interface-BAOIHuXS.js.map +1 -0
  8. package/dist/{agent-prompt-loader-CHixNPgY.js → agent-prompt-loader-7Pd4CfZO.js} +6 -6
  9. package/dist/agent-prompt-loader-7Pd4CfZO.js.map +1 -0
  10. package/dist/analytics-BcV-WCM4.js +2 -0
  11. package/dist/{analytics-C67F2vee.js → analytics-CHCZ_qUR.js} +10 -6
  12. package/dist/analytics-CHCZ_qUR.js.map +1 -0
  13. package/dist/{api-Dj1yabTj.js → api-Diy_2fp8.js} +4 -17
  14. package/dist/api-Diy_2fp8.js.map +1 -0
  15. package/dist/bin.js +410 -68
  16. package/dist/bin.js.map +1 -1
  17. package/dist/{bounded-fs-CWRYuLAn.js → bounded-fs-Bx9zTe6m.js} +4 -4
  18. package/dist/bounded-fs-Bx9zTe6m.js.map +1 -0
  19. package/dist/check-screens.tsx +1 -1
  20. package/dist/{ci-install-CvXL5h13.js → ci-install-CDdQYsPe.js} +6 -5
  21. package/dist/ci-install-CDdQYsPe.js.map +1 -0
  22. package/dist/constants-jFI2SaE1.js +260 -0
  23. package/dist/constants-jFI2SaE1.js.map +1 -0
  24. package/dist/debug-Ch4BDOtD.js +171 -0
  25. package/dist/debug-Ch4BDOtD.js.map +1 -0
  26. package/dist/{debug-CziFS0cA.js → debug-M2gV2iDq.js} +1 -1
  27. package/dist/{defaults-4c4YwTmW.js → defaults-C6J7yL4O.js} +1 -1
  28. package/dist/{defaults-4c4YwTmW.js.map → defaults-C6J7yL4O.js.map} +1 -1
  29. package/dist/endpoints-DCVbM06L.js +108 -0
  30. package/dist/endpoints-DCVbM06L.js.map +1 -0
  31. package/dist/{env-api-key-BZ5wE3Y4.js → env-api-key-Qx8NnYHm.js} +3 -3
  32. package/dist/env-api-key-Qx8NnYHm.js.map +1 -0
  33. package/dist/{environment-BEvsey6i.js → environment-B07Bmxae.js} +6 -6
  34. package/dist/environment-B07Bmxae.js.map +1 -0
  35. package/dist/{errors-BoJvrdw8.js → errors-CQ9kttJD.js} +27 -34
  36. package/dist/errors-CQ9kttJD.js.map +1 -0
  37. package/dist/{file-BoD3REGB.js → file-BcLTjU16.js} +2 -2
  38. package/dist/{file-BoD3REGB.js.map → file-BcLTjU16.js.map} +1 -1
  39. package/dist/{file-watcher-BPFazvG_.js → file-watcher-DWc_bTs6.js} +2 -2
  40. package/dist/{file-watcher-BPFazvG_.js.map → file-watcher-DWc_bTs6.js.map} +1 -1
  41. package/dist/{gateway-session-xPFv6p5c.js → gateway-CjoShdLa.js} +175 -20
  42. package/dist/gateway-CjoShdLa.js.map +1 -0
  43. package/dist/generate-version.cjs +1 -1
  44. package/dist/{headless-ui-CsmQrDIl.js → headless-ui-BFFmYC4v.js} +13 -2
  45. package/dist/headless-ui-BFFmYC4v.js.map +1 -0
  46. package/dist/{interactive-Dej-sxvR.js → interactive-D6zV7brJ.js} +2 -2
  47. package/dist/{interactive-Dej-sxvR.js.map → interactive-D6zV7brJ.js.map} +1 -1
  48. package/dist/{local-dev-DPZiIPCK.js → local-dev-McsurOC-.js} +2 -2
  49. package/dist/local-dev-McsurOC-.js.map +1 -0
  50. package/dist/logging-ui-_TwoMNbG.js +226 -0
  51. package/dist/logging-ui-_TwoMNbG.js.map +1 -0
  52. package/dist/mcp-DAgaoGk5.js +97 -0
  53. package/dist/mcp-DAgaoGk5.js.map +1 -0
  54. package/dist/{mcp-prompt-streaming-BU_kuur_.js → mcp-prompt-streaming-I2U_X7BC.js} +7 -6
  55. package/dist/mcp-prompt-streaming-I2U_X7BC.js.map +1 -0
  56. package/dist/{mint-failure-BrleGqMd.js → mint-failure-D4nd2XmZ.js} +82 -25
  57. package/dist/mint-failure-D4nd2XmZ.js.map +1 -0
  58. package/dist/models-DDdBJKwT.js +83 -0
  59. package/dist/models-DDdBJKwT.js.map +1 -0
  60. package/dist/{non-interactive-DcOjH2fw.js → non-interactive-Dzow7YKY.js} +3 -3
  61. package/dist/non-interactive-Dzow7YKY.js.map +1 -0
  62. package/dist/oauth-session-DJ8h6GFa.js +74 -0
  63. package/dist/oauth-session-DJ8h6GFa.js.map +1 -0
  64. package/dist/{orchestrator-tools-DXwr8Sp3.js → orchestrator-tools-szcdscwn.js} +4 -4
  65. package/dist/orchestrator-tools-szcdscwn.js.map +1 -0
  66. package/dist/{package-json-xt3eeyBI.js → package-json-DY70kkNp.js} +2 -2
  67. package/dist/package-json-DY70kkNp.js.map +1 -0
  68. package/dist/{pi-mY8I2XkG.js → pi-D3h5Ok0i.js} +329 -65
  69. package/dist/pi-D3h5Ok0i.js.map +1 -0
  70. package/dist/{playground-CDUUKLkC.js → playground-5AB4WgNF.js} +11 -7
  71. package/dist/playground-5AB4WgNF.js.map +1 -0
  72. package/dist/{posthog-Hc_-9wrr.js → posthog-DNn574nW.js} +8 -3
  73. package/dist/posthog-DNn574nW.js.map +1 -0
  74. package/dist/{provisioning-xfdjhFtA.js → provisioning-B8uSqRZk.js} +6 -5
  75. package/dist/provisioning-B8uSqRZk.js.map +1 -0
  76. package/dist/{queue-tools-C8y_xZJi.js → queue-tools-9OOVx5TE.js} +7 -86
  77. package/dist/queue-tools-9OOVx5TE.js.map +1 -0
  78. package/dist/{registry-DTmREJ-f.js → registry-8YG-kuXk.js} +265 -6
  79. package/dist/registry-8YG-kuXk.js.map +1 -0
  80. package/dist/run-agent-legacy-d7rWlzQR.js +3739 -0
  81. package/dist/run-agent-legacy-d7rWlzQR.js.map +1 -0
  82. package/dist/{security-Dw2oFJjP.js → security-Cg_4a7vB.js} +6 -6
  83. package/dist/security-Cg_4a7vB.js.map +1 -0
  84. package/dist/{setup-utils-fjJTBhaB.js → setup-utils-CmTCTPkX.js} +46 -18
  85. package/dist/setup-utils-CmTCTPkX.js.map +1 -0
  86. package/dist/smoke-test.sh +1 -1
  87. package/dist/{start-tui-UNe2xQ0U.js → start-tui-CB2PZs1x.js} +38 -44
  88. package/dist/start-tui-CB2PZs1x.js.map +1 -0
  89. package/dist/{steps-C2yqOk_h.js → steps-BZcXRJNY.js} +7 -7
  90. package/dist/{steps-C2yqOk_h.js.map → steps-BZcXRJNY.js.map} +1 -1
  91. package/dist/{store-Bic4Cr3L.js → store-UN7c-ASf.js} +18 -28
  92. package/dist/store-UN7c-ASf.js.map +1 -0
  93. package/dist/{subagent-Dz41vV9j.js → subagent-BofIDK-O.js} +8 -3
  94. package/dist/subagent-BofIDK-O.js.map +1 -0
  95. package/dist/{task-5-fw_Vw3.js → task-r9t1UhQP.js} +124 -36
  96. package/dist/task-r9t1UhQP.js.map +1 -0
  97. package/dist/{task-stream-dVzl6b_q.js → task-stream-CMUilu54.js} +45 -15
  98. package/dist/task-stream-CMUilu54.js.map +1 -0
  99. package/dist/{tasks-D1c2z1aw.js → tasks-Bbv_lOBG.js} +17 -13
  100. package/dist/tasks-Bbv_lOBG.js.map +1 -0
  101. package/dist/{telemetry-BRnxBRWK.js → telemetry-D6ruCtnv.js} +5 -5
  102. package/dist/telemetry-D6ruCtnv.js.map +1 -0
  103. package/dist/{terminal-9bvRa4Qt.js → terminal-DrGyci_a.js} +39 -74
  104. package/dist/terminal-DrGyci_a.js.map +1 -0
  105. package/dist/{tools-Dp6i9k70.js → tools-Dyfh9aCD.js} +11 -11
  106. package/dist/tools-Dyfh9aCD.js.map +1 -0
  107. package/dist/ui-BBVuTM1v.js +15 -0
  108. package/dist/ui-BBVuTM1v.js.map +1 -0
  109. package/dist/version-aXxpgRKx.js +6 -0
  110. package/dist/version-aXxpgRKx.js.map +1 -0
  111. package/dist/warlock-smoke-test.ts +2 -2
  112. package/dist/{wizard-abort-lE6umflt.js → wizard-abort-BBkiUxfS.js} +23 -20
  113. package/dist/wizard-abort-BBkiUxfS.js.map +1 -0
  114. package/dist/wizard-abort-BU4aLyvh.js +3 -0
  115. package/dist/{wizard-session-FSJCkTcP.js → wizard-session-2w4Ru-Wz.js} +12 -16
  116. package/dist/wizard-session-2w4Ru-Wz.js.map +1 -0
  117. package/dist/wizard-session-DGaUHOF3.js +2 -0
  118. package/dist/wizard-ui-DoyOZxK8.js +16 -0
  119. package/dist/wizard-ui-DoyOZxK8.js.map +1 -0
  120. package/dist/{yara-hooks-BTNJ6MGW.js → yara-hooks-DCeMDd1o.js} +19 -68
  121. package/dist/yara-hooks-DCeMDd1o.js.map +1 -0
  122. package/dist/yara-hooks-DSGuCU9A.js +2 -0
  123. package/package.json +1 -1
  124. package/dist/agent-interface-Avtr_5M5.js.map +0 -1
  125. package/dist/agent-prompt-loader-CHixNPgY.js.map +0 -1
  126. package/dist/agent-runner-COOIUJCP.js +0 -6188
  127. package/dist/agent-runner-COOIUJCP.js.map +0 -1
  128. package/dist/analytics-C67F2vee.js.map +0 -1
  129. package/dist/analytics-CJA1uLlk.js +0 -2
  130. package/dist/api-Dj1yabTj.js.map +0 -1
  131. package/dist/bounded-fs-CWRYuLAn.js.map +0 -1
  132. package/dist/ci-install-CvXL5h13.js.map +0 -1
  133. package/dist/debug-B4kzIZPi.js +0 -754
  134. package/dist/debug-B4kzIZPi.js.map +0 -1
  135. package/dist/env-api-key-BZ5wE3Y4.js.map +0 -1
  136. package/dist/environment-BEvsey6i.js.map +0 -1
  137. package/dist/errors-BoJvrdw8.js.map +0 -1
  138. package/dist/gateway-session-C118uACz.js +0 -2
  139. package/dist/gateway-session-xPFv6p5c.js.map +0 -1
  140. package/dist/headless-ui-CsmQrDIl.js.map +0 -1
  141. package/dist/local-dev-DPZiIPCK.js.map +0 -1
  142. package/dist/mcp-Cbuw_xss.js +0 -64
  143. package/dist/mcp-Cbuw_xss.js.map +0 -1
  144. package/dist/mcp-prompt-streaming-BU_kuur_.js.map +0 -1
  145. package/dist/mint-failure-BrleGqMd.js.map +0 -1
  146. package/dist/non-interactive-DcOjH2fw.js.map +0 -1
  147. package/dist/orchestrator-tools-DXwr8Sp3.js.map +0 -1
  148. package/dist/package-json-xt3eeyBI.js.map +0 -1
  149. package/dist/package-manager-DR23m5Jg.js +0 -290
  150. package/dist/package-manager-DR23m5Jg.js.map +0 -1
  151. package/dist/pi-mY8I2XkG.js.map +0 -1
  152. package/dist/playground-CDUUKLkC.js.map +0 -1
  153. package/dist/posthog-Hc_-9wrr.js.map +0 -1
  154. package/dist/provisioning-xfdjhFtA.js.map +0 -1
  155. package/dist/queue-tools-C8y_xZJi.js.map +0 -1
  156. package/dist/registry-DTmREJ-f.js.map +0 -1
  157. package/dist/security-Dw2oFJjP.js.map +0 -1
  158. package/dist/setup-utils-fjJTBhaB.js.map +0 -1
  159. package/dist/start-tui-UNe2xQ0U.js.map +0 -1
  160. package/dist/store-Bic4Cr3L.js.map +0 -1
  161. package/dist/subagent-Dz41vV9j.js.map +0 -1
  162. package/dist/task-5-fw_Vw3.js.map +0 -1
  163. package/dist/task-stream-dVzl6b_q.js.map +0 -1
  164. package/dist/tasks-D1c2z1aw.js.map +0 -1
  165. package/dist/telemetry-BRnxBRWK.js.map +0 -1
  166. package/dist/terminal-9bvRa4Qt.js.map +0 -1
  167. package/dist/tools-Dp6i9k70.js.map +0 -1
  168. package/dist/wizard-abort-CAcInAxg.js +0 -2
  169. package/dist/wizard-abort-lE6umflt.js.map +0 -1
  170. package/dist/wizard-session-CYvyYnti.js +0 -2
  171. package/dist/wizard-session-FSJCkTcP.js.map +0 -1
  172. package/dist/yara-hooks-BTNJ6MGW.js.map +0 -1
  173. package/dist/yara-hooks-CFY4pGcW.js +0 -2
@@ -1,9 +1,11 @@
1
- import { d as ErrorCodes } from "./errors-BoJvrdw8.js";
2
- import { b as checkLlmGatewayHealth, s as logToFile } from "./debug-B4kzIZPi.js";
3
- import { n as analytics } from "./analytics-C67F2vee.js";
4
- import { t as WizardError } from "./wizard-abort-lE6umflt.js";
1
+ import { d as ErrorCodes, l as WizardError } from "./errors-CQ9kttJD.js";
2
+ import { s as logToFile } from "./debug-Ch4BDOtD.js";
3
+ import { n as analytics } from "./analytics-CHCZ_qUR.js";
4
+ import { t as checkLlmGatewayHealth } from "./endpoints-DCVbM06L.js";
5
+ import { a as oauthLoginKey } from "./oauth-session-DJ8h6GFa.js";
6
+ import { i as modelCapabilities } from "./models-DDdBJKwT.js";
5
7
  import "node:fs";
6
- //#region src/lib/gateway-session.ts
8
+ //#region src/agent/gateway-session.ts
7
9
  /**
8
10
  * Gateway auth for a wizard run: a `phe_` scoped token the backend mints, with
9
11
  * pinned attribution, a spend cap and an expiry.
@@ -17,10 +19,6 @@ let cached = null;
17
19
  * task at once, and each would otherwise take its own token and its own cap.
18
20
  */
19
21
  let inFlight = null;
20
- let ciAuth = null;
21
- function configureGatewayCredentialsForCI(token, projectId, gatewayUrl) {
22
- throw new Error("CI gateway auth requires a non-production build");
23
- }
24
22
  function configureGatewayFromCIEnvironment(projectId, region) {
25
23
  throw new Error("CI gateway auth requires a non-production build");
26
24
  }
@@ -38,8 +36,7 @@ const MAX_REFUSAL_DETAIL_LENGTH = 500;
38
36
  const MAX_REFUSAL_OUTCOME_LENGTH = 64;
39
37
  /** Resolve this run's gateway auth, minting and re-minting near expiry. */
40
38
  async function gatewayAuth(host, accessToken, program) {
41
- if (ciAuth) return ciAuth;
42
- const key = `${host.apiHost}\n${accessToken}\n${program ?? ""}`;
39
+ const key = `${host.apiHost}\n${oauthLoginKey(accessToken)}\n${program ?? ""}`;
43
40
  if (cached && cached.key === key && Date.now() < cached.staleAtMs) return cached.auth;
44
41
  if (inFlight && inFlight.key === key) return inFlight.promise;
45
42
  const promise = resolveGatewayAuth(host, accessToken, key, program);
@@ -81,12 +78,6 @@ async function resolveGatewayAuth(host, accessToken, key, program) {
81
78
  };
82
79
  return auth;
83
80
  }
84
- /** Test hook: drop the cached auth so the next call re-resolves. */
85
- function resetGatewaySession() {
86
- cached = null;
87
- inFlight = null;
88
- ciAuth = null;
89
- }
90
81
  /** Whether a 401 on this bearer may be age (past its refresh instant) rather than a bad credential. */
91
82
  function isPastRefresh(auth, now = Date.now()) {
92
83
  return now >= auth.refreshAtMs;
@@ -232,10 +223,12 @@ async function mintGatewayToken(host, accessToken, program) {
232
223
  logToFile("[gateway] mint returned an untrusted gateway url; failing the run");
233
224
  throw new GatewayMintFailed("mint returned an untrusted gateway url");
234
225
  }
226
+ const gatewayUrl = new URL(body.gateway_url);
227
+ if (["localhost", "127.0.0.1"].includes(new URL(host.apiHost).hostname) && gatewayUrl.hostname === "host.docker.internal") gatewayUrl.hostname = "localhost";
235
228
  return {
236
229
  token: body.token,
237
230
  expiresAt: body.expires_at,
238
- gatewayUrl: body.gateway_url.replace(/\/+$/, ""),
231
+ gatewayUrl: gatewayUrl.origin,
239
232
  teamId: body.team_id
240
233
  };
241
234
  } catch (e) {
@@ -266,6 +259,168 @@ function stripPropertyPrefix(key) {
266
259
  return key.toUpperCase().startsWith(LEGACY_PROPERTY_PREFIX) ? key.slice(19).toLowerCase() : key;
267
260
  }
268
261
  //#endregion
269
- export { configureGatewayFromCIEnvironment as a, isTrustedGatewayUrl as c, configureGatewayCredentialsForCI as i, resetGatewaySession as l, GatewayMintRefused as n, gatewayAuth as o, buildWizardPropertiesBlob as r, isPastRefresh as s, GatewayMintFailed as t };
262
+ //#region src/agent/runner/harness/pi/gateway.ts
263
+ /**
264
+ * PostHog AI gateway provider spec for pi sessions, shared by the linear run
265
+ * and the orchestrator's per-task runs so both speak to the gateway
266
+ * identically: bearer auth, the wizard properties header, transport shape
267
+ * inferred from the model id. The caller registers the spec on its own
268
+ * (lazily imported, properly typed) pi ModelRegistry.
269
+ */
270
+ /** Provider registered on the in-memory registry for this run. */
271
+ const GATEWAY_PROVIDER = "posthog-gateway";
272
+ /**
273
+ * The gateway speaks two shapes on two endpoints: Anthropic models over
274
+ * `anthropic-messages` (the SDK appends `/v1/messages`, so the base URL has no
275
+ * `/v1`), and OpenAI-class models (`openai/gpt-5`, …) over an OpenAI shape at
276
+ * `/v1/responses` or `/v1/chat/completions` (base URL keeps `/v1`). Infer the
277
+ * shape from the model id so a pair's model selects the right transport.
278
+ *
279
+ * OpenAI models take the Responses API because OpenAI rejects function tools
280
+ * combined with `reasoning_effort` on chat completions and every task sends both.
281
+ */
282
+ function gatewayApiFor(modelId) {
283
+ return modelId.startsWith("openai/") ? "openai-responses" : "anthropic-messages";
284
+ }
285
+ /**
286
+ * Gateway HTTP headers, mirroring `buildAgentEnv` on the anthropic path: one
287
+ * `X-PostHog-Properties` JSON blob (Bedrock fallback is native, so no opt-in)
288
+ * plus the 1M context beta, since pi otherwise runs at 200k and overflows on
289
+ * larger projects (the post-run compaction failures).
290
+ */
291
+ function buildGatewayHeaders(wizardMetadata, wizardFlags, teamId) {
292
+ return {
293
+ "anthropic-beta": "context-1m-2025-08-07",
294
+ "X-PostHog-Properties": buildWizardPropertiesBlob(wizardMetadata, wizardFlags, teamId)
295
+ };
296
+ }
297
+ /**
298
+ * One gateway model spec — the single description of how to reach a model on
299
+ * the gateway. The provider spec below wraps it for pi's registry; one-shot
300
+ * callers (scan triage) hand it straight to `completeSimple`.
301
+ */
302
+ function buildGatewayModel(inputs) {
303
+ const { gatewayUrl, wizardMetadata, wizardFlags, modelId, teamId } = inputs;
304
+ const api = gatewayApiFor(modelId);
305
+ return {
306
+ id: modelId,
307
+ name: `${modelId} (PostHog Gateway)`,
308
+ api,
309
+ provider: GATEWAY_PROVIDER,
310
+ baseUrl: api === "anthropic-messages" ? gatewayUrl : `${gatewayUrl}/v1`,
311
+ reasoning: modelCapabilities(modelId).reasoning,
312
+ input: ["text"],
313
+ cost: {
314
+ input: 0,
315
+ output: 0,
316
+ cacheRead: 0,
317
+ cacheWrite: 0
318
+ },
319
+ contextWindow: 1e6,
320
+ maxTokens: 64e3,
321
+ headers: buildGatewayHeaders(wizardMetadata, wizardFlags, teamId)
322
+ };
323
+ }
324
+ /**
325
+ * The provider object for `registry.registerProvider(GATEWAY_PROVIDER, …)`,
326
+ * plus the derived traits the session setup needs (`caps.thinkingLevel`).
327
+ */
328
+ function buildGatewayProvider(inputs) {
329
+ const { gatewayUrl, accessToken, modelId, effort } = inputs;
330
+ const api = gatewayApiFor(modelId);
331
+ const tableCaps = modelCapabilities(modelId);
332
+ const caps = effort && effort !== "off" && tableCaps.reasoning ? modelCapabilities(modelId, effort) : effort === "off" && tableCaps.reasoning ? {
333
+ ...tableCaps,
334
+ thinkingLevel: "off"
335
+ } : tableCaps;
336
+ const model = buildGatewayModel(inputs);
337
+ return {
338
+ provider: {
339
+ name: "PostHog Gateway",
340
+ baseUrl: model.baseUrl,
341
+ apiKey: accessToken,
342
+ authHeader: true,
343
+ api,
344
+ headers: model.headers,
345
+ models: [model]
346
+ },
347
+ api,
348
+ caps,
349
+ gatewayUrl,
350
+ baseUrl: model.baseUrl
351
+ };
352
+ }
353
+ function gatewayTerminalFailure(turn) {
354
+ if (!turn || turn.stopReason !== "error" && turn.stopReason !== "aborted") return void 0;
355
+ const message = turn.errorMessage || (turn.stopReason === "aborted" ? "Agent turn aborted" : "Gateway request failed");
356
+ if (turn.stopReason === "aborted") return {
357
+ classification: "WIZARD_ABORT",
358
+ message
359
+ };
360
+ const structuredStatus = (turn.diagnostics?.map((d) => d.error?.code).filter((code) => code !== void 0) ?? []).map(Number).find((code) => Number.isInteger(code) && code >= 400 && code < 600);
361
+ return {
362
+ classification: (structuredStatus !== void 0 ? structuredStatus === 429 : /\b429\b|rate limit/i.test(message)) ? "WIZARD_RATE_LIMIT" : "WIZARD_API_ERROR",
363
+ message,
364
+ status: structuredStatus ?? (isGatewayAuthRejection(turn) ? 401 : void 0)
365
+ };
366
+ }
367
+ /**
368
+ * Whether a turn's error is the gateway rejecting the bearer. pi attaches the
369
+ * SDK's own error to `diagnostics`, so its code decides when one is present.
370
+ * The message match is the fallback for a turn that failed before pi built a
371
+ * diagnostic, where the status survives only as prose.
372
+ */
373
+ function isGatewayAuthRejection(turn) {
374
+ const { errorMessage, diagnostics } = typeof turn === "string" ? {
375
+ errorMessage: turn,
376
+ diagnostics: void 0
377
+ } : turn ?? {};
378
+ const structuredStatus = (diagnostics ?? []).map((diagnostic) => Number(diagnostic.error?.code)).find((code) => Number.isInteger(code) && code >= 400 && code < 600);
379
+ if (structuredStatus !== void 0) return structuredStatus === 401;
380
+ for (const diagnostic of diagnostics ?? []) {
381
+ const code = diagnostic.error?.code;
382
+ if (code === 401 || code === "401") return true;
383
+ if (/^authentication_?error$/i.test(diagnostic.error?.name ?? "")) return true;
384
+ }
385
+ return /\b401\b|authentication_error|unauthorized/i.test(errorMessage ?? "");
386
+ }
387
+ /**
388
+ * Wraps a pi session's prompt(): when a turn ends on a 401 from a bearer past
389
+ * its refresh instant, mint once, re-register the provider with the new
390
+ * bearer (pi resolves the apiKey per request), and continue. A 401 on a fresh
391
+ * bearer, or a second one, is left to the harness's normal failure path.
392
+ */
393
+ function withGatewayRemint(opts) {
394
+ let auth = opts.auth;
395
+ let rejected = false;
396
+ let reminted = false;
397
+ let lastTurn;
398
+ return {
399
+ noteAssistantTurn(message) {
400
+ lastTurn = message;
401
+ rejected = lastTurn?.stopReason === "error" && isGatewayAuthRejection(lastTurn);
402
+ },
403
+ terminalFailure: () => gatewayTerminalFailure(lastTurn),
404
+ async prompt(text) {
405
+ if (opts.signal?.aborted) return;
406
+ rejected = false;
407
+ lastTurn = void 0;
408
+ await opts.session.prompt(text);
409
+ if (opts.signal?.aborted || !rejected || reminted || !isPastRefresh(auth)) return;
410
+ reminted = true;
411
+ auth = await opts.refreshAuth();
412
+ if (opts.signal?.aborted) return;
413
+ opts.registry.registerProvider(GATEWAY_PROVIDER, buildGatewayProvider(opts.providerInputs(auth)).provider);
414
+ opts.onRemint?.();
415
+ rejected = false;
416
+ lastTurn = void 0;
417
+ const next = opts.continueText;
418
+ if (opts.signal?.aborted) return;
419
+ await opts.session.prompt(typeof next === "function" ? next() : next);
420
+ }
421
+ };
422
+ }
423
+ //#endregion
424
+ export { gatewayTerminalFailure as a, configureGatewayFromCIEnvironment as c, gatewayApiFor as i, gatewayAuth as l, buildGatewayModel as n, withGatewayRemint as o, buildGatewayProvider as r, buildWizardPropertiesBlob as s, GATEWAY_PROVIDER as t, isPastRefresh as u };
270
425
 
271
- //# sourceMappingURL=gateway-session-xPFv6p5c.js.map
426
+ //# sourceMappingURL=gateway-CjoShdLa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway-CjoShdLa.js","names":[],"sources":["../src/agent/gateway-session.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(B2): CI credential loading belongs to the headless provider, not the\n// agent. Leaves with the rest of this module once RunInput carries resolved\n// inference auth.\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 * 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;AAGZ,YAAU,mDAAmD;AAC7D,QAAM,IAAI,kBACR,oDACD;;CAEH,MAAM,SAAS,MAAM,iBAAiB,MAAM,aAAa,QAAQ;AAEjE,MADe,MAAM,sBAAsB,OAAO,WAAW,EAClD,WAAA,UACT,OAAM,IAAI,YACR,kEACA,KAAA,GACA,WAAW,iBACZ;CAEH,MAAM,cAAc,KAAK,MAAM,OAAO,UAAU;CAChD,MAAM,QAAQ,cAAc,KAAK,KAAK;AACtC,KAAI,CAAC,OAAO,SAAS,YAAY,IAAI,QAAQ,mBAAmB;AAG9D,YACE,wCAAwC,MAAM,6BAC/C;AACD,QAAM,IAAI,kBACR,2CAA2C,MAAM,YAClD;;CAEH,MAAM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AAK,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"}
@@ -6,6 +6,6 @@ const pkg = JSON.parse(
6
6
  );
7
7
  const output = `// Auto-generated by scripts/generate-version.js — do not edit\nexport const VERSION = '${pkg.version}';\n`;
8
8
  fs.writeFileSync(
9
- path.join(__dirname, '..', 'src', 'lib', 'version.ts'),
9
+ path.join(__dirname, '..', 'src', 'shared', 'version.ts'),
10
10
  output,
11
11
  );
@@ -1,4 +1,5 @@
1
- import { h as LoggingUI } from "./debug-B4kzIZPi.js";
1
+ import "./wizard-session-2w4Ru-Wz.js";
2
+ import { t as LoggingUI } from "./logging-ui-_TwoMNbG.js";
2
3
  //#region src/ui/headless-ui.ts
3
4
  /**
4
5
  * `LoggingUI` plus it feeds run state into a `WizardStore` so the background
@@ -13,6 +14,16 @@ var HeadlessUI = class extends LoggingUI {
13
14
  super();
14
15
  this.store = store;
15
16
  }
17
+ startRun() {
18
+ super.startRun();
19
+ this.store.setRunPhase("running");
20
+ }
21
+ setCredentials(credentials) {
22
+ this.store.setAccessToken(credentials);
23
+ }
24
+ setAccessToken(credentials) {
25
+ this.store.setAccessToken(credentials);
26
+ }
16
27
  syncTodos(todos) {
17
28
  super.syncTodos(todos);
18
29
  this.store.syncTodos(todos);
@@ -30,4 +41,4 @@ var HeadlessUI = class extends LoggingUI {
30
41
  //#endregion
31
42
  export { HeadlessUI };
32
43
 
33
- //# sourceMappingURL=headless-ui-CsmQrDIl.js.map
44
+ //# sourceMappingURL=headless-ui-BFFmYC4v.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headless-ui-BFFmYC4v.js","names":[],"sources":["../src/ui/headless-ui.ts"],"sourcesContent":["import { RunPhase, type Credentials } from '@lib/wizard-session';\nimport { LoggingUI } from './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"}
@@ -1,4 +1,4 @@
1
- import { X as posthogIntegrationConfig } from "./mint-failure-BrleGqMd.js";
1
+ import { X as posthogIntegrationConfig } from "./mint-failure-D4nd2XmZ.js";
2
2
  import { d as runWizard } from "./bin.js";
3
3
  //#region src/commands/basic-integration/interactive.ts
4
4
  /** Default flow: run the posthog-integration program through the TUI. */
@@ -8,4 +8,4 @@ function runInteractive(argv) {
8
8
  //#endregion
9
9
  export { runInteractive };
10
10
 
11
- //# sourceMappingURL=interactive-Dej-sxvR.js.map
11
+ //# sourceMappingURL=interactive-D6zV7brJ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-Dej-sxvR.js","names":[],"sources":["../src/commands/basic-integration/interactive.ts"],"sourcesContent":["import type { Arguments } from 'yargs';\nimport { runWizard } from '@lib/runners';\nimport { posthogIntegrationConfig } from '@lib/programs/posthog-integration/index';\n\n/** Default flow: run the posthog-integration program through the TUI. */\nexport function runInteractive(argv: Arguments): void {\n runWizard(posthogIntegrationConfig, argv);\n}\n"],"mappings":";;;;AAKA,SAAgB,eAAe,MAAuB;AACpD,WAAU,0BAA0B,KAAK"}
1
+ {"version":3,"file":"interactive-D6zV7brJ.js","names":[],"sources":["../src/commands/basic-integration/interactive.ts"],"sourcesContent":["import type { Arguments } from 'yargs';\nimport { runWizard } from '@lib/runners';\nimport { posthogIntegrationConfig } from '@lib/programs/posthog-integration/index';\n\n/** Default flow: run the posthog-integration program through the TUI. */\nexport function runInteractive(argv: Arguments): void {\n runWizard(posthogIntegrationConfig, argv);\n}\n"],"mappings":";;;;AAKA,SAAgB,eAAe,MAAuB;AACpD,WAAU,0BAA0B,KAAK"}
@@ -1,4 +1,4 @@
1
- //#region src/lib/local-dev.ts
1
+ //#region src/shared/local-dev.ts
2
2
  /**
3
3
  * Local development targets: context-mill (skills), MCP, and PostHog. Each is
4
4
  * independently switchable — CI runs local skills against the *production* MCP
@@ -132,4 +132,4 @@ function localMcpSkillsNotice(flags) {
132
132
  //#endregion
133
133
  export { getLocalDev as a, resolveLocalDev as c, checkLocalServices as i, MCP_LOCAL_URL as n, initLocalDev as o, POSTHOG_LOCAL_URL as r, localMcpSkillsNotice as s, CONTEXT_MILL_LOCAL_URL as t };
134
134
 
135
- //# sourceMappingURL=local-dev-DPZiIPCK.js.map
135
+ //# sourceMappingURL=local-dev-McsurOC-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-dev-McsurOC-.js","names":[],"sources":["../src/shared/local-dev.ts"],"sourcesContent":["/**\n * Local development targets: context-mill (skills), MCP, and PostHog. Each is\n * independently switchable — CI runs local skills against the *production* MCP\n * — with `--local-dev` as a shorthand for all three.\n *\n * `wizard mcp add --local` is unrelated: it writes a `posthog-local` entry into\n * the user's editor config rather than retargeting this run. Hence no\n * `--local` here.\n */\n\nexport const CONTEXT_MILL_LOCAL_URL = 'http://localhost:8765';\nexport const MCP_LOCAL_URL = 'http://localhost:8787/mcp';\n/** Pins the API, app, OAuth, and the LLM gateway derived from them. */\nexport const POSTHOG_LOCAL_URL = 'http://localhost:8010';\n\n/**\n * Raw yargs values. The three specific flags are declared without a `default`\n * so they stay `undefined` when absent — see `resolveLocalDev`.\n */\nexport type LocalDevFlags = {\n localDev?: boolean;\n localMcp?: boolean;\n localContextMill?: boolean;\n localPosthog?: boolean;\n};\n\nexport type ResolvedLocalDev = {\n localMcp: boolean;\n localContextMill: boolean;\n localPosthog: boolean;\n};\n\n/**\n * A specific flag beats `--local-dev` in both directions. `??` is load-bearing:\n * it falls through only on `undefined`, so giving the specific flags a yargs\n * `default: false` would silently break both the umbrella and `--no-local-mcp`.\n */\nexport function resolveLocalDev(flags: LocalDevFlags): ResolvedLocalDev {\n const umbrella = flags.localDev ?? false;\n return {\n localMcp: flags.localMcp ?? umbrella,\n localContextMill: flags.localContextMill ?? umbrella,\n localPosthog: flags.localPosthog ?? umbrella,\n };\n}\n\n/** yargs populates both spellings, so read either. */\nexport function localDevFromArgv(\n argv: Record<string, unknown>,\n): ResolvedLocalDev {\n const read = (kebab: string, camel: string): boolean | undefined => {\n const value = argv[camel] ?? argv[kebab];\n return typeof value === 'boolean' ? value : undefined;\n };\n return resolveLocalDev({\n localDev: read('local-dev', 'localDev'),\n localMcp: read('local-mcp', 'localMcp'),\n localContextMill: read('local-context-mill', 'localContextMill'),\n localPosthog: read('local-posthog', 'localPosthog'),\n });\n}\n\nconst PRODUCTION_TARGETS: ResolvedLocalDev = {\n localMcp: false,\n localContextMill: false,\n localPosthog: false,\n};\n\nlet resolved: ResolvedLocalDev | null = null;\n\n/**\n * Resolve this process's targets. Called once from the yargs middleware, which\n * covers every command and the env-var spellings alike.\n */\nexport function initLocalDev(argv: Record<string, unknown>): ResolvedLocalDev {\n resolved = localDevFromArgv(argv);\n return resolved;\n}\n\n/**\n * Where this run points. Resolved once because the flags are parsed at startup\n * and never change; threading them through state let call sites read whichever\n * field they happened to have, which is how the intro screens ended up asking\n * the MCP flag where to fetch skills.\n *\n * Uninitialized means no CLI parse ran (a direct-call test) — production.\n */\nexport function getLocalDev(): ResolvedLocalDev {\n return resolved ?? PRODUCTION_TARGETS;\n}\n\n/** Tests only. */\nexport function resetLocalDev(): void {\n resolved = null;\n}\n\ntype LocalService = {\n key: keyof ResolvedLocalDev;\n label: string;\n flag: string;\n /** Probed for reachability — any HTTP reply proves the port is bound. */\n url: string;\n startHint: string;\n};\n\nconst LOCAL_SERVICES: readonly LocalService[] = [\n {\n key: 'localContextMill',\n label: 'context-mill',\n flag: '--local-context-mill',\n url: `${CONTEXT_MILL_LOCAL_URL}/skill-menu.json`,\n startHint: 'npm run dev (in the context-mill repo)',\n },\n {\n key: 'localMcp',\n label: 'MCP server',\n flag: '--local-mcp',\n url: MCP_LOCAL_URL,\n startHint:\n 'hogli start (or pnpm dev:local-resources in posthog/services/mcp)',\n },\n {\n key: 'localPosthog',\n label: 'PostHog',\n flag: '--local-posthog',\n url: POSTHOG_LOCAL_URL,\n startHint: './bin/start (in the posthog repo)',\n },\n] as const;\n\n// Retries because this gate gates `fetchWithRetry` (see fetch-retry.ts) — a\n// blip it would ride out must not abort the run instead. A missing server\n// refuses instantly, so the retries only cost time when one is slow to answer,\n// which is exactly when they're worth paying for.\nconst PROBE_TIMEOUT_MS = 2_000;\nconst PROBE_ATTEMPTS = 3;\nconst PROBE_BACKOFF_MS = 250;\n\nasync function isReachable(url: string): Promise<boolean> {\n for (let attempt = 1; attempt <= PROBE_ATTEMPTS; attempt++) {\n try {\n // Any reply — including 404 or 405 — proves something is listening, which\n // is the only question here. Deliberately not `fetchWithRetry`: that\n // treats a non-ok status as failure, and here it is a pass.\n await fetch(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });\n return true;\n } catch {\n if (attempt < PROBE_ATTEMPTS) {\n await new Promise((r) =>\n setTimeout(r, PROBE_BACKOFF_MS * 2 ** (attempt - 1)),\n );\n }\n }\n }\n return false;\n}\n\n/**\n * Probe every service the flags asked to be local. Returns one message naming\n * each unreachable one, or undefined if all are up (or none were requested).\n *\n * Without this a dead local server surfaces late and badly: a missing\n * context-mill looks like a registry outage, a missing MCP fails mid-run after\n * the agent has already edited files.\n */\nexport async function checkLocalServices(\n resolved: ResolvedLocalDev,\n): Promise<string | undefined> {\n const requested = LOCAL_SERVICES.filter((s) => resolved[s.key]);\n if (requested.length === 0) return undefined;\n\n const reachable = await Promise.all(requested.map((s) => isReachable(s.url)));\n const dead = requested.filter((_, i) => !reachable[i]);\n if (dead.length === 0) return undefined;\n\n return [\n `Local ${dead.length === 1 ? 'service is' : 'services are'} not running:`,\n '',\n ...dead.map(\n (s) =>\n ` ${s.label} — nothing listening at ${new URL(s.url).origin}\\n` +\n ` requested by ${s.flag}\\n` +\n ` start it with: ${s.startHint}`,\n ),\n '',\n 'Start the missing services, or drop the flag to use production.',\n ].join('\\n');\n}\n\n/**\n * `--local-mcp` used to select local skills too; anyone still relying on that\n * would silently get production skills. Temporary — drop after a release or two.\n */\nexport function localMcpSkillsNotice(flags: LocalDevFlags): string | undefined {\n if (flags.localMcp !== true) return undefined;\n if (flags.localContextMill !== undefined || flags.localDev === true) {\n return undefined;\n }\n return (\n '--local-mcp now points only at the local MCP server. ' +\n 'For local skills, add --local-context-mill (or use --local-dev for both).'\n );\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,yBAAyB;AACtC,MAAa,gBAAgB;;AAE7B,MAAa,oBAAoB;;;;;;AAwBjC,SAAgB,gBAAgB,OAAwC;CACtE,MAAM,WAAW,MAAM,YAAY;AACnC,QAAO;EACL,UAAU,MAAM,YAAY;EAC5B,kBAAkB,MAAM,oBAAoB;EAC5C,cAAc,MAAM,gBAAgB;EACrC;;;AAIH,SAAgB,iBACd,MACkB;CAClB,MAAM,QAAQ,OAAe,UAAuC;EAClE,MAAM,QAAQ,KAAK,UAAU,KAAK;AAClC,SAAO,OAAO,UAAU,YAAY,QAAQ,KAAA;;AAE9C,QAAO,gBAAgB;EACrB,UAAU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G,QAAO,KAAA;AAE9B,QAAO;EACL,SAAS,KAAK,WAAW,IAAI,eAAe,eAAe;EAC3D;EACA,GAAG,KAAK,KACL,MACC,KAAK,EAAE,MAAM,0BAA0B,IAAI,IAAI,EAAE,IAAI,CAAC,OAAO,qBACzC,EAAE,KAAK,uBACL,EAAE,YAC3B;EACD;EACA;EACD,CAAC,KAAK,KAAK;;;;;;AAOd,SAAgB,qBAAqB,OAA0C;AAC7E,KAAI,MAAM,aAAa,KAAM,QAAO,KAAA;AACpC,KAAI,MAAM,qBAAqB,KAAA,KAAa,MAAM,aAAa,KAC7D;AAEF,QACE"}
@@ -0,0 +1,226 @@
1
+ import { s as logToFile } from "./debug-Ch4BDOtD.js";
2
+ import { E as OAUTH_TIMEOUT_MS } from "./constants-jFI2SaE1.js";
3
+ import "./wizard-ui-DoyOZxK8.js";
4
+ import { n as checkSkillsOriginHealth } from "./endpoints-DCVbM06L.js";
5
+ //#region src/shared/health-checks/readiness.ts
6
+ const SERVICE_LABELS = { skillsOrigin: "Skills download" };
7
+ const DEFAULT_WIZARD_READINESS_CONFIG = { downBlocksRun: ["skillsOrigin"] };
8
+ const SIGNUP_WIZARD_READINESS_CONFIG = DEFAULT_WIZARD_READINESS_CONFIG;
9
+ async function checkAllExternalServices() {
10
+ return { skillsOrigin: await checkSkillsOriginHealth() };
11
+ }
12
+ function describeResult(label, h) {
13
+ const parts = [`${label}: ${h.status}`];
14
+ if (h.rawIndicator) parts.push(`indicator=${h.rawIndicator}`);
15
+ if (h.error) parts.push(h.error);
16
+ return parts.join(" — ");
17
+ }
18
+ const READINESS_TIMEOUT_MS = 2e4;
19
+ async function evaluateWizardReadiness(config = DEFAULT_WIZARD_READINESS_CONFIG) {
20
+ try {
21
+ const health = await Promise.race([checkAllExternalServices(), new Promise((resolve) => setTimeout(() => resolve(allUnknown("Health check timed out")), READINESS_TIMEOUT_MS))]);
22
+ const blockingKeys = getBlockingServiceKeys(health, config);
23
+ const reasons = blockingKeys.map((key) => describeResult(SERVICE_LABELS[key], health[key]));
24
+ if (blockingKeys.length > 0) {
25
+ logToFile(`[health-checks] blocked by: ${blockingKeys.map((key) => {
26
+ const h = health[key];
27
+ return `${key} (${h.status}${h.error ? ` — ${h.error}` : ""})`;
28
+ }).join(", ")}`);
29
+ return {
30
+ decision: "no",
31
+ health,
32
+ reasons
33
+ };
34
+ }
35
+ return {
36
+ decision: "yes",
37
+ health,
38
+ reasons
39
+ };
40
+ } catch (err) {
41
+ logToFile(`[health-checks] error: ${err instanceof Error ? err.message : err}`);
42
+ return {
43
+ decision: "yes",
44
+ health: allUnknown("Unexpected error"),
45
+ reasons: []
46
+ };
47
+ }
48
+ }
49
+ function getBlockingServiceKeys(health, config = DEFAULT_WIZARD_READINESS_CONFIG) {
50
+ return Object.keys(health).filter((key) => {
51
+ const result = health[key];
52
+ if (config.downBlocksRun.includes(key) && (result.status === "down" || result.status === "no-connection")) return true;
53
+ if ((config.degradedBlocksRun ?? []).includes(key) && result.status !== "healthy") return true;
54
+ return false;
55
+ });
56
+ }
57
+ /** Build an AllServicesHealth where every service is Degraded with the given error. */
58
+ function allUnknown(error) {
59
+ return { skillsOrigin: {
60
+ status: "degraded",
61
+ error
62
+ } };
63
+ }
64
+ //#endregion
65
+ //#region src/ui/logging-ui.ts
66
+ var LoggingUI = class {
67
+ intro(message) {
68
+ console.log(`┌ ${message}`);
69
+ }
70
+ outro(message) {
71
+ console.log(`└ ${message}`);
72
+ }
73
+ outroError(data) {
74
+ console.log(`✖ ${data.message ?? "Wizard aborted"}`);
75
+ if (data.body) console.log(`│ ${data.body}`);
76
+ if (data.docsUrl) console.log(`│ Docs: ${data.docsUrl}`);
77
+ }
78
+ waitForOutroDismissed() {
79
+ return Promise.resolve();
80
+ }
81
+ waitForAiOptIn() {
82
+ return Promise.resolve();
83
+ }
84
+ cancel(message) {
85
+ console.log(`■ ${message}`);
86
+ }
87
+ log = {
88
+ info(message) {
89
+ console.log(`│ ${message}`);
90
+ },
91
+ warn(message) {
92
+ console.log(`▲ ${message}`);
93
+ },
94
+ error(message) {
95
+ console.log(`✖ ${message}`);
96
+ },
97
+ success(message) {
98
+ console.log(`✔ ${message}`);
99
+ },
100
+ step(message) {
101
+ console.log(`◇ ${message}`);
102
+ }
103
+ };
104
+ note(message) {
105
+ console.log(`│ ${message}`);
106
+ }
107
+ spinner() {
108
+ return {
109
+ start(message) {
110
+ if (message) console.log(`◌ ${message}`);
111
+ },
112
+ stop(message) {
113
+ if (message) console.log(`● ${message}`);
114
+ },
115
+ message(msg) {
116
+ if (msg) console.log(`◌ ${msg}`);
117
+ }
118
+ };
119
+ }
120
+ pushStatus(message) {
121
+ console.log(`◇ ${message}`);
122
+ }
123
+ setDetectedFramework(label) {
124
+ console.log(`✔ Framework: ${label}`);
125
+ }
126
+ onEnterScreen(_screen, _fn) {}
127
+ setLoginUrl(url) {
128
+ if (url) {
129
+ console.log(`│ If the browser didn't open automatically, use this link:`);
130
+ console.log(`│ ${url}`);
131
+ }
132
+ }
133
+ setAuthorizeUrl(_url) {}
134
+ showBlockingOutage(result) {
135
+ console.log(`▲ Service health issues detected.`);
136
+ const blockingKeys = getBlockingServiceKeys(result.health);
137
+ if (blockingKeys.length > 0) {
138
+ console.log(`│`);
139
+ console.log(`│ Blocking services:`);
140
+ for (const key of blockingKeys) {
141
+ const status = result.health[key].status;
142
+ const error = result.health[key].error;
143
+ const label = SERVICE_LABELS[key];
144
+ const detail = error ? ` — ${error}` : "";
145
+ console.log(`│ ✖ ${label}: ${status}${detail}`);
146
+ }
147
+ console.log(`│`);
148
+ }
149
+ for (const reason of result.reasons) console.log(`│ ${reason}`);
150
+ console.log(`│ Continuing anyway — health checks are advisory in non-interactive runs.`);
151
+ return Promise.resolve();
152
+ }
153
+ setReadinessWarnings(result) {
154
+ console.log(`▲ Service health warnings detected.`);
155
+ for (const reason of result.reasons) console.log(`│ ${reason}`);
156
+ }
157
+ showPortConflict(_processInfo) {
158
+ return Promise.resolve();
159
+ }
160
+ waitForManualAuthCode() {
161
+ return new Promise(() => {});
162
+ }
163
+ showTaskNotice(_notice) {
164
+ return Promise.resolve(false);
165
+ }
166
+ cancelTaskNotice() {}
167
+ showSettingsOverride(_conflicts, _backupAndFix) {
168
+ return Promise.resolve();
169
+ }
170
+ requestQuestion(_question) {
171
+ return Promise.reject(/* @__PURE__ */ new Error("wizard_ask is not available in CI / non-interactive mode. Re-run the wizard without --ci to answer interactively."));
172
+ }
173
+ cancelPendingQuestion() {}
174
+ showAuthError(detail) {
175
+ console.log(`✖ Authentication failed (401)`);
176
+ if (detail?.hasSettingsConflict) {
177
+ console.log(`│ Claude Code auth is conflicting with the wizard. Please try again after logging out:`);
178
+ console.log(`│ claude auth logout`);
179
+ } else {
180
+ console.log(`│ The PostHog LLM Gateway rejected the API key. Common causes:`);
181
+ console.log(`│ - Wrong key type: pass a personal API key (phx_xxx). pha_ is an OAuth access token, phc_ is a project key.`);
182
+ console.log(`│ - Missing scope: the personal API key needs the "llm_gateway:read" scope.`);
183
+ console.log(`│ - Expired or revoked key.`);
184
+ console.log(`│ - Region mismatch: --region must match the region the key was issued in (us vs eu).`);
185
+ }
186
+ if (detail?.logFilePath) console.log(`│ Verbose log: ${detail.logFilePath}`);
187
+ }
188
+ showSessionTimeout() {
189
+ const minutes = Math.round(OAUTH_TIMEOUT_MS / 6e4);
190
+ console.log(`✖ Login timed out. The OAuth link timed out after ${minutes} minutes.`);
191
+ console.log(`│ Re-run the wizard to get a fresh link and try again.`);
192
+ }
193
+ startRun() {}
194
+ setCredentials(_credentials) {}
195
+ setAccessToken(_credentials) {}
196
+ setRoleAtOrganization(_role) {}
197
+ setApiUser(_user) {}
198
+ lastTodoLine = "";
199
+ syncTodos(todos) {
200
+ const completed = todos.filter((t) => t.status === "completed").length;
201
+ const active = todos.filter((t) => t.status === "in_progress");
202
+ if (active.length === 0) return;
203
+ const labels = active.map((t) => t.activeForm || t.content).join(" · ");
204
+ const line = `◌ [${completed}/${todos.length}] ${labels}`;
205
+ if (line === this.lastTodoLine) return;
206
+ this.lastTodoLine = line;
207
+ console.log(line);
208
+ }
209
+ setEventPlan(_events) {}
210
+ setDashboardUrl(_url) {}
211
+ setStage(_stage) {}
212
+ setNotebookUrl(_url) {}
213
+ setHandoffText(_text) {}
214
+ addTokenUsage(_delta) {}
215
+ setFinalTokenCostUsd(_costUsd) {}
216
+ setOutroData(_data) {}
217
+ setFrameworkContext(_key, _value) {}
218
+ getFrameworkContext(_key) {}
219
+ waitForGate(_stepId) {
220
+ return Promise.resolve();
221
+ }
222
+ };
223
+ //#endregion
224
+ export { getBlockingServiceKeys as a, evaluateWizardReadiness as i, SERVICE_LABELS as n, SIGNUP_WIZARD_READINESS_CONFIG as r, LoggingUI as t };
225
+
226
+ //# sourceMappingURL=logging-ui-_TwoMNbG.js.map