@posthog/wizard 2.73.2 → 2.74.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/README.md +32 -28
- package/dist/README.md +11 -4
- package/dist/{add-mcp-server-to-clients-BaVuIyoj.js → add-mcp-server-to-clients-BtWwRG7O.js} +4 -4
- package/dist/{add-mcp-server-to-clients-BaVuIyoj.js.map → add-mcp-server-to-clients-BtWwRG7O.js.map} +1 -1
- package/dist/{agent-interface-Dm28tBj-.js → agent-interface-CK6pmvkF.js} +484 -339
- package/dist/agent-interface-CK6pmvkF.js.map +1 -0
- package/dist/{agent-prompt-loader-Dv9HIHm1.js → agent-prompt-loader-CPCNMvGh.js} +6 -7
- package/dist/agent-prompt-loader-CPCNMvGh.js.map +1 -0
- package/dist/{agent-runner-C1Dwg9sa.js → agent-runner-jz4yiJfh.js} +49 -67
- package/dist/agent-runner-jz4yiJfh.js.map +1 -0
- package/dist/analytics-CfadnLFG.js +2 -0
- package/dist/{analytics-BY4qZ0AC.js → analytics-DZNb3aRN.js} +2 -2
- package/dist/{analytics-BY4qZ0AC.js.map → analytics-DZNb3aRN.js.map} +1 -1
- package/dist/{api-DwWMv1Qc.js → api-DXGaiK94.js} +3 -3
- package/dist/{api-DwWMv1Qc.js.map → api-DXGaiK94.js.map} +1 -1
- package/dist/bin.js +59 -54
- package/dist/bin.js.map +1 -1
- package/dist/{bounded-fs-DIYnGoSv.js → bounded-fs-CErPpkN2.js} +3 -3
- package/dist/{bounded-fs-DIYnGoSv.js.map → bounded-fs-CErPpkN2.js.map} +1 -1
- package/dist/{ci-install-BL5ObQ3S.js → ci-install-CzWzi_qu.js} +21 -24
- package/dist/ci-install-CzWzi_qu.js.map +1 -0
- package/dist/{debug-CY2VLyCW.js → debug-D4y9vVWt.js} +1 -1
- package/dist/{debug-BrWB-OAq.js → debug-ECdmmlDM.js} +21 -33
- package/dist/debug-ECdmmlDM.js.map +1 -0
- package/dist/{env-api-key-C6XP1N9g.js → env-api-key-g5w775Ve.js} +2 -2
- package/dist/{env-api-key-C6XP1N9g.js.map → env-api-key-g5w775Ve.js.map} +1 -1
- package/dist/{environment-CXxQd0SR.js → environment-DDkdsWUr.js} +4 -4
- package/dist/{environment-CXxQd0SR.js.map → environment-DDkdsWUr.js.map} +1 -1
- package/dist/{errors-u8z27V-x.js → errors--OqLxmWR.js} +34 -3
- package/dist/errors--OqLxmWR.js.map +1 -0
- package/dist/{file-watcher-Duj0RMwi.js → file-watcher-BNdFPlI8.js} +2 -2
- package/dist/{file-watcher-Duj0RMwi.js.map → file-watcher-BNdFPlI8.js.map} +1 -1
- package/dist/{headless-ui-B1hA9Rx8.js → headless-ui-DBZCl4CG.js} +2 -2
- package/dist/{headless-ui-B1hA9Rx8.js.map → headless-ui-DBZCl4CG.js.map} +1 -1
- package/dist/{interactive-B2OUN9yB.js → interactive-BKxXUB0T.js} +3 -3
- package/dist/{interactive-B2OUN9yB.js.map → interactive-BKxXUB0T.js.map} +1 -1
- package/dist/{mcp-BkHaEmEn.js → mcp-CwM45_Kp.js} +2 -2
- package/dist/{mcp-BkHaEmEn.js.map → mcp-CwM45_Kp.js.map} +1 -1
- package/dist/{mcp-prompt-streaming-hV0rkw9s.js → mcp-prompt-streaming-R8H7uhuO.js} +5 -5
- package/dist/mcp-prompt-streaming-R8H7uhuO.js.map +1 -0
- package/dist/{non-interactive-ByaO-qoX.js → non-interactive-DxzBwNxJ.js} +3 -3
- package/dist/{non-interactive-ByaO-qoX.js.map → non-interactive-DxzBwNxJ.js.map} +1 -1
- package/dist/{orchestrator-tools-pBKJnRjl.js → orchestrator-tools-CTpKnk5-.js} +3 -3
- package/dist/{orchestrator-tools-pBKJnRjl.js.map → orchestrator-tools-CTpKnk5-.js.map} +1 -1
- package/dist/{package-manager-CIm2MNel.js → package-manager-Bi6gaPa4.js} +2 -2
- package/dist/{package-manager-CIm2MNel.js.map → package-manager-Bi6gaPa4.js.map} +1 -1
- package/dist/{pi-Dj0EHErj.js → pi-DpWFwz5u.js} +35 -20
- package/dist/pi-DpWFwz5u.js.map +1 -0
- package/dist/{playground-UJyt6uLu.js → playground-BtTCVaSD.js} +7 -12
- package/dist/playground-BtTCVaSD.js.map +1 -0
- package/dist/{posthog-BuIPmmdp.js → posthog-B99H8Zyk.js} +2 -2
- package/dist/{posthog-BuIPmmdp.js.map → posthog-B99H8Zyk.js.map} +1 -1
- package/dist/{posthog-integration-HXLZnann.js → posthog-integration-CxvkKY1j.js} +13 -13
- package/dist/{posthog-integration-HXLZnann.js.map → posthog-integration-CxvkKY1j.js.map} +1 -1
- package/dist/{provisioning-B9kEzRE_.js → provisioning-BewSEuFX.js} +4 -10
- package/dist/provisioning-BewSEuFX.js.map +1 -0
- package/dist/{queue-tools-CDqueOnz.js → queue-tools-CbRM-OET.js} +4 -31
- package/dist/queue-tools-CbRM-OET.js.map +1 -0
- package/dist/{registry-Cl77fAHR.js → registry-Bt2Mc4vC.js} +5 -5
- package/dist/{registry-Cl77fAHR.js.map → registry-Bt2Mc4vC.js.map} +1 -1
- package/dist/{security-CfoEOKN4.js → security-Cmxb64bz.js} +5 -5
- package/dist/{security-CfoEOKN4.js.map → security-Cmxb64bz.js.map} +1 -1
- package/dist/{setup-utils-BVQaFad8.js → setup-utils-CCphwDIz.js} +9 -15
- package/dist/setup-utils-CCphwDIz.js.map +1 -0
- package/dist/smoke-test-ci.sh +5 -2
- package/dist/{start-tui-DJGq1bFx.js → start-tui-BRwZzlWb.js} +22 -22
- package/dist/{start-tui-DJGq1bFx.js.map → start-tui-BRwZzlWb.js.map} +1 -1
- package/dist/{steps-BLrL5Kst.js → steps-CJrx1t72.js} +7 -7
- package/dist/{steps-BLrL5Kst.js.map → steps-CJrx1t72.js.map} +1 -1
- package/dist/{store-l1aCLB7H.js → store-BhcCTIn4.js} +6 -10
- package/dist/store-BhcCTIn4.js.map +1 -0
- package/dist/{subagent-BAU9BElX.js → subagent-BeMPBF5r.js} +2 -2
- package/dist/{subagent-BAU9BElX.js.map → subagent-BeMPBF5r.js.map} +1 -1
- package/dist/{task-B7LbltJW.js → task-DX3eZgBL.js} +36 -21
- package/dist/task-DX3eZgBL.js.map +1 -0
- package/dist/{task-stream-Du_99Tv-.js → task-stream-BW7BG70C.js} +5 -5
- package/dist/{task-stream-Du_99Tv-.js.map → task-stream-BW7BG70C.js.map} +1 -1
- package/dist/{tasks-7XjlfAbk.js → tasks-Did1AR7v.js} +2 -2
- package/dist/{tasks-7XjlfAbk.js.map → tasks-Did1AR7v.js.map} +1 -1
- package/dist/{telemetry-CW5a6Bog.js → telemetry-CPWHrsXK.js} +3 -3
- package/dist/{telemetry-CW5a6Bog.js.map → telemetry-CPWHrsXK.js.map} +1 -1
- package/dist/{terminal-DMZIApv7.js → terminal-CpVFsbGu.js} +12 -12
- package/dist/{terminal-DMZIApv7.js.map → terminal-CpVFsbGu.js.map} +1 -1
- package/dist/{tools-CIkbTll3.js → tools-DjiwCd53.js} +6 -6
- package/dist/{tools-CIkbTll3.js.map → tools-DjiwCd53.js.map} +1 -1
- package/dist/{wizard-abort-serrH83C.js → wizard-abort-DjJ-6y6S.js} +1 -1
- package/dist/{wizard-abort-DcuNitMi.js → wizard-abort-RUnY1Dax.js} +4 -4
- package/dist/{wizard-abort-DcuNitMi.js.map → wizard-abort-RUnY1Dax.js.map} +1 -1
- package/dist/yara-hooks-CBMSmD9F.js +2 -0
- package/dist/{yara-hooks-BKhDtn2N.js → yara-hooks-jBqAkgxw.js} +4 -4
- package/dist/{yara-hooks-BKhDtn2N.js.map → yara-hooks-jBqAkgxw.js.map} +1 -1
- package/package.json +1 -1
- package/dist/agent-interface-Dm28tBj-.js.map +0 -1
- package/dist/agent-prompt-loader-Dv9HIHm1.js.map +0 -1
- package/dist/agent-runner-C1Dwg9sa.js.map +0 -1
- package/dist/analytics-Bhw7ODc0.js +0 -2
- package/dist/ci-install-BL5ObQ3S.js.map +0 -1
- package/dist/debug-BrWB-OAq.js.map +0 -1
- package/dist/errors-u8z27V-x.js.map +0 -1
- package/dist/mcp-prompt-streaming-hV0rkw9s.js.map +0 -1
- package/dist/pi-Dj0EHErj.js.map +0 -1
- package/dist/playground-UJyt6uLu.js.map +0 -1
- package/dist/provisioning-B9kEzRE_.js.map +0 -1
- package/dist/queue-tools-CDqueOnz.js.map +0 -1
- package/dist/setup-utils-BVQaFad8.js.map +0 -1
- package/dist/store-l1aCLB7H.js.map +0 -1
- package/dist/task-B7LbltJW.js.map +0 -1
- package/dist/yara-hooks-rZT6WNop.js +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"setup-utils-BVQaFad8.js","names":["fs","path","join","fs"],"sources":["../src/utils/package-manager.ts","../src/lib/oauth/program-scopes.ts","../src/lib/host-resolution.ts","../src/utils/oauth-errors.ts","../src/utils/oauth.ts","../src/utils/project-resolution.ts","../src/utils/semver.ts","../src/utils/setup-utils.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { readFileHead } from './bounded-fs';\nimport { withProgress } from '../telemetry';\nimport { getPackageDotJson, updatePackageDotJson } from './setup-utils';\nimport type { PackageJson } from './package-json';\nimport { analytics } from './analytics';\nimport type { WizardRunOptions } from './types';\n\ntype InstallDirOpt = Pick<WizardRunOptions, 'installDir'>;\n\nexport interface PackageManager {\n name: string;\n label: string;\n installCommand: string;\n buildCommand: string;\n /** Command the manager uses to execute a `package.json` script. */\n runScriptCommand: string;\n flags: string;\n detect: (opts: InstallDirOpt) => boolean;\n addOverride: (\n pkgName: string,\n pkgVersion: string,\n opts: InstallDirOpt,\n ) => Promise<void>;\n}\n\nfunction hasLockfile(installDir: string, file: string): boolean {\n return fs.existsSync(path.join(installDir, file));\n}\n\nfunction lockfileHeaderContains(\n installDir: string,\n file: string,\n needle: string,\n): boolean {\n // Reads only the first 500 bytes of the lockfile.\n return (\n readFileHead(path.join(installDir, file), 500)?.includes(needle) ?? false\n );\n}\n\ntype OverrideSlot = 'npm' | 'yarn' | 'pnpm';\n\nasync function writeOverride(\n slot: OverrideSlot,\n pkgName: string,\n pkgVersion: string,\n { installDir }: InstallDirOpt,\n): Promise<void> {\n const pkg = await getPackageDotJson({ installDir });\n let next: PackageJson;\n if (slot === 'yarn') {\n next = {\n ...pkg,\n resolutions: { ...(pkg.resolutions ?? {}), [pkgName]: pkgVersion },\n };\n } else if (slot === 'pnpm') {\n next = {\n ...pkg,\n pnpm: {\n ...(pkg.pnpm ?? {}),\n overrides: { ...(pkg.pnpm?.overrides ?? {}), [pkgName]: pkgVersion },\n },\n };\n } else {\n next = {\n ...pkg,\n overrides: { ...(pkg.overrides ?? {}), [pkgName]: pkgVersion },\n };\n }\n await updatePackageDotJson(next, { installDir });\n}\n\nexport const BUN: PackageManager = {\n name: 'bun',\n label: 'Bun',\n installCommand: 'bun add',\n buildCommand: 'bun run build',\n runScriptCommand: 'bun run',\n flags: '',\n detect: ({ installDir }) =>\n hasLockfile(installDir, 'bun.lockb') || hasLockfile(installDir, 'bun.lock'),\n addOverride: (pkgName, pkgVersion, opts) =>\n writeOverride('npm', pkgName, pkgVersion, opts),\n};\n\nexport const YARN_V1: PackageManager = {\n name: 'yarn',\n label: 'Yarn V1',\n installCommand: 'yarn add',\n buildCommand: 'yarn build',\n runScriptCommand: 'yarn',\n flags: '--ignore-workspace-root-check',\n detect: ({ installDir }) =>\n lockfileHeaderContains(installDir, 'yarn.lock', 'yarn lockfile v1'),\n addOverride: (pkgName, pkgVersion, opts) =>\n writeOverride('yarn', pkgName, pkgVersion, opts),\n};\n\n/** YARN V2/3/4 */\nexport const YARN_V2: PackageManager = {\n name: 'yarn',\n label: 'Yarn V2/3/4',\n installCommand: 'yarn add',\n buildCommand: 'yarn build',\n runScriptCommand: 'yarn',\n flags: '',\n detect: ({ installDir }) =>\n lockfileHeaderContains(installDir, 'yarn.lock', '__metadata'),\n addOverride: (pkgName, pkgVersion, opts) =>\n writeOverride('yarn', pkgName, pkgVersion, opts),\n};\n\nexport const PNPM: PackageManager = {\n name: 'pnpm',\n label: 'pnpm',\n installCommand: 'pnpm add',\n buildCommand: 'pnpm build',\n runScriptCommand: 'pnpm',\n flags: '--ignore-workspace-root-check',\n detect: ({ installDir }) => hasLockfile(installDir, 'pnpm-lock.yaml'),\n addOverride: (pkgName, pkgVersion, opts) =>\n writeOverride('pnpm', pkgName, pkgVersion, opts),\n};\n\nexport const NPM: PackageManager = {\n name: 'npm',\n label: 'npm',\n installCommand: 'npm add',\n buildCommand: 'npm run build',\n runScriptCommand: 'npm run',\n flags: '',\n detect: ({ installDir }) => hasLockfile(installDir, 'package-lock.json'),\n addOverride: (pkgName, pkgVersion, opts) =>\n writeOverride('npm', pkgName, pkgVersion, opts),\n};\n\n// Expo is selected by upstream config (app.json / app.config.*) rather than\n// a lockfile, so its detect always returns false here.\nexport const EXPO: PackageManager = {\n name: 'expo',\n label: 'Expo',\n installCommand: 'npx expo install',\n buildCommand: 'npx expo build',\n runScriptCommand: 'npx expo run',\n flags: '',\n detect: () => false,\n addOverride: (pkgName, pkgVersion, opts) =>\n writeOverride('npm', pkgName, pkgVersion, opts),\n};\n\nexport const packageManagers: PackageManager[] = [\n BUN,\n YARN_V1,\n YARN_V2,\n PNPM,\n NPM,\n EXPO,\n];\n\nexport function detectAllPackageManagers({\n installDir,\n}: InstallDirOpt): PackageManager[] {\n return withProgress('detect-package-manager', () => {\n const matches = packageManagers.filter((pm) => pm.detect({ installDir }));\n if (matches.length === 0) {\n analytics.setTag('package-manager', 'not-detected');\n }\n return matches;\n });\n}\n","/**\n * OAuth scope resolver — every program starts from the shared\n * `WIZARD_OAUTH_SCOPES` base set and a program can layer additional\n * scopes on top via `PROGRAM_SCOPE_ADDITIONS`.\n *\n * final scope set = WIZARD_OAUTH_SCOPES ∪ programAdditions\n *\n * Additions are merged in declaration order and deduped, so a program\n * never accidentally weakens the base set — only widens it. Programs\n * not listed in `PROGRAM_SCOPE_ADDITIONS` request the unchanged\n * base set, exactly like before.\n *\n * Current additions: `McpTutorial` layers read-only on every product\n * surface (feature flags, experiments, surveys, replays, errors, web\n * analytics, LLM analytics, cohorts, persons) plus read/write on\n * annotations; `AgentSkill` adds feature-flag read/write; the default\n * `PostHogIntegration` run and the standalone `slack` flow add\n * `integration:read` for the Connect-Slack step. Persistence writes (dashboard:write,\n * insight:write, notebook:write, query:read) come for free from the\n * base set, so the tutorial's \"save as insight / pin to dashboard /\n * add to notebook\" follow-ups keep working.\n *\n * Add a new program override by extending `PROGRAM_SCOPE_ADDITIONS`\n * below — no other call-site changes required as long as the program's\n * `programId` is threaded into `getOrAskForProjectData`.\n */\n\n// IMPORTANT: type-only import. A value import would create a circular\n// dependency (setup-utils → program-scopes → program-registry →\n// posthog-integration → ... → setup-utils), and `Program` would be\n// read as `undefined` at module init. Keep this type-only and reference\n// program IDs by their string-literal value below — TypeScript still\n// catches renames via the `Partial<Record<ProgramId, ...>>` keying.\nimport type { ProgramId } from '@lib/programs/program-registry';\nimport {\n WIZARD_OAUTH_SCOPES,\n WIZARD_PROVISIONING_SCOPES,\n} from '@lib/constants';\n\n/**\n * Extra scopes the MCP tutorial needs on top of `WIZARD_OAUTH_SCOPES`.\n *\n * Every scope requested here must stay within the wizard OAuth app's\n * ceiling on the PostHog side (`OAuthApplication.scopes`) — the full\n * list lives in the README under \"OAuth app scope ceiling\". The\n * tutorial's prompts and follow-ups touch most of the read surface,\n * plus annotation write for the \"PostHog wizard install\" verify-prompt.\n *\n * Already in the base `WIZARD_OAUTH_SCOPES` (and therefore not\n * repeated here):\n * • user:read, project:read, llm_gateway:read — auth + gateway\n * • query:read — HogQL\n * • dashboard:write, insight:write, notebook:write — Phase-5 persist\n *\n * Deliberately omitted (writes on read-only product surfaces):\n * • feature_flag:write, experiment:write, survey:write,\n * cohort:write, session_recording:write, error_tracking:write,\n * alert:write, subscription:write\n */\nexport const MCP_TUTORIAL_SCOPE_ADDITIONS = [\n // Explicit reads on the persistence surfaces. `*:write` usually\n // implies read on PostHog, but the consent flow grants exactly the\n // strings requested — explicit reads avoid a 403 when the agent\n // lists existing dashboards/insights/notebooks before saving.\n 'dashboard:read',\n 'insight:read',\n 'notebook:read',\n\n // Read on every product surface the tutorial demos.\n 'feature_flag:read',\n 'experiment:read',\n 'experiment_saved_metric:read',\n 'survey:read',\n 'session_recording:read',\n 'error_tracking:read',\n 'web_analytics:read',\n 'llm_analytics:read',\n 'cohort:read',\n 'person:read',\n\n // Annotation read + write — the verify prompt's \"annotate today\"\n // is the only mutation the tutorial performs outside the\n // dashboard/insight/notebook persistence triplet.\n 'annotation:read',\n 'annotation:write',\n\n // Metadata / exploration reads — for \"break down by user property\",\n // \"did that change land alongside a deploy\", autocapture actions,\n // etc. Otherwise the agent 403s on the supporting catalog calls\n // even though the parent query has `query:read`.\n 'activity_log:read',\n 'property_definition:read',\n 'event_definition:read',\n 'action:read',\n\n // Data warehouse reads — for the data-role cross-sells that join\n // event data with Stripe / Salesforce / S3.\n 'warehouse_table:read',\n 'warehouse_view:read',\n\n // Inspection-only — we don't write alerts or subscriptions, but the\n // model might want to read existing ones (e.g. \"is there already an\n // alert on this metric?\").\n 'alert:read',\n 'subscription:read',\n 'integration:read',\n] as const;\n\n/**\n * Extra scopes the agent-skill program needs on top of `WIZARD_OAUTH_SCOPES`.\n *\n * Skills under this program (e.g. `creating-product-tours`) create feature\n * flags during the install flow. PostHog's consent grants exactly the scope\n * strings requested — `:write` does not imply `:read` — so listing existing\n * flags to avoid key collisions needs `feature_flag:read` explicitly.\n * `property_definition:read` lets the agent discover person properties when\n * building flag rollout filters instead of having to ask the user verbatim.\n */\nexport const AGENT_SKILL_SCOPE_ADDITIONS = [\n 'feature_flag:read',\n 'feature_flag:write',\n 'property_definition:read',\n] as const;\n\n/**\n * Extra scopes the self-driving program needs on top of\n * `WIZARD_OAUTH_SCOPES`. All consumed by the PostHog MCP tools the\n * agent drives during the run:\n * • task:read / task:write — the signal source config API\n * (`inbox-source-configs-*`) is permissioned under the generic\n * `task` scope object, NOT a signals-specific one. Unrelated to\n * the Tasks product.\n * • integration:read — `integrations-list`, to check whether the\n * team already has a GitHub integration and to verify the connect\n * flow completed.\n * • signal_scout:read / signal_scout:write — list, sync, and tune\n * the Signals scout troop (`signals-scout-config-*`).\n * • session_recording:read / survey:read / error_tracking:read —\n * server-side product-usage probes (`query-session-recordings-list`,\n * `survey-list`, `error-issue-list`). Product usage is a\n * project-level fact (often instrumented in another repo or via\n * the snippet), so the agent asks the server instead of inferring\n * only from the local setup report. All three are read-only and\n * already in the wizard OAuth app's production scope ceiling (the\n * mcp-tutorial program requests them).\n * • external_data_source:read / external_data_source:write — the\n * connected-tools step creates the GitHub Issues / Linear warehouse\n * sources directly (`external-data-sources-create`) and verifies\n * what's actually connected (`external-data-sources-list`) instead\n * of taking the user's word for it.\n * • llm_skill:read / llm_skill:write — the custom-scouts step\n * (skill step 6b): read the seeded `authoring-signals-scouts`\n * guide and canonical scout bodies (`llma-skill-get` /\n * `llma-skill-file-get`) and author the user-approved custom\n * `signals-scout-*` skills (`llma-skill-create`). Canonical scout\n * bodies are never edited.\n * • product_enablement:write — the \"Enable products\" step turns on\n * Session Replay / Error Tracking / Support so their sources have\n * data to read (`products-enable`). A purpose-built scope: the\n * server owns each enable recipe, so this can flip the product\n * toggles without the far broader `project:write`.\n * • replay_scanner:read / replay_scanner:write — the Replay Vision\n * scanners step (skill step 6c) lists the team's existing scanners\n * and creates the `emits_signals` ones whose findings land in the\n * inbox (`vision-scanners-list` / `-create` / `-update`, and the\n * advisory `vision-scanners-estimate-create` / `vision-quota-retrieve`).\n * The scope OBJECT is `replay_scanner` — the `vision-scanners-*`\n * names are MCP tool names, not scopes. Configuring a scanner also\n * requires `session_recording:read` (the API pairs the two, since a\n * scanner's config indirectly exposes recording contents); that one\n * is already in this list for the step-2 usage probes.\n *\n * No OAuth-ceiling edit is needed for any scope here: they are all normal\n * public (unprivileged, non-internal, non-hidden) scope objects, and the\n * live wizard apps' ceiling is the `@default` sentinel, which resolves to\n * every such scope (`UNPRIVILEGED_SCOPES`) and auto-tracks new ones. Only a\n * privileged/internal/hidden object (e.g. `llm_gateway:*`) would need a\n * manual per-app edit. See README → \"OAuth app scope ceiling\".\n */\nexport const SELF_DRIVING_SCOPE_ADDITIONS = [\n 'task:read',\n 'task:write',\n 'integration:read',\n 'signal_scout:read',\n 'signal_scout:write',\n 'session_recording:read',\n 'survey:read',\n 'error_tracking:read',\n 'external_data_source:read',\n 'external_data_source:write',\n 'llm_skill:read',\n 'llm_skill:write',\n 'product_enablement:write',\n 'replay_scanner:read',\n 'replay_scanner:write',\n] as const;\n\n/**\n * Extra scopes the warehouse-source program needs on top of\n * `WIZARD_OAUTH_SCOPES`. The agent creates data warehouse sources directly\n * (`external-data-sources-create`) and lists what's connected\n * (`external-data-sources-list`) to verify the result. Both are already within\n * the wizard OAuth app's scope ceiling — the self-driving program requests the\n * same pair.\n */\nexport const WAREHOUSE_SOURCE_SCOPE_ADDITIONS = [\n 'external_data_source:read',\n 'external_data_source:write',\n] as const;\n\n/**\n * Extra scope the Connect-Slack step needs on top of `WIZARD_OAUTH_SCOPES`.\n *\n * The step polls `/api/projects/:id/integrations/` (`fetchSlackConnected`)\n * to render the already-connected variant and to flip live once the user\n * completes the Slack OAuth step in the browser. Without `integration:read`\n * the first poll 403s, the screen stops polling, and an already-connected\n * project is nagged with the connect nudge. Used by the default integration\n * run (the step ends the run) and by the standalone `wizard slack` flow\n * (the step is the whole program).\n */\nexport const CONNECT_SLACK_SCOPE_ADDITIONS = ['integration:read'] as const;\n\n/**\n * Extra scopes the replay-vision program needs on top of `WIZARD_OAUTH_SCOPES`.\n * The same set self-driving's step 6c uses, narrowed to just this flow:\n * • replay_scanner:read / replay_scanner:write — the scanner tasks list the\n * team's existing scanners and create the ones scoped to the product's key\n * flows (`vision-scanners-list` / `-create`, plus the advisory\n * `vision-scanners-estimate-create` / `vision-quota-retrieve`). The scope\n * OBJECT is `replay_scanner`; `vision-scanners-*` are MCP tool names.\n * • session_recording:read — the scanner API pairs it with\n * `replay_scanner:*`, since a scanner's config indirectly exposes\n * recording contents. Configuring a scanner fails without it.\n * • product_enablement:write — the enable-replay task's server half turns on\n * Session Replay (`products-enable`) so there are recordings to scan.\n *\n * Without these the PostHog MCP omits the tools from the catalog it serves\n * this token, every scanner task takes its \"tool unknown\" skip path, and the\n * run reports success having created nothing (run 69afc6f8).\n *\n * No OAuth-ceiling edit needed — all are unprivileged public scope objects\n * covered by the apps' `@default` sentinel, and self-driving already requests\n * every one of them.\n */\nexport const REPLAY_VISION_SCOPE_ADDITIONS = [\n 'session_recording:read',\n 'product_enablement:write',\n 'replay_scanner:read',\n 'replay_scanner:write',\n] as const;\n\n/**\n * Per-program scope additions, layered on top of `WIZARD_OAUTH_SCOPES`.\n *\n * Programs not listed here request the unchanged base set. Use this\n * map only for programs that need *more* than the base — never for\n * narrowing, since narrowing risks breaking shared infrastructure\n * (e.g. dropping `llm_gateway:read` would 401 every agent call).\n *\n * Keyed by `ProgramId` so TypeScript catches stale entries when a\n * program is renamed or removed.\n */\nconst PROGRAM_SCOPE_ADDITIONS: Partial<Record<ProgramId, readonly string[]>> = {\n // String literal (not `Program.McpTutorial`) to avoid a runtime cycle\n // with `program-registry.ts`. The `Partial<Record<ProgramId, ...>>`\n // key constraint catches renames at compile time — if `mcpTutorialConfig.id`\n // ever changes, this line will fail to type-check.\n 'mcp-tutorial': MCP_TUTORIAL_SCOPE_ADDITIONS,\n 'agent-skill': AGENT_SKILL_SCOPE_ADDITIONS,\n 'self-driving': SELF_DRIVING_SCOPE_ADDITIONS,\n 'warehouse-source': WAREHOUSE_SOURCE_SCOPE_ADDITIONS,\n // The integration run carries the Slack outro step, and — when detection\n // finds data sources — the orchestrator's warehouse task, which creates\n // sources through `external-data-sources-create`. Without the warehouse pair\n // that call 403s on a token the user already granted.\n 'posthog-integration': [\n ...CONNECT_SLACK_SCOPE_ADDITIONS,\n ...WAREHOUSE_SOURCE_SCOPE_ADDITIONS,\n ],\n slack: CONNECT_SLACK_SCOPE_ADDITIONS,\n 'replay-vision': REPLAY_VISION_SCOPE_ADDITIONS,\n};\n\n/**\n * Resolve the OAuth scope list to request for a given program. Returns\n * `WIZARD_OAUTH_SCOPES` for programs without an addition entry; for\n * programs that do have one, returns the union of base + additions\n * with duplicates dropped (declaration order preserved, base first).\n *\n * `null` / `undefined` programId falls through to the default — same\n * behavior as the historical hardcoded `WIZARD_OAUTH_SCOPES` reference\n * in `askForWizardLogin`, so call sites that haven't been updated to\n * pass a programId continue to work unchanged.\n */\nexport function getOAuthScopesForProgram(\n programId: ProgramId | null | undefined,\n): readonly string[] {\n const additions = (programId && PROGRAM_SCOPE_ADDITIONS[programId]) || [];\n if (additions.length === 0) {\n return WIZARD_OAUTH_SCOPES;\n }\n // Dedupe while preserving order; base scopes appear first so the\n // consent screen shows them in their familiar slot.\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const s of [...WIZARD_OAUTH_SCOPES, ...additions]) {\n if (seen.has(s)) continue;\n seen.add(s);\n merged.push(s);\n }\n return merged;\n}\n\n/**\n * Resolve the scope list for the signup provisioning path. Same\n * base-plus-additions shape as `getOAuthScopesForProgram`, but layered on\n * `WIZARD_PROVISIONING_SCOPES` so a program's extra scopes only reach\n * tokens provisioned for that program.\n */\nexport function getProvisioningScopesForProgram(\n programId: ProgramId | null | undefined,\n): readonly string[] {\n const additions = (programId && PROGRAM_SCOPE_ADDITIONS[programId]) || [];\n if (additions.length === 0) {\n return WIZARD_PROVISIONING_SCOPES;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const s of [...WIZARD_PROVISIONING_SCOPES, ...additions]) {\n if (seen.has(s)) continue;\n seen.add(s);\n merged.push(s);\n }\n return merged;\n}\n","/**\n * HostResolution — the single, immutable snapshot of where the wizard talks to\n * PostHog for one run.\n *\n * One cloud region (or a pinned `--base-url`) implies a whole family of hosts:\n * the event-ingestion/API host, the user-facing web app host, the CDN asset\n * host, the LLM gateway, and the MCP server. Rather than re-deriving each of\n * these at every call site and threading `region` + `baseUrl` around as loose\n * params, resolve once at auth time and pass this frozen object around — read\n * the property you need.\n *\n * The actual region→URL math (and the `--base-url` override) lives in\n * `@utils/urls`; this class is a thin, immutable façade over those resolvers so\n * the override flows through every field without callers having to know about\n * it. The OAuth-server URL stays in `@utils/urls` (`getOAuthUrl`) because it is\n * needed *before* a region is known, so it can't come from this post-auth object.\n */\n\nimport {\n getHost,\n getCloudUrl,\n getLlmGatewayUrl,\n getUiHostFromHost,\n detectRegion,\n resolveBaseUrl,\n} from '@utils/urls';\nimport { IS_PRODUCTION_BUILD, runtimeEnv } from '@env';\nimport { MCP_LOCAL_URL } from '@lib/local-dev';\nimport type { CloudRegion } from '@utils/types';\n\n// The wizard's client gets CLI mode (a single `exec` tool) by server default,\n// so no mode is pinned; the dev env override (see env.ts) is taken verbatim.\nconst MCP_PROD_URL = 'https://mcp.posthog.com/mcp';\n\n/** Construction-time inputs that aren't implied by the region. */\nexport interface HostResolutionOptions {\n /** `--local-mcp`: the MCP url only; skills follow `--local-context-mill`. */\n localMcp?: boolean;\n /** `--base-url`: pin every PostHog origin to one URL, bypassing region resolution. */\n baseUrl?: string;\n /** `--region`: trust the explicitly-provided region. */\n region?: CloudRegion;\n}\n\nfunction assetHostFor(region: CloudRegion, baseUrl?: string): string {\n const override = resolveBaseUrl(baseUrl);\n if (override) return override;\n return region === 'eu'\n ? 'https://eu-assets.i.posthog.com'\n : 'https://us-assets.i.posthog.com';\n}\n\nfunction assetHostFromApiHost(apiHost: string): string {\n if (apiHost.includes('us.i.posthog.com')) {\n return 'https://us-assets.i.posthog.com';\n }\n if (apiHost.includes('eu.i.posthog.com')) {\n return 'https://eu-assets.i.posthog.com';\n }\n return apiHost;\n}\n\n/**\n * Dev/CI only: the env override (see env.ts) wins even under --local-mcp;\n * published builds strip the read. Don't name that env var in comments here —\n * smoke-test.sh greps dist/*.js for it, and JSDoc survives bundling.\n */\nexport function mcpUrlFor(localMcp: boolean): string {\n const override = IS_PRODUCTION_BUILD ? undefined : runtimeEnv('MCP_URL');\n if (override) return override;\n return localMcp ? MCP_LOCAL_URL : MCP_PROD_URL;\n}\n\nexport class HostResolution {\n /** The resolved cloud region. `'us'` when a base URL is pinned. */\n readonly region: CloudRegion;\n /**\n * Event-ingestion / REST API host (e.g. `https://us.i.posthog.com`, or the\n * pinned `--base-url`). The SDK `host` written into the user's `.env`, the\n * base for the wizard-session REST calls, and the host shown to the agent.\n */\n readonly apiHost: string;\n /**\n * User-facing web app host (e.g. `https://us.posthog.com`). Use for any link\n * we hand to the user or open in their browser (dashboards, settings, inbox,\n * deep-link base).\n */\n readonly appHost: string;\n /** CDN asset host (e.g. `https://us-assets.i.posthog.com`). */\n readonly assetHost: string;\n /** PostHog LLM gateway URL the agent SDK authenticates its model calls against. */\n readonly gatewayUrl: string;\n /**\n * PostHog MCP server URL the agent connects to. Region-independent — the\n * server resolves the user's region from the bearer token — so this is driven\n * only by `--local-mcp` / `--local-dev` and the dev env override, not by\n * region/base-url.\n */\n readonly mcpUrl: string;\n\n private constructor(fields: {\n region: CloudRegion;\n apiHost: string;\n appHost: string;\n assetHost: string;\n gatewayUrl: string;\n mcpUrl: string;\n }) {\n this.region = fields.region;\n this.apiHost = fields.apiHost;\n this.appHost = fields.appHost;\n this.assetHost = fields.assetHost;\n this.gatewayUrl = fields.gatewayUrl;\n this.mcpUrl = fields.mcpUrl;\n Object.freeze(this);\n }\n\n /**\n * Canonical path: build the host family from a resolved region. A pinned\n * `--base-url` (via `opts.baseUrl`) wins for every origin; otherwise the\n * region's standard hosts are used. Honors IS_DEV through `resolveBaseUrl`.\n */\n static fromRegion(\n region: CloudRegion,\n opts: HostResolutionOptions = {},\n ): HostResolution {\n const apiHost = getHost(region, opts.baseUrl);\n return new HostResolution({\n region,\n apiHost,\n appHost: getCloudUrl(region, opts.baseUrl),\n assetHost: assetHostFor(region, opts.baseUrl),\n gatewayUrl: getLlmGatewayUrl(apiHost),\n mcpUrl: mcpUrlFor(opts.localMcp ?? false),\n });\n }\n\n /**\n * Build from an ingestion host string (the provisioning API returns one). The\n * given host is preserved verbatim as `apiHost`; the region and the derived\n * app/asset/gateway hosts are inferred from it.\n */\n static fromApiHost(\n apiHost: string,\n opts: Pick<HostResolutionOptions, 'localMcp'> = {},\n ): HostResolution {\n const region: CloudRegion = apiHost.includes('eu.') ? 'eu' : 'us';\n return new HostResolution({\n region,\n apiHost,\n appHost: getUiHostFromHost(apiHost),\n assetHost: assetHostFromApiHost(apiHost),\n gatewayUrl: getLlmGatewayUrl(apiHost),\n mcpUrl: mcpUrlFor(opts.localMcp ?? false),\n });\n }\n\n /**\n * Resolve the region from an access token (the us/eu probe, skipped when a\n * base URL is pinned), then build the host family. Used after OAuth and after\n * CI-mode API-key auth.\n */\n static async fromAccessToken(\n accessToken: string,\n opts: HostResolutionOptions = {},\n ): Promise<HostResolution> {\n const region =\n opts.region ?? (await detectRegion(accessToken, opts.baseUrl));\n return HostResolution.fromRegion(region, opts);\n }\n}\n","/**\n * OAuth failure presentation — the structured error the flow throws and the\n * user-facing messaging built from it.\n *\n * `oauth.ts` owns the flow machinery (callback server, token exchange, port\n * retries); this module owns what a failure *means*: the RFC 6749 error\n * fields (`error`, `error_description`, `error_uri`), per-code remediation\n * copy, and safe rendering for the browser callback page. Everything here is\n * pure so the copy can be unit-tested without the HTTP machinery.\n */\n\nimport { z } from 'zod';\nimport {\n ISSUES_URL,\n POSTHOG_STATUS_PAGE_URL,\n WIZARD_CONTACT_EMAIL,\n} from '@lib/constants';\n\n/**\n * A structured OAuth failure (RFC 6749 §4.1.2.1 authorize errors, §5.2 token\n * errors). Thrown by both the authorize callback and the token exchange so\n * the flow's error handler keys remediation copy and analytics fingerprints\n * off `code` instead of re-parsing `message`.\n *\n * The message stays exactly `OAuth error: <code>` — the analytics fingerprint\n * scheme (`wizard_oauth_<code>`) and the legacy message-prefix parsing both\n * depend on that shape. The description/uri ride along as properties.\n *\n * NAMING: never bind an instance to a variable or property whose name\n * contains \"oauth\" (use `flowError`, `callbackError`, ...). CodeQL's\n * clear-text-logging heuristic classifies any `*oauth*`-named variable read\n * as password data, and these errors are deliberately shown to the user, so\n * such a binding flags every log statement downstream of it (CWE-312).\n */\nexport class OAuthError extends Error {\n readonly code: string;\n /** The server's human-readable explanation (`error_description`), if sent. */\n readonly description?: string;\n /** The server's \"more info\" link (`error_uri`), if sent. */\n readonly uri?: string;\n\n constructor(code: string, description?: string, uri?: string) {\n super(`OAuth error: ${code}`);\n this.name = 'OAuthError';\n this.code = code;\n this.description = description;\n this.uri = uri;\n }\n}\n\n/**\n * Sanitize an OAuth error param before logging or rendering it: these arrive\n * on a query string (or a token-endpoint body) that anything able to hit the\n * local callback port can populate. Strips non-printable/non-ASCII characters\n * and caps the length. Returns undefined when nothing printable remains.\n */\nexport function sanitizeOAuthParam(\n value: string | null | undefined,\n maxLength = 200,\n): string | undefined {\n if (!value) return undefined;\n const cleaned = value\n .replace(/[^\\x20-\\x7e]/g, '')\n .slice(0, maxLength)\n .trim();\n return cleaned || undefined;\n}\n\n/** Description sentences get more room than bare codes/URIs. */\nconst MAX_DESCRIPTION_LENGTH = 500;\n\nexport function escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\nconst OAuthErrorBodySchema = z.object({\n error: z.string().min(1),\n error_description: z.string().optional(),\n error_uri: z.string().optional(),\n});\n\n/**\n * Build an `OAuthError` from an authorize-callback's query params.\n * Sanitizes every field — the callback URL is attacker-reachable input.\n */\nexport function oauthErrorFromCallbackParams(\n params: URLSearchParams,\n): OAuthError {\n return new OAuthError(\n sanitizeOAuthParam(params.get('error')) ?? 'unknown',\n sanitizeOAuthParam(params.get('error_description'), MAX_DESCRIPTION_LENGTH),\n sanitizeOAuthParam(params.get('error_uri')),\n );\n}\n\n/**\n * Build an `OAuthError` from a token-endpoint JSON error body (RFC 6749\n * §5.2). Returns null when the body isn't an OAuth error shape (HTML error\n * pages, proxy bodies, network failures) — the caller rethrows the raw\n * error in that case.\n */\nexport function oauthErrorFromTokenBody(data: unknown): OAuthError | null {\n const parsed = OAuthErrorBodySchema.safeParse(data);\n if (!parsed.success) return null;\n return new OAuthError(\n sanitizeOAuthParam(parsed.data.error) ?? 'unknown',\n sanitizeOAuthParam(parsed.data.error_description, MAX_DESCRIPTION_LENGTH),\n sanitizeOAuthParam(parsed.data.error_uri),\n );\n}\n\n/**\n * The error paragraphs for the browser callback page. The constant framing\n * (title, styles, \"return to your terminal\") stays in `oauth.ts`; this owns\n * the part that varies by error, with everything HTML-escaped since the\n * values come straight off the callback query string.\n */\nexport function buildCallbackErrorHtml(error: OAuthError): string {\n if (error.code === 'access_denied') {\n return '<p>Authorization cancelled.</p>';\n }\n const paragraphs = [\n `<p>Authorization failed (${escapeHtml(error.code)}).</p>`,\n ];\n if (error.description) {\n paragraphs.push(`<p>${escapeHtml(error.description)}</p>`);\n }\n if (error.uri) {\n paragraphs.push(`<p>More info: ${escapeHtml(error.uri)}</p>`);\n }\n return paragraphs.join('\\n');\n}\n\ninterface FailureMessageParams {\n error: Error;\n /** Scopes the flow requested (base set + program additions). */\n requestedScopes: readonly string[];\n clientId: string;\n /** OAuth server origin the flow targeted. */\n oauthUrl: string;\n /**\n * True when the flow targets a dev-seeded stack (IS_DEV build or a pinned\n * `--base-url`) — selects the \"fix your local OAuth app\" remediation over\n * the production-runbook one. Same condition that selects the dev client ID.\n */\n isDevStack: boolean;\n}\n\n/**\n * Per-code headline + \"what to do\" remediation for the terminal failure\n * message. Codes not listed fall through to a generic rendering of the\n * error. `access_denied` and the flow timeout never reach this — they keep\n * their dedicated handling in `performOAuthFlow`.\n */\nfunction headlineAndRemediation(params: FailureMessageParams): {\n headline: string;\n whatToDo?: string;\n} {\n const { error, oauthUrl, isDevStack } = params;\n if (!(error instanceof OAuthError)) {\n return { headline: error.message };\n }\n\n switch (error.code) {\n case 'invalid_scope':\n return {\n headline:\n 'PostHog rejected one or more of the requested scopes (invalid_scope).',\n whatToDo: isDevStack\n ? 'The wizard OAuth app on your local stack allows fewer scopes than the wizard requests (its OAuthApplication.scopes ceiling). Re-run your local wizard OAuth app setup so it allows every scope listed below, or add the missing ones in Django admin, then try again.'\n : `The wizard OAuth app's server-side scope ceiling (OAuthApplication.scopes) is missing scopes the wizard requests. This needs a fix on the PostHog side, so email ${WIZARD_CONTACT_EMAIL} with the details below (PostHog staff: the \"scope-ceiling-invalid-scope\" runbook in PostHog/runbooks has the fix). Re-running the wizard will not help until the ceiling is updated.`,\n };\n case 'invalid_client':\n return {\n headline: `PostHog at ${oauthUrl} does not recognize the wizard's OAuth client (invalid_client).`,\n whatToDo:\n 'The client ID below is not registered on the target instance. If you pointed the wizard at a local or self-hosted stack (--base-url), seed its wizard OAuth app first; otherwise re-run without --base-url to use PostHog Cloud.',\n };\n case 'invalid_grant':\n return {\n headline:\n 'The login code was rejected (invalid_grant): it expired or was already used.',\n whatToDo:\n 'Re-run the wizard and complete the browser login promptly. Login codes expire after 5 minutes and can only be used once.',\n };\n case 'server_error':\n return {\n headline:\n \"PostHog's OAuth server hit an internal error (server_error).\",\n whatToDo: `This is usually transient. Wait a moment and re-run the wizard. If it keeps failing, check ${POSTHOG_STATUS_PAGE_URL}.`,\n };\n case 'temporarily_unavailable':\n return {\n headline:\n \"PostHog's OAuth server is temporarily unavailable (temporarily_unavailable).\",\n whatToDo: `This is usually transient. Wait a moment and re-run the wizard. If it keeps failing, check ${POSTHOG_STATUS_PAGE_URL}.`,\n };\n default:\n return {\n headline: `PostHog returned an OAuth error: ${error.code}.`,\n whatToDo:\n 'Re-run the wizard. If the error persists, include the details below when asking for help.',\n };\n }\n}\n\n/**\n * Terminal message for a failed OAuth flow. Always ends with the request\n * context (target host, client ID, requested scopes) so a pasted bug report\n * is actionable without follow-up questions, plus how to get help: the\n * support email (Zendesk-backed) and the issues link.\n */\nexport function buildOAuthFailureMessage(params: FailureMessageParams): string {\n const { error, requestedScopes, clientId, oauthUrl } = params;\n const flowError = error instanceof OAuthError ? error : null;\n const { headline, whatToDo } = headlineAndRemediation(params);\n\n const sections = [`Authorization failed: ${headline}`];\n if (flowError?.description) {\n sections.push(`The server said: ${flowError.description}`);\n }\n if (flowError?.uri) {\n sections.push(`More info: ${flowError.uri}`);\n }\n if (whatToDo) {\n sections.push(`What to do: ${whatToDo}`);\n }\n sections.push(\n [\n 'Details for bug reports:',\n ` target host: ${oauthUrl}`,\n ` client ID: ${clientId}`,\n ` requested scopes: ${requestedScopes.join(' ')}`,\n ].join('\\n'),\n );\n sections.push(\n `Need help? Email ${WIZARD_CONTACT_EMAIL} with the details above, or create an issue:\\n${ISSUES_URL}`,\n );\n return sections.join('\\n\\n');\n}\n","import * as crypto from 'node:crypto';\nimport * as http from 'node:http';\nimport { execSync } from 'node:child_process';\nimport axios from 'axios';\nimport { logToFile } from './debug';\nimport { z } from 'zod';\nimport { getUI } from '@ui';\nimport {\n OAUTH_PORTS,\n OAUTH_TIMEOUT_MS,\n POSTHOG_DEV_CLIENT_ID,\n POSTHOG_PROXY_CLIENT_ID,\n WIZARD_USER_AGENT,\n} from '@lib/constants';\nimport { getOAuthUrl, resolveBaseUrl } from './urls';\nimport { abort } from './setup-utils';\nimport { openTrackedLink, withUtm } from './links';\nimport { analytics } from './analytics';\nimport {\n OAuthError,\n buildCallbackErrorHtml,\n buildOAuthFailureMessage,\n oauthErrorFromCallbackParams,\n oauthErrorFromTokenBody,\n} from './oauth-errors';\n\nconst OAUTH_CALLBACK_STYLES = `\n <style>\n * {\n font-family: monospace;\n background-color: #1b0a00;\n color: #F7A502;\n font-weight: medium;\n font-size: 24px;\n margin: .25rem;\n }\n\n .blink {\n animation: blink-animation 1s steps(2, start) infinite;\n }\n\n @keyframes blink-animation {\n to {\n opacity: 0;\n }\n }\n </style>\n`;\n\nexport const OAuthTokenResponseSchema = z.object({\n access_token: z.string(),\n expires_in: z.number(),\n token_type: z.string(),\n scope: z.string(),\n refresh_token: z.string().optional(),\n scoped_teams: z.array(z.number()).optional(),\n scoped_organizations: z.array(z.string()).optional(),\n // Sent by PostHog Cloud (and passed through the oauth.posthog.com proxy); absent on\n // self-hosted. `.catch(undefined)` so an unrecognized value degrades to the probe\n // fallback instead of failing the whole login.\n posthog_region: z.enum(['us', 'eu']).optional().catch(undefined),\n posthog_base_url: z.string().optional().catch(undefined),\n});\n\nexport type OAuthTokenResponse = z.infer<typeof OAuthTokenResponseSchema>;\n\nexport const WIZARD_COMPLETION_SCOPE = 'event_definition:write';\n\nexport function parseOAuthScopes(scope: string): string[] {\n return scope.split(/\\s+/).filter(Boolean);\n}\n\n/**\n * Requested scopes the grant came back without.\n *\n * A token can legitimately carry fewer scopes than the wizard asked for: the\n * consent screen lets the user deselect any scope the OAuth app doesn't mark\n * required, and anything outside the app's ceiling is clamped server-side.\n * Neither path is an error — `/oauth/token` just returns a narrower `scope`.\n * Diff it at login, where the gap is fixable, rather than letting the run\n * discover it as a permission failure on some API call minutes in.\n */\nexport function missingOAuthScopes(\n requested: readonly string[],\n grantedScope: string,\n): string[] {\n const granted = new Set(parseOAuthScopes(grantedScope));\n return requested.filter((scope) => !granted.has(scope));\n}\n\nexport function assertWizardCompletionScope(scope: string): void {\n if (parseOAuthScopes(scope).includes(WIZARD_COMPLETION_SCOPE)) return;\n\n throw new Error(\n `This run was authorized without the ${WIZARD_COMPLETION_SCOPE} permission, which the wizard needs to finish setup. Please try again, approving all permissions on the PostHog authorization screen. If that screen does not reappear, revoke the existing PostHog Wizard authorization in your PostHog settings first.`,\n );\n}\n\n// Stable marker for the authorization-flow timeout. Detection keys off the exact\n// message rather than a loose substring — `.includes('timeout')` never matched\n// `'timed out'`, which silently routed timeouts to the generic failure message.\nconst AUTHORIZATION_TIMEOUT_MESSAGE = 'Authorization timed out';\n\nexport function isAuthorizationTimeout(error: Error): boolean {\n return error.message === AUTHORIZATION_TIMEOUT_MESSAGE;\n}\n\ninterface OAuthConfig {\n scopes: string[];\n signup?: boolean;\n /** Project to pre-select on the consent screen (the `--project-id` flag). */\n projectId?: number;\n /**\n * Explicit base URL override (`--base-url`, from `session.baseUrl`). Pins the\n * OAuth server and selects the matching client ID.\n */\n baseUrl?: string;\n}\n\n/**\n * OAuth client ID for the current target. A pinned base URL (`--base-url`, or\n * IS_DEV's implicit localhost) means we're talking to a dev-seeded stack, which\n * registers the dev client; prod uses the proxy client.\n *\n * TODO: this assumes any pinned base URL is a dev-seeded instance that\n * registers POSTHOG_DEV_CLIENT_ID. If we ever point `--base-url` at a non-dev\n * instance with its own OAuth app, make the client ID configurable (e.g. a\n * `--oauth-client-id` flag) instead of always falling back to the dev client.\n */\nfunction getOAuthClientId(baseUrl?: string): string {\n return resolveBaseUrl(baseUrl)\n ? POSTHOG_DEV_CLIENT_ID\n : POSTHOG_PROXY_CLIENT_ID;\n}\n\nfunction getLocalOAuthOrigin(port: number): string {\n return `http://localhost:${port}`;\n}\n\nfunction getCallbackUrl(port: number): string {\n return `${getLocalOAuthOrigin(port)}/callback`;\n}\n\nfunction getLocalLoginUrl(port: number): string {\n return `${getLocalOAuthOrigin(port)}/authorize`;\n}\n\nfunction getLocalSignupUrl(port: number): string {\n return `${getLocalLoginUrl(port)}?signup=true`;\n}\n\n/**\n * Extract an OAuth authorization code from raw user input. Accepts either the\n * bare code, the full callback URL the browser was redirected to\n * (`http://localhost:8239/callback?code=abc123&...`), or just the query\n * string. Returns null when no code can be found.\n *\n * This backs the manual-entry fallback: in headless/remote environments the\n * browser can't reach the wizard's local callback server, so the user copies\n * the failed callback URL (or the code from it) back into the terminal.\n */\nexport function extractOAuthCode(input: string): string | null {\n const trimmed = input.trim();\n if (!trimmed) return null;\n\n // Full URL — pull the `code` query param.\n let looksLikeUrl = false;\n try {\n const url = new URL(trimmed);\n looksLikeUrl = true;\n const code = url.searchParams.get('code');\n if (code) return code;\n } catch {\n // Not a parseable URL — fall through to the looser checks below.\n }\n\n // A pasted query string or `code=...` fragment.\n const match = trimmed.match(/[?&]?code=([^&\\s]+)/);\n if (match) return decodeURIComponent(match[1]);\n\n // A URL with no code is invalid — don't mistake the whole URL for a code.\n if (looksLikeUrl) return null;\n\n // Otherwise treat the whole input as the bare code (no embedded whitespace).\n if (!/\\s/.test(trimmed)) return trimmed;\n\n return null;\n}\n\nfunction generateCodeVerifier(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\nfunction generateCodeChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\nasync function startCallbackServer(\n authUrl: string,\n signupUrl: string,\n port: number,\n): Promise<{\n port: number;\n server: http.Server;\n waitForCallback: () => Promise<string>;\n}> {\n return new Promise((resolve, reject) => {\n let callbackResolve: (code: string) => void;\n let callbackReject: (error: Error) => void;\n\n const waitForCallback = () =>\n new Promise<string>((res, rej) => {\n callbackResolve = res;\n callbackReject = rej;\n });\n\n const server = http.createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400);\n res.end();\n return;\n }\n const url = new URL(req.url, getLocalOAuthOrigin(port));\n\n if (url.pathname === '/authorize') {\n const isSignup = url.searchParams.get('signup') === 'true';\n const redirectUrl = isSignup ? signupUrl : authUrl;\n res.writeHead(302, { Location: redirectUrl });\n res.end();\n return;\n }\n\n const code = url.searchParams.get('code');\n const error = url.searchParams.get('error');\n\n if (error) {\n // Carries error_description / error_uri (RFC 6749 §4.1.2.1) along\n // with the code, so the terminal message can show the server's own\n // explanation instead of just the bare code.\n const callbackError = oauthErrorFromCallbackParams(url.searchParams);\n const isAccessDenied = callbackError.code === 'access_denied';\n logToFile(\n `[oauth] callback received with error: ${callbackError.code}` +\n (callbackError.description\n ? ` (${callbackError.description})`\n : ''),\n );\n res.writeHead(isAccessDenied ? 200 : 400, {\n 'Content-Type': 'text/html; charset=utf-8',\n });\n res.end(`\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <title>PostHog wizard - Authorization ${\n isAccessDenied ? 'cancelled' : 'failed'\n }</title>\n ${OAUTH_CALLBACK_STYLES}\n </head>\n <body>\n ${buildCallbackErrorHtml(callbackError)}\n <p>Return to your terminal. This window will close automatically.</p>\n <script>window.close();</script>\n </body>\n </html>\n `);\n callbackReject(callbackError);\n return;\n }\n\n if (code) {\n logToFile('[oauth] callback received with authorization code');\n res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <title>PostHog wizard is ready</title>\n ${OAUTH_CALLBACK_STYLES}\n </head>\n <body>\n <p>PostHog login complete!</p>\n <p>Return to your terminal: the wizard is hard at work on your project<span class=\"blink\">█</span></p>\n <script>window.close();</script>\n </body>\n </html>\n `);\n callbackResolve(code);\n } else {\n res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n res.end(`\n <html>\n <head>\n <meta charset=\"UTF-8\">\n <title>PostHog wizard - Invalid request</title>\n ${OAUTH_CALLBACK_STYLES}\n </head>\n <body>\n <p>Invalid request - no authorization code received.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n `);\n }\n });\n\n server.listen(port, () => {\n resolve({ port, server, waitForCallback });\n });\n\n server.on('error', reject);\n });\n}\n\nfunction getPortProcessInfo(port: number): {\n command: string;\n pid: string;\n port: number;\n user: string;\n} {\n try {\n const output = execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {\n encoding: 'utf-8',\n timeout: 3000,\n }).trim();\n const lines = output.split('\\n');\n // First line is header, second is the process\n if (lines.length < 2)\n return { command: 'unknown', pid: 'unknown', port, user: 'unknown' };\n const fields = lines[1].split(/\\s+/);\n // lsof columns: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\n const command = fields[0] ?? 'unknown';\n const pid = fields[1] ?? 'unknown';\n const user = fields[2] ?? 'unknown';\n return { command, pid, port, user };\n } catch {\n return { command: 'unknown', pid: 'unknown', port, user: 'unknown' };\n }\n}\n\nfunction isPortInUseError(error: unknown): boolean {\n return (\n error instanceof Error &&\n 'code' in error &&\n (error as NodeJS.ErrnoException).code === 'EADDRINUSE'\n );\n}\n\nasync function exchangeCodeForToken(\n code: string,\n codeVerifier: string,\n callbackUrl: string,\n baseUrl?: string,\n): Promise<OAuthTokenResponse> {\n const clientId = getOAuthClientId(baseUrl);\n const oauthUrl = getOAuthUrl(baseUrl);\n\n logToFile(`[oauth] exchanging code for token at ${oauthUrl}/oauth/token`);\n let response;\n try {\n response = await axios.post(\n `${oauthUrl}/oauth/token`,\n {\n grant_type: 'authorization_code',\n code,\n redirect_uri: callbackUrl,\n client_id: clientId,\n code_verifier: codeVerifier,\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': WIZARD_USER_AGENT,\n },\n },\n );\n } catch (e) {\n const status = axios.isAxiosError(e) ? e.response?.status : undefined;\n logToFile(\n `[oauth] token exchange failed${status ? ` (HTTP ${status})` : ''}:`,\n e instanceof Error ? e.message : e,\n );\n // Surface the OAuth error body (RFC 6749 §5.2) when the token endpoint\n // sent one — otherwise `invalid_grant`, PKCE mismatches, etc. reach the\n // user as a bare axios \"Request failed with status code 400\".\n const exchangeError = axios.isAxiosError(e)\n ? oauthErrorFromTokenBody(e.response?.data)\n : null;\n if (exchangeError) {\n logToFile(\n `[oauth] token endpoint error: ${exchangeError.code}` +\n (exchangeError.description ? ` (${exchangeError.description})` : ''),\n );\n throw exchangeError;\n }\n throw e;\n }\n\n const token = OAuthTokenResponseSchema.parse(response.data);\n logToFile(\n `[oauth] token exchange succeeded, granted scopes: ${token.scope}` +\n `${token.posthog_region ? `, region: ${token.posthog_region}` : ''}` +\n `${\n token.scoped_teams\n ? `, scoped_teams: [${token.scoped_teams.join(', ')}]`\n : ''\n }` +\n `${\n token.scoped_organizations\n ? `, scoped_organizations: ${token.scoped_organizations.length}`\n : ''\n }`,\n );\n return token;\n}\n\n// Refresh-token grant (RFC 6749 §6); the server rotates, so callers must store the returned refresh_token.\nexport async function refreshAccessToken(\n refreshToken: string,\n baseUrl?: string,\n clientId?: string,\n): Promise<OAuthTokenResponse> {\n const oauthUrl = getOAuthUrl(baseUrl);\n logToFile(`[oauth] refreshing access token at ${oauthUrl}/oauth/token`);\n try {\n const response = await axios.post(\n `${oauthUrl}/oauth/token`,\n {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n // The grant only refreshes under its minting app — provisioning signups pass their regional client.\n client_id: clientId ?? getOAuthClientId(baseUrl),\n },\n {\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': WIZARD_USER_AGENT,\n },\n timeout: 30_000,\n },\n );\n const token = OAuthTokenResponseSchema.parse(response.data);\n logToFile('[oauth] access token refreshed');\n return token;\n } catch (e) {\n logToFile(\n '[oauth] token refresh failed:',\n e instanceof Error ? e.message : e,\n );\n const refreshError = axios.isAxiosError(e)\n ? oauthErrorFromTokenBody(e.response?.data)\n : null;\n throw refreshError ?? e;\n }\n}\n\n/**\n * Warn — at login, while the user is still watching — when the grant came back\n * narrower than the request, and record the gap so narrowed runs are countable.\n * Non-fatal by design: deselecting an optional scope is the user's call, and\n * most flows survive it. The one scope the wizard cannot run without has its\n * own hard check (`assertWizardCompletionScope`).\n */\nfunction reportNarrowedGrant(\n requestedScopes: readonly string[],\n grantedScope: string,\n): void {\n const missing = missingOAuthScopes(requestedScopes, grantedScope);\n if (missing.length === 0) return;\n\n logToFile(\n `[oauth] grant narrower than request, missing: ${missing.join(' ')}`,\n );\n analytics.wizardCapture('oauth grant narrowed', {\n requested_scopes: [...requestedScopes].sort().join(' '),\n granted_scopes: parseOAuthScopes(grantedScope).sort().join(' '),\n missing_scopes: missing.join(' '),\n missing_scope_count: missing.length,\n });\n const plural = missing.length > 1;\n getUI().log.warn(\n `Your PostHog authorization is missing ${\n plural ? `${missing.length} permissions` : 'a permission'\n } the wizard asked for: ${missing.join(', ')}. ` +\n `Setup will continue, but steps that need ${\n plural ? 'them' : 'it'\n } may fail. ` +\n `To grant ${\n plural ? 'them' : 'it'\n }, re-run the wizard and approve all permissions on the ` +\n 'authorization screen. If that screen does not reappear, revoke the ' +\n 'existing PostHog Wizard authorization in your PostHog settings first.',\n );\n}\n\nexport async function performOAuthFlow(\n config: OAuthConfig,\n): Promise<OAuthTokenResponse> {\n const clientId = getOAuthClientId(config.baseUrl);\n const oauthUrl = getOAuthUrl(config.baseUrl);\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = generateCodeChallenge(codeVerifier);\n let shouldRetry = false;\n\n logToFile(\n `[oauth] starting flow against ${oauthUrl}, ` +\n `requested scopes: ${config.scopes.join(' ')}`,\n );\n\n do {\n shouldRetry = false;\n let lastProcessInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n } | null = null;\n\n for (const port of OAUTH_PORTS) {\n const callbackUrl = getCallbackUrl(port);\n const authUrl = new URL(`${oauthUrl}/oauth/authorize`);\n authUrl.searchParams.set('client_id', clientId);\n authUrl.searchParams.set('redirect_uri', callbackUrl);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('code_challenge', codeChallenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n authUrl.searchParams.set('scope', config.scopes.join(' '));\n authUrl.searchParams.set('required_access_level', 'project');\n if (config.projectId !== undefined) {\n // Pre-select this project on the consent screen so the user just clicks Authorize.\n authUrl.searchParams.set('team_id', String(config.projectId));\n }\n\n // UTM-tag both kickoff URLs so the journey into the app is\n // attributable to the wizard command that started it.\n const taggedAuthUrl = withUtm(authUrl.toString(), 'oauth-authorize');\n const signupUrl = new URL(\n withUtm(\n `${oauthUrl}/signup?next=${encodeURIComponent(taggedAuthUrl)}`,\n 'oauth-signup',\n ),\n );\n const localSignupUrl = getLocalSignupUrl(port);\n const localLoginUrl = getLocalLoginUrl(port);\n const urlToOpen = config.signup ? localSignupUrl : localLoginUrl;\n\n logToFile(`[oauth] attempting callback server on port ${port}`);\n\n let server: http.Server;\n let waitForCallback: () => Promise<string>;\n try {\n ({ server, waitForCallback } = await startCallbackServer(\n taggedAuthUrl,\n signupUrl.toString(),\n port,\n ));\n } catch (e) {\n if (!isPortInUseError(e)) throw e;\n lastProcessInfo = getPortProcessInfo(port);\n continue;\n }\n\n logToFile('[oauth] callback server ready, showing login URL');\n\n getUI().setLoginUrl(urlToOpen);\n // The localhost proxy above only works on this machine. Surface the\n // direct PostHog authorize URL too, for the manual-paste modal — on a\n // remote/headless box the user opens it from another machine, where\n // localhost:<port> is unreachable.\n getUI().setAuthorizeUrl(\n config.signup ? signupUrl.toString() : taggedAuthUrl,\n );\n\n // The localhost proxy URL stays untagged — the PostHog destination\n // it redirects to carries the UTMs.\n openTrackedLink(urlToOpen, 'oauth', { auto: true, skipUtm: true });\n\n const loginSpinner = getUI().spinner();\n loginSpinner.start('Waiting for authorization...');\n\n try {\n // Race the local callback server against a manually-pasted code. The\n // manual path is the fallback for headless/remote shells where the\n // browser can't reach localhost — the user opens the auth screen's\n // paste modal and submits the callback URL or code by hand.\n const code = await Promise.race([\n waitForCallback(),\n getUI().waitForManualAuthCode(),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(AUTHORIZATION_TIMEOUT_MESSAGE)),\n OAUTH_TIMEOUT_MS,\n ),\n ),\n ]);\n\n const token = await exchangeCodeForToken(\n code,\n codeVerifier,\n callbackUrl,\n config.baseUrl,\n );\n\n server.close();\n getUI().setLoginUrl(null);\n getUI().setAuthorizeUrl(null);\n loginSpinner.stop('Authorization complete!');\n\n reportNarrowedGrant(config.scopes, token.scope);\n\n return token;\n } catch (e) {\n const error = e instanceof Error ? e : new Error('Unknown error');\n const timedOut = isAuthorizationTimeout(error);\n const flowError = error instanceof OAuthError ? error : null;\n\n loginSpinner.stop(\n timedOut ? 'Session timed out.' : 'Authorization failed.',\n );\n server.close();\n\n logToFile('[oauth] flow failed:', error);\n if (flowError?.description) {\n logToFile(\n `[oauth] server error_description: ${flowError.description}`,\n );\n }\n\n const accessDenied = flowError\n ? flowError.code === 'access_denied'\n : error.message.includes('access_denied');\n\n if (timedOut) {\n // Overlay bypasses the auth-step gating (which never completes\n // without credentials), so the user sees the failure instead of a\n // spinner that never stops; any key exits.\n getUI().showSessionTimeout();\n } else if (accessDenied) {\n getUI().log.info(\n `Authorization was cancelled.\\n\\nYou denied access to PostHog. To use the wizard, you need to authorize access to your PostHog account.\\n\\nYou can try again by re-running the wizard.`,\n );\n } else {\n getUI().log.error(\n buildOAuthFailureMessage({\n error,\n requestedScopes: config.scopes,\n clientId,\n oauthUrl,\n // Same condition that selects the dev client ID: a resolvable\n // base URL means a dev-seeded stack, where \"fix your local\n // OAuth app\" beats pointing at the production runbook.\n isDevStack: resolveBaseUrl(config.baseUrl) !== undefined,\n }),\n );\n }\n\n const oauthErrorCode = flowError\n ? flowError.code\n : error.message.startsWith('OAuth error: ')\n ? error.message.slice('OAuth error: '.length)\n : timedOut\n ? 'timeout'\n : 'unknown';\n\n analytics.captureException(error, {\n step: 'oauth_flow',\n oauth_error_code: oauthErrorCode,\n oauth_error_description: flowError?.description,\n client_id: clientId,\n requested_scopes: config.scopes.join(' '),\n // Collapse OAuth callback failures of the same kind into one issue\n // instead of fragmenting by each user's install path in the stack trace.\n $exception_fingerprint: `wizard_oauth_${oauthErrorCode}`,\n });\n\n await abort();\n throw error;\n }\n }\n\n if (!lastProcessInfo) {\n throw new Error('No OAuth callback ports configured');\n }\n\n await getUI().showPortConflict(lastProcessInfo);\n shouldRetry = true;\n } while (shouldRetry);\n\n throw new Error('OAuth port retry loop exited unexpectedly');\n}\n","export type GrantedProjectResolution =\n | { ok: true; projectId: number | undefined }\n | { ok: false; requested: number; granted: number };\n\n/**\n * Decide which project to use after OAuth. `--project-id` (when passed) is authoritative,\n * but only when the user granted access to it on the consent screen; a different grant is a\n * mismatch the caller must surface. With no `--project-id` this returns the granted project\n * (`scopedTeams[0]`), preserving the pre-flag behavior for every wizard program (the main\n * integration flow included).\n */\nexport function resolveGrantedProject(\n requestedProjectId: number | undefined,\n scopedTeams: number[] | undefined,\n): GrantedProjectResolution {\n // No --project-id: use whatever the user granted, exactly as before the flag existed.\n if (requestedProjectId === undefined) {\n return { ok: true, projectId: scopedTeams?.[0] };\n }\n // --project-id was among the granted teams: honor it.\n if (scopedTeams?.includes(requestedProjectId)) {\n return { ok: true, projectId: requestedProjectId };\n }\n // --project-id requested but a different project was authorized: mismatch.\n if (scopedTeams && scopedTeams.length > 0) {\n return {\n ok: false,\n requested: requestedProjectId,\n granted: scopedTeams[0],\n };\n }\n // Nothing granted at all — let the caller's \"no project access\" guard handle it.\n return { ok: true, projectId: undefined };\n}\n","import {\n major,\n minVersion,\n satisfies,\n subset,\n valid,\n validRange,\n} from 'semver';\n\n/**\n * Version strings from package.json that are not semver ranges.\n * URLs, git refs, dist-tags, local paths, workspace protocol, npm aliases, etc.\n * These should be rejected early — we can't determine a clear version from them.\n */\nfunction isNonSemverVersion(version: string): boolean {\n const v = version.trim();\n return (\n v === '' ||\n v.startsWith('http://') ||\n v.startsWith('https://') ||\n v.startsWith('git+') ||\n v.startsWith('git://') ||\n v.startsWith('file:') ||\n v.startsWith('npm:') ||\n v.startsWith('workspace:') ||\n v.startsWith('/') ||\n v.includes('/') // user/repo shorthand\n );\n}\n\nexport function versionSatisfiesRange({\n version,\n acceptableVersions,\n canBeLatest,\n}: {\n version: string;\n acceptableVersions: string;\n canBeLatest: boolean;\n}): boolean {\n if (version === 'latest') return canBeLatest;\n if (isNonSemverVersion(version)) return false;\n\n const concrete = valid(version);\n if (concrete !== null) {\n return satisfies(concrete, acceptableVersions);\n }\n\n const userRange = validRange(version);\n if (userRange === null) return false;\n return subset(userRange, acceptableVersions);\n}\n\n/**\n * Creates a version bucket function for analytics.\n * Converts versions like \"1.2.3\" to \"1.x\" for grouping in analytics.\n *\n * @param minMajorVersion - Optional minimum major version threshold.\n * Versions below this will be bucketed as \"<{min}.0.0\"\n *\n * @example\n * const getVersionBucket = createVersionBucket(); // no minimum\n * getVersionBucket(\"1.2.3\") // \"1.x\"\n *\n * const getVersionBucket = createVersionBucket(11);\n * getVersionBucket(\"15.3.0\") // \"15.x\"\n * getVersionBucket(\"10.0.0\") // \"<11.0.0\"\n */\nexport function createVersionBucket(minMajorVersion?: number) {\n return (version: string | undefined): string => {\n if (!version) {\n return 'none';\n }\n\n if (isNonSemverVersion(version)) {\n return 'unknown';\n }\n\n try {\n const minVer = minVersion(version);\n if (!minVer) {\n return 'invalid';\n }\n const majorVersion = major(minVer);\n if (minMajorVersion !== undefined && majorVersion < minMajorVersion) {\n return `<${minMajorVersion}.0.0`;\n }\n return `${majorVersion}.x`;\n } catch {\n return 'unknown';\n }\n };\n}\n","import * as childProcess from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport { basename, isAbsolute, join, relative } from 'node:path';\nimport { promisify } from 'node:util';\n\nimport { withProgress } from '../telemetry';\nimport { debug, logToFile } from './debug';\nimport type { PackageJson } from './package-json';\nimport {\n type PackageManager,\n detectAllPackageManagers,\n NPM as npm,\n} from './package-manager';\nimport type { CloudRegion, WizardRunOptions } from './types';\nimport { getDeclaredVersion } from './package-json';\nimport { DUMMY_PROJECT_API_KEY, ISSUES_URL } from '@lib/constants';\nimport {\n getOAuthScopesForProgram,\n getProvisioningScopesForProgram,\n} from '@lib/oauth/program-scopes';\nimport type { ProgramId } from '@lib/programs/program-registry';\nimport { analytics } from './analytics';\nimport { getUI } from '@ui';\nimport { HostResolution } from '@lib/host-resolution';\nimport {\n assertWizardCompletionScope,\n missingOAuthScopes,\n performOAuthFlow,\n} from './oauth';\nimport { resolveGrantedProject } from './project-resolution';\nimport {\n ProvisionedAccountUnreadableError,\n provisionNewAccount,\n} from './provisioning';\nimport {\n fetchUserData,\n fetchProjectData,\n type ApiUser,\n type ApiProject,\n} from '@lib/api';\nimport { versionSatisfiesRange } from './semver';\nimport { wizardAbort } from './wizard-abort';\nimport { OutroKind } from '@lib/wizard-session';\n\ninterface ProjectData {\n projectApiKey: string;\n accessToken: string;\n /** OAuth refresh token when the grant carried one; absent on the CI api-key path. */\n refreshToken?: string;\n /** Epoch ms when `accessToken` expires; absent on the CI api-key path. */\n expiresAt?: number;\n /** Minting OAuth client when it differs from the default login app (provisioning signups). */\n oauthClientId?: string;\n host: HostResolution;\n distinctId: string;\n projectId: number;\n /**\n * Optional `role_at_organization` from `/api/users/@me/`. Drives the\n * role-tailored prompt suggestions on the McpSuggestedPromptsScreen. Null\n * for signup flows (no role picked yet) and older accounts.\n */\n roleAtOrganization?: string | null;\n /**\n * Full user payload from `/api/users/@me/`. Carried through so\n * `getOrAskForProjectData` can forward it to the session as\n * `session.apiUser`. Null when the request failed or the CI key\n * lacked permissions.\n */\n user?: ApiUser | null;\n /**\n * Full project payload from `/api/projects/:id/`. Carries the team's\n * product opt-ins (replay, exception autocapture, surveys) so prompts\n * can state project-level product enablement instead of agents\n * inferring it from repo evidence. Null on signup flows.\n */\n project?: ApiProject | null;\n /**\n * Requested OAuth scopes the grant came back without (consent deselection\n * or ceiling clamp). Forwarded to `session.credentials.missingScopes` so\n * runs can degrade scope-gated steps instead of failing on a 403. Empty on\n * CI api-key and signup-provisioning paths.\n */\n missingScopes?: readonly string[];\n}\n\nexport interface CliSetupConfig {\n filename: string;\n name: string;\n gitignore: boolean;\n\n likelyAlreadyHasAuthToken(contents: string): boolean;\n tokenContent(authToken: string): string;\n\n likelyAlreadyHasOrgAndProject(contents: string): boolean;\n orgAndProjContent(org: string, project: string): string;\n\n likelyAlreadyHasUrl?(contents: string): boolean;\n urlContent?(url: string): string;\n}\n\nexport interface CliSetupConfigContent {\n authToken: string;\n org?: string;\n project?: string;\n url?: string;\n}\n\n/** @deprecated Use wizardAbort() directly for new code. */\nexport async function abort(message?: string, status?: number): Promise<never> {\n return wizardAbort({ message, exitCode: status });\n}\n\nexport function isInGitRepo(): boolean {\n try {\n childProcess.execSync('git rev-parse --show-toplevel', {\n stdio: 'ignore',\n });\n } catch {\n return false;\n }\n return true;\n}\n\nconst FREEMAIL_DOMAINS = new Set([\n 'gmail.com',\n 'googlemail.com',\n 'hotmail.com',\n 'outlook.com',\n 'yahoo.com',\n 'icloud.com',\n 'me.com',\n 'mail.com',\n 'protonmail.com',\n 'proton.me',\n 'live.com',\n 'aol.com',\n 'yandex.com',\n 'zoho.com',\n 'gmx.com',\n 'fastmail.com',\n]);\n\nfunction parseGitRemote(): { org: string; repo: string } | null {\n try {\n const url = childProcess\n .execSync('git remote get-url origin', {\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n .toString()\n .trim();\n // git@github.com:acme-corp/my-app.git or https://github.com/acme-corp/my-app.git\n const match = url.match(/[/:]([\\w.-]+)\\/([\\w.-]+?)(?:\\.git)?$/);\n if (match) return { org: match[1], repo: match[2] };\n } catch {\n // not in a git repo or no remote\n }\n return null;\n}\n\nexport function detectOrgAndProject(email: string): {\n orgName: string | undefined;\n projectName: string | undefined;\n} {\n const remote = parseGitRemote();\n\n // Project name: git repo name > directory name\n const projectName = remote?.repo || basename(process.cwd()) || undefined;\n\n // Org name: git remote org > email domain (skip freemail)\n let orgName: string | undefined;\n if (remote?.org) {\n orgName = remote.org;\n } else {\n const domain = email.split('@')[1]?.toLowerCase();\n if (domain && !FREEMAIL_DOMAINS.has(domain)) {\n orgName = domain.split('.')[0];\n }\n }\n\n return { orgName, projectName };\n}\n\nexport function getUncommittedOrUntrackedFiles(): string[] {\n let gitStatus: string;\n try {\n gitStatus = childProcess\n .execSync('git status --porcelain=v1', {\n // we only care about stdout\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n .toString();\n } catch {\n return [];\n }\n\n const result: string[] = [];\n for (const rawLine of gitStatus.split(os.EOL)) {\n const line = rawLine.trim();\n if (!line) continue;\n const match = /^\\S+\\s+(\\S+)/.exec(line);\n result.push(`- ${match?.[1]}`);\n }\n return result;\n}\n\nexport async function isReact19Installed({\n installDir,\n}: Pick<WizardRunOptions, 'installDir'>): Promise<boolean> {\n try {\n const packageJson = await tryGetPackageJson({ installDir });\n if (!packageJson) return false;\n const reactVersion = getDeclaredVersion('react', packageJson);\n\n if (!reactVersion) {\n return false;\n }\n\n return versionSatisfiesRange({\n version: reactVersion,\n acceptableVersions: '>=19.0.0',\n canBeLatest: true,\n });\n } catch {\n return false;\n }\n}\n\n/**\n * Installs or updates a package with the user's package manager.\n *\n * IMPORTANT: This function modifies the `package.json`! Be sure to re-read\n * it if you make additional modifications to it after calling this function!\n */\nexport async function installPackage({\n packageName,\n alreadyInstalled,\n packageNameDisplayLabel,\n packageManager,\n integration,\n installDir,\n}: {\n packageName: string;\n alreadyInstalled: boolean;\n packageNameDisplayLabel?: string;\n packageManager?: PackageManager;\n integration?: string;\n installDir: string;\n}): Promise<{ packageManager?: PackageManager }> {\n return withProgress('install-package', async () => {\n const sdkInstallSpinner = getUI().spinner();\n\n const pkgManager =\n packageManager || (await getPackageManager({ installDir }));\n\n const isReact19 = await isReact19Installed({ installDir });\n const legacyPeerDepsFlag =\n isReact19 && pkgManager.name === 'npm' ? '--legacy-peer-deps' : '';\n\n sdkInstallSpinner.start(\n `${alreadyInstalled ? 'Updating' : 'Installing'} ${\n packageNameDisplayLabel ?? packageName\n } with ${pkgManager.label}.`,\n );\n\n const execAsync = promisify(childProcess.exec);\n const installCommand =\n `${pkgManager.installCommand} ${packageName} ${pkgManager.flags} ${legacyPeerDepsFlag}`.trim();\n\n try {\n await execAsync(installCommand, { cwd: installDir });\n } catch (e) {\n const { stdout = '', stderr = '' } = (e ?? {}) as {\n stdout?: string;\n stderr?: string;\n };\n fs.writeFileSync(\n join(\n process.cwd(),\n `posthog-wizard-installation-error-${Date.now()}.log`,\n ),\n JSON.stringify({ stdout, stderr }),\n { encoding: 'utf8' },\n );\n sdkInstallSpinner.stop('Installation failed.');\n getUI().log.error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Encountered the following error during installation:\\n\\n${e}\\n\\nThe wizard has created a \\`posthog-wizard-installation-error-*.log\\` file. If you think this issue is caused by the PostHog wizard, create an issue on GitHub and include the log file's content:\\n${ISSUES_URL}`,\n );\n await abort();\n }\n\n sdkInstallSpinner.stop(\n `${alreadyInstalled ? 'Updated' : 'Installed'} ${\n packageNameDisplayLabel ?? packageName\n } with ${pkgManager.label}.`,\n );\n\n analytics.wizardCapture('package installed', {\n package_name: packageName,\n package_manager: pkgManager.name,\n integration,\n });\n\n return { packageManager: pkgManager };\n });\n}\n\n/**\n * Get package.json or abort the wizard if not found.\n * Only use where package.json is required (e.g., package install, overrides).\n * For detection/version-checks, use tryGetPackageJson() instead.\n */\nexport async function getPackageDotJson({\n installDir,\n}: Pick<WizardRunOptions, 'installDir'>): Promise<PackageJson> {\n const pkgPath = join(installDir, 'package.json');\n\n let raw: string;\n try {\n raw = await fs.promises.readFile(pkgPath, 'utf8');\n } catch {\n getUI().log.error(\n 'Could not find package.json. Make sure to run the wizard in the root of your app!',\n );\n await abort();\n return {};\n }\n\n try {\n const parsed = JSON.parse(raw) as PackageJson | null;\n return parsed ?? {};\n } catch {\n getUI().log.error(\n `Unable to parse your package.json. Make sure it has a valid format!`,\n );\n await abort();\n return {};\n }\n}\n\n/**\n * Try to get package.json, returning null if it doesn't exist.\n * Use this for detection purposes where missing package.json is expected (e.g., Python projects).\n */\nexport async function tryGetPackageJson({\n installDir,\n}: Pick<WizardRunOptions, 'installDir'>): Promise<PackageJson | null> {\n try {\n const packageJsonFileContents = await fs.promises.readFile(\n join(installDir, 'package.json'),\n 'utf8',\n );\n return JSON.parse(packageJsonFileContents) as PackageJson;\n } catch {\n return null;\n }\n}\n\nexport async function updatePackageDotJson(\n packageDotJson: PackageJson,\n { installDir }: Pick<WizardRunOptions, 'installDir'>,\n): Promise<void> {\n const pkgPath = join(installDir, 'package.json');\n const serialized = JSON.stringify(packageDotJson, null, 2);\n\n try {\n await fs.promises.writeFile(pkgPath, serialized, {\n encoding: 'utf8',\n flag: 'w',\n });\n return;\n } catch {\n getUI().log.error(`Unable to update your package.json.`);\n await abort();\n }\n}\n\n/**\n * Detect and return the package manager. Pure — no prompts.\n * Falls back to first detected or npm if ambiguous.\n */\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function getPackageManager(\n options: Pick<WizardRunOptions, 'installDir'> & { ci?: boolean },\n): Promise<PackageManager> {\n const detectedPackageManagers = detectAllPackageManagers({\n installDir: options.installDir,\n });\n\n if (detectedPackageManagers.length >= 1) {\n const selected = detectedPackageManagers[0];\n analytics.setTag('package-manager', selected.name);\n return selected;\n }\n\n // No package manager detected — default to npm\n analytics.setTag('package-manager', npm.name);\n return npm;\n}\n\nexport function isUsingTypeScript({\n installDir,\n}: Pick<WizardRunOptions, 'installDir'>): boolean {\n try {\n fs.accessSync(join(installDir, 'tsconfig.json'));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get project data for the wizard via OAuth or CI API key.\n */\nexport async function getOrAskForProjectData(\n _options: Pick<WizardRunOptions, 'signup' | 'ci' | 'apiKey' | 'projectId'> & {\n email?: string;\n region?: CloudRegion;\n /** Explicit base URL override (`--base-url`, from `session.baseUrl`). When\n * set, pins every PostHog origin and bypasses region resolution. */\n baseUrl?: string;\n /** `--local-mcp`: forwarded into the resolved host so `host.mcpUrl` is local. */\n localMcp?: boolean;\n /** Optional — picks the OAuth scope set via\n * `getOAuthScopesForProgram`. Omitted → default\n * `WIZARD_OAUTH_SCOPES`. Threaded into `askForWizardLogin`. */\n programId?: ProgramId | null;\n },\n): Promise<{\n host: HostResolution;\n projectApiKey: string;\n accessToken: string;\n /** OAuth refresh token when the grant carried one; absent on the CI api-key path. */\n refreshToken?: string;\n /** Epoch ms when `accessToken` expires; absent on the CI api-key path. */\n expiresAt?: number;\n /** Minting OAuth client when it differs from the default login app (provisioning signups). */\n oauthClientId?: string;\n projectId: number;\n roleAtOrganization: string | null;\n user: ApiUser | null;\n project: ApiProject | null;\n /** Requested OAuth scopes the grant came back without. Empty on CI/signup paths. */\n missingScopes: readonly string[];\n}> {\n // CI mode: bypass OAuth, use personal API key for LLM gateway\n if (_options.ci && _options.apiKey) {\n getUI().log.info('Using provided API key (CI mode - OAuth bypassed)');\n\n const host = await HostResolution.fromAccessToken(_options.apiKey, {\n region: _options.region,\n localMcp: _options.localMcp,\n baseUrl: _options.baseUrl,\n });\n const cloudUrl = host.appHost;\n\n const projectData =\n _options.projectId != null\n ? await fetchProjectDataById(\n _options.apiKey,\n _options.projectId,\n cloudUrl,\n )\n : await fetchProjectDataWithApiKey(_options.apiKey, cloudUrl);\n\n // Best-effort user fetch — CI flows may run with project-scoped keys\n // that 403 on /api/users/@me/, so swallow errors and continue with\n // a null user (and null role).\n let user: ApiUser | null = null;\n let roleAtOrganization: string | null = null;\n try {\n user = await fetchUserData(_options.apiKey, cloudUrl);\n roleAtOrganization = user.role_at_organization ?? null;\n } catch (err) {\n logToFile(\n '[ci-auth] user lookup failed:',\n err instanceof Error ? err.message : String(err),\n );\n }\n if (user) {\n analytics.identifyUser(user);\n logToFile(\n '[ci-auth] identified via API key; flags evaluate as the key owner',\n );\n } else {\n getUI().log.warn(\n 'Could not resolve the API key user (key needs user:read scope) — feature flags evaluate anonymously; user-targeted flags will not match.',\n );\n }\n\n return {\n host,\n projectApiKey: projectData.api_token,\n accessToken: _options.apiKey,\n projectId: projectData.id,\n roleAtOrganization,\n user,\n project: projectData.project,\n // A personal API key carries whatever scopes it carries — there is no\n // per-run scope request to diff against.\n missingScopes: [],\n };\n }\n\n const {\n host,\n projectApiKey,\n accessToken,\n refreshToken,\n expiresAt,\n oauthClientId,\n projectId,\n roleAtOrganization,\n user,\n project,\n missingScopes,\n } = await withProgress('login', () =>\n askForWizardLogin({\n signup: _options.signup,\n email: _options.email,\n region: _options.region,\n baseUrl: _options.baseUrl,\n programId: _options.programId,\n projectId: _options.projectId,\n localMcp: _options.localMcp,\n }),\n );\n\n if (!projectApiKey) {\n const cloudUrl = host.appHost;\n getUI().log.error(`Didn't receive a project token. This shouldn't happen :(\n\nPlease let us know if you think this is a bug in the wizard:\n${ISSUES_URL}`);\n\n getUI().log\n .info(`In the meantime, we'll add a dummy project token (\"${DUMMY_PROJECT_API_KEY}\") for you to replace later.\nYou can find your project token here:\n${cloudUrl}/settings/project#variables`);\n }\n\n return {\n accessToken,\n refreshToken,\n expiresAt,\n oauthClientId,\n host,\n projectApiKey: projectApiKey || DUMMY_PROJECT_API_KEY,\n projectId,\n roleAtOrganization: roleAtOrganization ?? null,\n user: user ?? null,\n project: project ?? null,\n missingScopes: missingScopes ?? [],\n };\n}\n\nasync function fetchProjectDataWithApiKey(\n apiKey: string,\n cloudUrl: string,\n): Promise<{ api_token: string; id: number; project: ApiProject }> {\n const userData = await fetchUserData(apiKey, cloudUrl);\n const projectId = userData.team?.id;\n\n if (!projectId) {\n throw new Error(\n 'Could not determine project ID from API key. Please ensure your API key has access to a project in this cloud region.',\n );\n }\n\n const projectData = await fetchProjectData(apiKey, projectId, cloudUrl);\n return {\n api_token: projectData.api_token,\n id: projectId,\n project: projectData,\n };\n}\n\nasync function fetchProjectDataById(\n apiKey: string,\n projectId: number,\n cloudUrl: string,\n): Promise<{ api_token: string; id: number; project: ApiProject }> {\n const projectData = await fetchProjectData(apiKey, projectId, cloudUrl);\n return {\n api_token: projectData.api_token,\n id: projectId,\n project: projectData,\n };\n}\n\nasync function askForWizardLogin(options: {\n signup: boolean;\n email?: string;\n region?: CloudRegion;\n /** Explicit base URL override (`--base-url`); pins every PostHog origin. */\n baseUrl?: string;\n /** Used to pick the right scope set via `getOAuthScopesForProgram`.\n * Omitted → default `WIZARD_OAUTH_SCOPES`. */\n programId?: ProgramId | null;\n /** `--project-id`, if passed. When the user granted access to it on the consent\n * screen we use it directly; otherwise we fall back to the first granted team. */\n projectId?: number;\n /** `--local-mcp`: forwarded into the resolved host so `host.mcpUrl` is local. */\n localMcp?: boolean;\n}): Promise<ProjectData> {\n if (options.signup) {\n return askForProvisioningSignup(\n options.email,\n options.region,\n options.baseUrl,\n options.localMcp,\n options.programId,\n );\n }\n\n const requestedScopes = [...getOAuthScopesForProgram(options.programId)];\n const tokenResponse = await performOAuthFlow({\n scopes: requestedScopes,\n signup: false,\n projectId: options.projectId,\n baseUrl: options.baseUrl,\n });\n\n try {\n assertWizardCompletionScope(tokenResponse.scope);\n } catch (error) {\n const scopeError =\n error instanceof Error ? error : new Error('OAuth scope check failed');\n const missing = missingOAuthScopes(requestedScopes, tokenResponse.scope);\n analytics.captureException(scopeError, {\n step: 'wizard_login',\n missing_scope: 'event_definition:write',\n });\n await wizardAbort({\n message: scopeError.message,\n outroData: {\n kind: OutroKind.Error,\n message: 'Setup needs permissions that were not granted',\n body: [\n 'Missing permissions:',\n ...missing.map((scope) => ` • ${scope}`),\n '',\n 'Re-run the wizard and approve all permissions on the PostHog authorization screen.',\n 'If that screen does not reappear, revoke the existing PostHog Wizard authorization in your PostHog settings first.',\n ].join('\\n'),\n },\n });\n }\n\n // `--project-id`, when provided, is authoritative — but only if the user actually\n // granted access to it on the consent screen. If they authorized a different\n // project, fail loudly instead of silently capturing into the wrong one. With no\n // `--project-id` this falls back to the granted project, unchanged for every program.\n const resolution = resolveGrantedProject(\n options.projectId,\n tokenResponse.scoped_teams,\n );\n if (!resolution.ok) {\n const error = new Error(\n `You authorized project ${resolution.granted}, but setup is targeting project ${resolution.requested} (from --project-id). ` +\n `If ${resolution.requested} is not a project you own — a copy-pasted example value, say — re-run without --project-id, or with the id shown in your PostHog project settings. ` +\n `If it is yours, re-run and grant access to project ${resolution.requested} on the authorization screen.`,\n );\n analytics.captureException(error, {\n step: 'wizard_login',\n requested_project_id: resolution.requested,\n granted_project_id: resolution.granted,\n });\n getUI().log.error(error.message);\n await abort(error.message);\n }\n\n const projectId = resolution.ok ? resolution.projectId : undefined;\n\n if (projectId === undefined) {\n const error = new Error(\n 'No project access granted. Please authorize with project-level access.',\n );\n analytics.captureException(error, {\n step: 'wizard_login',\n has_scoped_teams: !!tokenResponse.scoped_teams,\n });\n getUI().log.error(error.message);\n await abort(error.message);\n }\n\n // The issuing region comes with the token; the us/eu @me probe only runs when omitted.\n const host = await HostResolution.fromAccessToken(\n tokenResponse.access_token,\n {\n region: tokenResponse.posthog_region,\n localMcp: options.localMcp,\n baseUrl: options.baseUrl,\n },\n );\n const cloudUrl = host.appHost;\n\n const projectData = await fetchProjectData(\n tokenResponse.access_token,\n projectId!,\n cloudUrl,\n );\n const userData = await fetchUserData(tokenResponse.access_token, cloudUrl);\n\n const data = {\n accessToken: tokenResponse.access_token,\n refreshToken: tokenResponse.refresh_token,\n expiresAt: Date.now() + tokenResponse.expires_in * 1000,\n projectApiKey: projectData.api_token,\n host,\n distinctId: userData.distinct_id,\n projectId: projectId!,\n roleAtOrganization: userData.role_at_organization ?? null,\n user: userData,\n project: projectData,\n // What the user declined at consent (or the ceiling clamped) — carried to\n // the session so runs degrade scope-gated steps instead of 403ing blind.\n missingScopes: missingOAuthScopes(requestedScopes, tokenResponse.scope),\n };\n\n getUI().log.success('Login complete.');\n analytics.setTag('opened-wizard-link', true);\n analytics.identifyUser(userData);\n\n return data;\n}\n\nasync function askForProvisioningSignup(\n email?: string,\n region?: CloudRegion,\n baseUrl?: string,\n localMcp?: boolean,\n programId?: ProgramId | null,\n): Promise<ProjectData> {\n if (!email || !email.includes('@')) {\n getUI().log.error(\n 'Email is required for signup. Use --email your@email.com with --signup.',\n );\n await abort();\n throw new Error('unreachable');\n }\n\n const spinner = getUI().spinner();\n spinner.start('Creating your PostHog account...');\n\n try {\n const provisionRegion = (region ?? 'us').toUpperCase() as 'US' | 'EU';\n const { orgName, projectName } = detectOrgAndProject(email);\n const result = await provisionNewAccount(email, '', provisionRegion, {\n orgName,\n projectName,\n baseUrl,\n scopes: getProvisioningScopesForProgram(programId),\n });\n\n spinner.stop('Account created!');\n getUI().log.success('Welcome to PostHog!');\n\n const host = HostResolution.fromApiHost(result.host, { localMcp });\n\n analytics.setTag('provisioning-signup', true);\n\n return {\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresAt: result.expiresAt,\n oauthClientId: result.oauthClientId,\n projectApiKey: result.projectApiKey,\n host,\n distinctId: email,\n projectId: parseInt(result.projectId, 10) || 0,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n\n // The account exists — reporting a failed signup would send the user off to create a\n // second one on top of the org they already own.\n if (error instanceof ProvisionedAccountUnreadableError) {\n spinner.stop('Account created, but the project could not be read back.');\n getUI().log.warn(message);\n getUI().log.info('Signing you in to your new account instead...');\n\n return askForWizardLogin({ signup: false, baseUrl, localMcp });\n }\n\n spinner.stop('Account creation failed.');\n\n if (message.includes('already associated')) {\n getUI().log.info(\n 'This email already has a PostHog account. Switching to login flow...',\n );\n\n return askForWizardLogin({ signup: false, baseUrl, localMcp });\n }\n\n getUI().log.error(`Failed to create account: ${message}`);\n analytics.captureException(\n error instanceof Error ? error : new Error(message),\n { step: 'provisioning_signup' },\n );\n await abort();\n throw error;\n }\n}\n\n/**\n * Creates a new config file with the given filepath and codeSnippet.\n */\nexport async function createNewConfigFile(\n filepath: string,\n codeSnippet: string,\n { installDir }: Pick<WizardRunOptions, 'installDir'>,\n moreInformation?: string,\n): Promise<boolean> {\n if (!isAbsolute(filepath)) {\n debug(`createNewConfigFile: filepath is not absolute: ${filepath}`);\n return false;\n }\n\n const prettyFilename = relative(installDir, filepath);\n\n try {\n await fs.promises.writeFile(filepath, codeSnippet);\n\n getUI().log.success(`Added new ${prettyFilename} file.`);\n\n if (moreInformation) {\n getUI().log.info(moreInformation);\n }\n\n return true;\n } catch (e) {\n debug(e);\n getUI().log.warn(\n `Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`,\n );\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,YAAY,YAAoB,MAAuB;AAC9D,QAAOA,KAAG,WAAWC,OAAK,KAAK,YAAY,KAAK,CAAC;;AAGnD,SAAS,uBACP,YACA,MACA,QACS;AAET,QACE,aAAaA,OAAK,KAAK,YAAY,KAAK,EAAE,IAAI,EAAE,SAAS,OAAO,IAAI;;AAMxE,eAAe,cACb,MACA,SACA,YACA,EAAE,cACa;CACf,MAAM,MAAM,MAAM,kBAAkB,EAAE,YAAY,CAAC;CACnD,IAAI;AACJ,KAAI,SAAS,OACX,QAAO;EACL,GAAG;EACH,aAAa;GAAE,GAAI,IAAI,eAAe,EAAE;IAAI,UAAU;GAAY;EACnE;UACQ,SAAS,OAClB,QAAO;EACL,G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AAE,MAAM,uBAAuB,CAChC;AACD,QAAM,OAAO;AACb,QAAM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"store-l1aCLB7H.js","names":[],"sources":["../src/lib/programs/program-step.ts","../src/lib/programs/ai-opt-in-gate.ts","../src/ui/tui/screen-sequences.ts","../src/ui/tui/router.ts","../src/ui/tui/store.ts"],"sourcesContent":["import type {\n WizardSession,\n DiscoveredFeature,\n TaskNotice,\n} from '@lib/wizard-session';\nimport type { WizardReadinessResult } from '@lib/health-checks/readiness';\nimport type { ProgramRun } from '@lib/agent/agent-runner';\nimport type { Integration } from '@lib/constants';\nimport type { FrameworkConfig } from '@lib/framework-config';\nimport type { ContentBlock } from '@ui/tui/primitives/index';\nimport type { WizardStore } from '@ui/tui/store';\nimport type { Tip } from '@ui/tui/components/TipsCard';\n// Type-only — erased at compile time, so no runtime cycle with the\n// registry that imports `ProgramConfig` back from this module.\nimport type { ProgramId } from './program-registry.js';\n\n/**\n * A program step is the primary unit of the wizard's execution model.\n *\n * It can own:\n * - a screen in the TUI (optional — some steps are headless)\n * - agent work via a program reference (optional — some steps are UI-only)\n * - completion and visibility predicates\n *\n * The PostHog integration program is one ordered list of steps.\n * Other programs (e.g. revenue analytics) register a different step list.\n */\n/**\n * Context passed to onInit callbacks — fires when the TUI starts\n * rendering, before bin.ts has assigned the real session.\n */\nexport interface StoreInitContext {\n readonly session: WizardSession;\n readonly setReadinessResult: (result: WizardReadinessResult | null) => void;\n readonly setFrameworkContext: (key: string, value: unknown) => void;\n readonly emitChange: () => void;\n}\n\n/**\n * Context passed to onReady callbacks — fires after bin.ts has assigned\n * the real session, so reading `session.installDir` returns the target\n * project. Use for async pre-program work like prerequisite detection.\n */\nexport interface ProgramReadyContext {\n readonly session: WizardSession;\n readonly setFrameworkContext: (key: string, value: unknown) => void;\n\n // Detection-specific methods — used by core-integration's detect step\n readonly setFrameworkConfig: (\n integration: Integration,\n config: FrameworkConfig,\n ) => void;\n readonly setDetectedFramework: (label: string) => void;\n readonly setSkillId: (skillId: string | null) => void;\n readonly setUnsupportedVersion: (info: {\n current: string;\n minimum: string;\n docsUrl: string;\n }) => void;\n readonly addDiscoveredFeature: (feature: DiscoveredFeature) => void;\n readonly setDetectionComplete: () => void;\n}\n\nexport interface ProgramStep {\n /** Unique identifier for this step */\n id: string;\n\n /** Human-readable label for progress display */\n label: string;\n\n /**\n * TUI screen this step owns, if any.\n * Matches the ScreenId enum values (e.g. 'intro', 'run', 'outro').\n */\n screenId?: string;\n\n /**\n * For a run step (`screenId: 'run'`): runs this step's own agent. A program\n * exports a self-contained run step and another imports it into its step list\n * — e.g. posthog-integration exports a run step that runs its agent, and\n * self-driving imports it before its own run step. Omit to run the host\n * program's own agent (`config.run`).\n */\n run?: (session: WizardSession) => Promise<void>;\n\n /**\n * For a run step: prepare a derived session before its agent runs — e.g.\n * gather framework context for the chosen project. The session it receives is\n * the run's own, so writes don't leak into later runs.\n */\n onRunPrep?: (session: WizardSession) => Promise<void>;\n\n /**\n * For a run step: the working directory its agent runs in, resolved from the\n * session (e.g. self-driving's integration runs in the picked monorepo\n * sub-app, not the repo root). The runner scopes a derived session to this\n * dir for that run only. Defaults to `session.installDir`.\n */\n targetDir?: (session: WizardSession) => string;\n\n /**\n * Whether this step should be visible in the current program.\n * If omitted, the step is always visible.\n */\n show?: (session: WizardSession) => boolean;\n\n /**\n * Exit condition for the screen. Router advances when true.\n * Defaults to `gate` if unset.\n */\n isComplete?: (session: WizardSession) => boolean;\n\n /**\n * Define a gate if your screen needs to await user interactions.\n * bin.ts can `await store.getGate(stepId)` to pause until the\n * predicate becomes true.\n */\n gate?: (session: WizardSession) => boolean;\n\n /**\n * Called once when the TUI starts rendering, with the default\n * session. Use for session-independent fire-and-forget work that\n * should start as early as possible (e.g. health check kicked off\n * while the user is still reading the intro screen). Never fires for\n * a store that isn't rendering screens (tests, playground).\n */\n onInit?: (ctx: StoreInitContext) => void;\n\n /**\n * Called once after bin.ts has assigned the real session to the store,\n * before any gate is awaited. Awaited in sequence with other steps'\n * onReady callbacks. Use for session-dependent pre-program work like\n * scanning the installDir for prerequisites. May be sync or async.\n */\n onReady?: (ctx: ProgramReadyContext) => void | Promise<void>;\n\n /**\n * Report this step's analytics under a different program than its host, for\n * steps shared across programs (the MCP tutorial is all of `mcp-tutorial`\n * and the last step of `mcp-add`). Attribution only — scopes, bindings, and\n * sequences still follow the host. Matched by `screenId`, so headless steps\n * are unaffected.\n */\n reportsAsProgramId?: ProgramId;\n}\n\n/**\n * Declares a program's place in the wizard CLI surface.\n *\n * Mirrors the `cli:` block in context-mill skill configs so wizard-native\n * programs and skill-backed programs share one vocabulary. Field names\n * match `ProgramConfig.command` / `parentCommand` above, so contributors\n * only learn one set of words.\n *\n * - `role: 'command'` — appears as a normal wizard command.\n * - `role: 'skill'` — reachable only via `wizard skill <id>`.\n * - `role: 'internal'` — hidden everywhere, only reachable via the\n * `--skill=<id>` dev escape hatch.\n *\n * Mapping table — declaration on the left, registered command on the right:\n *\n * { role: 'command', → wizard revenue-analytics\n * command: 'revenue-analytics' }\n *\n * { role: 'command', → wizard audit feature-flags\n * parentCommand: 'audit',\n * command: 'feature-flags' }\n *\n * { role: 'skill' } → wizard skill <id>\n *\n * `cli` only configures the command shape — the verbs the user types.\n * Flags and positional args (e.g. `--since=30d`) are configured on\n * `cliOptions`, not here.\n *\n * Naming rule: commands use the full PostHog product name with hyphens\n * (`revenue-analytics`, `feature-flags`, `session-replay`), not\n * abbreviations like `revenue` or `flags`.\n */\nexport interface ProgramCliSurface {\n /** Where the program appears in the wizard CLI surface. */\n role: 'command' | 'skill' | 'internal';\n /**\n * The user-typed word that registers this program (e.g. `'feature-flags'`\n * in `wizard audit feature-flags`, or `'revenue-analytics'` in\n * `wizard revenue-analytics`). Required when `role` is `'command'`.\n */\n command?: string;\n /**\n * The command this program nests under (e.g. `'audit'` for\n * `wizard audit feature-flags`). Omit for flat / standalone commands.\n */\n parentCommand?: string;\n}\n\n/**\n * Uniform configuration for a wizard program.\n *\n * Each program directory exports one of these. The system uses it\n * for CLI registration, sequence/step wiring, and skill bootstrap.\n */\nexport interface ProgramConfig {\n /** CLI command name (e.g. 'revenue-analytics'). Omit for the default program. */\n command?: string;\n /**\n * Parent CLI command to nest this program under. When set, the program is\n * registered as `<parentCommand> <command>` instead of as a top-level\n * command. The parent must itself be a registered subcommand program. Omit\n * for top-level programs.\n */\n parentCommand?: string;\n /** CLI description shown in --help */\n description: string;\n /** Unique program id — matches the Program enum value */\n id: string;\n /**\n * Content-mill flow the orchestrator loads its agent prompts + step-skills\n * from (`agents/<flow>/` and `skills/<flow>/`). Defaults to `id`; set it when\n * the content-mill flow name diverges from the program id.\n */\n agentFlow?: string;\n /**\n * Whether this program's agent run requires third-party AI services.\n *\n * When true (the default), the wizard checks\n * `apiUser.organization.is_ai_data_processing_approved` after auth and\n * renders `AiOptInRequiredScreen` if the org has not opted in. Matches\n * Max's strict reading: only literal `true` proceeds.\n *\n * Opt out (set to `false`) for programs that don't run the agent —\n * doctor, mcp install/remove/tutorial, source-map upload. The safe\n * default is `true` so future programs gate by declaration.\n */\n requiresAi?: boolean;\n /**\n * Context-mill skill ID this program installs and runs. When present,\n * bin.ts seeds `session.skillId` with this value before the TUI renders\n * so intro screens can resolve skill metadata without waiting for the\n * agent run.\n */\n skillId?: string;\n /** The ordered step list */\n steps: ProgramStep[];\n /** Agent run config. Static object or async function for dynamic config. */\n run?: ProgramRun | ((session: WizardSession) => Promise<ProgramRun>);\n /**\n * CI-mode pre-run strategy. When set, runWizardCI awaits this after building\n * the ci:true session and before the agent runs, instead of walking step\n * onReady hooks. Use for headless prerequisite work (e.g. framework\n * detection) that the TUI performs via step onReady callbacks.\n */\n ciPreRun?: (session: WizardSession) => Promise<void>;\n /**\n * Tasks the orchestrator queues itself, before the planner runs, from what\n * the wizard detected. Their types are marked `runnerSeeded: true` in the\n * agent prompt, so the planner never sees them: whether such a task runs is\n * decided here, in code, not by a model that could invent it or forget it.\n * Return an empty list to queue none.\n */\n seedTasks?: (session: WizardSession) => Array<{\n type: string;\n label?: string;\n inputs?: Record<string, unknown>;\n /**\n * Shown before the run starts, letting the user decline the task. The\n * program owns the words — the runner and the modal only carry them. A\n * task without one is queued silently.\n */\n notice?: TaskNotice;\n }>;\n /** Prerequisites: other program ids that must have run first */\n requires?: string[];\n /**\n * Path (relative to installDir) of the report file the program writes.\n * Mirrors `run.reportFile` but lifted to the top level so UI screens can\n * read it synchronously without resolving a deferred `run` function.\n */\n reportFile?: string;\n /**\n * Agent-authored event-plan artifact to mirror into the wizard session.\n * Relative to `session.installDir`. Programs that do not produce an event\n * plan leave this unset, so generic runner machinery does not inspect a\n * stale or unrelated `.posthog-events.json` file.\n */\n eventPlanFile?: string;\n /**\n * LearnCard deck rendered in the shared `RunScreen` while the agent\n * runs. Lives at `<program>/content/index.tsx` by convention.\n * Programs that ship a custom RunScreen variant (audit) or skip the\n * run step (posthog-doctor) leave this unset.\n */\n getContentBlocks?: (store?: WizardStore) => ContentBlock[];\n /**\n * Tips shown in the run screen's right pane (the `Tips` sidebar) once\n * the LearnCard finishes. Lets a program supply its own explainer copy\n * (e.g. self-driving explaining what signal sources and scouts are)\n * instead of the generic onboarding deck. Unset → `RunScreen` falls back\n * to `DEFAULT_TIPS`, so every other program is unaffected. Lives at\n * `<program>/content/tips.ts` by convention.\n */\n getTips?: (store?: WizardStore) => Tip[];\n /**\n * Subcommand-specific CLI options. Spread into yargs `.options(...)` when the\n * program's subcommand is registered. Program-specific knowledge stays in\n * the program config, not in bin.ts. Typed as `unknown` to avoid pulling a\n * yargs dependency into this module.\n */\n cliOptions?: Record<string, unknown>;\n /**\n * Translate parsed CLI argv into extra options the runner consumes. Runs\n * after yargs validation, before runWizard/runWizardCI. Use this when a flag\n * needs to derive another field (e.g. `--product=statsig` → `skillId:\n * 'migrate-statsig'`).\n */\n mapCliOptions?: (argv: Record<string, unknown>) => Record<string, unknown>;\n /**\n * Extra tool names added on top of BASE_ALLOWED_TOOLS for this program's\n * agent run. Use for tools that only this program needs.\n */\n allowedTools?: readonly string[];\n /**\n * Tool names removed from BASE_ALLOWED_TOOLS for this program's agent\n * run. Use to forbid a base tool — e.g. `['Agent']` to block subagent\n * dispatch in a program whose steps are explicitly single-agent.\n */\n disallowedTools?: readonly string[];\n /**\n * Declares this program's place in the wizard CLI surface. See\n * `ProgramCliSurface` for semantics.\n */\n cli?: ProgramCliSurface;\n}\n\n/**\n * Project program steps into the narrower Screen shape the router consumes.\n *\n * Two things happen here:\n * 1. Headless steps (no `screenId`) are filtered out. The router walks\n * visible screens; gate-only steps like `detect` are store concerns.\n * 2. The step is narrowed to just { id, show, isComplete } — the\n * router has no business touching gate, onInit, or label.\n *\n * This intentional separation keeps the router focused on one question:\n * \"Which screen should be rendered right now?\"\n */\nexport function createProgramSequence(steps: ProgramStep[]): Array<{\n id: string;\n show?: (session: WizardSession) => boolean;\n isComplete?: (session: WizardSession) => boolean;\n}> {\n const entries = steps\n .filter((step) => step.screenId != null)\n .map((step) => ({\n id: step.screenId!,\n show: step.show,\n // `isComplete` defaults to `gate` — for most steps they're the same\n // predicate (e.g. intro: setupConfirmed unblocks bin.ts AND finishes\n // the screen). Only override when the two conditions diverge.\n isComplete: step.isComplete ?? step.gate,\n }));\n\n // Every program ends with the exit screen.\n entries.push({ id: 'exit', show: undefined, isComplete: undefined });\n\n return entries;\n}\n","/**\n * AI opt-in gate — step injection for programs whose agent run sends\n * source to Anthropic Claude.\n *\n * Injected after the `auth` step for every program that doesn't declare\n * `requiresAi: false`. The injected step carries three predicates:\n *\n * show — renders AiOptInRequiredScreen when the org hasn't\n * approved third-party AI\n * isComplete — router advances once approval lands\n * gate — `await store.getGate('ai-opt-in')` parks the agent\n * runner until approval lands. THIS is the enforcement:\n * the screen alone is cosmetic; the gate is what stops\n * source from leaving the machine.\n *\n * Used by BOTH screen-sequences.ts (screen injection) and the store's\n * _initFromProgram (gate registration) so the two layers can't drift.\n *\n * The predicates mirror Max's strict reading of\n * `organization.is_ai_data_processing_approved`: only literal `true`\n * proceeds; `null` / `undefined` / `false` all block. CI and signup\n * sessions skip the gate:\n * - `--ci` auto-consents to AI usage per the README, and the\n * interactive kill screen would be unworkable headless.\n * - signup (account provisioning) auto-consents too: the provisioning\n * access token deliberately omits the `organization:read` scope\n * (`WIZARD_PROVISIONING_SCOPES` in constants.ts), so the org's\n * approval can never be read back — `apiUser` stays null and the gate\n * could never clear. Creating an account through the wizard to run the\n * AI agent is itself the consent, mirroring how `shouldDisableAsk`\n * already treats `ci || signup` as one non-interactive mode.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport type { ProgramConfig, ProgramStep } from './program-step.js';\n\n/** Step id — also the ScreenId.AiOptIn enum value in screen-sequences. */\nexport const AI_OPT_IN_STEP_ID = 'ai-opt-in';\n\nfunction aiApproved(session: WizardSession): boolean {\n return !!session.apiUser?.organization?.is_ai_data_processing_approved;\n}\n\n/**\n * Returns the program's steps with the AI opt-in gate injected after\n * `auth`. Programs with `requiresAi: false` or no auth step pass\n * through unchanged — without auth, `apiUser` would never be populated\n * for evaluation anyway.\n */\nexport function withAiOptInGate(config: ProgramConfig): ProgramStep[] {\n if (config.requiresAi === false) return config.steps;\n\n const authIdx = config.steps.findIndex((s) => s.id === 'auth');\n if (authIdx === -1) return config.steps;\n\n const gateStep: ProgramStep = {\n id: AI_OPT_IN_STEP_ID,\n label: 'AI opt-in check',\n screenId: AI_OPT_IN_STEP_ID,\n // Only fire once apiUser has actually been populated — between\n // setCredentials and setApiUser there's a brief emitChange window\n // where apiUser is null, and we don't want to flash the gate then.\n show: (session) =>\n !session.ci &&\n !session.signup &&\n session.apiUser != null &&\n !aiApproved(session),\n isComplete: (session) =>\n session.ci || session.signup || aiApproved(session),\n gate: (session) => session.ci || session.signup || aiApproved(session),\n };\n\n return [\n ...config.steps.slice(0, authIdx + 1),\n gateStep,\n ...config.steps.slice(authIdx + 1),\n ];\n}\n","/**\n * Screen taxonomy + per-program screen sequences.\n *\n * Owns the ScreenId enum and projects each registered program's steps\n * into the router-shaped screen sequence (filtering headless steps and\n * appending the exit screen). Pure leaf module — no store, no React.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport {\n PROGRAM_REGISTRY,\n type ProgramId,\n} from '@lib/programs/program-registry';\nimport { createProgramSequence } from '@lib/programs/program-step';\nimport { withAiOptInGate } from '@lib/programs/ai-opt-in-gate';\n\n/** Screens that participate in linear programs. */\nexport enum ScreenId {\n Intro = 'intro',\n RevenueIntro = 'revenue-intro',\n WarehouseIntro = 'warehouse-intro',\n SourceMapsIntro = 'source-maps-intro',\n SourceMapsDetect = 'source-maps-detect',\n SourceMapsOutro = 'source-maps-outro',\n MigrationIntro = 'migration-intro',\n AgentSkillIntro = 'agent-skill-intro',\n AiObservabilityIntro = 'ai-observability-intro',\n MetricsIntro = 'metrics-intro',\n SelfDrivingIntro = 'self-driving-intro',\n SelfDrivingIntegrationCheck = 'self-driving-integration-check',\n SelfDrivingIntegrationDetect = 'self-driving-integration-detect',\n SelfDrivingHandoff = 'self-driving-handoff',\n SelfDrivingGithub = 'self-driving-github',\n AuditIntro = 'audit-intro',\n AuditRun = 'audit-run',\n AuditOutro = 'audit-outro',\n HealthCheck = 'health-check',\n DoctorIntro = 'doctor-intro',\n DoctorReport = 'doctor-report',\n Setup = 'setup',\n Auth = 'auth',\n Run = 'run',\n Mcp = 'mcp',\n McpSuggestedPrompts = 'mcp-suggested-prompts',\n SlackConnect = 'slack-connect',\n KeepSkills = 'keep-skills',\n Outro = 'outro',\n Exit = 'exit',\n McpAdd = 'mcp-add',\n McpRemove = 'mcp-remove',\n AiOptIn = 'ai-opt-in',\n}\n\nexport interface Screen {\n /** ScreenId to show */\n id: ScreenId;\n /** If provided, screen is skipped when this returns false. Omit = always show. */\n show?: (session: WizardSession) => boolean;\n /** If provided, screen is considered complete when this returns true. */\n isComplete?: (session: WizardSession) => boolean;\n}\n\n/** An ordered list of screens — a program's screen journey. */\nexport type Sequence = Screen[];\n\n/** All program screen sequences keyed by program id. */\nexport const PROGRAM_SEQUENCES: Record<ProgramId, Sequence> =\n Object.fromEntries(\n PROGRAM_REGISTRY.map((c) => [\n c.id,\n createProgramSequence(withAiOptInGate(c)) as Sequence,\n ]),\n ) as Record<ProgramId, Sequence>;\n","/**\n * WizardRouter — declarative program pipelines + overlay stack.\n *\n * Two layers:\n * Program cursor — linear sequence of screens, advanced with next()\n * Overlay stack — interrupts (outage, auth-expired, etc.) that push/pop\n *\n * The visible screen is: top of overlay stack if non-empty, otherwise the program cursor.\n *\n * Adding a program screen = append to a sequence array.\n * Adding an overlay = call pushOverlay() from anywhere.\n * No switch statements, no hardcoded transitions in business logic.\n */\n\nimport { RunPhase, type WizardSession } from '@lib/wizard-session';\nimport { Program, type ProgramId } from '@lib/programs/program-registry';\nimport {\n PROGRAM_SEQUENCES,\n ScreenId,\n type Screen,\n type Sequence,\n} from './screen-sequences.js';\n\n// Re-export so existing imports from './router.js' keep working\nexport { ScreenId, Program };\nexport type { Screen, Sequence, ProgramId };\n\n// ── ScreenId name taxonomy ──────────────────────────────────────────────\n\n/** Screens that interrupt programs as overlays */\nexport enum Overlay {\n SettingsOverride = 'settings-override',\n ManagedSettings = 'managed-settings',\n PortConflict = 'port-conflict',\n ManualAuthCode = 'manual-auth-code',\n AuthError = 'auth-error',\n SessionTimeout = 'session-timeout',\n WizardAsk = 'wizard-ask',\n TaskNotice = 'task-notice',\n}\n\n/** Union of all screen names */\nexport type ScreenName = ScreenId | Overlay;\n\n// ── Router ────────────────────────────────────────────────────────────\n\nexport class WizardRouter {\n private sequence: Sequence;\n private programId: ProgramId;\n private overlays: Overlay[] = [];\n\n constructor(programId: ProgramId = Program.PostHogIntegration) {\n this.programId = programId;\n this.sequence = PROGRAM_SEQUENCES[programId];\n }\n\n /**\n * Resolve which screen should be active based on session state.\n * Walks the program sequence, skipping hidden entries and completed entries,\n * returns the first incomplete screen.\n */\n resolve(session: WizardSession): ScreenName {\n if (this.overlays.length > 0) {\n return this.overlays[this.overlays.length - 1];\n }\n\n for (const entry of this.sequence) {\n if (entry.show && !entry.show(session)) continue;\n if (entry.isComplete && entry.isComplete(session)) continue;\n // A failed login aborts the run: wizardAbort renders the error outro\n // and then waits for its dismissal. But the auth step only completes\n // on credentials — which an aborted login never set — so the walk\n // would park here forever: auth spinner up, outro unreachable, and\n // that wait deadlocked. Route to the outro so the error can be read\n // and dismissed. Auth only: the run steps already complete on\n // RunPhase.Error, so later aborts reach their program's own outro.\n if (\n entry.id === ScreenId.Auth &&\n session.runPhase === RunPhase.Error &&\n session.outroData\n ) {\n return ScreenId.Outro;\n }\n return entry.id;\n }\n\n // All entries complete — show the last screen (outro)\n return this.sequence[this.sequence.length - 1].id;\n }\n\n /** The screen that should be rendered right now. */\n get activeScreen(): ScreenName {\n // Overlays take priority — resolve() handles this too,\n // but activeScreen is called before session is available in some paths\n if (this.overlays.length > 0) {\n return this.overlays[this.overlays.length - 1];\n }\n return this.sequence[0].id;\n }\n\n /** The id of the active program. */\n get activeProgram(): ProgramId {\n return this.programId;\n }\n\n /** Whether an overlay is currently active. */\n get hasOverlay(): boolean {\n return this.overlays.length > 0;\n }\n\n /**\n * Push an overlay that interrupts the current program.\n * The program resumes when the overlay is dismissed via popOverlay().\n */\n pushOverlay(overlay: Overlay): void {\n this.overlays.push(overlay);\n }\n\n /**\n * Dismiss the topmost overlay. The program screen underneath resumes.\n */\n popOverlay(): void {\n this.overlays.pop();\n }\n\n /**\n * Direction hint for screen transitions.\n */\n private _lastDirection: 'push' | 'pop' | null = null;\n\n get lastNavDirection(): 'push' | 'pop' | null {\n return this._lastDirection;\n }\n\n /** @internal — called by store wrapper to track direction */\n _setDirection(dir: 'push' | 'pop' | null): void {\n this._lastDirection = dir;\n }\n}\n","/**\n * WizardStore — Nanostore-backed reactive store for the TUI.\n * React components subscribe via useSyncExternalStore.\n *\n * The active screen is derived from session state — WizardRouter walks\n * the flow and shows the first step whose `isComplete` is still false.\n *\n * Define a step `gate` if your screen needs to await user interactions.\n * bin.ts calls `await store.getGate(stepId)` to pause until the gate\n * predicate becomes true.\n *\n * All session mutations that affect screen resolution go through\n * explicit setters so emitChange() is always called.\n */\n\nimport { atom, map } from 'nanostores';\nimport { logToFile } from '@utils/debug';\nimport {\n TaskStatus,\n isTaskStatus,\n type AuthErrorDetail,\n type TokenUsageDelta,\n} from '@ui/wizard-ui';\nimport {\n type WizardSession,\n type OutroData,\n type DiscoveredFeature,\n type PendingQuestion,\n type AskAnswers,\n type CloudRegion,\n AdditionalFeature,\n McpOutcome,\n RunPhase,\n ScanConsent,\n buildSession,\n type TaskNotice,\n} from '@lib/wizard-session';\nimport type { SettingsConflict } from '@lib/agent/claude-settings';\nimport {\n WizardReadiness,\n getBlockingServiceKeys,\n type WizardReadinessResult,\n} from '@lib/health-checks/readiness';\nimport { ServiceHealthStatus } from '@lib/health-checks/types';\nimport {\n WizardRouter,\n type ScreenName,\n ScreenId,\n Overlay,\n Program,\n type ProgramId,\n} from './router.js';\nimport { analytics, sessionProperties } from '@utils/analytics';\nimport type {\n StoreInitContext,\n ProgramReadyContext,\n} from '@lib/programs/program-step';\nimport { getProgramConfig } from '@lib/programs/program-registry';\nimport { withAiOptInGate } from '@lib/programs/ai-opt-in-gate';\nimport { reportWarehouseSourcesDetected } from '@lib/programs/posthog-integration/detect';\nimport { EXPANDED_COUNT } from '@ui/tui/constants';\nimport { IS_DEV } from '@lib/constants';\nimport { computeTokenCostUsd } from '@lib/agent/token-pricing';\n\nexport { TaskStatus, ScreenId, Overlay, Program, RunPhase, McpOutcome };\nexport type { ScreenName, OutroData, WizardSession, ProgramId };\n\nexport interface TaskItem {\n label: string;\n activeForm?: string;\n status: TaskStatus;\n /** Legacy compat */\n done: boolean;\n}\n\nexport interface PlannedEvent {\n name: string;\n description: string;\n}\n\n/**\n * Running token/cost estimate for the hidden Ctrl+T HUD. Accumulated live\n * from each assistant turn's usage (see `agent-interface.ts`), then\n * reconciled to the SDK's authoritative `total_cost_usd` once the run\n * completes — `costIsFinal` flips so the HUD can show the number as exact\n * rather than a running estimate.\n */\nexport interface TokenUsageSnapshot {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n costUsd: number;\n costIsFinal: boolean;\n}\n\nconst EMPTY_TOKEN_USAGE: TokenUsageSnapshot = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheCreationTokens: 0,\n costUsd: 0,\n costIsFinal: false,\n};\n\n/** Total tokens across all counters in a `TokenUsageSnapshot` — used by\n * both `TokenCostHud` and `exit-line.ts` to detect \"no agent turns yet\". */\nexport function totalTokenCount(usage: TokenUsageSnapshot): number {\n return (\n usage.inputTokens +\n usage.outputTokens +\n usage.cacheReadTokens +\n usage.cacheCreationTokens\n );\n}\n\ninterface GateEntry {\n predicate: (session: WizardSession) => boolean;\n promise: Promise<void>;\n resolve: () => void;\n resolved: boolean;\n}\n\n/**\n * FIFO cap on retained status lines. The status bar is the only consumer and\n * renders at most EXPANDED_COUNT lines, so there is no reason to retain more —\n * the cap is tied to the window it feeds.\n */\nconst MAX_STATUS_MESSAGES = EXPANDED_COUNT;\n\n/**\n * Fired once per blocked readiness result, so we can quantify how often\n * the wizard refuses to start and — crucially — split that between\n * confirmed PostHog outages and probe-level reachability failures that\n * are most likely the user's network. Helps us decide whether the\n * health-check UX is over-firing.\n */\nfunction captureHealthCheckBlocked(result: WizardReadinessResult): void {\n try {\n const health = result.health;\n const blockingKeys = getBlockingServiceKeys(health);\n const blockingStatuses = blockingKeys.map((k) => health[k]?.status);\n\n const allNoConnection =\n blockingStatuses.length > 0 &&\n blockingStatuses.every((s) => s === ServiceHealthStatus.NoConnection);\n const onlySkillsOrigin =\n blockingKeys.length === 1 && blockingKeys[0] === 'skillsOrigin';\n\n const decision = onlySkillsOrigin\n ? 'skills-origin-down'\n : allNoConnection\n ? 'no-connection'\n : 'confirmed-outage';\n\n const posthogStatus = health.posthogOverall?.status;\n const retriesUsed = Math.max(\n 0,\n ...(['llmGateway', 'mcp', 'skillsOrigin'] as const).map((k) => {\n const ind = health[k]?.rawIndicator ?? '';\n const m = ind.match(/attempts=(\\d+)/);\n return m ? Number(m[1]) - 1 : 0;\n }),\n );\n\n analytics.wizardCapture('health check blocked', {\n decision,\n blocking_keys: blockingKeys,\n posthog_status_reachable:\n posthogStatus !== ServiceHealthStatus.NoConnection,\n posthog_status_reports_incident:\n posthogStatus === ServiceHealthStatus.Down ||\n posthogStatus === ServiceHealthStatus.Degraded,\n retries_used: retriesUsed,\n });\n } catch (err) {\n logToFile(\n `[health-checks] failed to capture analytics: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n}\n\nexport class WizardStore {\n // ── Internal nanostore atoms ─────────────────────────────────────\n private $session = map<WizardSession>(buildSession({}));\n private $statusMessages = atom<string[]>([]);\n private $statusExpanded = atom(false);\n private $tasks = atom<TaskItem[]>([]);\n private $eventPlan = atom<PlannedEvent[]>([]);\n private $handoffText = atom<string | null>(null);\n private $learnCardBlockIdx = atom(0);\n private $learnCardComplete = atom(false);\n private $version = atom(0);\n private $currentStage = atom<{ stage: string; startedAt: number } | null>(\n null,\n );\n private $tokenUsage = atom<TokenUsageSnapshot>(EMPTY_TOKEN_USAGE);\n // Defaults on for local/dev/test runs (tsx, `pnpm try`, vitest) so\n // contributors see it without needing to know the shortcut; defaults off\n // for the published build, where it stays genuinely hidden. Still\n // Ctrl+T-toggleable either way.\n private $tokenHudVisible = atom(IS_DEV);\n\n private _onTasksChanged: (() => void) | null = null;\n /** Last screen seen — used to detect screen transitions for analytics. */\n private _lastScreen: ScreenName | null = null;\n\n /** Hooks run when transitioning onto a screen. */\n private _enterScreenHooks = new Map<ScreenName, (() => void)[]>();\n\n /** Gate promises derived from program step definitions. */\n private _gates = new Map<string, GateEntry>();\n\n version = '';\n\n /** Navigation router — resolves active screen from session state. */\n readonly router: WizardRouter;\n\n /** Blocks agent execution until the settings-override overlay is dismissed. */\n private _resolveSettingsOverride: (() => void) | null = null;\n private _backupAndFixSettings: (() => boolean) | null = null;\n\n /** Blocks the run until an optional step's notice is answered. */\n private _resolveTaskNotice: ((keep: boolean) => void) | null = null;\n /** Blocks OAuth flow until the port-conflict overlay is dismissed. */\n private _resolvePortConflict: (() => void) | null = null;\n\n /** Resolves the OAuth flow with a manually-entered authorization code. */\n private _resolveManualAuthCode: ((code: string) => void) | null = null;\n\n /** Resolves the in-flight wizard_ask request. */\n private _resolvePendingQuestion: ((answers: AskAnswers) => void) | null =\n null;\n\n constructor(program: ProgramId = Program.PostHogIntegration) {\n this.router = new WizardRouter(program);\n this._initFromProgram(program);\n }\n\n /**\n * Scan program steps for gate predicates and create gate promises.\n *\n * Steps are wrapped with withAiOptInGate so the injected ai-opt-in\n * step's gate registers here — the agent runner awaits it (via\n * WizardUI.waitForAiOptIn) before any source leaves the machine.\n * Same wrapper screen-sequences.ts uses, so the gate and its screen\n * can't drift apart.\n */\n private _initFromProgram(program: ProgramId): void {\n const steps = withAiOptInGate(getProgramConfig(program));\n\n // Create gate promises from steps that define them\n for (const step of steps) {\n if (step.gate) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n this._gates.set(step.id, {\n predicate: step.gate,\n promise,\n resolve,\n resolved: false,\n });\n }\n }\n }\n\n /**\n * Run the program steps' onInit callbacks. startTUI calls this once\n * the screens are actually rendering — constructing a store alone\n * (tests, playground) must not fire init work like the health-check\n * pre-flight, whose probes belong only to flows that show its screen.\n */\n runInitHooks(): void {\n const steps = getProgramConfig(this.router.activeProgram).steps;\n const getSession = (): WizardSession => this.session;\n const ctx: StoreInitContext = {\n get session() {\n return getSession();\n },\n setReadinessResult: (r) => this.setReadinessResult(r),\n setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),\n emitChange: () => this.emitChange(),\n };\n for (const step of steps) {\n step.onInit?.(ctx);\n }\n }\n\n /**\n * Run all `onReady` hooks declared by the current flow's steps, in\n * order. Must be called after `store.session = session` so hooks see\n * the real installDir. bin.ts calls this generically — it doesn't\n * need to know which program has which pre-flow work.\n */\n async runReadyHooks(): Promise<void> {\n const steps = getProgramConfig(this.router.activeProgram).steps;\n const ctx: ProgramReadyContext = {\n session: this.session,\n setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),\n setFrameworkConfig: (i, c) => this.setFrameworkConfig(i, c),\n setDetectedFramework: (l) => this.setDetectedFramework(l),\n setSkillId: (id) => this.setSkillId(id),\n setUnsupportedVersion: (info) => this.setUnsupportedVersion(info),\n addDiscoveredFeature: (f) => this.addDiscoveredFeature(f),\n setDetectionComplete: () => this.setDetectionComplete(),\n };\n for (const step of steps) {\n if (step.onReady) {\n await step.onReady(ctx);\n }\n }\n }\n\n // ── Gate API ────────────────────────────────────────────────────\n\n /**\n * Get a gate promise by step ID — the primary blocking checkpoint API\n * for bin.ts. `await store.getGate('...')` parks the caller until the\n * corresponding program step's gate predicate flips to true (if the\n * predicate stays false, the caller stays parked indefinitely — the\n * TUI keeps rendering so the user can resolve whatever is blocking).\n *\n * If the program doesn't define a step with this ID, or the step\n * has no `gate` predicate, this returns an already-resolved promise\n * so bin.ts flows straight through. This lets programs opt in to\n * gates on a per-step basis without bin.ts needing to know which\n * gates exist in which flow.\n */\n getGate(stepId: string): Promise<void> {\n return this._gates.get(stepId)?.promise ?? Promise.resolve();\n }\n\n /**\n * Resolve once `predicate(session)` is true. Unlike a gate, this is created\n * at the await point and evaluated live against the current session, so it\n * never latches on a startup value — the orchestrator uses it to wait for a\n * decision (a project picked, a handoff acknowledged) without the \"true while\n * undecided\" trap that latched gate predicates have.\n */\n waitUntil(predicate: (session: WizardSession) => boolean): Promise<void> {\n if (predicate(this.session)) return Promise.resolve();\n return new Promise((resolve) => {\n const unsub = this.subscribe(() => {\n if (predicate(this.session)) {\n unsub();\n resolve();\n }\n });\n });\n }\n\n /**\n * Re-evaluate every gate predicate against the current session and\n * resolve any whose predicate now returns true. Called after every\n * emitChange(), so gates unblock as soon as the session mutation\n * that satisfies them lands. Gates only resolve once — a predicate\n * that goes true → false → true will NOT re-block a caller that\n * already awaited through.\n */\n private _checkGates(): void {\n for (const [, gate] of this._gates) {\n if (!gate.resolved && gate.predicate(this.session)) {\n gate.resolved = true;\n gate.resolve();\n }\n }\n }\n\n // ── State accessors (read from atoms) ────────────────────────────\n\n get session(): WizardSession {\n return this.$session.get();\n }\n\n set session(value: WizardSession) {\n this.$session.set(value);\n this.emitChange();\n }\n\n get statusMessages(): string[] {\n return this.$statusMessages.get();\n }\n\n get tasks(): TaskItem[] {\n return this.$tasks.get();\n }\n\n get eventPlan(): PlannedEvent[] {\n return this.$eventPlan.get();\n }\n\n get handoffText(): string | null {\n return this.$handoffText.get();\n }\n\n get currentStage(): { stage: string; startedAt: number } | null {\n return this.$currentStage.get();\n }\n\n /** No-op when the stage hasn't changed, so `startedAt` survives across\n * re-renders and tab switches and measures real stage time. */\n setCurrentStage(stage: string): void {\n const cur = this.$currentStage.get();\n if (cur?.stage === stage) return;\n this.$currentStage.set({ stage, startedAt: Date.now() });\n this.emitChange();\n }\n\n get statusExpanded(): boolean {\n return this.$statusExpanded.get();\n }\n\n toggleStatusExpanded(): void {\n this.$statusExpanded.set(!this.$statusExpanded.get());\n this.emitChange();\n }\n\n setStatusExpanded(expanded: boolean): void {\n if (this.$statusExpanded.get() !== expanded) {\n this.$statusExpanded.set(expanded);\n this.emitChange();\n }\n }\n\n // ── Session setters ─────────────────────────────────────────────\n // Every setter that affects screen resolution calls emitChange().\n // Business logic calls these instead of mutating session directly.\n\n /** Sets setupConfirmed, and is the point consent becomes final. */\n completeSetup(): void {\n this.$session.setKey('setupConfirmed', true);\n // Reports first: analytics merges tags into an event as it is sent, so\n // `setup confirmed` only carries the warehouse tags if they are already\n // set. On main they were, because reporting happened back in detect.\n this._markWarehouseSourcesReportedIfNeeded();\n analytics.wizardCapture('setup confirmed', sessionProperties(this.session));\n this.emitChange();\n }\n\n /**\n * Sharing is on: either the user turned it back on in the panel, or they\n * pressed Continue without ever touching it. Both are reversible until\n * completeSetup() resolves the intro gate and reports.\n */\n grantSharing(): void {\n this.$session.setKey('scanConsent', ScanConsent.Granted);\n this.emitChange();\n }\n\n /**\n * Sharing is off. Suppresses reporting only — local detection still ran and\n * the results stay in the session, so the outro suggestion and the warehouse\n * task are unaffected; see `scanConsent` on `WizardSession`.\n *\n * Deliberately does not report. The panel's toggle can come back here, so\n * marking the run reported would strand a user who turns sharing off and\n * then on again. completeSetup() owns the single report.\n */\n declineSharing(): void {\n this.$session.setKey('scanConsent', ScanConsent.Declined);\n this.emitChange();\n }\n\n /**\n * reportWarehouseSourcesDetected() is the single place scan results turn\n * into telemetry; this just supplies its idempotency flag via the normal\n * setter path (never mutate session directly). A no-op once\n * `warehouseSourcesReported` is set, or for any program that never\n * populated a warehouse-scan result in the first place.\n */\n private _markWarehouseSourcesReportedIfNeeded(): void {\n if (reportWarehouseSourcesDetected(this.session)) {\n this.$session.setKey('warehouseSourcesReported', true);\n }\n }\n\n setRunPhase(phase: RunPhase): void {\n this.$session.setKey('runPhase', phase);\n analytics.setTag('run_phase', phase);\n this.emitChange();\n }\n\n setCredentials(credentials: WizardSession['credentials']): void {\n this.$session.setKey('credentials', credentials);\n if (credentials?.projectId) {\n analytics.setTag('project_id', credentials.projectId);\n }\n analytics.wizardCapture('auth complete', {\n project_id: credentials?.projectId,\n });\n this.emitChange();\n }\n\n /** Post-refresh credential swap. No `auth complete` — see WizardUI. */\n setAccessToken(credentials: WizardSession['credentials']): void {\n this.$session.setKey('credentials', credentials);\n this.emitChange();\n }\n\n setRoleAtOrganization(role: string | null): void {\n this.$session.setKey('roleAtOrganization', role);\n this.emitChange();\n }\n\n setApiUser(user: WizardSession['apiUser']): void {\n this.$session.setKey('apiUser', user);\n this.emitChange();\n }\n\n setFrameworkConfig(\n integration: WizardSession['integration'],\n config: WizardSession['frameworkConfig'],\n ): void {\n this.$session.setKey('integration', integration);\n this.$session.setKey('frameworkConfig', config);\n this.$session.setKey('unsupportedVersion', null);\n if (integration) analytics.setTag('integration', integration);\n this.emitChange();\n }\n\n setDetectionComplete(): void {\n this.$session.setKey('detectionComplete', true);\n this.emitChange();\n }\n\n setDetectedFramework(label: string): void {\n this.$session.setKey('detectedFrameworkLabel', label);\n analytics.setTag('detected_framework', label);\n this.emitChange();\n }\n\n setSkillId(skillId: string | null): void {\n this.$session.setKey('skillId', skillId);\n this.emitChange();\n }\n\n setUnsupportedVersion(info: {\n current: string;\n minimum: string;\n docsUrl: string;\n }): void {\n this.$session.setKey('unsupportedVersion', info);\n this.emitChange();\n }\n\n setLoginUrl(url: string | null): void {\n this.$session.setKey('loginUrl', url);\n this.emitChange();\n }\n\n setAuthorizeUrl(url: string | null): void {\n this.$session.setKey('authorizeUrl', url);\n this.emitChange();\n }\n\n setReadinessResult(result: WizardReadinessResult | null): void {\n this.$session.setKey('readinessResult', result);\n if (result && result.decision === WizardReadiness.No) {\n captureHealthCheckBlocked(result);\n }\n this.emitChange();\n }\n\n /** User dismissed the blocking outage screen. Gate resolves via _checkGates(). */\n dismissOutage(): void {\n logToFile('[health-checks] user dismissed outage screen, continuing');\n this.$session.setKey('outageDismissed', true);\n this.emitChange();\n }\n\n /**\n * Push the settings-override overlay and return a promise that blocks\n * until the user dismisses it via backupAndFixSettingsOverride().\n */\n showSettingsOverride(\n conflicts: SettingsConflict[],\n backupAndFix: () => boolean,\n ): Promise<void> {\n const allKeys = conflicts.flatMap((c) => c.keys);\n this.$session.setKey('settingsOverrideKeys', allKeys);\n this.$session.setKey('settingsConflicts', conflicts);\n this._backupAndFixSettings = backupAndFix;\n\n const hasReadOnly = conflicts.some((c) => !c.writable);\n if (hasReadOnly) {\n this.pushOverlay(Overlay.ManagedSettings);\n } else {\n this.pushOverlay(Overlay.SettingsOverride);\n }\n\n return new Promise((resolve) => {\n this._resolveSettingsOverride = resolve;\n });\n }\n\n /**\n * Push the port-conflict overlay and return a promise that blocks\n * until the user frees the ports and retries, or exits.\n */\n showPortConflict(processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void> {\n this.$session.setKey('portConflictProcess', processInfo);\n this.pushOverlay(Overlay.PortConflict);\n return new Promise((resolve) => {\n this._resolvePortConflict = resolve;\n });\n }\n\n /** Dismiss the port-conflict overlay and retry the OAuth port loop. */\n resolvePortConflict(): void {\n this.$session.setKey('portConflictProcess', null);\n this.popOverlay();\n this._resolvePortConflict?.();\n this._resolvePortConflict = null;\n }\n\n /**\n * Show an optional step's notice and return whether to keep that step.\n * Asked before the step runs, so nobody is surprised by a prompt mid-run.\n */\n showTaskNotice(notice: TaskNotice): Promise<boolean> {\n this.$session.setKey('taskNotice', notice);\n this.pushOverlay(Overlay.TaskNotice);\n return new Promise((resolve) => {\n this._resolveTaskNotice = resolve;\n });\n }\n\n /** Dismiss the notice, keeping (`true`) or skipping (`false`) the step. */\n resolveTaskNotice(keep: boolean): void {\n this.$session.setKey('taskNotice', null);\n this.popOverlay();\n this._resolveTaskNotice?.(keep);\n this._resolveTaskNotice = null;\n }\n\n /**\n * Return a promise that resolves when the user submits a manually-entered\n * OAuth code via the paste modal. The OAuth flow races this against the\n * local callback server — see `performOAuthFlow`.\n */\n waitForManualAuthCode(): Promise<string> {\n return new Promise<string>((resolve) => {\n this._resolveManualAuthCode = resolve;\n });\n }\n\n /** Open the manual OAuth code-entry overlay over the auth screen. */\n showManualAuthCode(): void {\n this.pushOverlay(Overlay.ManualAuthCode);\n }\n\n /** Dismiss the manual OAuth code overlay without submitting. */\n dismissManualAuthCode(): void {\n this.popOverlay();\n }\n\n /**\n * Submit a manually-entered authorization code: dismiss the overlay and\n * resolve the in-flight OAuth flow so it can exchange the code for a token.\n */\n submitManualAuthCode(code: string): void {\n this.popOverlay();\n this._resolveManualAuthCode?.(code);\n this._resolveManualAuthCode = null;\n }\n\n /**\n * Open the WizardAsk overlay with a set of questions and return a promise\n * that resolves once the user submits answers (or the request is cancelled).\n *\n * Only one request is in flight at a time — calling this while a request\n * is already pending throws.\n */\n requestQuestion(question: PendingQuestion): Promise<AskAnswers> {\n if (this._resolvePendingQuestion) {\n throw new Error(\n 'requestQuestion called while another wizard_ask request is pending',\n );\n }\n this.$session.setKey('pendingQuestion', question);\n this.pushOverlay(Overlay.WizardAsk);\n analytics.wizardCapture('wizard_ask shown', {\n source: question.source,\n question_count: question.questions.length,\n kinds: question.questions.map((q) => q.kind),\n });\n return new Promise<AskAnswers>((resolve) => {\n this._resolvePendingQuestion = resolve;\n });\n }\n\n /**\n * Resolve the in-flight wizard_ask request with the user's answers and\n * dismiss the overlay. Answers flow back to the agent as the tool result.\n */\n resolvePendingQuestion(answers: AskAnswers): void {\n const resolve = this._resolvePendingQuestion;\n this._resolvePendingQuestion = null;\n this.$session.setKey('pendingQuestion', null);\n this.popOverlay();\n resolve?.(answers);\n }\n\n /**\n * Cancel the in-flight wizard_ask request — the bridge sends a sentinel\n * answer (\"__cancelled__\") so the skill can decide how to handle it.\n */\n cancelPendingQuestion(): void {\n const pending = this.session.pendingQuestion;\n if (!pending) return;\n const cancelled: AskAnswers = {};\n for (const q of pending.questions) {\n cancelled[q.id] = '__cancelled__';\n }\n this.resolvePendingQuestion(cancelled);\n }\n\n /**\n * Back up .claude/settings.json. Dismisses the overlay on success.\n */\n backupAndFixSettingsOverride(): boolean {\n const ok = this._backupAndFixSettings?.() ?? false;\n if (ok) {\n this.$session.setKey('settingsOverrideKeys', null);\n this.$session.setKey('settingsConflicts', null);\n this.popOverlay();\n this._resolveSettingsOverride?.();\n this._resolveSettingsOverride = null;\n this._backupAndFixSettings = null;\n }\n return ok;\n }\n\n /** Push the auth-error overlay (no dismiss — user must exit). */\n showAuthError(detail?: AuthErrorDetail): void {\n this.$session.setKey('authErrorDetail', detail ?? null);\n this.pushOverlay(Overlay.AuthError);\n }\n\n /** Push the session-timeout overlay (no dismiss — user must exit). */\n showSessionTimeout(): void {\n this.pushOverlay(Overlay.SessionTimeout);\n }\n\n addDiscoveredFeature(feature: DiscoveredFeature): void {\n if (!this.session.discoveredFeatures.includes(feature)) {\n this.session.discoveredFeatures.push(feature);\n this.emitChange();\n }\n }\n\n /**\n * Enable an additional feature: enqueue it for the stop hook\n * and set any feature-specific session flags.\n */\n enableFeature(feature: AdditionalFeature): void {\n if (!this.session.additionalFeatureQueue.includes(feature)) {\n this.session.additionalFeatureQueue.push(feature);\n // Distinct key from `sessionProperties()`'s array-valued\n // `additional_features` — see the note in posthog-integration/detect.ts.\n analytics.setTag(\n 'additional_feature_kinds',\n this.session.additionalFeatureQueue.join(','),\n );\n }\n // Feature-specific flags\n if (feature === AdditionalFeature.LLM) {\n this.session.llmOptIn = true;\n }\n analytics.wizardCapture('feature enabled', { feature });\n this.emitChange();\n }\n\n setMcpComplete(\n outcome: McpOutcome = McpOutcome.Skipped,\n installedClients: string[] = [],\n featuresSelected?: 'all' | string[],\n loginCommands: string[] = [],\n ): void {\n this.$session.setKey('mcpComplete', true);\n this.$session.setKey('mcpOutcome', outcome);\n this.$session.setKey('mcpInstalledClients', installedClients);\n this.$session.setKey('mcpLoginCommands', loginCommands);\n const featuresPayload =\n outcome === McpOutcome.Installed && featuresSelected !== undefined\n ? { mcp_features_selected: featuresSelected }\n : {};\n analytics.wizardCapture('mcp complete', {\n mcp_outcome: outcome,\n mcp_installed_clients: installedClients,\n ...featuresPayload,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n setSkillsComplete(kept: boolean): void {\n this.$session.setKey('skillsComplete', true);\n analytics.wizardCapture('skills complete', {\n skills_kept: kept,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n setMcpSuggestedPromptsDismissed(): void {\n this.$session.setKey('mcpSuggestedPromptsDismissed', true);\n this.emitChange();\n }\n\n setSlackStepDismissed(): void {\n this.$session.setKey('slackStepDismissed', true);\n this.emitChange();\n }\n\n setSlackConnected(connected: boolean): void {\n this.$session.setKey('slackConnected', connected);\n this.emitChange();\n }\n\n setGithubConnected(connected: boolean): void {\n this.$session.setKey('githubConnected', connected);\n this.emitChange();\n }\n\n /**\n * Self-driving GitHub gate declined. Carries the outro the user lands on,\n * since declining ends the flow before the agent runs and there is no abort\n * case to render one.\n */\n declineGithub(outroData: OutroData): void {\n this.$session.setKey('githubDeclined', true);\n this.$session.setKey('outroData', outroData);\n this.emitChange();\n }\n\n /**\n * Self-driving integration-check answer. `true` → integrate the SDK as part\n * of this run; `false` → PostHog is already set up, go straight to\n * Self-driving. Resolves `session.integrate` from null.\n */\n setIntegrate(\n integrate: boolean,\n extra?: { via?: string; path?: string },\n ): void {\n this.$session.setKey('integrate', integrate);\n analytics.wizardCapture('self-driving integration check', {\n self_driving_integrate: integrate,\n ...(extra?.via ? { self_driving_integrate_via: extra.via } : {}),\n ...(extra?.path ? { self_driving_integrate_path: extra.path } : {}),\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n /**\n * Self-driving \"no PostHog account\" branch of the integration check. The\n * project has no SDK, so we always integrate (`integrate = true`); and since\n * the user has no account, we flip `signup` and record the `email` / `region`\n * collected on the screen so `authenticate` → `getOrAskForProjectData` takes\n * the provisioning path (create account + email a login link) instead of\n * OAuth. The \"yes, I have an account\" branch uses `setIntegrate(true)` and\n * leaves `signup` false so auth runs the normal OAuth login.\n */\n chooseProvisionAccount(email: string, region: CloudRegion): void {\n this.$session.setKey('signup', true);\n this.$session.setKey('email', email);\n this.$session.setKey('region', region);\n this.$session.setKey('integrate', true);\n analytics.wizardCapture('self-driving integration check', {\n self_driving_integrate: true,\n self_driving_has_account: false,\n provision_region: region,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n /**\n * Self-driving handoff confirmed — the user acknowledged the post-integration\n * screen, so the Self-driving run can begin. Gate resolves via _checkGates().\n */\n confirmSelfDrivingHandoff(): void {\n this.$session.setKey('selfDrivingHandoffConfirmed', true);\n this.emitChange();\n }\n\n /**\n * Mark a composed run step complete (e.g. self-driving's `integrate-run`).\n * Records the step id so its `isComplete` predicate holds, clears the task\n * list, and resets run phase to Idle so the next run step starts fresh.\n */\n completeRunStep(stepId: string): void {\n const done = this.session.completedRuns;\n if (!done.includes(stepId)) {\n this.$session.setKey('completedRuns', [...done, stepId]);\n }\n this.$tasks.set([]);\n this.setRunPhase(RunPhase.Idle);\n }\n\n setOutroDismissed(): void {\n this.$session.setKey('outroDismissed', true);\n this.emitChange();\n }\n\n setOutroData(data: OutroData): void {\n this.$session.setKey('outroData', data);\n this.emitChange();\n }\n\n setDashboardUrl(url: string): void {\n logToFile(`store.setDashboardUrl: ${url}`);\n this.$session.setKey('dashboardUrl', url);\n this.emitChange();\n }\n\n setNotebookUrl(url: string): void {\n logToFile(`store.setNotebookUrl: ${url}`);\n this.$session.setKey('notebookUrl', url);\n this.emitChange();\n }\n\n setFrameworkContext(key: string, value: unknown): void {\n const ctx = { ...this.$session.get().frameworkContext, [key]: value };\n this.$session.setKey('frameworkContext', ctx);\n this.emitChange();\n }\n\n // ── Derived state ───────────────────────────────────────────────\n\n /**\n * The screen that should be rendered right now.\n * Derived from session state via the router.\n */\n get currentScreen(): ScreenName {\n return this.router.resolve(this.session);\n }\n\n /** Direction hint for screen transitions. */\n get lastNavDirection(): 'push' | 'pop' | null {\n return this.router.lastNavDirection;\n }\n\n // ── Change notification ─────────────────────────────────────────\n\n getVersion(): number {\n return this.$version.get();\n }\n\n /**\n * Notify React that state has changed.\n * The router re-resolves the active screen on next render.\n * Gate predicates are checked and resolved if ready.\n */\n emitChange(): void {\n this.router._setDirection('push');\n this.$version.set(this.$version.get() + 1);\n this._checkGates();\n this._detectTransition();\n }\n\n // ── Overlay navigation ──────────────────────────────────────────\n\n pushOverlay(overlay: Overlay): void {\n this.router._setDirection('push');\n this.router.pushOverlay(overlay);\n this.$version.set(this.$version.get() + 1);\n this._detectTransition();\n }\n\n popOverlay(): void {\n this.router._setDirection('pop');\n this.router.popOverlay();\n this.$version.set(this.$version.get() + 1);\n this._detectTransition();\n }\n\n // ── ScreenId transition analytics ─────────────────────────────────\n\n /**\n * Register a callback to run when transitioning onto the given screen.\n * Fires after every transition that lands on this screen.\n */\n onEnterScreen(screen: ScreenName, fn: () => void): void {\n const list = this._enterScreenHooks.get(screen) ?? [];\n list.push(fn);\n this._enterScreenHooks.set(screen, list);\n }\n\n /**\n * The program `screen` reports under — its step's `reportsAsProgramId` if it\n * claims one, else the running program (also the fallback for overlays and\n * screens with no owning step).\n */\n private _programIdForScreen(screen: ScreenName): ProgramId {\n const program = this.router.activeProgram;\n const step = getProgramConfig(program).steps.find(\n (s) => s.screenId === screen,\n );\n return step?.reportsAsProgramId ?? program;\n }\n\n /** The program the visible screen reports under; screens stamp this on their\n * own events rather than relying on the run-level `program_id` tag. */\n get analyticsProgramId(): ProgramId {\n return this._programIdForScreen(this.router.resolve(this.session));\n }\n\n /**\n * Detect screen transitions, run enter-screen hooks, and fire analytics.\n * Called at the end of emitChange/pushOverlay/popOverlay.\n */\n private _detectTransition(): void {\n const next = this.router.resolve(this.session);\n const prev = this._lastScreen;\n if (next !== prev) {\n // Every event carries the active TUI screen, filling the\n // \"URL / Screen\" column in PostHog.\n analytics.setTag('$screen_name', next);\n }\n if (prev !== null && next !== prev) {\n const hooks = this._enterScreenHooks.get(next);\n if (hooks) {\n for (const fn of hooks) fn();\n }\n analytics.wizardCapture(`screen ${next}`, {\n from_screen: prev,\n program_id: this._programIdForScreen(next),\n ...sessionProperties(this.session),\n });\n }\n this._lastScreen = next;\n }\n\n // ── Agent observation state ─────────────────────────────────────\n\n pushStatus(message: string): void {\n const msgs = this.$statusMessages.get();\n // Skip consecutive duplicate messages (no allocation on the hot path)\n if (msgs.length > 0 && msgs[msgs.length - 1] === message) return;\n // Nanostore detects change by reference equality, so a new array is\n // required. At the cap, allocate exactly once at the final size (dropping\n // the oldest entry) rather than push-then-truncate.\n const next =\n msgs.length >= MAX_STATUS_MESSAGES\n ? [...msgs.slice(msgs.length - MAX_STATUS_MESSAGES + 1), message]\n : [...msgs, message];\n this.$statusMessages.set(next);\n this.emitChange();\n }\n\n get tokenUsage(): TokenUsageSnapshot {\n return this.$tokenUsage.get();\n }\n\n get tokenHudVisible(): boolean {\n return this.$tokenHudVisible.get();\n }\n\n /** Hidden Ctrl+T shortcut — see ScreenContainer. Not registered as a\n * keyboard hint, so it never shows in the hints bar. */\n toggleTokenHud(): void {\n this.$tokenHudVisible.set(!this.$tokenHudVisible.get());\n this.emitChange();\n }\n\n /**\n * Accumulate one assistant turn's token usage into the running estimate.\n * Approximate by design (no dedup for SDK-retried/replayed turns, unlike\n * the benchmark middleware's TurnCounterPlugin) — it's a live indicator\n * for a hidden debug HUD, not a billing record, and `setFinalTokenCostUsd`\n * corrects the total once the run's authoritative cost is known.\n */\n addTokenUsage(delta: TokenUsageDelta): void {\n const cur = this.$tokenUsage.get();\n if (cur.costIsFinal) return;\n const deltaCostUsd = computeTokenCostUsd(delta);\n this.$tokenUsage.set({\n inputTokens: cur.inputTokens + delta.inputTokens,\n outputTokens: cur.outputTokens + delta.outputTokens,\n cacheReadTokens: cur.cacheReadTokens + delta.cacheReadTokens,\n cacheCreationTokens: cur.cacheCreationTokens + delta.cacheCreationTokens,\n costUsd: cur.costUsd + deltaCostUsd,\n costIsFinal: false,\n });\n this.emitChange();\n }\n\n /** Reconcile the running cost estimate to the SDK's authoritative total\n * once the agent run completes — same trick the benchmark's\n * CostTrackerPlugin.onFinalize uses to correct any per-turn drift. */\n setFinalTokenCostUsd(costUsd: number): void {\n const cur = this.$tokenUsage.get();\n this.$tokenUsage.set({ ...cur, costUsd, costIsFinal: true });\n this.emitChange();\n }\n\n setTasks(tasks: TaskItem[]): void {\n this.$tasks.set(tasks);\n this.emitChange();\n }\n\n updateTask(index: number, done: boolean): void {\n const tasks = this.$tasks.get();\n if (tasks[index]) {\n const updated = [...tasks];\n updated[index] = {\n ...updated[index],\n done,\n status: done ? TaskStatus.Completed : TaskStatus.Pending,\n };\n this.$tasks.set(updated);\n this.emitChange();\n }\n }\n\n setEventPlan(events: PlannedEvent[]): void {\n this.$eventPlan.set(events);\n this.emitChange();\n }\n\n /** No-op on identical text: an emit here means a network push downstream. */\n setHandoffText(text: string): void {\n if (this.$handoffText.get() === text) return;\n logToFile(`store.setHandoffText: ${text.length} chars`);\n this.$handoffText.set(text);\n this.emitChange();\n }\n\n get learnCardBlockIdx(): number {\n return this.$learnCardBlockIdx.get();\n }\n\n setLearnCardBlockIdx(idx: number): void {\n this.$learnCardBlockIdx.set(idx);\n }\n\n get learnCardComplete(): boolean {\n return this.$learnCardComplete.get();\n }\n\n setLearnCardComplete(): void {\n this.$learnCardComplete.set(true);\n this.emitChange();\n }\n\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void {\n const incoming = todos.map((t) => {\n const status = isTaskStatus(t.status) ? t.status : TaskStatus.Pending;\n return {\n label: t.content,\n activeForm: t.activeForm,\n status,\n done: status === TaskStatus.Completed,\n };\n });\n\n const incomingLabels = new Set(incoming.map((t) => t.label));\n\n const retained = this.$tasks\n .get()\n .filter((t) => t.done && !incomingLabels.has(t.label));\n\n this.$tasks.set([...retained, ...incoming]);\n this.emitChange();\n this._onTasksChanged?.();\n }\n\n /** Register a listener for task state changes (e.g. task stream push). */\n set onTasksChanged(fn: () => void) {\n this._onTasksChanged = fn;\n }\n\n // ── React integration ───────────────────────────────────────────\n\n subscribe(callback: () => void): () => void {\n return this.$version.listen(() => callback());\n }\n\n getSnapshot(): number {\n return this.$version.get();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwVA,SAAgB,sBAAsB,OAInC;CACD,MAAM,UAAU,MACb,QAAQ,SAAS,KAAK,YAAY,KAAK,CACvC,KAAK,UAAU;EACd,IAAI,KAAK;EACT,MAAM,KAAK;EAIX,YAAY,KAAK,cAAc,KAAK;EACrC,EAAE;AAGL,SAAQ,KAAK;EAAE,IAAI;EAAQ,MAAM,KAAA;EAAW,YAAY,KAAA;EAAW,CAAC;AAEpE,QAAO;;;;;ACtUT,MAAa,oBAAoB;AAEjC,SAAS,WAAW,SAAiC;AACnD,QAAO,CAAC,CAAC,QAAQ,SAAS,cAAc;;;;;;;;AAS1C,SAAgB,gBAAgB,QAAsC;AACpE,KAA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OAAO,EAAE;IACT,YAAY,EAAE;IACd;IACA,MAAM,WAAA;IACP;IACD;EAEF,MAAM,iBAAiB,IAAI,IAAI,SAAS,KAAK,MAAM,EAAE,MAAM,CAAC;EAE5D,MAAM,WAAW,KAAK,OACnB,KAAK,CACL,QAAQ,MAAM,EAAE,QAAQ,CAAC,eAAe,IAAI,EAAE,MAAM,CAAC;AAExD,OAAK,OAAO,IAAI,CAAC,GAAG,UAAU,GAAG,SAAS,CAAC;AAC3C,OAAK,YAAY;AACjB,OAAK,mBAAmB;;;CAI1B,IAAI,eAAe,IAAgB;AACjC,OAAK,kBAAkB;;CAKzB,UAAU,UAAkC;AAC1C,SAAO,KAAK,SAAS,aAAa,UAAU,CAAC;;CAG/C,cAAsB;AACpB,SAAO,KAAK,SAAS,KAAK"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"task-B7LbltJW.js","names":[],"sources":["../src/lib/agent/runner/harness/pi/task.ts"],"sourcesContent":["/**\n * Orchestrator-mode execution on pi: one fresh pi session per unit of work —\n * the seed plan, or one drained task. The linear pipeline's concerns (skill\n * menu, todo panel, event-plan cleanup) stay in `index.ts`; this module builds\n * the leaner per-task session: gateway model, security fence, the task's\n * allowed coding tools, the wizard env tools, and the in-process orchestrator\n * queue tools.\n *\n * The task's `allowedTools` / `disallowedTools` arrive in the wizard's tool\n * vocabulary (`Read`, `Edit`, `Glob`, …, plus MCP-qualified orchestrator names\n * from `agentRunTools`). pi is where they become real: allowed names decide\n * which pi tool definitions get registered at all, and the disallow list is\n * ALSO handed to the security fence, so a name that never got registered stays\n * blocked even if the model hallucinates it.\n *\n * Loaded lazily from `index.ts` (typebox/ESM constraint, same as tools.ts).\n */\n\nimport { getUI } from '@ui';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport {\n Harness,\n Sequence,\n WIZARD_REMARK_EVENT_NAME,\n WIZARD_USER_AGENT,\n} from '@lib/constants';\nimport {\n allowsPostHogMcp,\n queueTools,\n renderToolInventory,\n} from '@lib/agent/agent-prompt-loader';\nimport { AgentErrorType } from '@lib/agent/agent-interface';\nimport { REMARK_INSTRUCTION } from '@lib/agent/signals';\nimport { AgentOutputSignals } from '@lib/agent/output-signals';\nimport { TaskStatus } from '../../sequence/orchestrator/queue';\nimport type { OrchestratorToolsContext } from '../../sequence/orchestrator/queue-tools';\nimport type { AgentResult, TaskRunInputs } from '../types';\nimport { gatewayAuth } from '@lib/gateway-session';\nimport { buildGatewayProvider, GATEWAY_PROVIDER } from './gateway';\nimport { assembleCommandments } from '../../switchboard/commandments';\nimport {\n applyOutroMarkers,\n buildScrubbedEnv,\n extractText,\n lastStatusLine,\n withMode,\n} from './index';\nimport { createAioCapture } from '@lib/agent/aio-capture';\n\n/** wizard tool vocabulary → the pi tool definitions it unlocks. */\nconst CODING_TOOL_MAP: Record<string, readonly string[]> = {\n Read: ['read'],\n Edit: ['edit'],\n Write: ['write'],\n Bash: ['bash'],\n Glob: ['find', 'ls'],\n Grep: ['grep'],\n};\n\n/** `mcp__wizard-tools__wizard_ask` → `wizard_ask`; native names pass through. */\nfunction shortToolName(name: string): string {\n return name.replace(/^mcp__.+?__/, '');\n}\n\n/**\n * The pi coding tools a task may use. An empty allow list means \"no\n * restriction\" (mirrors the SDK), so every coding tool registers.\n */\nexport function allowedPiCodingTools(\n allowedTools: readonly string[] | undefined,\n): Set<string> {\n const allowed = (allowedTools ?? []).map(shortToolName);\n const names = allowed.length\n ? allowed.flatMap((name) => CODING_TOOL_MAP[name] ?? [])\n : Object.values(CODING_TOOL_MAP).flat();\n return new Set(names);\n}\n\n/**\n * The orchestrator queue tools this agent gets. Everything not disallowed:\n * the seed's frontmatter disallows `complete_task` (it is not a task), a\n * task's disallows `enqueue_task` (the seed owns the graph).\n */\nexport function allowedOrchestratorTools(\n disallowedTools: readonly string[] | undefined,\n): Set<string> {\n return new Set(queueTools(disallowedTools ?? []));\n}\n\n/**\n * The wizard tools a task gets. Four are always on — their handlers are fenced\n * and the coding tasks depend on them. The rest are opt-in per task through\n * its frontmatter: `wizard_ask` stops the run until a person answers, and the\n * skill-menu pair (`load_skill_menu`, `install_skill`) lets a task pull its\n * own skill variant.\n */\nconst ALWAYS_ON_WIZARD_TOOLS = [\n 'check_env_keys',\n 'set_env_values',\n 'detect_package_manager',\n 'publish_handoff',\n];\n\nconst OPT_IN_WIZARD_TOOLS = ['wizard_ask', 'load_skill_menu', 'install_skill'];\n\nexport function allowedPiWizardTools(\n allowedTools: readonly string[] | undefined,\n): Set<string> {\n const allowed = (allowedTools ?? []).map(shortToolName);\n return new Set([\n ...ALWAYS_ON_WIZARD_TOOLS,\n ...OPT_IN_WIZARD_TOOLS.filter((tool) => allowed.includes(tool)),\n ]);\n}\n\n/**\n * The disallow list for the security fence: the wizard-vocabulary names as\n * given (the fence translates pi built-ins to the same vocabulary) plus the\n * short names, so a disallowed orchestrator tool is blocked under the name pi\n * would call it by.\n */\nexport function fenceDisallowList(\n disallowedTools: readonly string[] | undefined,\n): string[] {\n const names = disallowedTools ?? [];\n return [...new Set([...names, ...names.map(shortToolName)])];\n}\n\n/** Nudges when the session returns without the work reaching a terminal state. */\nconst MAX_TASK_NUDGES = 3;\n\nconst TASK_NUDGE =\n 'You have not called complete_task yet. Finish your task now: if the work is done, call complete_task with your handoff; if it cannot be done, call it with status \"failed\" or \"not needed\" and say why.';\n\nconst SEED_NUDGE =\n 'The queue is still empty. Seed it now with enqueue_task calls for the task graph you planned.';\n\n/** Whether this unit of work has reached its terminal state. */\nfunction isSettled(ctx: OrchestratorToolsContext): boolean {\n if (!ctx.currentTaskId) {\n // The seed's job is a seeded queue, not a complete_task call.\n return ctx.store.list().length > 0;\n }\n const task = ctx.store.get(ctx.currentTaskId);\n return (\n !!task &&\n (task.status === TaskStatus.Done ||\n task.status === TaskStatus.Failed ||\n task.status === TaskStatus.Skipped)\n );\n}\n\nexport async function runPiTask(inputs: TaskRunInputs): Promise<AgentResult> {\n const {\n session,\n programConfig,\n boot,\n prompt,\n spinner,\n model: modelId,\n effort,\n allowedTools,\n disallowedTools,\n askBridge,\n orchestrator,\n spinnerMessage,\n successMessage,\n errorMessage,\n requestRemark,\n analyticsProperties,\n } = inputs;\n\n if (spinnerMessage) spinner.start(spinnerMessage);\n\n const capture = createAioCapture({\n enabled: session.captureAio,\n projectApiKey: boot.credentials.projectApiKey,\n apiHost: boot.credentials.host.apiHost,\n runTags: boot.wizardMetadata,\n });\n\n const startTime = Date.now();\n const signals = new AgentOutputSignals();\n let assistantTurns = 0;\n const runDurations = () => {\n const durationMs = Date.now() - startTime;\n return {\n duration_ms: durationMs,\n duration_seconds: Math.round(durationMs / 1000),\n };\n };\n const captureAborted = () =>\n analytics.wizardCapture('agent aborted', {\n ...runDurations(),\n model: modelId,\n ...analyticsProperties,\n });\n\n try {\n const sdk = await import('@earendil-works/pi-coding-agent');\n const {\n createAgentSession,\n DefaultResourceLoader,\n SessionManager,\n AuthStorage,\n ModelRegistry,\n getAgentDir,\n createLsToolDefinition,\n createFindToolDefinition,\n createGrepToolDefinition,\n createBashToolDefinition,\n createReadToolDefinition,\n createEditToolDefinition,\n createWriteToolDefinition,\n } = sdk;\n\n const auth = await gatewayAuth(\n boot.credentials.host,\n boot.credentials.accessToken,\n boot.programId,\n );\n const { provider, caps } = buildGatewayProvider({\n gatewayUrl: auth.gatewayUrl,\n accessToken: auth.token,\n edition: auth.edition,\n teamId: auth.teamId,\n wizardMetadata: boot.wizardMetadata,\n wizardFlags: boot.wizardFlags,\n modelId,\n // Per-task agents own their effort via the prompt frontmatter, falling\n // back to the model table.\n effort,\n });\n const registry = ModelRegistry.inMemory(AuthStorage.create());\n registry.registerProvider(GATEWAY_PROVIDER, provider as never);\n const model = registry.find(GATEWAY_PROVIDER, modelId);\n if (!model) {\n return {\n error: AgentErrorType.API_ERROR,\n message: 'pi: gateway model could not be resolved',\n };\n }\n\n // Shared flag: true while a wizard_ask overlay is open. The ask tool sets\n // it (onAskPendingChange, below); the security fence reads it to pause\n // Write/Edit until the answer comes back. Wired the same way as the linear\n // pi run — without it the warehouse task could mutate files while its\n // credential prompt sits open (up to TASK_ASK_TIMEOUT_MS).\n const askState = { pending: false };\n\n // The same fail-closed fence as the linear run, with the task's disallow\n // list layered in (both the wizard-vocabulary and pi-short names).\n const { createSecurityExtension } = await import('./security');\n const security = createSecurityExtension({\n disallowedTools: fenceDisallowList(disallowedTools),\n triageProvider: boot.triageProvider,\n getWizardAskPending: () => askState.pending,\n });\n const { prewarmYaraScanner } = await import('@lib/yara-hooks');\n void prewarmYaraScanner();\n\n // PostHog MCP, for the tasks whose prompt requests it. Tasks that never\n // asked skip the handshake and never see a posthog tool.\n const extensionFactories = [security.factory] as Array<\n (pi: unknown) => void\n >;\n let mcpCleanup: (() => void) | undefined;\n let posthogMcp = false;\n if (allowsPostHogMcp(allowedTools)) {\n try {\n const { setupPostHogMcp } = await import('./mcp');\n const mcp = await setupPostHogMcp({\n mcpUrl: boot.credentials.host.mcpUrl,\n accessToken: boot.credentials.accessToken,\n userAgent: WIZARD_USER_AGENT,\n });\n extensionFactories.push(mcp.extensionFactory);\n mcpCleanup = mcp.cleanup;\n posthogMcp = true;\n } catch (err) {\n // Silent here reads as a task failure minutes later: a task that asked\n // for this tool can only skip or fail without it.\n logToFile(`[pi-task] PostHog MCP setup skipped: ${String(err)}`);\n analytics.wizardCapture('mcp setup failed', {\n harness: 'pi',\n scope: 'task',\n error: String(err).slice(0, 300),\n });\n }\n }\n\n const codingTools = allowedPiCodingTools(allowedTools);\n const orchestratorTools = allowedOrchestratorTools(disallowedTools);\n\n const resourceLoader = new DefaultResourceLoader({\n cwd: session.installDir,\n agentDir: getAgentDir(),\n systemPrompt: assembleCommandments({\n program: programConfig.id,\n sequence: Sequence.orchestrator,\n harness: Harness.pi,\n caps: { bash: codingTools.has('bash'), posthogMcp },\n }),\n noExtensions: true,\n noSkills: true,\n noContextFiles: true,\n noPromptTemplates: true,\n noThemes: true,\n extensionFactories,\n });\n await resourceLoader.reload();\n\n // The task's coding tools, gated by its allow list. Reads and searches run\n // in parallel; mutating tools stay sequential. Bash subprocesses get the\n // scrubbed env, same as the linear run.\n const dir = session.installDir;\n const codingToolFactories = {\n read: () => withMode(createReadToolDefinition(dir), 'parallel'),\n edit: () => withMode(createEditToolDefinition(dir), 'sequential'),\n write: () => withMode(createWriteToolDefinition(dir), 'sequential'),\n bash: () =>\n withMode(\n createBashToolDefinition(dir, {\n spawnHook: (ctx) => ({ ...ctx, env: buildScrubbedEnv() }),\n }),\n 'sequential',\n ),\n ls: () => withMode(createLsToolDefinition(dir), 'parallel'),\n find: () => withMode(createFindToolDefinition(dir), 'parallel'),\n grep: () => withMode(createGrepToolDefinition(dir), 'parallel'),\n } as const;\n const codingToolDefs = Object.entries(codingToolFactories)\n .filter(([name]) => codingTools.has(name))\n .map(([, make]) => make());\n\n // Wizard env + package-manager tools are always on — their handlers are\n // fenced, and init/build tasks depend on them. publish_handoff rides\n // along (store-only handler) so the report task can publish the handoff.\n const { createWizardPiTools } = await import('./tools');\n const wizardToolNames = allowedPiWizardTools(allowedTools);\n const wizardTools = createWizardPiTools({\n workingDirectory: dir,\n skillsBaseUrl: boot.skillsBaseUrl,\n triageProvider: boot.triageProvider,\n // Present only for a task allowed to ask; without it wizard_ask errors\n // instead of hanging on a prompt nobody will ever see.\n askBridge,\n // Pause Write/Edit while the ask overlay is open (see askState above).\n onAskPendingChange: (pending) => {\n askState.pending = pending;\n },\n }).filter((t) => wizardToolNames.has(t.name));\n\n const { createPiOrchestratorTools } = await import('./orchestrator-tools');\n const queueTools = createPiOrchestratorTools(orchestrator).filter((t) =>\n orchestratorTools.has(t.name),\n );\n\n const customTools = [...codingToolDefs, ...wizardTools, ...queueTools];\n const { session: agentSession } = await createAgentSession({\n model,\n modelRegistry: registry,\n thinkingLevel: caps.thinkingLevel,\n cwd: dir,\n sessionManager: SessionManager.inMemory(dir),\n resourceLoader,\n noTools: 'builtin',\n customTools,\n });\n await agentSession.bindExtensions({});\n\n // The one complete list: exactly the tools registered on this session, in\n // the names the agent will call them by. posthog_exec binds as an extension.\n const toolNames = [\n ...customTools.map((t) => t.name),\n ...(posthogMcp ? ['posthog_exec'] : []),\n ];\n logToFile(`[pi-task] tools passed to model: ${toolNames.join(', ')}`);\n const taskPrompt = `${prompt}\\n\\n${renderToolInventory(toolNames)}`;\n\n const unsubscribe = agentSession.subscribe((event) => {\n // Mirror the turn into AIO. No-op when --capture-aio is off. Runs\n // before the role guard so the module's own filter is authoritative.\n capture.captureFromPiMessageEndEvent(event);\n\n switch (event.type) {\n case 'message_end': {\n // User prompts also emit message_end; only assistant turns count.\n if ((event.message as { role?: string })?.role !== 'assistant') {\n break;\n }\n assistantTurns += 1;\n const assistant = extractText(event.message).trim();\n if (assistant) {\n logToFile(`[pi-task] assistant: ${assistant.slice(0, 1000)}`);\n applyOutroMarkers(assistant);\n const statusText = lastStatusLine(assistant);\n if (statusText) {\n getUI().pushStatus(statusText);\n spinner.message(statusText);\n }\n for (const line of assistant.split('\\n')) signals.push(line);\n }\n break;\n }\n case 'tool_execution_start': {\n const args = JSON.stringify(event.args ?? {}).slice(0, 200);\n logToFile(`[pi-task] → ${event.toolName} ${args}`);\n break;\n }\n case 'tool_execution_end': {\n if (event.isError) {\n const detail =\n typeof event.result === 'string'\n ? event.result\n : JSON.stringify(event.result ?? '');\n logToFile(`[pi-task] ✗ ${event.toolName}: ${detail.slice(0, 300)}`);\n }\n break;\n }\n default:\n break;\n }\n });\n\n // Seed AIO capture with this task's prompt — includes any handoff data\n // from prior tasks (the orchestrator bakes it into the prompt string\n // before it reaches this call site).\n capture.setInitialPrompt(taskPrompt);\n\n try {\n await agentSession.prompt(taskPrompt);\n\n // pi's prompt() resolves the moment a turn carries no tool call — which\n // an agent mid-plan does emit. While the work has not reached its\n // terminal state (task not reported, seed queue still empty), nudge.\n let nudges = 0;\n while (\n nudges < MAX_TASK_NUDGES &&\n !security.state.criticalViolation &&\n !isSettled(orchestrator)\n ) {\n nudges += 1;\n logToFile(\n `[pi-task] completion guard: not settled, nudge ${nudges}/${MAX_TASK_NUDGES}`,\n );\n await agentSession.prompt(\n orchestrator.currentTaskId ? TASK_NUDGE : SEED_NUDGE,\n );\n }\n\n if (requestRemark && !security.state.criticalViolation) {\n try {\n await agentSession.prompt(REMARK_INSTRUCTION);\n } catch (err) {\n logToFile(`[pi-task] remark request failed: ${String(err)}`);\n }\n }\n } finally {\n unsubscribe();\n mcpCleanup?.();\n }\n\n if (security.state.criticalViolation) {\n spinner.stop('Security violation detected');\n logToFile(\n `[pi-task] terminated: YARA violation (blocked ${security.state.blockedCount} call(s))`,\n );\n captureAborted();\n return { error: AgentErrorType.YARA_VIOLATION };\n }\n\n const remark = signals.remark();\n if (remark) {\n analytics.capture(WIZARD_REMARK_EVENT_NAME, { remark });\n }\n\n const stats = agentSession.getSessionStats();\n const durations = runDurations();\n analytics.wizardCapture('agent completed', {\n ...durations,\n model: modelId,\n num_turns: assistantTurns,\n input_tokens: stats.tokens.input,\n output_tokens: stats.tokens.output,\n cache_creation_input_tokens: stats.tokens.cacheWrite,\n cache_read_input_tokens: stats.tokens.cacheRead,\n ...analyticsProperties,\n });\n // Per-task usage on one parseable line so a run's per-task time and cost are\n // observable from the log, not only from analytics.\n const taskType =\n typeof (analyticsProperties as { task_type?: unknown })?.task_type ===\n 'string'\n ? (analyticsProperties as { task_type: string }).task_type\n : modelId;\n logToFile(\n `[pi-task] usage task=${taskType} model=${modelId} effort=${caps.thinkingLevel} dur=${durations.duration_seconds}s turns=${assistantTurns} in=${stats.tokens.input} out=${stats.tokens.output} cacheR=${stats.tokens.cacheRead} cacheW=${stats.tokens.cacheWrite}`,\n );\n if (successMessage) spinner.stop(successMessage);\n return {};\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logToFile(`[pi-task] run error: ${message}`);\n if (errorMessage || spinnerMessage) {\n spinner.stop(errorMessage ?? 'Task failed');\n }\n captureAborted();\n const lower = message.toLowerCase();\n if (lower.includes('rate limit') || lower.includes('429')) {\n return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