@posthog/wizard 2.67.0 → 2.68.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 (101) hide show
  1. package/dist/{add-mcp-server-to-clients-DHTRbyJX.js → add-mcp-server-to-clients-y0swAr9I.js} +4 -4
  2. package/dist/{add-mcp-server-to-clients-DHTRbyJX.js.map → add-mcp-server-to-clients-y0swAr9I.js.map} +1 -1
  3. package/dist/{agent-interface-tM_b0l__.js → agent-interface-CaEptZuu.js} +283 -41
  4. package/dist/agent-interface-CaEptZuu.js.map +1 -0
  5. package/dist/{agent-prompt-loader-BSMh5bfD.js → agent-prompt-loader-DZHc9tIG.js} +5 -5
  6. package/dist/{agent-prompt-loader-BSMh5bfD.js.map → agent-prompt-loader-DZHc9tIG.js.map} +1 -1
  7. package/dist/{agent-runner-DD65OMkB.js → agent-runner-Do5kyhPo.js} +32 -17
  8. package/dist/agent-runner-Do5kyhPo.js.map +1 -0
  9. package/dist/analytics-BNCWoTKa.js +2 -0
  10. package/dist/{analytics-CtIYzkK4.js → analytics-tF06lcmE.js} +2 -2
  11. package/dist/{analytics-CtIYzkK4.js.map → analytics-tF06lcmE.js.map} +1 -1
  12. package/dist/{api-BJft9v6K.js → api-D7-8R4xx.js} +3 -3
  13. package/dist/{api-BJft9v6K.js.map → api-D7-8R4xx.js.map} +1 -1
  14. package/dist/bin.js +50 -50
  15. package/dist/{bounded-fs-BWqoFQvQ.js → bounded-fs-BwuqKpBH.js} +3 -3
  16. package/dist/{bounded-fs-BWqoFQvQ.js.map → bounded-fs-BwuqKpBH.js.map} +1 -1
  17. package/dist/{ci-install-BXGnVI7T.js → ci-install-CrqqhXAw.js} +4 -4
  18. package/dist/{ci-install-BXGnVI7T.js.map → ci-install-CrqqhXAw.js.map} +1 -1
  19. package/dist/{debug-mO3yg4Z7.js → debug-CWn7PsPd.js} +1 -1
  20. package/dist/{debug-BsHD83Vy.js → debug-aA5dm2MR.js} +3 -3
  21. package/dist/{debug-BsHD83Vy.js.map → debug-aA5dm2MR.js.map} +1 -1
  22. package/dist/{env-api-key-DS0ghlcO.js → env-api-key-CwkRyrgi.js} +2 -2
  23. package/dist/{env-api-key-DS0ghlcO.js.map → env-api-key-CwkRyrgi.js.map} +1 -1
  24. package/dist/environment-BGUJxuvj.js +44 -0
  25. package/dist/environment-BGUJxuvj.js.map +1 -0
  26. package/dist/{file-watcher-D1bdo9mq.js → file-watcher-Cn7tD95m.js} +2 -2
  27. package/dist/{file-watcher-D1bdo9mq.js.map → file-watcher-Cn7tD95m.js.map} +1 -1
  28. package/dist/{headless-ui-6QuByWZ_.js → headless-ui-DtIYZNVv.js} +2 -2
  29. package/dist/{headless-ui-6QuByWZ_.js.map → headless-ui-DtIYZNVv.js.map} +1 -1
  30. package/dist/{interactive-DUpW84WU.js → interactive-BRB6w6KG.js} +2 -2
  31. package/dist/{interactive-DUpW84WU.js.map → interactive-BRB6w6KG.js.map} +1 -1
  32. package/dist/{mcp-CHo9h-WV.js → mcp-BXdSTZe6.js} +2 -2
  33. package/dist/{mcp-CHo9h-WV.js.map → mcp-BXdSTZe6.js.map} +1 -1
  34. package/dist/{mcp-prompt-streaming-CHRPxxd0.js → mcp-prompt-streaming-DhOT15Jj.js} +13 -12
  35. package/dist/mcp-prompt-streaming-DhOT15Jj.js.map +1 -0
  36. package/dist/{non-interactive-Cr-chffe.js → non-interactive-ezilF3PY.js} +2 -2
  37. package/dist/{non-interactive-Cr-chffe.js.map → non-interactive-ezilF3PY.js.map} +1 -1
  38. package/dist/{orchestrator-tools-Tx18_TMb.js → orchestrator-tools-D82843t_.js} +3 -3
  39. package/dist/{orchestrator-tools-Tx18_TMb.js.map → orchestrator-tools-D82843t_.js.map} +1 -1
  40. package/dist/{package-manager-CLfc31yf.js → package-manager-BPoVLj7W.js} +2 -2
  41. package/dist/{package-manager-CLfc31yf.js.map → package-manager-BPoVLj7W.js.map} +1 -1
  42. package/dist/{pi-RlnYUHdb.js → pi-CKyt4bcu.js} +16 -13
  43. package/dist/pi-CKyt4bcu.js.map +1 -0
  44. package/dist/{playground-DQ633rje.js → playground-Dnyb4jLu.js} +7 -7
  45. package/dist/{playground-DQ633rje.js.map → playground-Dnyb4jLu.js.map} +1 -1
  46. package/dist/{posthog-DSn9bIZc.js → posthog-BHyJiU05.js} +2 -2
  47. package/dist/{posthog-DSn9bIZc.js.map → posthog-BHyJiU05.js.map} +1 -1
  48. package/dist/{posthog-integration-DFfBRGOC.js → posthog-integration-DJX4qTDQ.js} +16 -15
  49. package/dist/posthog-integration-DJX4qTDQ.js.map +1 -0
  50. package/dist/{provisioning-Cvy_vQHV.js → provisioning-DEEt9xl4.js} +3 -3
  51. package/dist/{provisioning-Cvy_vQHV.js.map → provisioning-DEEt9xl4.js.map} +1 -1
  52. package/dist/{queue-tools-BC9HxOV6.js → queue-tools-i_TmeI02.js} +3 -3
  53. package/dist/{queue-tools-BC9HxOV6.js.map → queue-tools-i_TmeI02.js.map} +1 -1
  54. package/dist/{registry-DCAElOyj.js → registry-CbXqxcX0.js} +5 -5
  55. package/dist/{registry-DCAElOyj.js.map → registry-CbXqxcX0.js.map} +1 -1
  56. package/dist/{security-CuSX3XVo.js → security-DZ1rkONB.js} +5 -5
  57. package/dist/{security-CuSX3XVo.js.map → security-DZ1rkONB.js.map} +1 -1
  58. package/dist/{setup-utils-D1tv0v_R.js → setup-utils-BLKhAx6g.js} +9 -9
  59. package/dist/{setup-utils-D1tv0v_R.js.map → setup-utils-BLKhAx6g.js.map} +1 -1
  60. package/dist/{start-tui-B5YfmqNr.js → start-tui-D1MqJVT1.js} +19 -19
  61. package/dist/{start-tui-B5YfmqNr.js.map → start-tui-D1MqJVT1.js.map} +1 -1
  62. package/dist/{steps-CLaSMwfR.js → steps-Dsw-zBET.js} +7 -7
  63. package/dist/{steps-CLaSMwfR.js.map → steps-Dsw-zBET.js.map} +1 -1
  64. package/dist/{store-DzEgsAPN.js → store-OGBMWp3H.js} +5 -5
  65. package/dist/{store-DzEgsAPN.js.map → store-OGBMWp3H.js.map} +1 -1
  66. package/dist/{subagent-BUV6aD7p.js → subagent-DrnKYgvu.js} +2 -2
  67. package/dist/{subagent-BUV6aD7p.js.map → subagent-DrnKYgvu.js.map} +1 -1
  68. package/dist/{task-GnWId75q.js → task-DyvLyDsO.js} +17 -14
  69. package/dist/task-DyvLyDsO.js.map +1 -0
  70. package/dist/{task-stream-DSzvwJrD.js → task-stream-CLXzeuPO.js} +5 -5
  71. package/dist/{task-stream-DSzvwJrD.js.map → task-stream-CLXzeuPO.js.map} +1 -1
  72. package/dist/{tasks-BO0W8ocx.js → tasks-D77GNdOU.js} +2 -2
  73. package/dist/{tasks-BO0W8ocx.js.map → tasks-D77GNdOU.js.map} +1 -1
  74. package/dist/{telemetry-Vi9dWddJ.js → telemetry-wp-z9LXH.js} +3 -3
  75. package/dist/{telemetry-Vi9dWddJ.js.map → telemetry-wp-z9LXH.js.map} +1 -1
  76. package/dist/{terminal-B5wZK7aS.js → terminal-D9j4wbpD.js} +12 -12
  77. package/dist/{terminal-B5wZK7aS.js.map → terminal-D9j4wbpD.js.map} +1 -1
  78. package/dist/{tools-C9cNluqc.js → tools-D0r4e-Vu.js} +10 -7
  79. package/dist/tools-D0r4e-Vu.js.map +1 -0
  80. package/dist/{wizard-abort-CGv3lVxw.js → wizard-abort-Bv87YVSp.js} +4 -4
  81. package/dist/{wizard-abort-CGv3lVxw.js.map → wizard-abort-Bv87YVSp.js.map} +1 -1
  82. package/dist/{wizard-abort-BsNbguJt.js → wizard-abort-oazJA1Jb.js} +1 -1
  83. package/dist/{wizard-session-Cex1BiXs.js → wizard-session-C_7r3-rO.js} +2 -1
  84. package/dist/wizard-session-C_7r3-rO.js.map +1 -0
  85. package/dist/{wizard-session-DHbUcjI7.js → wizard-session-D1KQqUml.js} +1 -1
  86. package/dist/yara-hooks-Bl-FeANN.js +2 -0
  87. package/dist/{yara-hooks-DZIVzhA6.js → yara-hooks-DeonKbE_.js} +4 -4
  88. package/dist/{yara-hooks-DZIVzhA6.js.map → yara-hooks-DeonKbE_.js.map} +1 -1
  89. package/package.json +1 -1
  90. package/dist/agent-interface-tM_b0l__.js.map +0 -1
  91. package/dist/agent-runner-DD65OMkB.js.map +0 -1
  92. package/dist/analytics-B4Igh5nv.js +0 -2
  93. package/dist/environment-C7CKGIOE.js +0 -22
  94. package/dist/environment-C7CKGIOE.js.map +0 -1
  95. package/dist/mcp-prompt-streaming-CHRPxxd0.js.map +0 -1
  96. package/dist/pi-RlnYUHdb.js.map +0 -1
  97. package/dist/posthog-integration-DFfBRGOC.js.map +0 -1
  98. package/dist/task-GnWId75q.js.map +0 -1
  99. package/dist/tools-C9cNluqc.js.map +0 -1
  100. package/dist/wizard-session-Cex1BiXs.js.map +0 -1
  101. package/dist/yara-hooks-C3Vm2Gow.js +0 -2
@@ -1,12 +1,12 @@
1
1
  import { n as __require } from "./rolldown-runtime-B_-DWIq7.js";
2
2
  import { a as AgentSignals, o as REMARK_INSTRUCTION, s as classifyAuthFailure } from "./errors-BHervYGs.js";
3
- import { G as POSTHOG_FLAG_HEADER_PREFIX, J as POSTHOG_PROPERTY_HEADER_PREFIX, a as getLogFilePath, dt as WIZARD_REMARK_EVENT_NAME, f as getUI, ht as wizardUserAgentForProgram, o as initLogFile, r as debug, s as logToFile, xt as runtimeEnv } from "./debug-BsHD83Vy.js";
4
- import { n as analytics } from "./analytics-CtIYzkK4.js";
5
- import { a as safeReadFile, i as readProjectFile, o as walkProjectFiles } from "./bounded-fs-BWqoFQvQ.js";
6
- import { n as ADDITIONAL_FEATURE_PROMPTS } from "./wizard-session-Cex1BiXs.js";
7
- import { i as wizardAbort, n as registerCleanup, t as WizardError } from "./wizard-abort-CGv3lVxw.js";
8
- import { _ as modelCapabilities, m as writeJsonAtomic, o as buildOrchestratorTools, p as makeMutex, y as triageModelFor } from "./queue-tools-BC9HxOV6.js";
9
- import { b as coerceAuditChecks, g as AUDIT_CHECKS_FILE, l as prewarmYaraScanner, n as createPostToolUseYaraHooks, p as scanInstalledSkill, r as createPreToolUseYaraHooks } from "./yara-hooks-DZIVzhA6.js";
3
+ import { G as POSTHOG_FLAG_HEADER_PREFIX, J as POSTHOG_PROPERTY_HEADER_PREFIX, a as getLogFilePath, dt as WIZARD_REMARK_EVENT_NAME, f as getUI, ht as wizardUserAgentForProgram, o as initLogFile, r as debug, s as logToFile, xt as runtimeEnv } from "./debug-aA5dm2MR.js";
4
+ import { n as analytics } from "./analytics-tF06lcmE.js";
5
+ import { a as safeReadFile, i as readProjectFile, o as walkProjectFiles } from "./bounded-fs-BwuqKpBH.js";
6
+ import { n as ADDITIONAL_FEATURE_PROMPTS } from "./wizard-session-C_7r3-rO.js";
7
+ import { i as wizardAbort, n as registerCleanup, t as WizardError } from "./wizard-abort-Bv87YVSp.js";
8
+ import { _ as modelCapabilities, m as writeJsonAtomic, o as buildOrchestratorTools, p as makeMutex, y as triageModelFor } from "./queue-tools-i_TmeI02.js";
9
+ import { b as coerceAuditChecks, g as AUDIT_CHECKS_FILE, l as prewarmYaraScanner, n as createPostToolUseYaraHooks, p as scanInstalledSkill, r as createPreToolUseYaraHooks } from "./yara-hooks-DeonKbE_.js";
10
10
  import { createRequire } from "node:module";
11
11
  import * as fs$1 from "fs";
12
12
  import fs from "fs";
@@ -19,6 +19,225 @@ import { z } from "zod";
19
19
  import * as os from "os";
20
20
  import { unzipSync } from "fflate";
21
21
  import { randomUUID } from "crypto";
22
+ //#region src/lib/gateway-session.ts
23
+ /**
24
+ * Gateway auth for a wizard run: a `phe_` scoped token the backend mints, with
25
+ * pinned attribution, a spend cap and an expiry.
26
+ *
27
+ * A 404 resolves to the legacy posture (OAuth token, Python gateway); every
28
+ * other failure throws, because the legacy path enforces none of those, so a
29
+ * silent downgrade spends unattributed money to hide an outage.
30
+ */
31
+ let cached = null;
32
+ /**
33
+ * Shared so concurrent callers mint once. The orchestrator starts every runnable
34
+ * task at once, and each would otherwise take its own token and its own cap.
35
+ */
36
+ let inFlight = null;
37
+ /**
38
+ * Adoption floor. The anthropic subprocess holds its credential for the whole
39
+ * session, so a token below this 401s mid-run.
40
+ */
41
+ const MIN_USABLE_TTL_MS = 120 * 1e3;
42
+ /** Re-resolve at this fraction of the token's life, leaving a usable remainder. */
43
+ const REFRESH_AT_FRACTION = .8;
44
+ /** How long a legacy fallback sticks before the mint endpoint is retried. */
45
+ const LEGACY_RETRY_MS = 600 * 1e3;
46
+ const MINT_TIMEOUT_MS = 2e4;
47
+ /** Resolve this run's gateway auth, minting and re-minting near expiry. */
48
+ async function gatewayAuth(host, accessToken, program) {
49
+ const key = `${host.apiHost}\n${accessToken}\n${program ?? ""}`;
50
+ if (cached && cached.key === key && Date.now() < cached.staleAtMs) return cached.auth;
51
+ if (inFlight && inFlight.key === key) return inFlight.promise;
52
+ const promise = resolveGatewayAuth(host, accessToken, key, program);
53
+ inFlight = {
54
+ key,
55
+ promise
56
+ };
57
+ try {
58
+ return await promise;
59
+ } finally {
60
+ if (inFlight?.promise === promise) inFlight = null;
61
+ }
62
+ }
63
+ async function resolveGatewayAuth(host, accessToken, key, program) {
64
+ if (!program) {
65
+ logToFile("[gateway] run has no program id; failing the run");
66
+ throw new GatewayMintFailed("this run has no program to attribute its spend to");
67
+ }
68
+ const minted = await mintGatewayToken(host, accessToken, program);
69
+ if (!minted) {
70
+ const auth = legacyAuth(host, accessToken);
71
+ cached = {
72
+ key,
73
+ auth,
74
+ staleAtMs: Date.now() + LEGACY_RETRY_MS
75
+ };
76
+ return auth;
77
+ }
78
+ const expiresAtMs = Date.parse(minted.expiresAt);
79
+ const ttlMs = expiresAtMs - Date.now();
80
+ if (!Number.isFinite(expiresAtMs) || ttlMs < MIN_USABLE_TTL_MS) {
81
+ logToFile(`[gateway] mint returned a token with ${ttlMs}ms of life; failing the run`);
82
+ throw new GatewayMintFailed(`the PostHog gateway issued a token with ${ttlMs}ms of life`);
83
+ }
84
+ const staleAtMs = Date.now() + ttlMs * REFRESH_AT_FRACTION;
85
+ const auth = {
86
+ gatewayUrl: minted.gatewayUrl,
87
+ token: minted.token,
88
+ edition: "v2",
89
+ teamId: minted.teamId
90
+ };
91
+ cached = {
92
+ key,
93
+ auth,
94
+ staleAtMs
95
+ };
96
+ return auth;
97
+ }
98
+ /** The legacy posture: the user's OAuth token against the Python gateway. */
99
+ function legacyAuth(host, accessToken) {
100
+ return {
101
+ gatewayUrl: host.gatewayUrl,
102
+ token: accessToken,
103
+ edition: "legacy"
104
+ };
105
+ }
106
+ /**
107
+ * Whether a server-supplied origin may receive a bearer and prompt content:
108
+ * https (loopback excepted), and either a posthog.com host or the one the run
109
+ * authenticated against.
110
+ */
111
+ function isTrustedGatewayUrl(value, apiHost) {
112
+ let url;
113
+ try {
114
+ url = new URL(value);
115
+ } catch {
116
+ return false;
117
+ }
118
+ if (url.pathname !== "/" || url.search || url.hash || url.username || url.password) return false;
119
+ if (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "host.docker.internal") return true;
120
+ if (url.protocol !== "https:") return false;
121
+ if (url.hostname.endsWith(".posthog.com")) return true;
122
+ try {
123
+ return url.hostname === new URL(apiHost).hostname;
124
+ } catch {
125
+ return false;
126
+ }
127
+ }
128
+ /**
129
+ * A deliberate refusal from the mint endpoint, as opposed to the mint being
130
+ * unavailable. Thrown rather than folded into the legacy fallback, so the run
131
+ * stops instead of proceeding without the controls the refusal was enforcing.
132
+ */
133
+ var GatewayMintRefused = class extends Error {
134
+ status;
135
+ constructor(status, message) {
136
+ super(message);
137
+ this.name = "GatewayMintRefused";
138
+ this.status = status;
139
+ }
140
+ };
141
+ /**
142
+ * The mint could not produce a usable credential: unreachable, a 5xx, or a
143
+ * response the client cannot use.
144
+ */
145
+ var GatewayMintFailed = class extends Error {
146
+ constructor(message) {
147
+ super(message);
148
+ this.name = "GatewayMintFailed";
149
+ }
150
+ };
151
+ /**
152
+ * Whether a mint status means "refused this run" rather than "not available".
153
+ * 429 is the daily run limit, 403 revoked project access, 401 a credential that
154
+ * may not mint. Only 404 falls back; it is the rollout switch.
155
+ */
156
+ function isMintRefusal(status) {
157
+ return status === 400 || status === 401 || status === 403 || status === 429;
158
+ }
159
+ function mintRefusalMessage(status) {
160
+ switch (status) {
161
+ case 429: return "This wizard program has used its daily run limit. Try again tomorrow.";
162
+ case 403: return "Your access to this project has changed. Re-authenticate and try again.";
163
+ case 400: return "Your PostHog login must cover exactly one project. Re-authenticate and try again.";
164
+ default: return "The wizard could not authenticate to the PostHog gateway.";
165
+ }
166
+ }
167
+ async function mintGatewayToken(host, accessToken, program) {
168
+ try {
169
+ const resp = await fetch(`${host.apiHost}/api/wizard/gateway_token/`, {
170
+ method: "POST",
171
+ headers: {
172
+ Authorization: `Bearer ${accessToken}`,
173
+ "Content-Type": "application/json"
174
+ },
175
+ body: JSON.stringify({ program }),
176
+ signal: AbortSignal.timeout(MINT_TIMEOUT_MS)
177
+ });
178
+ if (!resp.ok) {
179
+ if (isMintRefusal(resp.status)) {
180
+ logToFile(`[gateway] mint refused with HTTP ${resp.status}; failing the run`);
181
+ throw new GatewayMintRefused(resp.status, mintRefusalMessage(resp.status));
182
+ }
183
+ if (resp.status === 404) {
184
+ logToFile("[gateway] mint not enabled for this org; staying on the existing gateway");
185
+ return null;
186
+ }
187
+ logToFile(`[gateway] mint failed with HTTP ${resp.status}; failing the run`);
188
+ throw new GatewayMintFailed(`the PostHog gateway could not issue a token (HTTP ${resp.status})`);
189
+ }
190
+ const body = await resp.json();
191
+ if (!body.token) {
192
+ logToFile("[gateway] mint response omitted token; failing the run");
193
+ throw new GatewayMintFailed("mint response omitted token");
194
+ }
195
+ if (!body.expires_at) {
196
+ logToFile("[gateway] mint response omitted expires_at; failing the run");
197
+ throw new GatewayMintFailed("mint response omitted expires_at");
198
+ }
199
+ if (!body.gateway_url) {
200
+ logToFile("[gateway] mint response omitted gateway_url; failing the run");
201
+ throw new GatewayMintFailed("mint response omitted gateway_url");
202
+ }
203
+ if (!isTrustedGatewayUrl(body.gateway_url, host.apiHost)) {
204
+ logToFile("[gateway] mint returned an untrusted gateway url; failing the run");
205
+ throw new GatewayMintFailed("mint returned an untrusted gateway url");
206
+ }
207
+ return {
208
+ token: body.token,
209
+ expiresAt: body.expires_at,
210
+ gatewayUrl: body.gateway_url.replace(/\/+$/, ""),
211
+ teamId: body.team_id
212
+ };
213
+ } catch (e) {
214
+ if (e instanceof GatewayMintRefused || e instanceof GatewayMintFailed) throw e;
215
+ logToFile(`[gateway] mint transport failure (${String(e)}); failing the run`);
216
+ throw new GatewayMintFailed(`could not reach the PostHog gateway (${String(e)})`);
217
+ }
218
+ }
219
+ /**
220
+ * The v2 run-metadata carrier: one JSON blob for the `X-PostHog-Properties`
221
+ * header. Plain keys only, since the gateway strips `$`-prefixed keys as reserved,
222
+ * so feature-flag variants land as `wizard_flag_<key>` instead of the legacy
223
+ * `$feature/<key>` (dashboards keying on `$feature/wizard-*` read the new key
224
+ * post-cutover).
225
+ */
226
+ function buildWizardPropertiesBlob(wizardMetadata, wizardFlags, teamId) {
227
+ const props = {};
228
+ if (teamId !== void 0) props.team_id = teamId;
229
+ for (const [key, value] of Object.entries(wizardMetadata)) props[stripPropertyPrefix(key)] = value;
230
+ for (const [flagKey, variant] of Object.entries(wizardFlags)) {
231
+ if (!flagKey.toLowerCase().startsWith("wizard")) continue;
232
+ props[`wizard_flag_${flagKey.toLowerCase()}`] = variant;
233
+ }
234
+ return JSON.stringify(props);
235
+ }
236
+ const LEGACY_PROPERTY_PREFIX = "X-POSTHOG-PROPERTY-";
237
+ function stripPropertyPrefix(key) {
238
+ return key.toUpperCase().startsWith(LEGACY_PROPERTY_PREFIX) ? key.slice(19).toLowerCase() : key;
239
+ }
240
+ //#endregion
22
241
  //#region src/lib/agent/runner/harness/pi/gateway.ts
23
242
  /**
24
243
  * PostHog LLM gateway provider spec for pi sessions — shared by the linear run
@@ -40,15 +259,20 @@ function gatewayApiFor(modelId) {
40
259
  return modelId.startsWith("openai/") ? "openai-completions" : "anthropic-messages";
41
260
  }
42
261
  /**
43
- * Gateway HTTP headers, mirroring `buildAgentEnv` on the anthropic path: always
44
- * the Bedrock-fallback header, plus wizard metadata (`X-POSTHOG-PROPERTY-*`) and
45
- * wizard feature flags (`X-POSTHOG-FLAG-*`).
262
+ * Gateway HTTP headers, mirroring `buildAgentEnv` on the anthropic path. The
263
+ * shape follows the gateway edition: legacy sends per-key metadata/flag
264
+ * headers plus the explicit Bedrock-fallback opt-in; v2 (the Go ai-gateway)
265
+ * takes one `X-PostHog-Properties` JSON blob and falls back natively. The 1M
266
+ * context beta rides both, since pi otherwise runs at 200k and overflows on larger
267
+ * projects (the post-run compaction failures).
46
268
  */
47
- function buildGatewayHeaders(wizardMetadata, wizardFlags) {
48
- const headers = {
49
- "x-posthog-use-bedrock-fallback": "true",
50
- "anthropic-beta": "context-1m-2025-08-07"
51
- };
269
+ function buildGatewayHeaders(wizardMetadata, wizardFlags, edition = "legacy", teamId) {
270
+ const headers = { "anthropic-beta": "context-1m-2025-08-07" };
271
+ if (edition === "v2") {
272
+ headers["X-PostHog-Properties"] = buildWizardPropertiesBlob(wizardMetadata, wizardFlags, teamId);
273
+ return headers;
274
+ }
275
+ headers["x-posthog-use-bedrock-fallback"] = "true";
52
276
  for (const [key, value] of Object.entries(wizardMetadata)) {
53
277
  const name = key.startsWith("X-POSTHOG-PROPERTY-") ? key : `${POSTHOG_PROPERTY_HEADER_PREFIX}${key}`;
54
278
  headers[name] = value;
@@ -65,7 +289,7 @@ function buildGatewayHeaders(wizardMetadata, wizardFlags) {
65
289
  * callers (scan triage) hand it straight to `completeSimple`.
66
290
  */
67
291
  function buildGatewayModel(inputs) {
68
- const { gatewayUrl, wizardMetadata, wizardFlags, modelId } = inputs;
292
+ const { gatewayUrl, wizardMetadata, wizardFlags, modelId, edition, teamId } = inputs;
69
293
  const api = gatewayApiFor(modelId);
70
294
  return {
71
295
  id: modelId,
@@ -83,7 +307,7 @@ function buildGatewayModel(inputs) {
83
307
  },
84
308
  contextWindow: 1e6,
85
309
  maxTokens: 64e3,
86
- headers: buildGatewayHeaders(wizardMetadata, wizardFlags)
310
+ headers: buildGatewayHeaders(wizardMetadata, wizardFlags, edition, teamId)
87
311
  };
88
312
  }
89
313
  /**
@@ -94,9 +318,9 @@ function buildGatewayProvider(inputs) {
94
318
  const { gatewayUrl, accessToken, modelId, effort } = inputs;
95
319
  const api = gatewayApiFor(modelId);
96
320
  const tableCaps = modelCapabilities(modelId);
97
- const caps = effort && tableCaps.reasoning ? {
321
+ const caps = effort && effort !== "off" && tableCaps.reasoning ? modelCapabilities(modelId, effort) : effort === "off" && tableCaps.reasoning ? {
98
322
  ...tableCaps,
99
- thinkingLevel: effort
323
+ thinkingLevel: "off"
100
324
  } : tableCaps;
101
325
  const model = buildGatewayModel(inputs);
102
326
  return {
@@ -131,6 +355,8 @@ function createTriageLLMProvider(auth, harness) {
131
355
  const model = buildGatewayModel({
132
356
  gatewayUrl: baseURL,
133
357
  accessToken: authToken,
358
+ edition: auth.edition,
359
+ teamId: auth.teamId,
134
360
  wizardMetadata: auth?.wizardMetadata ?? {},
135
361
  wizardFlags: auth?.wizardFlags ?? {},
136
362
  modelId
@@ -836,7 +1062,7 @@ function isFullyCancelled(answers) {
836
1062
  }
837
1063
  function createWizardAskBridge(opts) {
838
1064
  const timeoutMs = opts.timeoutMs ?? 3e5;
839
- return { async request({ questions }) {
1065
+ return { async request({ questions, subject }) {
840
1066
  const pending = {
841
1067
  id: randomUUID(),
842
1068
  questions,
@@ -857,12 +1083,14 @@ function createWizardAskBridge(opts) {
857
1083
  const durationMs = Date.now() - startedAt;
858
1084
  if (isFullyCancelled(answers)) analytics.wizardCapture("wizard_ask cancelled", {
859
1085
  source: pending.source,
1086
+ subject,
860
1087
  question_count: questions.length,
861
1088
  duration_ms: durationMs,
862
1089
  timed_out: durationMs >= timeoutMs
863
1090
  });
864
1091
  else analytics.wizardCapture("wizard_ask answered", {
865
1092
  source: pending.source,
1093
+ subject,
866
1094
  question_count: questions.length,
867
1095
  duration_ms: durationMs
868
1096
  });
@@ -1926,7 +2154,10 @@ async function createWizardToolsServer(options) {
1926
2154
  }
1927
2155
  askAccounting.record(args.subject);
1928
2156
  try {
1929
- const answers = await askBridge.request({ questions: args.questions });
2157
+ const answers = await askBridge.request({
2158
+ questions: args.questions,
2159
+ subject: normaliseAskSubject(args.subject)
2160
+ });
1930
2161
  if (isFullyCancelled(answers)) askAccounting.refund(args.subject);
1931
2162
  const sanitised = vaultSensitiveAnswers(args.questions, answers, secretVault);
1932
2163
  logToFile(`wizard_ask: resolved ${Object.keys(answers).length} answer(s) for ${args.questions.length} question(s)`);
@@ -2774,17 +3005,23 @@ function isWarlockDisabled() {
2774
3005
  return runtimeEnv("POSTHOG_WIZARD_WARLOCK_DISABLED") === "true";
2775
3006
  }
2776
3007
  /**
2777
- * Build env for the SDK subprocess: process.env plus ANTHROPIC_CUSTOM_HEADERS, which always
2778
- * includes `x-posthog-use-bedrock-fallback: true` so the LLM gateway falls back to Bedrock on
2779
- * Anthropic 5xx, plus any wizard metadata/flags.
3008
+ * Build env for the SDK subprocess: process.env plus ANTHROPIC_CUSTOM_HEADERS.
3009
+ * The header shape follows the gateway edition. Legacy (Python gateway):
3010
+ * per-key `X-POSTHOG-PROPERTY-*`/`X-POSTHOG-FLAG-*` plus the explicit
3011
+ * `x-posthog-use-bedrock-fallback` opt-in. v2 (Go ai-gateway): one
3012
+ * `X-PostHog-Properties` JSON blob. Bedrock fallback is native there, and
3013
+ * per-key metadata headers are not read.
2780
3014
  */
2781
- function buildAgentEnv(wizardMetadata, wizardFlags) {
3015
+ function buildAgentEnv(wizardMetadata, wizardFlags, auth) {
2782
3016
  const headers = createCustomHeaders();
2783
- headers.add("x-posthog-use-bedrock-fallback", "true");
2784
- for (const [key, value] of Object.entries(wizardMetadata)) headers.add(key.startsWith("X-POSTHOG-PROPERTY-") ? key : `${POSTHOG_PROPERTY_HEADER_PREFIX}${key}`, value);
2785
- for (const [flagKey, variant] of Object.entries(wizardFlags)) {
2786
- if (!flagKey.toLowerCase().startsWith("wizard")) continue;
2787
- headers.addFlag(flagKey, variant);
3017
+ if (auth?.edition === "v2") headers.add("X-PostHog-Properties", buildWizardPropertiesBlob(wizardMetadata, wizardFlags, auth.teamId));
3018
+ else {
3019
+ headers.add("x-posthog-use-bedrock-fallback", "true");
3020
+ for (const [key, value] of Object.entries(wizardMetadata)) headers.add(key.startsWith("X-POSTHOG-PROPERTY-") ? key : `${POSTHOG_PROPERTY_HEADER_PREFIX}${key}`, value);
3021
+ for (const [flagKey, variant] of Object.entries(wizardFlags)) {
3022
+ if (!flagKey.toLowerCase().startsWith("wizard")) continue;
3023
+ headers.addFlag(flagKey, variant);
3024
+ }
2788
3025
  }
2789
3026
  const encoded = headers.encode();
2790
3027
  logToFile("ANTHROPIC_CUSTOM_HEADERS", encoded);
@@ -2879,13 +3116,17 @@ async function initializeAgent(config, options) {
2879
3116
  logToFile("Install directory:", options.installDir);
2880
3117
  try {
2881
3118
  process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = "true";
2882
- const gatewayUrl = config.host.gatewayUrl;
3119
+ const auth = await gatewayAuth(config.host, config.posthogApiKey, config.programId);
3120
+ const gatewayUrl = auth.gatewayUrl;
2883
3121
  process.env.ANTHROPIC_BASE_URL = gatewayUrl;
2884
- process.env.ANTHROPIC_AUTH_TOKEN = config.posthogApiKey;
2885
- process.env.CLAUDE_CODE_OAUTH_TOKEN = config.posthogApiKey;
3122
+ process.env.ANTHROPIC_AUTH_TOKEN = auth.token;
3123
+ process.env.CLAUDE_CODE_OAUTH_TOKEN = auth.token;
3124
+ logToFile("Gateway edition:", auth.edition);
2886
3125
  const triageProvider = createTriageLLMProvider({
2887
3126
  baseURL: gatewayUrl,
2888
- authToken: config.posthogApiKey,
3127
+ authToken: auth.token,
3128
+ edition: auth.edition,
3129
+ teamId: auth.teamId,
2889
3130
  wizardMetadata: {
2890
3131
  ...config.wizardMetadata ?? {},
2891
3132
  call_type: "yara-triage"
@@ -2942,6 +3183,7 @@ async function initializeAgent(config, options) {
2942
3183
  suppressTaskRender: !!config.orchestrator,
2943
3184
  capture: config.capture,
2944
3185
  triageProvider,
3186
+ gatewayAuth: auth,
2945
3187
  program: config.integrationLabel,
2946
3188
  sequence: config.orchestrator ? "orchestrator" : "linear"
2947
3189
  };
@@ -3115,13 +3357,13 @@ async function runAgent(agentConfig, prompt, options, spinner, config, middlewar
3115
3357
  },
3116
3358
  env: {
3117
3359
  ...sanitizeAgentSubprocessEnv(process.env),
3118
- ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL,
3119
- ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN,
3120
- CLAUDE_CODE_OAUTH_TOKEN: process.env.CLAUDE_CODE_OAUTH_TOKEN,
3360
+ ANTHROPIC_BASE_URL: agentConfig.gatewayAuth.gatewayUrl,
3361
+ ANTHROPIC_AUTH_TOKEN: agentConfig.gatewayAuth.token,
3362
+ CLAUDE_CODE_OAUTH_TOKEN: agentConfig.gatewayAuth.token,
3121
3363
  CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: "true",
3122
3364
  POSTHOG_MCP_TOKEN: agentConfig.posthogApiKey,
3123
3365
  MCP_CONNECTION_NONBLOCKING: "0",
3124
- ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(agentConfig.wizardMetadata ?? {}, agentConfig.wizardFlags ?? {})
3366
+ ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(agentConfig.wizardMetadata ?? {}, agentConfig.wizardFlags ?? {}, agentConfig.gatewayAuth)
3125
3367
  },
3126
3368
  canUseTool: (toolName, input) => {
3127
3369
  logToFile("canUseTool called:", {
@@ -3200,7 +3442,7 @@ async function runAgent(agentConfig, prompt, options, spinner, config, middlewar
3200
3442
  if (message.type === "assistant" && signals.hasApiErrorStatus(401)) {
3201
3443
  signalDone();
3202
3444
  spinner.stop("Authentication failed");
3203
- const authError = buildAuthErrorContext(options.installDir, process.env.ANTHROPIC_BASE_URL ?? "", os.homedir(), signals.apiKeySource);
3445
+ const authError = buildAuthErrorContext(options.installDir, agentConfig.gatewayAuth.gatewayUrl, os.homedir(), signals.apiKeySource);
3204
3446
  const authCode = classifyAuthFailure({
3205
3447
  hasSettingsConflict: authError.hasSettingsConflict,
3206
3448
  usingManagedLogin: authError.usingManagedLogin,
@@ -3572,6 +3814,6 @@ function handleSDKMessage(message, options, spinner, signals, receivedSuccessRes
3572
3814
  }
3573
3815
  }
3574
3816
  //#endregion
3575
- export { installSkillById as A, isEnvFileName as B, WIZARD_ASK_SUBJECT_DESCRIPTION as C, createAskAccounting as D, checkEnvKeys as E, vaultSensitiveAnswers as F, buildGatewayProvider as G, toPromptSafeRelativePath as H, fetchWithRetry as I, createWizardAskBridge as L, resolveEnvPath as M, resolveEnvSecretRefs as N, downloadSkill as O, templateEnvWriteRefusal as P, isFullyCancelled as R, WIZARD_ASK_SENSITIVE_DESCRIPTION as S, WIZARD_TOOL_NAMES as T, createTriageLLMProvider as U, parseEnvKeyNames as V, GATEWAY_PROVIDER as W, PUBLISH_HANDOFF_TOOL_NAME as _, wizardCanUseTool as a, CHECK_ENV_KEYS_FILE_PATH_DESCRIPTION as b, classifySettingsConflicts as c, sanitizeAgentSubprocessEnv as d, AgentOutputSignals as f, PUBLISH_HANDOFF_DESCRIPTION as g, PUBLISH_HANDOFF_CONTENT_DESCRIPTION as h, runAgent as i, mergeEnvValues as j, fetchSkillMenu as k, recoverOrphanedSettingsBackups as l, createSecretVault as m, buildRunTags as n, backupAndFixClaudeSettings as o, assembleCommandments as p, initializeAgent as r, checkAllSettingsConflicts as s, buildAgentEnv as t, restoreClaudeSettings as u, publishHandoff as v, WIZARD_ASK_TOOL_DESCRIPTION as w, ENV_FILE_PATH_DESCRIPTION as x, CHECK_ENV_KEYS_DESCRIPTION as y, MAX_ENV_KEY_SET as z };
3817
+ export { installSkillById as A, MAX_ENV_KEY_SET as B, WIZARD_ASK_SUBJECT_DESCRIPTION as C, createAskAccounting as D, checkEnvKeys as E, templateEnvWriteRefusal as F, GATEWAY_PROVIDER as G, parseEnvKeyNames as H, vaultSensitiveAnswers as I, buildGatewayProvider as K, fetchWithRetry as L, normaliseAskSubject as M, resolveEnvPath as N, downloadSkill as O, resolveEnvSecretRefs as P, createWizardAskBridge as R, WIZARD_ASK_SENSITIVE_DESCRIPTION as S, WIZARD_TOOL_NAMES as T, toPromptSafeRelativePath as U, isEnvFileName as V, createTriageLLMProvider as W, PUBLISH_HANDOFF_TOOL_NAME as _, wizardCanUseTool as a, CHECK_ENV_KEYS_FILE_PATH_DESCRIPTION as b, classifySettingsConflicts as c, sanitizeAgentSubprocessEnv as d, AgentOutputSignals as f, PUBLISH_HANDOFF_DESCRIPTION as g, PUBLISH_HANDOFF_CONTENT_DESCRIPTION as h, runAgent as i, mergeEnvValues as j, fetchSkillMenu as k, recoverOrphanedSettingsBackups as l, createSecretVault as m, buildRunTags as n, backupAndFixClaudeSettings as o, assembleCommandments as p, gatewayAuth as q, initializeAgent as r, checkAllSettingsConflicts as s, buildAgentEnv as t, restoreClaudeSettings as u, publishHandoff as v, WIZARD_ASK_TOOL_DESCRIPTION as w, ENV_FILE_PATH_DESCRIPTION as x, CHECK_ENV_KEYS_DESCRIPTION as y, isFullyCancelled as z };
3576
3818
 
3577
- //# sourceMappingURL=agent-interface-tM_b0l__.js.map
3819
+ //# sourceMappingURL=agent-interface-CaEptZuu.js.map