@posthog/wizard 2.77.0 → 2.79.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 (175) hide show
  1. package/README.md +50 -26
  2. package/dist/{add-mcp-server-to-clients-BnRyE4pw.js → add-mcp-server-to-clients-amlJWW7W.js} +6 -5
  3. package/dist/{add-mcp-server-to-clients-BnRyE4pw.js.map → add-mcp-server-to-clients-amlJWW7W.js.map} +1 -1
  4. package/dist/agent-CNrEC-9v.js +3184 -0
  5. package/dist/agent-CNrEC-9v.js.map +1 -0
  6. package/dist/{agent-interface-Avtr_5M5.js → agent-interface-BXvmAm4c.js} +462 -385
  7. package/dist/agent-interface-BXvmAm4c.js.map +1 -0
  8. package/dist/{agent-prompt-loader-CHixNPgY.js → agent-prompt-loader-DiKUbhi_.js} +6 -6
  9. package/dist/agent-prompt-loader-DiKUbhi_.js.map +1 -0
  10. package/dist/analytics-DxwRi2Hf.js +2 -0
  11. package/dist/{analytics-C67F2vee.js → analytics-VRYdebXW.js} +10 -6
  12. package/dist/analytics-VRYdebXW.js.map +1 -0
  13. package/dist/{api-Dj1yabTj.js → api-DGuJTzjr.js} +4 -17
  14. package/dist/api-DGuJTzjr.js.map +1 -0
  15. package/dist/bin.js +415 -70
  16. package/dist/bin.js.map +1 -1
  17. package/dist/{bounded-fs-CWRYuLAn.js → bounded-fs-Cpn129A4.js} +4 -4
  18. package/dist/bounded-fs-Cpn129A4.js.map +1 -0
  19. package/dist/check-screens.tsx +1 -1
  20. package/dist/{ci-install-CvXL5h13.js → ci-install-BPA6gzEq.js} +6 -5
  21. package/dist/ci-install-BPA6gzEq.js.map +1 -0
  22. package/dist/constants-CuJfQEcC.js +260 -0
  23. package/dist/constants-CuJfQEcC.js.map +1 -0
  24. package/dist/{debug-CziFS0cA.js → debug-B9k4ideV.js} +1 -1
  25. package/dist/debug-Cj-8vfXY.js +171 -0
  26. package/dist/debug-Cj-8vfXY.js.map +1 -0
  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-DnIX0pZH.js +108 -0
  30. package/dist/endpoints-DnIX0pZH.js.map +1 -0
  31. package/dist/{env-api-key-BZ5wE3Y4.js → env-api-key-BWdKpGEr.js} +3 -3
  32. package/dist/env-api-key-BWdKpGEr.js.map +1 -0
  33. package/dist/{environment-BEvsey6i.js → environment-DZYUSCpV.js} +6 -6
  34. package/dist/environment-DZYUSCpV.js.map +1 -0
  35. package/dist/{errors-BoJvrdw8.js → errors-ddDE6MbA.js} +27 -76
  36. package/dist/errors-ddDE6MbA.js.map +1 -0
  37. package/dist/{file-BoD3REGB.js → file-dEhr-l3n.js} +3 -3
  38. package/dist/file-dEhr-l3n.js.map +1 -0
  39. package/dist/{file-watcher-BPFazvG_.js → file-watcher-CPM-Nn9L.js} +2 -2
  40. package/dist/{file-watcher-BPFazvG_.js.map → file-watcher-CPM-Nn9L.js.map} +1 -1
  41. package/dist/{gateway-session-xPFv6p5c.js → gateway-CVU1G0H3.js} +205 -20
  42. package/dist/gateway-CVU1G0H3.js.map +1 -0
  43. package/dist/generate-version.cjs +1 -1
  44. package/dist/{headless-ui-CsmQrDIl.js → headless-ui-pY2xB5ug.js} +13 -2
  45. package/dist/headless-ui-pY2xB5ug.js.map +1 -0
  46. package/dist/{interactive-Dej-sxvR.js → interactive-BOGlinZe.js} +2 -2
  47. package/dist/interactive-BOGlinZe.js.map +1 -0
  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-CUxNYF2t.js +226 -0
  51. package/dist/logging-ui-CUxNYF2t.js.map +1 -0
  52. package/dist/mcp-JcsBBnWv.js +97 -0
  53. package/dist/mcp-JcsBBnWv.js.map +1 -0
  54. package/dist/{mcp-prompt-streaming-BU_kuur_.js → mcp-prompt-streaming-B-p_Pvb2.js} +7 -6
  55. package/dist/mcp-prompt-streaming-B-p_Pvb2.js.map +1 -0
  56. package/dist/{mint-failure-BrleGqMd.js → mint-failure-CZFZpHpW.js} +749 -130
  57. package/dist/mint-failure-CZFZpHpW.js.map +1 -0
  58. package/dist/models-DnAY67Lg.js +83 -0
  59. package/dist/models-DnAY67Lg.js.map +1 -0
  60. package/dist/{non-interactive-DcOjH2fw.js → non-interactive-DR1CWXY1.js} +3 -3
  61. package/dist/non-interactive-DR1CWXY1.js.map +1 -0
  62. package/dist/oauth-session-CQTFOk-I.js +74 -0
  63. package/dist/oauth-session-CQTFOk-I.js.map +1 -0
  64. package/dist/{orchestrator-tools-DXwr8Sp3.js → orchestrator-tools-CBdt-SXO.js} +4 -4
  65. package/dist/orchestrator-tools-CBdt-SXO.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-BtqcLX3y.js} +444 -81
  69. package/dist/pi-BtqcLX3y.js.map +1 -0
  70. package/dist/{playground-CDUUKLkC.js → playground-Dz-ZVjBk.js} +11 -7
  71. package/dist/playground-Dz-ZVjBk.js.map +1 -0
  72. package/dist/{posthog-Hc_-9wrr.js → posthog-6Uqw_Eux.js} +9 -4
  73. package/dist/posthog-6Uqw_Eux.js.map +1 -0
  74. package/dist/{provisioning-xfdjhFtA.js → provisioning-Zf7yPcEs.js} +6 -5
  75. package/dist/provisioning-Zf7yPcEs.js.map +1 -0
  76. package/dist/{queue-tools-C8y_xZJi.js → queue-tools-B7_aCyd-.js} +7 -86
  77. package/dist/queue-tools-B7_aCyd-.js.map +1 -0
  78. package/dist/{registry-DTmREJ-f.js → registry-B6iLGorH.js} +307 -48
  79. package/dist/registry-B6iLGorH.js.map +1 -0
  80. package/dist/run-agent-legacy-6WcYMaR9.js +3541 -0
  81. package/dist/run-agent-legacy-6WcYMaR9.js.map +1 -0
  82. package/dist/{security-Dw2oFJjP.js → security-lkBwWbrK.js} +17 -7
  83. package/dist/security-lkBwWbrK.js.map +1 -0
  84. package/dist/{setup-utils-fjJTBhaB.js → setup-utils-dCViCC6s.js} +47 -19
  85. package/dist/setup-utils-dCViCC6s.js.map +1 -0
  86. package/dist/smoke-test.sh +1 -1
  87. package/dist/{start-tui-UNe2xQ0U.js → start-tui-oCWMgsDP.js} +40 -46
  88. package/dist/start-tui-oCWMgsDP.js.map +1 -0
  89. package/dist/{steps-C2yqOk_h.js → steps-gx0Pq4I4.js} +7 -7
  90. package/dist/{steps-C2yqOk_h.js.map → steps-gx0Pq4I4.js.map} +1 -1
  91. package/dist/{store-Bic4Cr3L.js → store-xYy_6Ruv.js} +19 -29
  92. package/dist/store-xYy_6Ruv.js.map +1 -0
  93. package/dist/{subagent-Dz41vV9j.js → subagent-Bfy0sfhU.js} +8 -3
  94. package/dist/subagent-Bfy0sfhU.js.map +1 -0
  95. package/dist/{task-5-fw_Vw3.js → task-BOfw7GPc.js} +124 -36
  96. package/dist/task-BOfw7GPc.js.map +1 -0
  97. package/dist/{task-stream-dVzl6b_q.js → task-stream-kYlm9qd0.js} +47 -17
  98. package/dist/task-stream-kYlm9qd0.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-Bpv-Mh5B.js} +5 -5
  102. package/dist/telemetry-Bpv-Mh5B.js.map +1 -0
  103. package/dist/{terminal-9bvRa4Qt.js → terminal-D07EQ2y0.js} +41 -76
  104. package/dist/terminal-D07EQ2y0.js.map +1 -0
  105. package/dist/{tools-Dp6i9k70.js → tools-Cc41af5W.js} +11 -11
  106. package/dist/tools-Cc41af5W.js.map +1 -0
  107. package/dist/ui-CGXtC7Vn.js +15 -0
  108. package/dist/ui-CGXtC7Vn.js.map +1 -0
  109. package/dist/version-Cadof0Z_.js +6 -0
  110. package/dist/version-Cadof0Z_.js.map +1 -0
  111. package/dist/warlock-smoke-test.ts +2 -2
  112. package/dist/{wizard-abort-lE6umflt.js → wizard-abort-HDbP3YcS.js} +23 -20
  113. package/dist/wizard-abort-HDbP3YcS.js.map +1 -0
  114. package/dist/wizard-abort-Y-Ip2K4z.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-B49RIk5d.js +2 -0
  121. package/dist/{yara-hooks-BTNJ6MGW.js → yara-hooks-DCfROpZt.js} +19 -68
  122. package/dist/yara-hooks-DCfROpZt.js.map +1 -0
  123. package/package.json +2 -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/file-BoD3REGB.js.map +0 -1
  139. package/dist/gateway-session-C118uACz.js +0 -2
  140. package/dist/gateway-session-xPFv6p5c.js.map +0 -1
  141. package/dist/headless-ui-CsmQrDIl.js.map +0 -1
  142. package/dist/interactive-Dej-sxvR.js.map +0 -1
  143. package/dist/local-dev-DPZiIPCK.js.map +0 -1
  144. package/dist/mcp-Cbuw_xss.js +0 -64
  145. package/dist/mcp-Cbuw_xss.js.map +0 -1
  146. package/dist/mcp-prompt-streaming-BU_kuur_.js.map +0 -1
  147. package/dist/mint-failure-BrleGqMd.js.map +0 -1
  148. package/dist/non-interactive-DcOjH2fw.js.map +0 -1
  149. package/dist/orchestrator-tools-DXwr8Sp3.js.map +0 -1
  150. package/dist/package-json-xt3eeyBI.js.map +0 -1
  151. package/dist/package-manager-DR23m5Jg.js +0 -290
  152. package/dist/package-manager-DR23m5Jg.js.map +0 -1
  153. package/dist/pi-mY8I2XkG.js.map +0 -1
  154. package/dist/playground-CDUUKLkC.js.map +0 -1
  155. package/dist/posthog-Hc_-9wrr.js.map +0 -1
  156. package/dist/provisioning-xfdjhFtA.js.map +0 -1
  157. package/dist/queue-tools-C8y_xZJi.js.map +0 -1
  158. package/dist/registry-DTmREJ-f.js.map +0 -1
  159. package/dist/security-Dw2oFJjP.js.map +0 -1
  160. package/dist/setup-utils-fjJTBhaB.js.map +0 -1
  161. package/dist/start-tui-UNe2xQ0U.js.map +0 -1
  162. package/dist/store-Bic4Cr3L.js.map +0 -1
  163. package/dist/subagent-Dz41vV9j.js.map +0 -1
  164. package/dist/task-5-fw_Vw3.js.map +0 -1
  165. package/dist/task-stream-dVzl6b_q.js.map +0 -1
  166. package/dist/tasks-D1c2z1aw.js.map +0 -1
  167. package/dist/telemetry-BRnxBRWK.js.map +0 -1
  168. package/dist/terminal-9bvRa4Qt.js.map +0 -1
  169. package/dist/tools-Dp6i9k70.js.map +0 -1
  170. package/dist/wizard-abort-CAcInAxg.js +0 -2
  171. package/dist/wizard-abort-lE6umflt.js.map +0 -1
  172. package/dist/wizard-session-CYvyYnti.js +0 -2
  173. package/dist/wizard-session-FSJCkTcP.js.map +0 -1
  174. package/dist/yara-hooks-BTNJ6MGW.js.map +0 -1
  175. 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 { 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";
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,198 @@ 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/signals.ts
263
+ /**
264
+ * Agent signal vocabulary — the marker strings the agent emits and the error
265
+ * taxonomy the runner returns. Kept as a dependency-free leaf module so both
266
+ * `agent-interface.ts` and `output-signals.ts` can import it without a cycle.
267
+ */
268
+ const AgentSignals = {
269
+ STATUS: "[STATUS]",
270
+ ERROR_MCP_MISSING: "[ERROR-MCP-MISSING]",
271
+ ERROR_RESOURCE_MISSING: "[ERROR-RESOURCE-MISSING]",
272
+ SKILL_INSTALL_FAILED: "[SKILL-INSTALL-FAILED]",
273
+ ABORT: "[ABORT]",
274
+ WIZARD_REMARK: "[WIZARD-REMARK]",
275
+ BENCHMARK: "[BENCHMARK]",
276
+ DASHBOARD_URL: "[DASHBOARD_URL]",
277
+ NOTEBOOK_URL: "[NOTEBOOK_URL]"
278
+ };
279
+ /**
280
+ * End-of-run reflection ask, shared by both harnesses so remarks are
281
+ * comparable. The format clause comes FIRST and nothing trails the marker —
282
+ * literal models (gpt-5-mini) echo whatever text follows it. The parser also
283
+ * drops remarks that quote this instruction (see AgentOutputSignals.remark).
284
+ */
285
+ 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.`;
286
+ /**
287
+ * First prompt of a session resumed after a mid-run re-mint. The transcript
288
+ * carries the work so far; the model only needs to pick it up.
289
+ */
290
+ const RESUME_INSTRUCTION = "Your previous request failed with a transient gateway authentication error that has since been fixed. Continue the task from where you left off.";
291
+ //#endregion
292
+ //#region src/agent/runner/harness/pi/gateway.ts
293
+ /**
294
+ * PostHog AI gateway provider spec for pi sessions, shared by the linear run
295
+ * and the orchestrator's per-task runs so both speak to the gateway
296
+ * identically: bearer auth, the wizard properties header, transport shape
297
+ * inferred from the model id. The caller registers the spec on its own
298
+ * (lazily imported, properly typed) pi ModelRegistry.
299
+ */
300
+ /** Provider registered on the in-memory registry for this run. */
301
+ const GATEWAY_PROVIDER = "posthog-gateway";
302
+ /**
303
+ * The gateway speaks two shapes on two endpoints: Anthropic models over
304
+ * `anthropic-messages` (the SDK appends `/v1/messages`, so the base URL has no
305
+ * `/v1`), and OpenAI-class models (`openai/gpt-5`, …) over an OpenAI shape at
306
+ * `/v1/responses` or `/v1/chat/completions` (base URL keeps `/v1`). Infer the
307
+ * shape from the model id so a pair's model selects the right transport.
308
+ *
309
+ * OpenAI models take the Responses API because OpenAI rejects function tools
310
+ * combined with `reasoning_effort` on chat completions and every task sends both.
311
+ */
312
+ function gatewayApiFor(modelId) {
313
+ return modelId.startsWith("openai/") ? "openai-responses" : "anthropic-messages";
314
+ }
315
+ /**
316
+ * Gateway HTTP headers, mirroring `buildAgentEnv` on the anthropic path: one
317
+ * `X-PostHog-Properties` JSON blob (Bedrock fallback is native, so no opt-in)
318
+ * plus the 1M context beta, since pi otherwise runs at 200k and overflows on
319
+ * larger projects (the post-run compaction failures).
320
+ */
321
+ function buildGatewayHeaders(wizardMetadata, wizardFlags, teamId) {
322
+ return {
323
+ "anthropic-beta": "context-1m-2025-08-07",
324
+ "X-PostHog-Properties": buildWizardPropertiesBlob(wizardMetadata, wizardFlags, teamId)
325
+ };
326
+ }
327
+ /**
328
+ * One gateway model spec — the single description of how to reach a model on
329
+ * the gateway. The provider spec below wraps it for pi's registry; one-shot
330
+ * callers (scan triage) hand it straight to `completeSimple`.
331
+ */
332
+ function buildGatewayModel(inputs) {
333
+ const { gatewayUrl, wizardMetadata, wizardFlags, modelId, teamId } = inputs;
334
+ const api = gatewayApiFor(modelId);
335
+ return {
336
+ id: modelId,
337
+ name: `${modelId} (PostHog Gateway)`,
338
+ api,
339
+ provider: GATEWAY_PROVIDER,
340
+ baseUrl: api === "anthropic-messages" ? gatewayUrl : `${gatewayUrl}/v1`,
341
+ reasoning: modelCapabilities(modelId).reasoning,
342
+ input: ["text"],
343
+ cost: {
344
+ input: 0,
345
+ output: 0,
346
+ cacheRead: 0,
347
+ cacheWrite: 0
348
+ },
349
+ contextWindow: 1e6,
350
+ maxTokens: 64e3,
351
+ headers: buildGatewayHeaders(wizardMetadata, wizardFlags, teamId)
352
+ };
353
+ }
354
+ /**
355
+ * The provider object for `registry.registerProvider(GATEWAY_PROVIDER, …)`,
356
+ * plus the derived traits the session setup needs (`caps.thinkingLevel`).
357
+ */
358
+ function buildGatewayProvider(inputs) {
359
+ const { gatewayUrl, accessToken, modelId, effort } = inputs;
360
+ const api = gatewayApiFor(modelId);
361
+ const tableCaps = modelCapabilities(modelId);
362
+ const caps = effort && effort !== "off" && tableCaps.reasoning ? modelCapabilities(modelId, effort) : effort === "off" && tableCaps.reasoning ? {
363
+ ...tableCaps,
364
+ thinkingLevel: "off"
365
+ } : tableCaps;
366
+ const model = buildGatewayModel(inputs);
367
+ return {
368
+ provider: {
369
+ name: "PostHog Gateway",
370
+ baseUrl: model.baseUrl,
371
+ apiKey: accessToken,
372
+ authHeader: true,
373
+ api,
374
+ headers: model.headers,
375
+ models: [model]
376
+ },
377
+ api,
378
+ caps,
379
+ gatewayUrl,
380
+ baseUrl: model.baseUrl
381
+ };
382
+ }
383
+ function gatewayTerminalFailure(turn) {
384
+ if (!turn || turn.stopReason !== "error" && turn.stopReason !== "aborted") return void 0;
385
+ const message = turn.errorMessage || (turn.stopReason === "aborted" ? "Agent turn aborted" : "Gateway request failed");
386
+ if (turn.stopReason === "aborted") return {
387
+ classification: "WIZARD_ABORT",
388
+ message
389
+ };
390
+ 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);
391
+ return {
392
+ classification: (structuredStatus !== void 0 ? structuredStatus === 429 : /\b429\b|rate limit/i.test(message)) ? "WIZARD_RATE_LIMIT" : "WIZARD_API_ERROR",
393
+ message,
394
+ status: structuredStatus ?? (isGatewayAuthRejection(turn) ? 401 : void 0)
395
+ };
396
+ }
397
+ /**
398
+ * Whether a turn's error is the gateway rejecting the bearer. pi attaches the
399
+ * SDK's own error to `diagnostics`, so its code decides when one is present.
400
+ * The message match is the fallback for a turn that failed before pi built a
401
+ * diagnostic, where the status survives only as prose.
402
+ */
403
+ function isGatewayAuthRejection(turn) {
404
+ const { errorMessage, diagnostics } = typeof turn === "string" ? {
405
+ errorMessage: turn,
406
+ diagnostics: void 0
407
+ } : turn ?? {};
408
+ const structuredStatus = (diagnostics ?? []).map((diagnostic) => Number(diagnostic.error?.code)).find((code) => Number.isInteger(code) && code >= 400 && code < 600);
409
+ if (structuredStatus !== void 0) return structuredStatus === 401;
410
+ for (const diagnostic of diagnostics ?? []) {
411
+ const code = diagnostic.error?.code;
412
+ if (code === 401 || code === "401") return true;
413
+ if (/^authentication_?error$/i.test(diagnostic.error?.name ?? "")) return true;
414
+ }
415
+ return /\b401\b|authentication_error|unauthorized/i.test(errorMessage ?? "");
416
+ }
417
+ /**
418
+ * Wraps a pi session's prompt(): when a turn ends on a 401 from a bearer past
419
+ * its refresh instant, mint once, re-register the provider with the new
420
+ * bearer (pi resolves the apiKey per request), and continue. A 401 on a fresh
421
+ * bearer, or a second one, is left to the harness's normal failure path.
422
+ */
423
+ function withGatewayRemint(opts) {
424
+ let auth = opts.auth;
425
+ let rejected = false;
426
+ let reminted = false;
427
+ let lastTurn;
428
+ return {
429
+ noteAssistantTurn(message) {
430
+ lastTurn = message;
431
+ rejected = lastTurn?.stopReason === "error" && isGatewayAuthRejection(lastTurn);
432
+ },
433
+ terminalFailure: () => gatewayTerminalFailure(lastTurn),
434
+ async prompt(text) {
435
+ if (opts.signal?.aborted) return;
436
+ rejected = false;
437
+ lastTurn = void 0;
438
+ await opts.session.prompt(text);
439
+ if (opts.signal?.aborted || !rejected || reminted || !isPastRefresh(auth)) return;
440
+ reminted = true;
441
+ auth = await opts.refreshAuth();
442
+ if (opts.signal?.aborted) return;
443
+ opts.registry.registerProvider(GATEWAY_PROVIDER, buildGatewayProvider(opts.providerInputs(auth)).provider);
444
+ opts.onRemint?.();
445
+ rejected = false;
446
+ lastTurn = void 0;
447
+ const next = opts.continueText;
448
+ if (opts.signal?.aborted) return;
449
+ await opts.session.prompt(typeof next === "function" ? next() : next);
450
+ }
451
+ };
452
+ }
453
+ //#endregion
454
+ 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 };
270
455
 
271
- //# sourceMappingURL=gateway-session-xPFv6p5c.js.map
456
+ //# sourceMappingURL=gateway-CVU1G0H3.js.map
@@ -0,0 +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 === '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,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A6C,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-CUxNYF2t.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-pY2xB5ug.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headless-ui-pY2xB5ug.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-CZFZpHpW.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-BOGlinZe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interactive-BOGlinZe.js","names":[],"sources":["../src/commands/basic-integration/interactive.ts"],"sourcesContent":["import type { Arguments } from 'yargs';\nimport { runWizard } from '@lib/runners';\nimport { posthogIntegrationConfig } from '@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,KAAK,aAAa,WAAW;EACvC,UAAU,KAAK,aAAa,WAAW;EACvC,kBAAkB,KAAK,sBAAsB,mBAAmB;EAChE,cAAc,KAAK,iBAAiB,eAAe;EACpD,CAAC;;AAGJ,MAAM,qBAAuC;CAC3C,UAAU;CACV,kBAAkB;CAClB,cAAc;CACf;AAED,IAAI,WAAoC;;;;;AAMxC,SAAgB,aAAa,MAAiD;AAC5E,YAAW,iBAAiB,KAAK;AACjC,QAAO;;;;;;;;;;AAWT,SAAgB,cAAgC;AAC9C,QAAO,YAAY;;AAiBrB,MAAM,iBAA0C;CAC9C;EACE,KAAK;EACL,O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