@posthog/wizard 2.46.0 → 2.47.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.
- package/dist/{add-mcp-server-to-clients-Bv2CBSil.js → add-mcp-server-to-clients-Dg64O4OZ.js} +4 -4
- package/dist/{add-mcp-server-to-clients-Bv2CBSil.js.map → add-mcp-server-to-clients-Dg64O4OZ.js.map} +1 -1
- package/dist/{agent-interface-B8roB2UP.js → agent-interface-RZY46R62.js} +10 -6
- package/dist/agent-interface-RZY46R62.js.map +1 -0
- package/dist/{agent-runner-CV3qh_2p.js → agent-runner-D8pEOs_2.js} +17 -12
- package/dist/{agent-runner-CV3qh_2p.js.map → agent-runner-D8pEOs_2.js.map} +1 -1
- package/dist/{analytics-k76OWsl0.js → analytics-B4dny8FA.js} +2 -2
- package/dist/{analytics-k76OWsl0.js.map → analytics-B4dny8FA.js.map} +1 -1
- package/dist/analytics-BAhDPsPK.js +2 -0
- package/dist/{api-CmIWcW-U.js → api-CdPvsnUm.js} +3 -3
- package/dist/{api-CmIWcW-U.js.map → api-CdPvsnUm.js.map} +1 -1
- package/dist/bin.js +109 -38
- package/dist/bin.js.map +1 -1
- package/dist/{ci-install-CNEJxdHf.js → ci-install-g8govb-6.js} +4 -4
- package/dist/{ci-install-CNEJxdHf.js.map → ci-install-g8govb-6.js.map} +1 -1
- package/dist/{debug-C9HmIrwx.js → debug-BiU-S12q.js} +3 -3
- package/dist/{debug-C9HmIrwx.js.map → debug-BiU-S12q.js.map} +1 -1
- package/dist/{debug-BwIo7nwn.js → debug-DQWRmiju.js} +1 -1
- package/dist/{environment-NJykOp33.js → environment-BT0RRheV.js} +3 -3
- package/dist/{environment-NJykOp33.js.map → environment-BT0RRheV.js.map} +1 -1
- package/dist/{file-utils-CLMcNIKi.js → file-utils-B1_Eciop.js} +2 -2
- package/dist/{file-utils-CLMcNIKi.js.map → file-utils-B1_Eciop.js.map} +1 -1
- package/dist/{file-watcher-CBDCNQVV.js → file-watcher-4frv2dFl.js} +2 -2
- package/dist/{file-watcher-CBDCNQVV.js.map → file-watcher-4frv2dFl.js.map} +1 -1
- package/dist/{headless-ui-B3QKxbz8.js → headless-ui-DQVBpo0v.js} +2 -2
- package/dist/{headless-ui-B3QKxbz8.js.map → headless-ui-DQVBpo0v.js.map} +1 -1
- package/dist/{interactive-CIJRex02.js → interactive-Bgb8njPS.js} +2 -2
- package/dist/{interactive-CIJRex02.js.map → interactive-Bgb8njPS.js.map} +1 -1
- package/dist/{mcp-qTjKHqXN.js → mcp-BEWwXAXk.js} +2 -2
- package/dist/{mcp-qTjKHqXN.js.map → mcp-BEWwXAXk.js.map} +1 -1
- package/dist/{mcp-prompt-streaming-D6OgW3lC.js → mcp-prompt-streaming-MfYiLHox.js} +3 -3
- package/dist/{mcp-prompt-streaming-D6OgW3lC.js.map → mcp-prompt-streaming-MfYiLHox.js.map} +1 -1
- package/dist/{non-interactive-8Eypq_h-.js → non-interactive-C0NbQTcD.js} +2 -2
- package/dist/{non-interactive-8Eypq_h-.js.map → non-interactive-C0NbQTcD.js.map} +1 -1
- package/dist/{orchestrator-tools-DVXOV-kz.js → orchestrator-tools-KtXpYp6j.js} +3 -3
- package/dist/{orchestrator-tools-DVXOV-kz.js.map → orchestrator-tools-KtXpYp6j.js.map} +1 -1
- package/dist/{package-manager-CAD9Uklp.js → package-manager-L1RLE1ne.js} +2 -2
- package/dist/{package-manager-CAD9Uklp.js.map → package-manager-L1RLE1ne.js.map} +1 -1
- package/dist/{pi-C9iHv5uG.js → pi-BMs3MY7y.js} +11 -11
- package/dist/{pi-C9iHv5uG.js.map → pi-BMs3MY7y.js.map} +1 -1
- package/dist/{playground-C-9Q3ETa.js → playground-DZoNrDEM.js} +6 -6
- package/dist/{playground-C-9Q3ETa.js.map → playground-DZoNrDEM.js.map} +1 -1
- package/dist/{posthog-integration-Do997QON.js → posthog-integration-BnWgrvts.js} +14 -14
- package/dist/{posthog-integration-Do997QON.js.map → posthog-integration-BnWgrvts.js.map} +1 -1
- package/dist/{provisioning-DpqnGk3z.js → provisioning-DS8zDveH.js} +3 -3
- package/dist/{provisioning-DpqnGk3z.js.map → provisioning-DS8zDveH.js.map} +1 -1
- package/dist/{queue-tools-CTUgbOU8.js → queue-tools-rAN2wwDC.js} +2 -2
- package/dist/{queue-tools-CTUgbOU8.js.map → queue-tools-rAN2wwDC.js.map} +1 -1
- package/dist/{registry-DT58jEYr.js → registry-Zp3B2L4q.js} +4 -4
- package/dist/{registry-DT58jEYr.js.map → registry-Zp3B2L4q.js.map} +1 -1
- package/dist/{security-CTigdAWm.js → security-R8m9JSHq.js} +4 -4
- package/dist/{security-CTigdAWm.js.map → security-R8m9JSHq.js.map} +1 -1
- package/dist/{setup-utils-Cb5uACEO.js → setup-utils-BMy5Zj3Z.js} +7 -7
- package/dist/{setup-utils-Cb5uACEO.js.map → setup-utils-BMy5Zj3Z.js.map} +1 -1
- package/dist/{start-tui-Cwc-PFma.js → start-tui-CJ7i0pbr.js} +95 -17
- package/dist/start-tui-CJ7i0pbr.js.map +1 -0
- package/dist/{steps-DyEKYM4I.js → steps-CsvYRuTV.js} +7 -7
- package/dist/{steps-DyEKYM4I.js.map → steps-CsvYRuTV.js.map} +1 -1
- package/dist/{store-4sj-vWr5.js → store-CVZL9JJe.js} +4 -4
- package/dist/store-CVZL9JJe.js.map +1 -0
- package/dist/{subagent-D8_yDgCB.js → subagent-C1OOk1kh.js} +2 -2
- package/dist/{subagent-D8_yDgCB.js.map → subagent-C1OOk1kh.js.map} +1 -1
- package/dist/{task-D8Y8pkzd.js → task-BMaazWIr.js} +11 -11
- package/dist/{task-D8Y8pkzd.js.map → task-BMaazWIr.js.map} +1 -1
- package/dist/{task-stream-DQT3vjwS.js → task-stream-DlgLKdMC.js} +3 -3
- package/dist/{task-stream-DQT3vjwS.js.map → task-stream-DlgLKdMC.js.map} +1 -1
- package/dist/{tasks-D2WKssA5.js → tasks-BcsQlnuL.js} +2 -2
- package/dist/{tasks-D2WKssA5.js.map → tasks-BcsQlnuL.js.map} +1 -1
- package/dist/{telemetry-CYr4HgS2.js → telemetry-3Y8LxNVU.js} +3 -3
- package/dist/{telemetry-CYr4HgS2.js.map → telemetry-3Y8LxNVU.js.map} +1 -1
- package/dist/{terminal-1RfyHQC2.js → terminal-B4cCBtMj.js} +11 -11
- package/dist/{terminal-1RfyHQC2.js.map → terminal-B4cCBtMj.js.map} +1 -1
- package/dist/{tools-DQCUOQZX.js → tools-C07lR0s-.js} +6 -6
- package/dist/{tools-DQCUOQZX.js.map → tools-C07lR0s-.js.map} +1 -1
- package/dist/{wizard-abort-FuyIaI_0.js → wizard-abort-D1UxHeiE.js} +3 -3
- package/dist/{wizard-abort-FuyIaI_0.js.map → wizard-abort-D1UxHeiE.js.map} +1 -1
- package/dist/{wizard-abort-D_-v1zvS.js → wizard-abort-DoI_ZWM-.js} +1 -1
- package/dist/yara-hooks-ChkXWyzs.js +2 -0
- package/dist/{yara-hooks-DdYRRxfH.js → yara-hooks-D9PSjEqo.js} +3 -3
- package/dist/{yara-hooks-DdYRRxfH.js.map → yara-hooks-D9PSjEqo.js.map} +1 -1
- package/package.json +1 -1
- package/dist/agent-interface-B8roB2UP.js.map +0 -1
- package/dist/analytics-D7vUZgzf.js +0 -2
- package/dist/start-tui-Cwc-PFma.js.map +0 -1
- package/dist/store-4sj-vWr5.js.map +0 -1
- package/dist/yara-hooks-6gNnPFPo.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY, S as ANALYTICS_HOST_URL, St as RUN_SURFACE, r as debug, s as logToFile, w as ANALYTICS_TEAM_TAG } from "./debug-
|
|
1
|
+
import { C as ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY, S as ANALYTICS_HOST_URL, St as RUN_SURFACE, r as debug, s as logToFile, w as ANALYTICS_TEAM_TAG } from "./debug-BiU-S12q.js";
|
|
2
2
|
import { PostHog } from "posthog-node";
|
|
3
3
|
import { v4 } from "uuid";
|
|
4
4
|
//#region src/utils/ci-flag-overrides.ts
|
|
@@ -247,4 +247,4 @@ const analytics = new Analytics();
|
|
|
247
247
|
//#endregion
|
|
248
248
|
export { ciExcludedTaskTypes as a, sessionProperties as i, analytics as n, groupsFromUser as r, Analytics as t };
|
|
249
249
|
|
|
250
|
-
//# sourceMappingURL=analytics-
|
|
250
|
+
//# sourceMappingURL=analytics-B4dny8FA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics-k76OWsl0.js","names":["uuidv4"],"sources":["../src/utils/ci-flag-overrides.ts","../src/utils/analytics.ts"],"sourcesContent":["/**\n * CI-only feature-flag overrides.\n *\n * CI must route deterministically: a run that tests the orchestrator arm says\n * so explicitly instead of depending on a live feature flag someone can edit\n * mid-week. The override env var (see the allowlist in `env.ts`) is a JSON\n * object of flag key → value, merged over whatever PostHog returned.\n *\n * The override path exists only in CI builds (`pnpm build:ci`). Published\n * builds inline NODE_ENV as the literal \"production\", the guards collapse,\n * and tsdown strips the rest from the bundle — and the smoke test asserts the\n * env var names are physically absent from production output (which is also\n * why no comment in this file may spell them out), so this can never quietly\n * become a production surface.\n */\nimport { runtimeEnv } from '@env';\nimport { logToFile } from './debug';\n\nexport function applyCiFlagOverrides(\n flags: Record<string, string>,\n payloads: Record<string, unknown> = {},\n): { flags: Record<string, string>; payloads: Record<string, unknown> } {\n // Compared inline (not via env.ts's IS_PRODUCTION_BUILD) so tsdown replaces\n // it with a literal right here and the bundler can prove the rest of this\n // function unreachable in production builds. The smoke test enforces that.\n if (process.env.NODE_ENV === 'production') return { flags, payloads };\n\n const raw = runtimeEnv('WIZARD_CI_FLAG_OVERRIDES');\n if (!raw) return { flags, payloads };\n\n let overrides: Record<string, unknown>;\n try {\n overrides = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n // A malformed override is a CI misconfiguration. Fail the run loudly\n // rather than silently testing whatever the live flags happen to say.\n throw new Error(\n 'The CI flag-override env var is not valid JSON (expected {\"flag-key\": value, ...}).',\n );\n }\n\n const mergedFlags = { ...flags };\n const mergedPayloads = { ...payloads };\n for (const [key, value] of Object.entries(overrides)) {\n // An object/array override is a flag payload: the flag reads 'true' and\n // the value rides the payload channel, matching a payload-carrying flag.\n if (typeof value === 'object' && value !== null) {\n mergedFlags[key] = 'true';\n mergedPayloads[key] = value;\n } else {\n mergedFlags[key] = String(value);\n }\n }\n logToFile('[flags] CI overrides applied', overrides);\n return { flags: mergedFlags, payloads: mergedPayloads };\n}\n\n/**\n * Task types excluded from this run. The exclusion env var (see the allowlist\n * in `env.ts`) is a comma-separated list (e.g. `dashboard`), set by the CI\n * harness that owns the policy — the wizard and the served content stay\n * run-mode agnostic. CI-build only, same as the flag overrides: published\n * builds strip this path.\n */\nexport function ciExcludedTaskTypes(): readonly string[] {\n if (process.env.NODE_ENV === 'production') return [];\n\n const raw = runtimeEnv('WIZARD_CI_EXCLUDE_TASKS');\n if (!raw) return [];\n const types = raw\n .split(',')\n .map((t) => t.trim())\n .filter(Boolean);\n if (types.length > 0) logToFile('[flags] CI task exclusions', types);\n return types;\n}\n","import { PostHog } from 'posthog-node';\nimport {\n ANALYTICS_HOST_URL,\n ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY,\n ANALYTICS_TEAM_TAG,\n} from '@lib/constants';\nimport type { WizardSession } from '@lib/wizard-session';\nimport type { ApiUser } from '@lib/api';\nimport { v4 as uuidv4 } from 'uuid';\nimport { IS_PRODUCTION_BUILD, RUN_SURFACE } from '@env';\nimport { debug, logToFile } from './debug';\nimport { applyCiFlagOverrides } from './ci-flag-overrides';\n\n/**\n * Extract a standard property bag from the current session.\n * Used by store-level analytics and available for ad-hoc captures.\n */\nexport function sessionProperties(\n session: WizardSession,\n): Record<string, unknown> {\n return {\n integration: session.integration,\n detected_framework: session.detectedFrameworkLabel,\n typescript: session.typescript,\n project_id: session.credentials?.projectId,\n discovered_features: session.discoveredFeatures,\n additional_features: session.additionalFeatureQueue,\n run_phase: session.runPhase,\n };\n}\n\nexport function groupsFromUser(\n user: ApiUser | null,\n host: string,\n): Record<string, string> {\n const groups: Record<string, string> = { instance: host };\n if (!user) return groups;\n\n const organizationId = user.organization?.id;\n if (organizationId) groups.organization = organizationId;\n\n const customerId = user.organization?.customer_id;\n if (customerId) groups.customer = customerId;\n\n const projectUuid = user.team?.uuid;\n if (projectUuid) groups.project = projectUuid;\n\n return groups;\n}\n\nexport class Analytics {\n private client: PostHog;\n private tags: Record<string, string | boolean | number | null | undefined> =\n {};\n private distinctId?: string;\n private anonymousId: string;\n private _runId: string;\n private sessionId: string | null = null;\n private appName = 'wizard';\n private activeFlags: Record<string, string> | null = null;\n private activeFlagPayloads: Record<string, unknown> = {};\n private groups: Record<string, string> = {};\n private personProperties: Record<string, string> = {};\n private terminalEventSent = false;\n\n constructor() {\n this.client = new PostHog(ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY, {\n host: ANALYTICS_HOST_URL,\n flushAt: 1,\n flushInterval: 0,\n enableExceptionAutocapture: true,\n before_send: (event) => {\n if (!event) return event;\n if (Object.keys(this.groups).length > 0) {\n event.groups = { ...this.groups, ...event.groups };\n }\n // Autocaptured exceptions arrive with a random uuid and\n // `$process_person_profile: false` — reattach the run's identity\n // and tags so they land on the same person as everything else.\n if (event.event === '$exception') {\n event.distinctId = this.distinctId ?? this.anonymousId;\n const { $process_person_profile, ...properties } =\n event.properties ?? {};\n void $process_person_profile;\n event.properties = { ...this.tags, ...properties };\n }\n return event;\n },\n });\n\n this.tags = { $app_name: this.appName };\n // Tag every run with its build type so prod / dev / ci / headless segment\n // cleanly in analytics. tsdown inlines IS_PRODUCTION_BUILD to `true` in\n // published builds and `false` for dev/tsx/test runs. Non-interactive runs\n // upgrade this in runWizardCI: dev `--ci` runs to 'ci', published headless\n // runs to 'headless'.\n this.tags.build = IS_PRODUCTION_BUILD ? 'prod' : 'dev';\n\n this.tags.run_surface = RUN_SURFACE;\n\n this.anonymousId = uuidv4();\n\n // One id per process = one id per wizard run, registered in the tag bag\n // so it rides on every capture, exception, and autocaptured exception\n // (all of which merge `this.tags`). Lets you separate two runs by the\n // same logged-in user, who otherwise share one distinct id. Distinct\n // from `anonymousId`, the pre-login *person* id that gets aliased onto\n // the real user at login. `$session_id` is intentionally not set here —\n // it stays null until OAuth completes (see identifyUser).\n this._runId = uuidv4();\n this.tags.run_id = this._runId;\n\n this.distinctId = undefined;\n }\n\n /** Per-process run id, tagged on every event and gateway trace. */\n get runId(): string {\n return this._runId;\n }\n\n /** Build type for this run ('prod' | 'dev' | 'ci' | 'headless') — the same value tagged on every analytics event. */\n get build(): string {\n return String(this.tags.build ?? 'dev');\n }\n\n /**\n * Associate the run with the logged-in user, once per id. Identifies them\n * (email, name) and records those person properties so events carry them and\n * feature flags can target the individual user — without the email here the\n * wizard only sends `$app_name`, so email-targeted flags never match. Opens\n * the analytics session on first login, then aliases the run's anonymous id\n * onto the identified person so pre-login events merge in.\n */\n identifyUser(user: ApiUser) {\n const distinctId = user.distinct_id;\n if (this.distinctId === distinctId || distinctId === this.anonymousId) {\n return;\n }\n this.distinctId = distinctId;\n // Open the analytics session on first login. Null until here, so\n // pre-OAuth events carry only `run_id`; from now on every event also\n // carries `$session_id` and PostHog groups the authenticated run into a\n // native Session. Stored in the tag bag so it rides on every subsequent\n // capture and exception.\n if (!this.sessionId) {\n this.sessionId = uuidv4();\n this.tags.$session_id = this.sessionId;\n }\n const props: Record<string, string> = {};\n if (user.email) props.email = user.email;\n const name = [user.first_name, user.last_name]\n .filter(Boolean)\n .join(' ')\n .trim();\n if (name) props.name = name;\n this.personProperties = props;\n this.client.identify({ distinctId, properties: { $set: props } });\n this.client.alias({\n distinctId,\n alias: this.anonymousId,\n });\n // The flag snapshot is per identity. Anything evaluated before login (the\n // intro screen reads the tools-menu flag) was anonymous — drop it so the\n // next read re-evaluates as this user.\n this.activeFlags = null;\n this.activeFlagPayloads = {};\n }\n\n /** Person properties sent with flag evaluation: app name plus the user's. */\n private flagPersonProperties(): Record<string, string> {\n return { $app_name: this.appName, ...this.personProperties };\n }\n\n setTag(key: string, value: string | boolean | number | null | undefined) {\n this.tags[key] = value;\n }\n\n setGroups(groups: Record<string, string>) {\n this.groups = groups;\n }\n\n captureException(error: Error, properties: Record<string, unknown> = {}) {\n this.client.captureException(error, this.distinctId ?? this.anonymousId, {\n team: ANALYTICS_TEAM_TAG,\n ...this.tags,\n ...properties,\n });\n }\n\n capture(eventName: string, properties?: Record<string, unknown>) {\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: eventName,\n properties: {\n ...this.tags,\n ...properties,\n },\n });\n }\n\n /**\n * Capture a wizard-specific event. Automatically prepends \"wizard: \" to the event name.\n * All new wizard analytics should use this method instead of capture() directly.\n */\n wizardCapture(eventName: string, properties?: Record<string, unknown>): void {\n this.capture(`wizard: ${eventName}`, properties);\n }\n\n /**\n * Flush pending events without firing the \"setup wizard finished\" terminal\n * event. Use this from CLI error paths that exit before any wizard run\n * starts — `shutdown()` would inflate the run count with a \"finished\" event\n * for a parse error that never actually ran the wizard.\n */\n async flush(): Promise<void> {\n await this.client.shutdown();\n }\n\n async getFeatureFlag(flagKey: string): Promise<string | boolean | undefined> {\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n return await this.client.getFeatureFlag(flagKey, distinctId, {\n sendFeatureFlagEvents: true,\n personProperties: this.flagPersonProperties(),\n });\n } catch (error) {\n debug('Failed to get feature flag:', flagKey, error);\n return undefined;\n }\n }\n\n /**\n * Evaluate all feature flags for the current user at the start of a run.\n * Result is cached; subsequent calls in the same run return the same map.\n * Returns flag key -> string value (booleans become 'true'/'false').\n */\n async getAllFlagsForWizard(): Promise<Record<string, string>> {\n if (this.activeFlags !== null) {\n return this.activeFlags;\n }\n const out: Record<string, string> = {};\n let payloads: Record<string, unknown> = {};\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n logToFile('[flags] evaluating as', {\n distinctId,\n identified: this.distinctId !== undefined,\n personProperties: this.flagPersonProperties(),\n });\n const result = await this.client.getAllFlagsAndPayloads(distinctId, {\n personProperties: this.flagPersonProperties(),\n });\n const flags = result.featureFlags ?? {};\n for (const [key, value] of Object.entries(flags)) {\n if (value === undefined) continue;\n out[key] = typeof value === 'boolean' ? String(value) : String(value);\n }\n payloads = result.featureFlagPayloads ?? {};\n } catch (error) {\n debug('Failed to get all feature flags:', error);\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'get_all_flags' },\n );\n }\n // Outside the fetch guard on purpose: a malformed CI override must fail\n // the run loudly, and a valid one applies even when the fetch failed —\n // CI routing stays deterministic either way.\n const merged = applyCiFlagOverrides(out, payloads);\n this.activeFlags = merged.flags;\n this.activeFlagPayloads = merged.payloads;\n logToFile('[flags] evaluated', this.activeFlags);\n return this.activeFlags;\n }\n\n /** Flag payloads from the same snapshot; empty until the flags are fetched. */\n getWizardFlagPayloads(): Record<string, unknown> {\n return this.activeFlagPayloads;\n }\n\n async shutdown(status: 'success' | 'error' | 'cancelled') {\n if (Object.keys(this.tags).length === 0) {\n return;\n }\n\n // First status wins. The interrupt fallback in start-tui fires\n // shutdown('cancelled') on every TUI teardown; without this guard a run\n // that already reported 'success' would emit a second, contradicting\n // terminal event when the user dismisses the outro.\n if (this.terminalEventSent) {\n return;\n }\n this.terminalEventSent = true;\n\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: 'setup wizard finished',\n properties: {\n // Flat for filtering; the nested `tags` snapshot stays for back-compat.\n ...this.tags,\n run_id: this._runId,\n ...(this.sessionId ? { $session_id: this.sessionId } : {}),\n status,\n tags: this.tags,\n },\n });\n\n await this.client.shutdown();\n }\n}\n\nexport const analytics = new Analytics();\n"],"mappings":";;;;AAkBA,SAAgB,qBACd,OACA,WAAoC,EAAE,EACgC;AAI3B,QAAO;EAAE;EAAO;EAAU;;;;;;;;;AAuCvE,SAAgB,sBAAyC;AACZ,QAAO,EAAE;;;;;;;;AChDtD,SAAgB,kBACd,SACyB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AAK,YAAY;AAChD,SAAO,KAAK;;;CAId,wBAAiD;AAC/C,SAAO,KAAK;;CAGd,MAAM,SAAS,QAA2C;AACxD,MAAI,OAAO,KAAK,KAAK,KAAK,CAAC,WAAW,EACpC;AAOF,MAAI,KAAK,kBACP;AAEF,OAAK,oBAAoB;AAEzB,OAAK,OAAO,QAAQ;GAClB,YAAY,KAAK,cAAc,KAAK;GACpC,OAAO;GACP,YAAY;IAEV,GAAG,KAAK;IACR,QAAQ,KAAK;IACb,GAAI,KAAK,YAAY,EAAE,aAAa,KAAK,WAAW,GAAG,EAAE;IACzD;IACA,MAAM,KAAK;IACZ;GACF,CAAC;AAEF,QAAM,KAAK,OAAO,UAAU;;;AAIhC,MAAa,YAAY,IAAI,WAAW"}
|
|
1
|
+
{"version":3,"file":"analytics-B4dny8FA.js","names":["uuidv4"],"sources":["../src/utils/ci-flag-overrides.ts","../src/utils/analytics.ts"],"sourcesContent":["/**\n * CI-only feature-flag overrides.\n *\n * CI must route deterministically: a run that tests the orchestrator arm says\n * so explicitly instead of depending on a live feature flag someone can edit\n * mid-week. The override env var (see the allowlist in `env.ts`) is a JSON\n * object of flag key → value, merged over whatever PostHog returned.\n *\n * The override path exists only in CI builds (`pnpm build:ci`). Published\n * builds inline NODE_ENV as the literal \"production\", the guards collapse,\n * and tsdown strips the rest from the bundle — and the smoke test asserts the\n * env var names are physically absent from production output (which is also\n * why no comment in this file may spell them out), so this can never quietly\n * become a production surface.\n */\nimport { runtimeEnv } from '@env';\nimport { logToFile } from './debug';\n\nexport function applyCiFlagOverrides(\n flags: Record<string, string>,\n payloads: Record<string, unknown> = {},\n): { flags: Record<string, string>; payloads: Record<string, unknown> } {\n // Compared inline (not via env.ts's IS_PRODUCTION_BUILD) so tsdown replaces\n // it with a literal right here and the bundler can prove the rest of this\n // function unreachable in production builds. The smoke test enforces that.\n if (process.env.NODE_ENV === 'production') return { flags, payloads };\n\n const raw = runtimeEnv('WIZARD_CI_FLAG_OVERRIDES');\n if (!raw) return { flags, payloads };\n\n let overrides: Record<string, unknown>;\n try {\n overrides = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n // A malformed override is a CI misconfiguration. Fail the run loudly\n // rather than silently testing whatever the live flags happen to say.\n throw new Error(\n 'The CI flag-override env var is not valid JSON (expected {\"flag-key\": value, ...}).',\n );\n }\n\n const mergedFlags = { ...flags };\n const mergedPayloads = { ...payloads };\n for (const [key, value] of Object.entries(overrides)) {\n // An object/array override is a flag payload: the flag reads 'true' and\n // the value rides the payload channel, matching a payload-carrying flag.\n if (typeof value === 'object' && value !== null) {\n mergedFlags[key] = 'true';\n mergedPayloads[key] = value;\n } else {\n mergedFlags[key] = String(value);\n }\n }\n logToFile('[flags] CI overrides applied', overrides);\n return { flags: mergedFlags, payloads: mergedPayloads };\n}\n\n/**\n * Task types excluded from this run. The exclusion env var (see the allowlist\n * in `env.ts`) is a comma-separated list (e.g. `dashboard`), set by the CI\n * harness that owns the policy — the wizard and the served content stay\n * run-mode agnostic. CI-build only, same as the flag overrides: published\n * builds strip this path.\n */\nexport function ciExcludedTaskTypes(): readonly string[] {\n if (process.env.NODE_ENV === 'production') return [];\n\n const raw = runtimeEnv('WIZARD_CI_EXCLUDE_TASKS');\n if (!raw) return [];\n const types = raw\n .split(',')\n .map((t) => t.trim())\n .filter(Boolean);\n if (types.length > 0) logToFile('[flags] CI task exclusions', types);\n return types;\n}\n","import { PostHog } from 'posthog-node';\nimport {\n ANALYTICS_HOST_URL,\n ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY,\n ANALYTICS_TEAM_TAG,\n} from '@lib/constants';\nimport type { WizardSession } from '@lib/wizard-session';\nimport type { ApiUser } from '@lib/api';\nimport { v4 as uuidv4 } from 'uuid';\nimport { IS_PRODUCTION_BUILD, RUN_SURFACE } from '@env';\nimport { debug, logToFile } from './debug';\nimport { applyCiFlagOverrides } from './ci-flag-overrides';\n\n/**\n * Extract a standard property bag from the current session.\n * Used by store-level analytics and available for ad-hoc captures.\n */\nexport function sessionProperties(\n session: WizardSession,\n): Record<string, unknown> {\n return {\n integration: session.integration,\n detected_framework: session.detectedFrameworkLabel,\n typescript: session.typescript,\n project_id: session.credentials?.projectId,\n discovered_features: session.discoveredFeatures,\n additional_features: session.additionalFeatureQueue,\n run_phase: session.runPhase,\n };\n}\n\nexport function groupsFromUser(\n user: ApiUser | null,\n host: string,\n): Record<string, string> {\n const groups: Record<string, string> = { instance: host };\n if (!user) return groups;\n\n const organizationId = user.organization?.id;\n if (organizationId) groups.organization = organizationId;\n\n const customerId = user.organization?.customer_id;\n if (customerId) groups.customer = customerId;\n\n const projectUuid = user.team?.uuid;\n if (projectUuid) groups.project = projectUuid;\n\n return groups;\n}\n\nexport class Analytics {\n private client: PostHog;\n private tags: Record<string, string | boolean | number | null | undefined> =\n {};\n private distinctId?: string;\n private anonymousId: string;\n private _runId: string;\n private sessionId: string | null = null;\n private appName = 'wizard';\n private activeFlags: Record<string, string> | null = null;\n private activeFlagPayloads: Record<string, unknown> = {};\n private groups: Record<string, string> = {};\n private personProperties: Record<string, string> = {};\n private terminalEventSent = false;\n\n constructor() {\n this.client = new PostHog(ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY, {\n host: ANALYTICS_HOST_URL,\n flushAt: 1,\n flushInterval: 0,\n enableExceptionAutocapture: true,\n before_send: (event) => {\n if (!event) return event;\n if (Object.keys(this.groups).length > 0) {\n event.groups = { ...this.groups, ...event.groups };\n }\n // Autocaptured exceptions arrive with a random uuid and\n // `$process_person_profile: false` — reattach the run's identity\n // and tags so they land on the same person as everything else.\n if (event.event === '$exception') {\n event.distinctId = this.distinctId ?? this.anonymousId;\n const { $process_person_profile, ...properties } =\n event.properties ?? {};\n void $process_person_profile;\n event.properties = { ...this.tags, ...properties };\n }\n return event;\n },\n });\n\n this.tags = { $app_name: this.appName };\n // Tag every run with its build type so prod / dev / ci / headless segment\n // cleanly in analytics. tsdown inlines IS_PRODUCTION_BUILD to `true` in\n // published builds and `false` for dev/tsx/test runs. Non-interactive runs\n // upgrade this in runWizardCI: dev `--ci` runs to 'ci', published headless\n // runs to 'headless'.\n this.tags.build = IS_PRODUCTION_BUILD ? 'prod' : 'dev';\n\n this.tags.run_surface = RUN_SURFACE;\n\n this.anonymousId = uuidv4();\n\n // One id per process = one id per wizard run, registered in the tag bag\n // so it rides on every capture, exception, and autocaptured exception\n // (all of which merge `this.tags`). Lets you separate two runs by the\n // same logged-in user, who otherwise share one distinct id. Distinct\n // from `anonymousId`, the pre-login *person* id that gets aliased onto\n // the real user at login. `$session_id` is intentionally not set here —\n // it stays null until OAuth completes (see identifyUser).\n this._runId = uuidv4();\n this.tags.run_id = this._runId;\n\n this.distinctId = undefined;\n }\n\n /** Per-process run id, tagged on every event and gateway trace. */\n get runId(): string {\n return this._runId;\n }\n\n /** Build type for this run ('prod' | 'dev' | 'ci' | 'headless') — the same value tagged on every analytics event. */\n get build(): string {\n return String(this.tags.build ?? 'dev');\n }\n\n /**\n * Associate the run with the logged-in user, once per id. Identifies them\n * (email, name) and records those person properties so events carry them and\n * feature flags can target the individual user — without the email here the\n * wizard only sends `$app_name`, so email-targeted flags never match. Opens\n * the analytics session on first login, then aliases the run's anonymous id\n * onto the identified person so pre-login events merge in.\n */\n identifyUser(user: ApiUser) {\n const distinctId = user.distinct_id;\n if (this.distinctId === distinctId || distinctId === this.anonymousId) {\n return;\n }\n this.distinctId = distinctId;\n // Open the analytics session on first login. Null until here, so\n // pre-OAuth events carry only `run_id`; from now on every event also\n // carries `$session_id` and PostHog groups the authenticated run into a\n // native Session. Stored in the tag bag so it rides on every subsequent\n // capture and exception.\n if (!this.sessionId) {\n this.sessionId = uuidv4();\n this.tags.$session_id = this.sessionId;\n }\n const props: Record<string, string> = {};\n if (user.email) props.email = user.email;\n const name = [user.first_name, user.last_name]\n .filter(Boolean)\n .join(' ')\n .trim();\n if (name) props.name = name;\n this.personProperties = props;\n this.client.identify({ distinctId, properties: { $set: props } });\n this.client.alias({\n distinctId,\n alias: this.anonymousId,\n });\n // The flag snapshot is per identity. Anything evaluated before login (the\n // intro screen reads the tools-menu flag) was anonymous — drop it so the\n // next read re-evaluates as this user.\n this.activeFlags = null;\n this.activeFlagPayloads = {};\n }\n\n /** Person properties sent with flag evaluation: app name plus the user's. */\n private flagPersonProperties(): Record<string, string> {\n return { $app_name: this.appName, ...this.personProperties };\n }\n\n setTag(key: string, value: string | boolean | number | null | undefined) {\n this.tags[key] = value;\n }\n\n setGroups(groups: Record<string, string>) {\n this.groups = groups;\n }\n\n captureException(error: Error, properties: Record<string, unknown> = {}) {\n this.client.captureException(error, this.distinctId ?? this.anonymousId, {\n team: ANALYTICS_TEAM_TAG,\n ...this.tags,\n ...properties,\n });\n }\n\n capture(eventName: string, properties?: Record<string, unknown>) {\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: eventName,\n properties: {\n ...this.tags,\n ...properties,\n },\n });\n }\n\n /**\n * Capture a wizard-specific event. Automatically prepends \"wizard: \" to the event name.\n * All new wizard analytics should use this method instead of capture() directly.\n */\n wizardCapture(eventName: string, properties?: Record<string, unknown>): void {\n this.capture(`wizard: ${eventName}`, properties);\n }\n\n /**\n * Flush pending events without firing the \"setup wizard finished\" terminal\n * event. Use this from CLI error paths that exit before any wizard run\n * starts — `shutdown()` would inflate the run count with a \"finished\" event\n * for a parse error that never actually ran the wizard.\n */\n async flush(): Promise<void> {\n await this.client.shutdown();\n }\n\n async getFeatureFlag(flagKey: string): Promise<string | boolean | undefined> {\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n return await this.client.getFeatureFlag(flagKey, distinctId, {\n sendFeatureFlagEvents: true,\n personProperties: this.flagPersonProperties(),\n });\n } catch (error) {\n debug('Failed to get feature flag:', flagKey, error);\n return undefined;\n }\n }\n\n /**\n * Evaluate all feature flags for the current user at the start of a run.\n * Result is cached; subsequent calls in the same run return the same map.\n * Returns flag key -> string value (booleans become 'true'/'false').\n */\n async getAllFlagsForWizard(): Promise<Record<string, string>> {\n if (this.activeFlags !== null) {\n return this.activeFlags;\n }\n const out: Record<string, string> = {};\n let payloads: Record<string, unknown> = {};\n try {\n const distinctId = this.distinctId ?? this.anonymousId;\n logToFile('[flags] evaluating as', {\n distinctId,\n identified: this.distinctId !== undefined,\n personProperties: this.flagPersonProperties(),\n });\n const result = await this.client.getAllFlagsAndPayloads(distinctId, {\n personProperties: this.flagPersonProperties(),\n });\n const flags = result.featureFlags ?? {};\n for (const [key, value] of Object.entries(flags)) {\n if (value === undefined) continue;\n out[key] = typeof value === 'boolean' ? String(value) : String(value);\n }\n payloads = result.featureFlagPayloads ?? {};\n } catch (error) {\n debug('Failed to get all feature flags:', error);\n this.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'get_all_flags' },\n );\n }\n // Outside the fetch guard on purpose: a malformed CI override must fail\n // the run loudly, and a valid one applies even when the fetch failed —\n // CI routing stays deterministic either way.\n const merged = applyCiFlagOverrides(out, payloads);\n this.activeFlags = merged.flags;\n this.activeFlagPayloads = merged.payloads;\n logToFile('[flags] evaluated', this.activeFlags);\n return this.activeFlags;\n }\n\n /** Flag payloads from the same snapshot; empty until the flags are fetched. */\n getWizardFlagPayloads(): Record<string, unknown> {\n return this.activeFlagPayloads;\n }\n\n async shutdown(status: 'success' | 'error' | 'cancelled') {\n if (Object.keys(this.tags).length === 0) {\n return;\n }\n\n // First status wins. The interrupt fallback in start-tui fires\n // shutdown('cancelled') on every TUI teardown; without this guard a run\n // that already reported 'success' would emit a second, contradicting\n // terminal event when the user dismisses the outro.\n if (this.terminalEventSent) {\n return;\n }\n this.terminalEventSent = true;\n\n this.client.capture({\n distinctId: this.distinctId ?? this.anonymousId,\n event: 'setup wizard finished',\n properties: {\n // Flat for filtering; the nested `tags` snapshot stays for back-compat.\n ...this.tags,\n run_id: this._runId,\n ...(this.sessionId ? { $session_id: this.sessionId } : {}),\n status,\n tags: this.tags,\n },\n });\n\n await this.client.shutdown();\n }\n}\n\nexport const analytics = new Analytics();\n"],"mappings":";;;;AA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MAAM,CAAC,EACzD,EAAE,MAAM,iBAAiB,CAC1B;;EAKH,MAAM,SAAS,qBAAqB,KAAK,SAAS;AAClD,OAAK,cAAc,OAAO;AAC1B,OAAK,qBAAqB,OAAO;AACjC,YAAU,qBAAqB,KAAK,YAAY;AAChD,SAAO,KAAK;;;CAId,wBAAiD;AAC/C,SAAO,KAAK;;CAGd,MAAM,SAAS,QAA2C;AACxD,MAAI,OAAO,KAAK,KAAK,KAAK,CAAC,WAAW,EACpC;AAOF,MAAI,KAAK,kBACP;AAEF,OAAK,oBAAoB;AAEzB,OAAK,OAAO,QAAQ;GAClB,YAAY,KAAK,cAAc,KAAK;GACpC,OAAO;GACP,YAAY;IAEV,GAAG,KAAK;IACR,QAAQ,KAAK;IACb,GAAI,KAAK,YAAY,EAAE,aAAa,KAAK,WAAW,GAAG,EAAE;IACzD;IACA,MAAM,KAAK;IACZ;GACF,CAAC;AAEF,QAAM,KAAK,OAAO,UAAU;;;AAIhC,MAAa,YAAY,IAAI,WAAW"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
|
|
2
|
-
import { gt as WIZARD_USER_AGENT } from "./debug-
|
|
3
|
-
import { n as analytics } from "./analytics-
|
|
2
|
+
import { gt as WIZARD_USER_AGENT } from "./debug-BiU-S12q.js";
|
|
3
|
+
import { n as analytics } from "./analytics-B4dny8FA.js";
|
|
4
4
|
import axios from "axios";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
//#region src/lib/api.ts
|
|
@@ -170,4 +170,4 @@ function handleApiError(error, operation) {
|
|
|
170
170
|
//#endregion
|
|
171
171
|
export { fetchUserData as a, fetchSlackConnected as i, api_exports as n, handleApiError as o, fetchProjectData as r, ApiError as t };
|
|
172
172
|
|
|
173
|
-
//# sourceMappingURL=api-
|
|
173
|
+
//# sourceMappingURL=api-CdPvsnUm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-CmIWcW-U.js","names":[],"sources":["../src/lib/api.ts"],"sourcesContent":["import axios, { AxiosError } from 'axios';\nimport { z } from 'zod';\nimport { analytics } from '@utils/analytics';\nimport { WIZARD_USER_AGENT } from './constants';\n\n/**\n * User payload from `/api/users/@me/`. Schema typed for the fields the\n * wizard actually reads + passthrough on everything else so the full\n * upstream response rides through to the session for downstream features\n * (account-aware copy, plan-gated flows, org/team metadata, etc.).\n *\n * Top-level uses `.passthrough()` so unknown fields aren't stripped;\n * the few nested objects we care about (team, organization,\n * organizations[]) do the same so their additional fields survive too.\n *\n * Keep `distinct_id` required — analytics depends on it. Everything\n * else added here is nullish so partial responses don't fail parsing.\n */\nexport const ApiUserSchema = z\n .object({\n // Identifiers\n distinct_id: z.string(),\n uuid: z.string().nullish(),\n id: z.number().nullish(),\n\n // Profile\n email: z.string().nullish(),\n first_name: z.string().nullish(),\n last_name: z.string().nullish(),\n date_joined: z.string().nullish(),\n is_email_verified: z.boolean().nullish(),\n is_2fa_enabled: z.boolean().nullish(),\n is_staff: z.boolean().nullish(),\n\n // Preferences\n theme_mode: z.string().nullish(),\n toolbar_mode: z.string().nullish(),\n hide_mcp_hints: z.boolean().nullish(),\n\n // Optional / nullable on the backend — pre-onboarding signup paths\n // return null and older accounts may not have it set. Treat as a\n // hint, never a guarantee.\n role_at_organization: z.string().nullish(),\n\n // Current team + organization (objects from the API, kept typed on\n // the fields the wizard uses; passthrough preserves the rest).\n team: z\n .object({\n id: z.number(),\n uuid: z.string().nullish(),\n organization: z.string().uuid(),\n api_token: z.string().nullish(),\n project_id: z.number().nullish(),\n name: z.string().nullish(),\n timezone: z.string().nullish(),\n })\n .passthrough(),\n organization: z\n .object({\n id: z.string().uuid(),\n name: z.string().nullish(),\n slug: z.string().nullish(),\n membership_level: z.number().nullish(),\n customer_id: z.string().nullish(),\n // Org-level AI consent gate. Signals drops all findings while\n // this is not true. Null on older orgs (pre-2026-05 default\n // flip) — treat null as \"unknown\", not \"off\".\n is_ai_data_processing_approved: z.boolean().nullish(),\n })\n .passthrough(),\n organizations: z.array(\n z\n .object({\n id: z.string().uuid(),\n name: z.string().nullish(),\n membership_level: z.number().nullish(),\n })\n .passthrough(),\n ),\n })\n .passthrough();\n\n/**\n * Single activity log entry the wizard cares about. The PostHog endpoint\n * returns much more — schema kept minimal so changes upstream don't break us.\n *\n * @unused — no current caller after the Phase 6 streaming-agent pivot\n * dropped activity_log polling. Deliberately retained: this is a thin,\n * well-typed wrapper around a stable PostHog endpoint, and we're likely\n * to want it again for a future feature (e.g. \"what changed in your\n * project recently\"). Re-deriving the schema is more work than letting\n * it sit dormant.\n */\nexport const ActivityLogEntrySchema = z\n .object({\n scope: z.string().nullish(),\n activity: z.string().nullish(),\n created_at: z.string().nullish(),\n })\n .passthrough();\n\n/** @unused — see ActivityLogEntrySchema. */\nexport const ActivityLogResponseSchema = z.object({\n results: z.array(ActivityLogEntrySchema),\n});\n\n/** @unused — see ActivityLogEntrySchema. */\nexport type ActivityLogEntry = z.infer<typeof ActivityLogEntrySchema>;\n\nexport const ApiProjectSchema = z.object({\n id: z.number(),\n uuid: z.string().uuid(),\n organization: z.string().uuid(),\n api_token: z.string(),\n name: z.string(),\n // Product opt-ins (TeamSerializer-compat fields on /api/projects/:id).\n // Project-level truth for \"is this product enabled\" — a product can be\n // instrumented from another repo or the snippet, so these settings\n // override repo-local evidence. Null/absent = unknown. Only the\n // opt-ins a signals decision consumes: replay + exception autocapture\n // feed signal-source choices; surveys feeds the surveys-scout tuning.\n session_recording_opt_in: z.boolean().nullish(),\n autocapture_exceptions_opt_in: z.boolean().nullish(),\n surveys_opt_in: z.boolean().nullish(),\n});\n\nexport type ApiUser = z.infer<typeof ApiUserSchema>;\nexport type ApiProject = z.infer<typeof ApiProjectSchema>;\n\nexport class ApiError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly endpoint?: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n\nexport async function fetchUserData(\n accessToken: string,\n baseUrl: string,\n): Promise<ApiUser> {\n try {\n const response = await axios.get(`${baseUrl}/api/users/@me/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n });\n\n return ApiUserSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch user data');\n analytics.captureException(apiError, {\n endpoint: '/api/users/@me/',\n baseUrl,\n });\n throw apiError;\n }\n}\n\n/**\n * Best-effort fetch of recent activity log entries. Returns [] on any error\n * so callers can treat absence of results as \"haven't detected anything yet\"\n * rather than a hard failure.\n *\n * @unused — no current caller after the Phase 6 streaming-agent pivot\n * dropped activity_log polling from McpSuggestedPromptsScreen.\n * Deliberately retained for future features that want a soft signal of\n * recent project changes (e.g. dashboards, audit summaries). See the\n * ActivityLogEntrySchema doc comment for the keep-vs-delete rationale.\n */\nexport async function fetchRecentActivity(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n since: Date,\n): Promise<ActivityLogEntry[]> {\n try {\n const response = await axios.get(\n `${baseUrl}/api/projects/${projectId}/activity_log/`,\n {\n params: { limit: 10 },\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n // Short timeout — best-effort probe, not a critical path.\n timeout: 4000,\n },\n );\n const parsed = ActivityLogResponseSchema.safeParse(response.data);\n if (!parsed.success) return [];\n const sinceMs = since.getTime();\n return parsed.data.results.filter((entry) => {\n if (!entry.created_at) return false;\n const t = Date.parse(entry.created_at);\n return Number.isFinite(t) && t >= sinceMs;\n });\n } catch {\n return [];\n }\n}\n\nexport async function fetchProjectData(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n): Promise<ApiProject> {\n try {\n const response = await axios.get(`${baseUrl}/api/projects/${projectId}/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n });\n\n return ApiProjectSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch project data');\n analytics.captureException(apiError, {\n endpoint: `/api/projects/${projectId}/`,\n baseUrl,\n projectId,\n });\n throw apiError;\n }\n}\n\n/** Minimal shape of `/api/projects/:id/integrations/` — we only read `kind`. */\nconst IntegrationsResponseSchema = z.object({\n results: z.array(z.object({ kind: z.string().nullish() }).passthrough()),\n});\n\n/**\n * Check whether the project already has a Slack integration connected.\n * Requires the `integration:read` scope. Throws on failure — callers\n * (including the SlackConnectScreen poll) decide how to degrade and\n * are responsible for capturing the error exactly once.\n */\nexport async function fetchSlackConnected(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n signal?: AbortSignal,\n): Promise<boolean> {\n const response = await axios.get(\n `${baseUrl}/api/projects/${projectId}/integrations/`,\n {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n signal,\n },\n );\n const parsed = IntegrationsResponseSchema.safeParse(response.data);\n if (!parsed.success) return false;\n return parsed.data.results.some((i) => i.kind === 'slack');\n}\n\nexport function handleApiError(error: unknown, operation: string): ApiError {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<{ detail?: string }>;\n const status = axiosError.response?.status;\n const detail = axiosError.response?.data?.detail;\n const endpoint = axiosError.config?.url;\n\n if (status === 401) {\n return new ApiError(\n `Authentication failed while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 403) {\n return new ApiError(\n `Access denied while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 404) {\n return new ApiError(\n `Resource not found while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n const message = detail || `Failed to ${operation}`;\n return new ApiError(message, status, endpoint);\n }\n\n if (error instanceof z.ZodError) {\n return new ApiError(`Invalid response format while trying to ${operation}`);\n }\n\n return new ApiError(\n `Unexpected error while trying to ${operation}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,gBAAgB,EAC1B,OAAO;CAEN,aAAa,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|
|
1
|
+
{"version":3,"file":"api-CdPvsnUm.js","names":[],"sources":["../src/lib/api.ts"],"sourcesContent":["import axios, { AxiosError } from 'axios';\nimport { z } from 'zod';\nimport { analytics } from '@utils/analytics';\nimport { WIZARD_USER_AGENT } from './constants';\n\n/**\n * User payload from `/api/users/@me/`. Schema typed for the fields the\n * wizard actually reads + passthrough on everything else so the full\n * upstream response rides through to the session for downstream features\n * (account-aware copy, plan-gated flows, org/team metadata, etc.).\n *\n * Top-level uses `.passthrough()` so unknown fields aren't stripped;\n * the few nested objects we care about (team, organization,\n * organizations[]) do the same so their additional fields survive too.\n *\n * Keep `distinct_id` required — analytics depends on it. Everything\n * else added here is nullish so partial responses don't fail parsing.\n */\nexport const ApiUserSchema = z\n .object({\n // Identifiers\n distinct_id: z.string(),\n uuid: z.string().nullish(),\n id: z.number().nullish(),\n\n // Profile\n email: z.string().nullish(),\n first_name: z.string().nullish(),\n last_name: z.string().nullish(),\n date_joined: z.string().nullish(),\n is_email_verified: z.boolean().nullish(),\n is_2fa_enabled: z.boolean().nullish(),\n is_staff: z.boolean().nullish(),\n\n // Preferences\n theme_mode: z.string().nullish(),\n toolbar_mode: z.string().nullish(),\n hide_mcp_hints: z.boolean().nullish(),\n\n // Optional / nullable on the backend — pre-onboarding signup paths\n // return null and older accounts may not have it set. Treat as a\n // hint, never a guarantee.\n role_at_organization: z.string().nullish(),\n\n // Current team + organization (objects from the API, kept typed on\n // the fields the wizard uses; passthrough preserves the rest).\n team: z\n .object({\n id: z.number(),\n uuid: z.string().nullish(),\n organization: z.string().uuid(),\n api_token: z.string().nullish(),\n project_id: z.number().nullish(),\n name: z.string().nullish(),\n timezone: z.string().nullish(),\n })\n .passthrough(),\n organization: z\n .object({\n id: z.string().uuid(),\n name: z.string().nullish(),\n slug: z.string().nullish(),\n membership_level: z.number().nullish(),\n customer_id: z.string().nullish(),\n // Org-level AI consent gate. Signals drops all findings while\n // this is not true. Null on older orgs (pre-2026-05 default\n // flip) — treat null as \"unknown\", not \"off\".\n is_ai_data_processing_approved: z.boolean().nullish(),\n })\n .passthrough(),\n organizations: z.array(\n z\n .object({\n id: z.string().uuid(),\n name: z.string().nullish(),\n membership_level: z.number().nullish(),\n })\n .passthrough(),\n ),\n })\n .passthrough();\n\n/**\n * Single activity log entry the wizard cares about. The PostHog endpoint\n * returns much more — schema kept minimal so changes upstream don't break us.\n *\n * @unused — no current caller after the Phase 6 streaming-agent pivot\n * dropped activity_log polling. Deliberately retained: this is a thin,\n * well-typed wrapper around a stable PostHog endpoint, and we're likely\n * to want it again for a future feature (e.g. \"what changed in your\n * project recently\"). Re-deriving the schema is more work than letting\n * it sit dormant.\n */\nexport const ActivityLogEntrySchema = z\n .object({\n scope: z.string().nullish(),\n activity: z.string().nullish(),\n created_at: z.string().nullish(),\n })\n .passthrough();\n\n/** @unused — see ActivityLogEntrySchema. */\nexport const ActivityLogResponseSchema = z.object({\n results: z.array(ActivityLogEntrySchema),\n});\n\n/** @unused — see ActivityLogEntrySchema. */\nexport type ActivityLogEntry = z.infer<typeof ActivityLogEntrySchema>;\n\nexport const ApiProjectSchema = z.object({\n id: z.number(),\n uuid: z.string().uuid(),\n organization: z.string().uuid(),\n api_token: z.string(),\n name: z.string(),\n // Product opt-ins (TeamSerializer-compat fields on /api/projects/:id).\n // Project-level truth for \"is this product enabled\" — a product can be\n // instrumented from another repo or the snippet, so these settings\n // override repo-local evidence. Null/absent = unknown. Only the\n // opt-ins a signals decision consumes: replay + exception autocapture\n // feed signal-source choices; surveys feeds the surveys-scout tuning.\n session_recording_opt_in: z.boolean().nullish(),\n autocapture_exceptions_opt_in: z.boolean().nullish(),\n surveys_opt_in: z.boolean().nullish(),\n});\n\nexport type ApiUser = z.infer<typeof ApiUserSchema>;\nexport type ApiProject = z.infer<typeof ApiProjectSchema>;\n\nexport class ApiError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly endpoint?: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n\nexport async function fetchUserData(\n accessToken: string,\n baseUrl: string,\n): Promise<ApiUser> {\n try {\n const response = await axios.get(`${baseUrl}/api/users/@me/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n });\n\n return ApiUserSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch user data');\n analytics.captureException(apiError, {\n endpoint: '/api/users/@me/',\n baseUrl,\n });\n throw apiError;\n }\n}\n\n/**\n * Best-effort fetch of recent activity log entries. Returns [] on any error\n * so callers can treat absence of results as \"haven't detected anything yet\"\n * rather than a hard failure.\n *\n * @unused — no current caller after the Phase 6 streaming-agent pivot\n * dropped activity_log polling from McpSuggestedPromptsScreen.\n * Deliberately retained for future features that want a soft signal of\n * recent project changes (e.g. dashboards, audit summaries). See the\n * ActivityLogEntrySchema doc comment for the keep-vs-delete rationale.\n */\nexport async function fetchRecentActivity(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n since: Date,\n): Promise<ActivityLogEntry[]> {\n try {\n const response = await axios.get(\n `${baseUrl}/api/projects/${projectId}/activity_log/`,\n {\n params: { limit: 10 },\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n // Short timeout — best-effort probe, not a critical path.\n timeout: 4000,\n },\n );\n const parsed = ActivityLogResponseSchema.safeParse(response.data);\n if (!parsed.success) return [];\n const sinceMs = since.getTime();\n return parsed.data.results.filter((entry) => {\n if (!entry.created_at) return false;\n const t = Date.parse(entry.created_at);\n return Number.isFinite(t) && t >= sinceMs;\n });\n } catch {\n return [];\n }\n}\n\nexport async function fetchProjectData(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n): Promise<ApiProject> {\n try {\n const response = await axios.get(`${baseUrl}/api/projects/${projectId}/`, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n });\n\n return ApiProjectSchema.parse(response.data);\n } catch (error) {\n const apiError = handleApiError(error, 'fetch project data');\n analytics.captureException(apiError, {\n endpoint: `/api/projects/${projectId}/`,\n baseUrl,\n projectId,\n });\n throw apiError;\n }\n}\n\n/** Minimal shape of `/api/projects/:id/integrations/` — we only read `kind`. */\nconst IntegrationsResponseSchema = z.object({\n results: z.array(z.object({ kind: z.string().nullish() }).passthrough()),\n});\n\n/**\n * Check whether the project already has a Slack integration connected.\n * Requires the `integration:read` scope. Throws on failure — callers\n * (including the SlackConnectScreen poll) decide how to degrade and\n * are responsible for capturing the error exactly once.\n */\nexport async function fetchSlackConnected(\n accessToken: string,\n projectId: number,\n baseUrl: string,\n signal?: AbortSignal,\n): Promise<boolean> {\n const response = await axios.get(\n `${baseUrl}/api/projects/${projectId}/integrations/`,\n {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n },\n signal,\n },\n );\n const parsed = IntegrationsResponseSchema.safeParse(response.data);\n if (!parsed.success) return false;\n return parsed.data.results.some((i) => i.kind === 'slack');\n}\n\nexport function handleApiError(error: unknown, operation: string): ApiError {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<{ detail?: string }>;\n const status = axiosError.response?.status;\n const detail = axiosError.response?.data?.detail;\n const endpoint = axiosError.config?.url;\n\n if (status === 401) {\n return new ApiError(\n `Authentication failed while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 403) {\n return new ApiError(\n `Access denied while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n if (status === 404) {\n return new ApiError(\n `Resource not found while trying to ${operation}`,\n status,\n endpoint,\n );\n }\n\n const message = detail || `Failed to ${operation}`;\n return new ApiError(message, status, endpoint);\n }\n\n if (error instanceof z.ZodError) {\n return new ApiError(`Invalid response format while trying to ${operation}`);\n }\n\n return new ApiError(\n `Unexpected error while trying to ${operation}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,gBAA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AAQ,MAAM,UAAU,kBAE5C"}
|
package/dist/bin.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { B as Integration, Et as regionOption, K as POSTHOG_DOCS_URL, Tt as isHeadless, a as getLogFilePath, bt as VERSION, f as getUI, gt as WIZARD_USER_AGENT, m as LoggingUI, p as setUI, r as debug, s as logToFile, vt as getSkillsBaseUrl, wt as headlessOption } from "./debug-
|
|
3
|
-
import { n as analytics } from "./analytics-
|
|
4
|
-
import { r as setEntryCommand } from "./telemetry-
|
|
5
|
-
import { n as isUsingTypeScript } from "./setup-utils-
|
|
6
|
-
import { o as handleApiError } from "./api-
|
|
2
|
+
import { B as Integration, Et as regionOption, K as POSTHOG_DOCS_URL, Tt as isHeadless, a as getLogFilePath, bt as VERSION, f as getUI, gt as WIZARD_USER_AGENT, m as LoggingUI, p as setUI, r as debug, s as logToFile, vt as getSkillsBaseUrl, wt as headlessOption } from "./debug-BiU-S12q.js";
|
|
3
|
+
import { n as analytics } from "./analytics-B4dny8FA.js";
|
|
4
|
+
import { r as setEntryCommand } from "./telemetry-3Y8LxNVU.js";
|
|
5
|
+
import { n as isUsingTypeScript } from "./setup-utils-BMy5Zj3Z.js";
|
|
6
|
+
import { o as handleApiError } from "./api-CdPvsnUm.js";
|
|
7
7
|
import "./wizard-session-tp4Zdbwl.js";
|
|
8
|
-
import { r as runCleanups } from "./wizard-abort-
|
|
9
|
-
import { n as isNonInteractiveEnvironment } from "./environment-
|
|
10
|
-
import { n as runAgent, o as authenticate } from "./agent-runner-
|
|
11
|
-
import { l as recoverOrphanedSettingsBackups, p as AgentSignals, v as WIZARD_TOOL_NAMES, x as fetchSkillMenu } from "./agent-interface-
|
|
12
|
-
import { _ as AUDIT_CHECKS_FILE, h as SETUP_REPORT_FILE, v as AUDIT_CHECKS_KEY, y as AUDIT_REPORT_FILE } from "./yara-hooks-
|
|
13
|
-
import { i as SPINNER_MESSAGE } from "./registry-
|
|
14
|
-
import { S as gatherFrameworkContext, _ as detectWarehousePrerequisites, a as LINE_CHART_BLOCK, g as WAREHOUSE_ABORT_CASES, h as HEALTH_CHECK_STEP, i as FUNNEL_BLOCK, m as Icons, n as integrationRunStep, o as PRODUCT_SUITE_BLOCK, p as Colors, r as posthogIntegrationConfig, s as StatusPeekTrigger, u as isClearBlock, v as getDetectedWarehouseSources, x as resolveProjectDir, y as detectIntegrationProjects } from "./posthog-integration-
|
|
15
|
-
import { t as IGNORED_DIRS } from "./file-utils-
|
|
8
|
+
import { r as runCleanups } from "./wizard-abort-D1UxHeiE.js";
|
|
9
|
+
import { n as isNonInteractiveEnvironment } from "./environment-BT0RRheV.js";
|
|
10
|
+
import { n as runAgent, o as authenticate } from "./agent-runner-D8pEOs_2.js";
|
|
11
|
+
import { l as recoverOrphanedSettingsBackups, p as AgentSignals, v as WIZARD_TOOL_NAMES, x as fetchSkillMenu } from "./agent-interface-RZY46R62.js";
|
|
12
|
+
import { _ as AUDIT_CHECKS_FILE, h as SETUP_REPORT_FILE, v as AUDIT_CHECKS_KEY, y as AUDIT_REPORT_FILE } from "./yara-hooks-D9PSjEqo.js";
|
|
13
|
+
import { i as SPINNER_MESSAGE } from "./registry-Zp3B2L4q.js";
|
|
14
|
+
import { S as gatherFrameworkContext, _ as detectWarehousePrerequisites, a as LINE_CHART_BLOCK, g as WAREHOUSE_ABORT_CASES, h as HEALTH_CHECK_STEP, i as FUNNEL_BLOCK, m as Icons, n as integrationRunStep, o as PRODUCT_SUITE_BLOCK, p as Colors, r as posthogIntegrationConfig, s as StatusPeekTrigger, u as isClearBlock, v as getDetectedWarehouseSources, x as resolveProjectDir, y as detectIntegrationProjects } from "./posthog-integration-BnWgrvts.js";
|
|
15
|
+
import { t as IGNORED_DIRS } from "./file-utils-B1_Eciop.js";
|
|
16
16
|
import { n as readApiKeyFromEnv } from "./env-api-key-C3LzH8Lr.js";
|
|
17
17
|
import { satisfies } from "semver";
|
|
18
18
|
import yargs from "yargs";
|
|
@@ -200,7 +200,7 @@ function runProvision(argv) {
|
|
|
200
200
|
}
|
|
201
201
|
async function provision({ email, region, name, baseUrl, jsonMode }) {
|
|
202
202
|
try {
|
|
203
|
-
const { provisionNewAccount } = await import("./provisioning-
|
|
203
|
+
const { provisionNewAccount } = await import("./provisioning-DS8zDveH.js").then((n) => n.n);
|
|
204
204
|
if (!jsonMode) getUI().log.info(`Provisioning account for ${email} in ${region}...`);
|
|
205
205
|
emitResult(await provisionNewAccount(email, name, region, { baseUrl }), jsonMode);
|
|
206
206
|
process.exit(0);
|
|
@@ -267,22 +267,22 @@ const basicIntegrationCommand = {
|
|
|
267
267
|
setEntryCommand("integrate");
|
|
268
268
|
(async () => {
|
|
269
269
|
if (isHeadless(argv)) {
|
|
270
|
-
const { runHeadlessInstall } = await import("./ci-install-
|
|
270
|
+
const { runHeadlessInstall } = await import("./ci-install-g8govb-6.js");
|
|
271
271
|
return runHeadlessInstall(argv);
|
|
272
272
|
}
|
|
273
273
|
if (argv.ci) {
|
|
274
|
-
const { runCIInstall } = await import("./ci-install-
|
|
274
|
+
const { runCIInstall } = await import("./ci-install-g8govb-6.js");
|
|
275
275
|
return runCIInstall(argv);
|
|
276
276
|
}
|
|
277
277
|
if (isNonInteractiveEnvironment()) {
|
|
278
|
-
const { failNonInteractive } = await import("./non-interactive-
|
|
278
|
+
const { failNonInteractive } = await import("./non-interactive-C0NbQTcD.js");
|
|
279
279
|
return failNonInteractive();
|
|
280
280
|
}
|
|
281
281
|
if (argv.playground) {
|
|
282
|
-
const { runPlayground } = await import("./playground-
|
|
282
|
+
const { runPlayground } = await import("./playground-DZoNrDEM.js");
|
|
283
283
|
return runPlayground();
|
|
284
284
|
}
|
|
285
|
-
const { runInteractive } = await import("./interactive-
|
|
285
|
+
const { runInteractive } = await import("./interactive-Bgb8njPS.js");
|
|
286
286
|
runInteractive(argv);
|
|
287
287
|
})();
|
|
288
288
|
}
|
|
@@ -3623,6 +3623,61 @@ const mcpAnalyticsConfig = createSkillProgram({
|
|
|
3623
3623
|
}]
|
|
3624
3624
|
});
|
|
3625
3625
|
//#endregion
|
|
3626
|
+
//#region src/lib/programs/ai-observability/index.ts
|
|
3627
|
+
const AI_OBSERVABILITY_STEPS = AGENT_SKILL_STEPS.map((step) => step.id === "intro" ? {
|
|
3628
|
+
...step,
|
|
3629
|
+
screenId: "ai-observability-intro"
|
|
3630
|
+
} : step);
|
|
3631
|
+
const AI_OBSERVABILITY_REPORT_FILE = "posthog-ai-observability-report.md";
|
|
3632
|
+
/**
|
|
3633
|
+
* `wizard ai-observability` — wrap the project's LLM client calls so they emit
|
|
3634
|
+
* `$ai_generation` events into LLM Analytics.
|
|
3635
|
+
*
|
|
3636
|
+
* No `run.skillId`: the context-mill `ai-observability` group ships one variant
|
|
3637
|
+
* per (LLM provider × language) and the wizard does no provider detection —
|
|
3638
|
+
* the agent loads the menu, matches the manifest's vendor SDK, and installs
|
|
3639
|
+
* the right variant itself (see `customPrompt`). Stays flat while a single
|
|
3640
|
+
* "add AIO to a project" flow is the only action.
|
|
3641
|
+
*/
|
|
3642
|
+
const aiObservabilityConfig = {
|
|
3643
|
+
command: "ai-observability",
|
|
3644
|
+
description: "Add PostHog AI Observability to your LLM calls",
|
|
3645
|
+
id: "ai-observability",
|
|
3646
|
+
steps: AI_OBSERVABILITY_STEPS,
|
|
3647
|
+
reportFile: AI_OBSERVABILITY_REPORT_FILE,
|
|
3648
|
+
getContentBlocks: getContentBlocks$3,
|
|
3649
|
+
run: {
|
|
3650
|
+
integrationLabel: "ai-observability",
|
|
3651
|
+
customPrompt: () => `Instrument this project's LLM calls with PostHog AI Observability.
|
|
3652
|
+
|
|
3653
|
+
This flow has no pre-installed skill — you install the right one yourself:
|
|
3654
|
+
|
|
3655
|
+
1. Call \`load_skill_menu\` with \`category: "ai-observability"\`. The menu is
|
|
3656
|
+
the source of truth: one variant per (LLM provider × language), plus a
|
|
3657
|
+
\`manual-capture\` variant for projects with no vendor SDK.
|
|
3658
|
+
|
|
3659
|
+
2. Scan the project manifest (\`package.json\`, \`pyproject.toml\`,
|
|
3660
|
+
\`requirements.txt\`) for a vendor LLM SDK and pick the variant that matches
|
|
3661
|
+
it — the language follows the manifest (\`package.json\` → Node, Python
|
|
3662
|
+
tooling → Python). Multiple SDKs (e.g. LangChain wrapping OpenAI) → prefer
|
|
3663
|
+
the higher abstraction. No vendor SDK → the \`manual-capture\` variant.
|
|
3664
|
+
Genuinely ambiguous → \`wizard_ask\` with a multi-choice picker.
|
|
3665
|
+
|
|
3666
|
+
3. Call \`install_skill\` with the picked variant id. Then follow that skill's
|
|
3667
|
+
\`SKILL.md\` and references end-to-end. The skill itself will install
|
|
3668
|
+
packages, wire OTel, set env vars, and describe verification.
|
|
3669
|
+
|
|
3670
|
+
Make only additive changes — do not touch existing PostHog init, identify
|
|
3671
|
+
calls, event capture, or dashboards. Those belong to other skills. The
|
|
3672
|
+
final report is written to ./${AI_OBSERVABILITY_REPORT_FILE}.`,
|
|
3673
|
+
successMessage: `AI Observability configured! View the report at ./${AI_OBSERVABILITY_REPORT_FILE}`,
|
|
3674
|
+
reportFile: AI_OBSERVABILITY_REPORT_FILE,
|
|
3675
|
+
docsUrl: "https://posthog.com/docs/ai-observability",
|
|
3676
|
+
spinnerMessage: "Setting up AI Observability...",
|
|
3677
|
+
estimatedDurationMinutes: 5
|
|
3678
|
+
}
|
|
3679
|
+
};
|
|
3680
|
+
//#endregion
|
|
3626
3681
|
//#region src/lib/programs/slack/index.ts
|
|
3627
3682
|
const slackConnectConfig = {
|
|
3628
3683
|
id: "slack",
|
|
@@ -3671,6 +3726,7 @@ const PROGRAM_REGISTRY = [
|
|
|
3671
3726
|
mcpRemoveConfig,
|
|
3672
3727
|
mcpTutorialConfig,
|
|
3673
3728
|
mcpAnalyticsConfig,
|
|
3729
|
+
aiObservabilityConfig,
|
|
3674
3730
|
slackConnectConfig
|
|
3675
3731
|
];
|
|
3676
3732
|
/**
|
|
@@ -3694,6 +3750,7 @@ const Program = {
|
|
|
3694
3750
|
McpRemove: mcpRemoveConfig.id,
|
|
3695
3751
|
McpTutorial: mcpTutorialConfig.id,
|
|
3696
3752
|
McpAnalytics: mcpAnalyticsConfig.id,
|
|
3753
|
+
AiObservability: aiObservabilityConfig.id,
|
|
3697
3754
|
SlackConnect: slackConnectConfig.id
|
|
3698
3755
|
};
|
|
3699
3756
|
/**
|
|
@@ -3734,7 +3791,7 @@ function runMcpAdd(argv) {
|
|
|
3734
3791
|
const debug = argv.debug;
|
|
3735
3792
|
const localMcp = argv.local;
|
|
3736
3793
|
try {
|
|
3737
|
-
const { startTUI } = await import("./start-tui-
|
|
3794
|
+
const { startTUI } = await import("./start-tui-CJ7i0pbr.js");
|
|
3738
3795
|
const { buildSession } = await import("./wizard-session-DWHe83uk.js");
|
|
3739
3796
|
const tui = startTUI(VERSION, Program.McpAdd);
|
|
3740
3797
|
tui.store.session = buildSession({
|
|
@@ -3747,7 +3804,7 @@ function runMcpAdd(argv) {
|
|
|
3747
3804
|
} catch (error) {
|
|
3748
3805
|
if (!isTUIUnavailable(error)) throw error;
|
|
3749
3806
|
setUI(new LoggingUI());
|
|
3750
|
-
const { addMCPServerToClientsStep } = await import("./add-mcp-server-to-clients-
|
|
3807
|
+
const { addMCPServerToClientsStep } = await import("./add-mcp-server-to-clients-Dg64O4OZ.js").then((n) => n.r);
|
|
3751
3808
|
await addMCPServerToClientsStep({
|
|
3752
3809
|
local: localMcp,
|
|
3753
3810
|
features,
|
|
@@ -3786,7 +3843,7 @@ function runMcpRemove(argv) {
|
|
|
3786
3843
|
const debug = argv.debug;
|
|
3787
3844
|
const localMcp = argv.local;
|
|
3788
3845
|
try {
|
|
3789
|
-
const { startTUI } = await import("./start-tui-
|
|
3846
|
+
const { startTUI } = await import("./start-tui-CJ7i0pbr.js");
|
|
3790
3847
|
const { buildSession } = await import("./wizard-session-DWHe83uk.js");
|
|
3791
3848
|
const tui = startTUI(VERSION, Program.McpRemove);
|
|
3792
3849
|
tui.store.session = buildSession({
|
|
@@ -3796,7 +3853,7 @@ function runMcpRemove(argv) {
|
|
|
3796
3853
|
});
|
|
3797
3854
|
} catch {
|
|
3798
3855
|
setUI(new LoggingUI());
|
|
3799
|
-
const { removeMCPServerFromClientsStep } = await import("./add-mcp-server-to-clients-
|
|
3856
|
+
const { removeMCPServerFromClientsStep } = await import("./add-mcp-server-to-clients-Dg64O4OZ.js").then((n) => n.r);
|
|
3800
3857
|
await removeMCPServerFromClientsStep({ local: localMcp });
|
|
3801
3858
|
}
|
|
3802
3859
|
})();
|
|
@@ -3818,7 +3875,7 @@ function runMcpTutorial(argv) {
|
|
|
3818
3875
|
const debug = argv.debug;
|
|
3819
3876
|
const localMcp = argv.local;
|
|
3820
3877
|
try {
|
|
3821
|
-
const { startTUI } = await import("./start-tui-
|
|
3878
|
+
const { startTUI } = await import("./start-tui-CJ7i0pbr.js");
|
|
3822
3879
|
const { buildSession } = await import("./wizard-session-DWHe83uk.js");
|
|
3823
3880
|
const tui = startTUI(VERSION, Program.McpTutorial);
|
|
3824
3881
|
tui.store.session = buildSession({
|
|
@@ -3899,9 +3956,9 @@ function runWizard(config, options) {
|
|
|
3899
3956
|
(async () => {
|
|
3900
3957
|
try {
|
|
3901
3958
|
const installDir = options.installDir || process.cwd();
|
|
3902
|
-
const { startTUI } = await import("./start-tui-
|
|
3959
|
+
const { startTUI } = await import("./start-tui-CJ7i0pbr.js");
|
|
3903
3960
|
const { buildSession, RunPhase } = await import("./wizard-session-DWHe83uk.js");
|
|
3904
|
-
const { TaskStreamPush } = await import("./task-stream-
|
|
3961
|
+
const { TaskStreamPush } = await import("./task-stream-DlgLKdMC.js");
|
|
3905
3962
|
const { PostHogDestination } = await import("./posthog-DZZbziJ1.js");
|
|
3906
3963
|
tui = startTUI(WIZARD_VERSION, config.id);
|
|
3907
3964
|
const activeTui = tui;
|
|
@@ -3967,7 +4024,7 @@ function runWizard(config, options) {
|
|
|
3967
4024
|
if (shown(step)) await advanceStep(step, activeTui.store, config);
|
|
3968
4025
|
}
|
|
3969
4026
|
else if (skipAgent) {
|
|
3970
|
-
const { getOrAskForProjectData } = await import("./setup-utils-
|
|
4027
|
+
const { getOrAskForProjectData } = await import("./setup-utils-BMy5Zj3Z.js").then((n) => n.r);
|
|
3971
4028
|
const { projectApiKey, host, accessToken, projectId } = await getOrAskForProjectData({
|
|
3972
4029
|
signup: session.signup,
|
|
3973
4030
|
ci: session.ci,
|
|
@@ -4069,10 +4126,10 @@ function runNonInteractive(config, options, mode) {
|
|
|
4069
4126
|
(async () => {
|
|
4070
4127
|
const path = await import("path");
|
|
4071
4128
|
const { buildSession, RunPhase, OutroKind } = await import("./wizard-session-DWHe83uk.js");
|
|
4072
|
-
const { readEnvironment } = await import("./environment-
|
|
4129
|
+
const { readEnvironment } = await import("./environment-BT0RRheV.js").then((n) => n.t);
|
|
4073
4130
|
const { readApiKeyFromEnv } = await import("./env-api-key-C3LzH8Lr.js").then((n) => n.t);
|
|
4074
|
-
const { configureLogFileFromEnvironment, logToFile } = await import("./debug-
|
|
4075
|
-
const { wizardAbort, WizardError } = await import("./wizard-abort-
|
|
4131
|
+
const { configureLogFileFromEnvironment, logToFile } = await import("./debug-DQWRmiju.js");
|
|
4132
|
+
const { wizardAbort, WizardError } = await import("./wizard-abort-DoI_ZWM-.js");
|
|
4076
4133
|
configureLogFileFromEnvironment();
|
|
4077
4134
|
const env = readEnvironment();
|
|
4078
4135
|
const apiKey = options.apiKey ?? readApiKeyFromEnv() ?? void 0;
|
|
@@ -4104,9 +4161,9 @@ function runNonInteractive(config, options, mode) {
|
|
|
4104
4161
|
let store = null;
|
|
4105
4162
|
let taskStream = null;
|
|
4106
4163
|
if (mode === "headless") {
|
|
4107
|
-
const { WizardStore } = await import("./store-
|
|
4108
|
-
const { HeadlessUI } = await import("./headless-ui-
|
|
4109
|
-
const { TaskStreamPush, PostHogDestination } = await import("./task-stream-
|
|
4164
|
+
const { WizardStore } = await import("./store-CVZL9JJe.js").then((n) => n.n);
|
|
4165
|
+
const { HeadlessUI } = await import("./headless-ui-DQVBpo0v.js");
|
|
4166
|
+
const { TaskStreamPush, PostHogDestination } = await import("./task-stream-DlgLKdMC.js");
|
|
4110
4167
|
store = new WizardStore(config.id);
|
|
4111
4168
|
store.session = session;
|
|
4112
4169
|
setUI(new HeadlessUI(store));
|
|
@@ -4162,7 +4219,7 @@ function runNonInteractive(config, options, mode) {
|
|
|
4162
4219
|
});
|
|
4163
4220
|
}
|
|
4164
4221
|
}
|
|
4165
|
-
const { runAgent } = await import("./agent-runner-
|
|
4222
|
+
const { runAgent } = await import("./agent-runner-D8pEOs_2.js").then((n) => n.t);
|
|
4166
4223
|
await runAgent(config, session);
|
|
4167
4224
|
await settleStream(RunPhase.Completed);
|
|
4168
4225
|
} catch (error) {
|
|
@@ -4306,6 +4363,20 @@ function nativeCommandFactory(config, opts = {}) {
|
|
|
4306
4363
|
*/
|
|
4307
4364
|
const mcpAnalyticsCommand = nativeCommandFactory(mcpAnalyticsConfig);
|
|
4308
4365
|
//#endregion
|
|
4366
|
+
//#region src/commands/ai-observability.ts
|
|
4367
|
+
/**
|
|
4368
|
+
* `wizard ai-observability` — flat skill command, wire AI Observability into a
|
|
4369
|
+
* project today.
|
|
4370
|
+
*
|
|
4371
|
+
* Installs the OpenTelemetry SDK, the PostHog span processor, and the
|
|
4372
|
+
* provider-specific instrumentation so LLM calls emit `$ai_generation` events.
|
|
4373
|
+
* The `ai-observability` context-mill skill has one variant per (LLM provider ×
|
|
4374
|
+
* language); the agent picks the right one at run time by scanning the
|
|
4375
|
+
* project's manifest and (when ambiguous) asking the user via `wizard_ask`.
|
|
4376
|
+
* Stays flat while a single "add AIO to a project" flow is the only action.
|
|
4377
|
+
*/
|
|
4378
|
+
const aiObservabilityCommand = nativeCommandFactory(aiObservabilityConfig);
|
|
4379
|
+
//#endregion
|
|
4309
4380
|
//#region src/lib/programs/dispatch-family.ts
|
|
4310
4381
|
/**
|
|
4311
4382
|
* Capture a CLI dispatch error, flush analytics, and exit. The wizard never
|
|
@@ -5091,7 +5162,7 @@ async function runDoctorCI(options) {
|
|
|
5091
5162
|
getUI().intro("Welcome to the PostHog setup wizard");
|
|
5092
5163
|
getUI().log.info("Running posthog-doctor in CI mode");
|
|
5093
5164
|
try {
|
|
5094
|
-
const { getOrAskForProjectData } = await import("./setup-utils-
|
|
5165
|
+
const { getOrAskForProjectData } = await import("./setup-utils-BMy5Zj3Z.js").then((n) => n.r);
|
|
5095
5166
|
const { host, accessToken, projectId } = await getOrAskForProjectData({
|
|
5096
5167
|
signup: false,
|
|
5097
5168
|
ci: true,
|
|
@@ -5109,7 +5180,7 @@ async function runDoctorCI(options) {
|
|
|
5109
5180
|
for (const issue of sorted) getUI().log.info(` • [${issue.severity}] ${getKindMeta(issue.kind).title}`);
|
|
5110
5181
|
process.exit(1);
|
|
5111
5182
|
} catch (error) {
|
|
5112
|
-
const { ApiError } = await import("./api-
|
|
5183
|
+
const { ApiError } = await import("./api-CdPvsnUm.js").then((n) => n.n);
|
|
5113
5184
|
const message = error instanceof ApiError && error.statusCode === 401 ? "Your PostHog API key is invalid or expired." : error instanceof Error ? error.message : String(error);
|
|
5114
5185
|
getUI().log.error(`Doctor failed: ${message}`);
|
|
5115
5186
|
process.exit(1);
|
|
@@ -5191,7 +5262,7 @@ function runSlackConnect(argv) {
|
|
|
5191
5262
|
(async () => {
|
|
5192
5263
|
const debug = argv.debug;
|
|
5193
5264
|
try {
|
|
5194
|
-
const { startTUI } = await import("./start-tui-
|
|
5265
|
+
const { startTUI } = await import("./start-tui-CJ7i0pbr.js");
|
|
5195
5266
|
const { buildSession } = await import("./wizard-session-DWHe83uk.js");
|
|
5196
5267
|
const tui = startTUI(VERSION, Program.SlackConnect);
|
|
5197
5268
|
tui.store.session = buildSession({
|
|
@@ -5472,7 +5543,7 @@ function resolveInstallDir() {
|
|
|
5472
5543
|
if (inline) return inline.slice(14);
|
|
5473
5544
|
return process.env.POSTHOG_WIZARD_INSTALL_DIR ?? process.cwd();
|
|
5474
5545
|
}
|
|
5475
|
-
Wizard.use(basicIntegrationCommand).use(mcpCommand).use(mcpAnalyticsCommand).use(cliCommand).use(auditCommand).use(doctorCommand).use(migrateCommand).use(revenueCommand).use(warehouseCommand).use(selfDrivingCommand).use(slackCommand).use(uploadSourcemapsCommand).use(skillCommand).init();
|
|
5546
|
+
Wizard.use(basicIntegrationCommand).use(mcpCommand).use(mcpAnalyticsCommand).use(aiObservabilityCommand).use(cliCommand).use(auditCommand).use(doctorCommand).use(migrateCommand).use(revenueCommand).use(warehouseCommand).use(selfDrivingCommand).use(slackCommand).use(uploadSourcemapsCommand).use(skillCommand).init();
|
|
5476
5547
|
//#endregion
|
|
5477
5548
|
export { STRIPE_SDKS as S, SOURCE_MAPS_CONTEXT_KEYS as _, ConfirmButton as a, getContentBlocks$3 as b, runWizardCI as c, Program as d, getProgramConfig as f, DISPLAY_NAME as g, AUTOMATABLE_VARIANTS as h, useKeyboardHintsContext as i, runWizard as l, SELF_DRIVING_INTEGRATE_PATH_KEY as m, useKeyBindings as n, PromptLabel as o, detectSelfDrivingIntegrationProjects as p, KeyboardHintsProvider as r, runWizardHeadless as s, PickerMenu as t, PROGRAM_REGISTRY as u, getKindMeta as v, POSTHOG_SDKS as x, fetchHealthIssues as y };
|
|
5478
5549
|
|