@posthog/wizard 2.49.0 → 2.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/{add-mcp-server-to-clients-DnyxFVhW.js → add-mcp-server-to-clients-C1f2al7N.js} +5 -5
  2. package/dist/{add-mcp-server-to-clients-DnyxFVhW.js.map → add-mcp-server-to-clients-C1f2al7N.js.map} +1 -1
  3. package/dist/{agent-interface-Doo3apDE.js → agent-interface-BL2wCV3b.js} +33 -71
  4. package/dist/agent-interface-BL2wCV3b.js.map +1 -0
  5. package/dist/agent-prompt-loader-CEWWA98d.js +275 -0
  6. package/dist/agent-prompt-loader-CEWWA98d.js.map +1 -0
  7. package/dist/{agent-runner-D7OZPgIV.js → agent-runner-DSKXFDXa.js} +101 -319
  8. package/dist/agent-runner-DSKXFDXa.js.map +1 -0
  9. package/dist/{analytics-D6gRGiqt.js → analytics-Ddf3zJgF.js} +20 -2
  10. package/dist/analytics-Ddf3zJgF.js.map +1 -0
  11. package/dist/analytics-GD_xM1XO.js +2 -0
  12. package/dist/{api-ZT2Zd5yp.js → api-BdanR3Zp.js} +3 -3
  13. package/dist/{api-ZT2Zd5yp.js.map → api-BdanR3Zp.js.map} +1 -1
  14. package/dist/bin.js +89 -90
  15. package/dist/bin.js.map +1 -1
  16. package/dist/bounded-fs-d0dw1Qv5.js +242 -0
  17. package/dist/bounded-fs-d0dw1Qv5.js.map +1 -0
  18. package/dist/{ci-install-CQWSPGdM.js → ci-install-DnVNVs0f.js} +4 -4
  19. package/dist/{ci-install-CQWSPGdM.js.map → ci-install-DnVNVs0f.js.map} +1 -1
  20. package/dist/commandments-BagyrYRW.js +2 -0
  21. package/dist/{commandments-DSNrOeOC.js → commandments-DiMtIz1o.js} +1 -1
  22. package/dist/{commandments-DSNrOeOC.js.map → commandments-DiMtIz1o.js.map} +1 -1
  23. package/dist/{debug-D8AJ_YCW.js → debug-By1_VtgZ.js} +1 -1
  24. package/dist/{debug-DF51kDvZ.js → debug-DaXKSXEy.js} +8 -27
  25. package/dist/debug-DaXKSXEy.js.map +1 -0
  26. package/dist/{defaults-CtWMmC8s.js → defaults-DAE9_QMn.js} +1 -1
  27. package/dist/{defaults-CtWMmC8s.js.map → defaults-DAE9_QMn.js.map} +1 -1
  28. package/dist/{env-api-key-C3LzH8Lr.js → env-api-key-DDVkPQmo.js} +1 -1
  29. package/dist/{env-api-key-C3LzH8Lr.js.map → env-api-key-DDVkPQmo.js.map} +1 -1
  30. package/dist/{environment-Csj7vBHM.js → environment-DJQOs7MR.js} +4 -4
  31. package/dist/environment-DJQOs7MR.js.map +1 -0
  32. package/dist/{file-watcher-CQB00KDS.js → file-watcher-LZe_W3hM.js} +2 -2
  33. package/dist/{file-watcher-CQB00KDS.js.map → file-watcher-LZe_W3hM.js.map} +1 -1
  34. package/dist/{headless-ui-DfSOfXEo.js → headless-ui-wIeUgvJ8.js} +2 -2
  35. package/dist/{headless-ui-DfSOfXEo.js.map → headless-ui-wIeUgvJ8.js.map} +1 -1
  36. package/dist/{interactive-DmRqhAUD.js → interactive-j4DoJDnk.js} +2 -2
  37. package/dist/{interactive-DmRqhAUD.js.map → interactive-j4DoJDnk.js.map} +1 -1
  38. package/dist/{mcp-B_ycbOus.js → mcp-Butt7ktW.js} +2 -2
  39. package/dist/{mcp-B_ycbOus.js.map → mcp-Butt7ktW.js.map} +1 -1
  40. package/dist/{mcp-prompt-streaming-ChEBHPQ-.js → mcp-prompt-streaming-D25BQfRa.js} +3 -3
  41. package/dist/{mcp-prompt-streaming-ChEBHPQ-.js.map → mcp-prompt-streaming-D25BQfRa.js.map} +1 -1
  42. package/dist/{non-interactive-ViR2FrQC.js → non-interactive-Cpof2JsA.js} +2 -2
  43. package/dist/{non-interactive-ViR2FrQC.js.map → non-interactive-Cpof2JsA.js.map} +1 -1
  44. package/dist/{orchestrator-tools-B0vrJlpS.js → orchestrator-tools-CsJizPpV.js} +3 -3
  45. package/dist/{orchestrator-tools-B0vrJlpS.js.map → orchestrator-tools-CsJizPpV.js.map} +1 -1
  46. package/dist/{package-json-DCuoye-H.js → package-json-CDs1ZVKu.js} +1 -1
  47. package/dist/{package-json-DCuoye-H.js.map → package-json-CDs1ZVKu.js.map} +1 -1
  48. package/dist/{package-manager-B6QAvLyt.js → package-manager-DnzNEjci.js} +2 -2
  49. package/dist/{package-manager-B6QAvLyt.js.map → package-manager-DnzNEjci.js.map} +1 -1
  50. package/dist/{pi-CXhGyUbi.js → pi-DE2cAVfO.js} +89 -138
  51. package/dist/pi-DE2cAVfO.js.map +1 -0
  52. package/dist/{playground-D_cP2oXt.js → playground-C3sLBq6A.js} +7 -7
  53. package/dist/{playground-D_cP2oXt.js.map → playground-C3sLBq6A.js.map} +1 -1
  54. package/dist/{posthog-integration-Bt8jQC7c.js → posthog-integration-_GSKRotZ.js} +45 -38
  55. package/dist/posthog-integration-_GSKRotZ.js.map +1 -0
  56. package/dist/{posthog-DZZbziJ1.js → posthog-mgz-FQlS.js} +1 -1
  57. package/dist/{posthog-DZZbziJ1.js.map → posthog-mgz-FQlS.js.map} +1 -1
  58. package/dist/{provisioning-By5DVLJr.js → provisioning-BndgugFk.js} +3 -3
  59. package/dist/{provisioning-By5DVLJr.js.map → provisioning-BndgugFk.js.map} +1 -1
  60. package/dist/{queue-tools-3iQHCpWF.js → queue-tools-DZjAjiqk.js} +97 -10
  61. package/dist/queue-tools-DZjAjiqk.js.map +1 -0
  62. package/dist/{registry-DG8r_Wks.js → registry-BMjfECF2.js} +272 -429
  63. package/dist/registry-BMjfECF2.js.map +1 -0
  64. package/dist/{security-BpbwefgM.js → security-D5hjYVFi.js} +4 -4
  65. package/dist/{security-BpbwefgM.js.map → security-D5hjYVFi.js.map} +1 -1
  66. package/dist/{setup-utils-CFejYe1M.js → setup-utils-ZKEk71yV.js} +14 -17
  67. package/dist/setup-utils-ZKEk71yV.js.map +1 -0
  68. package/dist/smoke-test.sh +1 -1
  69. package/dist/{start-tui-BINHq3Yp.js → start-tui-B2Tb427o.js} +19 -19
  70. package/dist/{start-tui-BINHq3Yp.js.map → start-tui-B2Tb427o.js.map} +1 -1
  71. package/dist/{steps-DhmMIChh.js → steps-ClMZ6MZd.js} +7 -7
  72. package/dist/{steps-DhmMIChh.js.map → steps-ClMZ6MZd.js.map} +1 -1
  73. package/dist/{store-Bj1m0ws-.js → store-Db77bfRv.js} +5 -5
  74. package/dist/{store-Bj1m0ws-.js.map → store-Db77bfRv.js.map} +1 -1
  75. package/dist/{subagent-DND7lZg6.js → subagent--VXEEc8S.js} +2 -2
  76. package/dist/{subagent-DND7lZg6.js.map → subagent--VXEEc8S.js.map} +1 -1
  77. package/dist/{task-CsAczwW6.js → task-CBQfx_f5.js} +30 -45
  78. package/dist/task-CBQfx_f5.js.map +1 -0
  79. package/dist/{task-stream-BaiI6TNY.js → task-stream-DCrqCmFa.js} +5 -5
  80. package/dist/{task-stream-BaiI6TNY.js.map → task-stream-DCrqCmFa.js.map} +1 -1
  81. package/dist/{tasks-DqDHx5pW.js → tasks-BJuz1XQ1.js} +2 -2
  82. package/dist/{tasks-DqDHx5pW.js.map → tasks-BJuz1XQ1.js.map} +1 -1
  83. package/dist/{telemetry-DXzPfSXl.js → telemetry-tdU6F90U.js} +3 -3
  84. package/dist/{telemetry-DXzPfSXl.js.map → telemetry-tdU6F90U.js.map} +1 -1
  85. package/dist/{terminal-DKsibL3T.js → terminal-ClWui_UN.js} +13 -13
  86. package/dist/{terminal-DKsibL3T.js.map → terminal-ClWui_UN.js.map} +1 -1
  87. package/dist/{tools-D5pL_r3K.js → tools-DwpaEyEv.js} +10 -8
  88. package/dist/tools-DwpaEyEv.js.map +1 -0
  89. package/dist/{wizard-abort-Br1Dps20.js → wizard-abort-B1iPXM3K.js} +4 -4
  90. package/dist/{wizard-abort-Br1Dps20.js.map → wizard-abort-B1iPXM3K.js.map} +1 -1
  91. package/dist/{wizard-abort-DG6Atd5I.js → wizard-abort-cX4Kytai.js} +1 -1
  92. package/dist/{wizard-session-tp4Zdbwl.js → wizard-session-BAZql11N.js} +1 -1
  93. package/dist/{wizard-session-tp4Zdbwl.js.map → wizard-session-BAZql11N.js.map} +1 -1
  94. package/dist/{wizard-session-DWHe83uk.js → wizard-session-C5lZPPEc.js} +1 -1
  95. package/dist/{yara-hooks-DEHfsDSF.js → yara-hooks-CEs3jx7j.js} +139 -56
  96. package/dist/yara-hooks-CEs3jx7j.js.map +1 -0
  97. package/dist/yara-hooks-gz4AceFG.js +2 -0
  98. package/package.json +2 -2
  99. package/dist/agent-interface-Doo3apDE.js.map +0 -1
  100. package/dist/agent-runner-D7OZPgIV.js.map +0 -1
  101. package/dist/analytics-AOHLZy1k.js +0 -2
  102. package/dist/analytics-D6gRGiqt.js.map +0 -1
  103. package/dist/commandments-qTW7pwaT.js +0 -2
  104. package/dist/debug-DF51kDvZ.js.map +0 -1
  105. package/dist/environment-Csj7vBHM.js.map +0 -1
  106. package/dist/file-utils-Dj3UqDJz.js +0 -116
  107. package/dist/file-utils-Dj3UqDJz.js.map +0 -1
  108. package/dist/pi-CXhGyUbi.js.map +0 -1
  109. package/dist/posthog-integration-Bt8jQC7c.js.map +0 -1
  110. package/dist/queue-tools-3iQHCpWF.js.map +0 -1
  111. package/dist/registry-DG8r_Wks.js.map +0 -1
  112. package/dist/setup-utils-CFejYe1M.js.map +0 -1
  113. package/dist/task-CsAczwW6.js.map +0 -1
  114. package/dist/tools-D5pL_r3K.js.map +0 -1
  115. package/dist/yara-hooks-BExxs6sG.js +0 -2
  116. package/dist/yara-hooks-DEHfsDSF.js.map +0 -1
@@ -1,8 +1,9 @@
1
- import { s as logToFile } from "./debug-DF51kDvZ.js";
2
- import { n as analytics } from "./analytics-D6gRGiqt.js";
3
- import { A as isFullyCancelled, C as mergeEnvValues, D as vaultSensitiveAnswers, E as resolveEnvSecretRefs, S as installSkillById, T as resolveEnvPath, _ as ENV_FILE_PATH_DESCRIPTION, b as evaluateAskCap, g as createSecretVault, v as WIZARD_TOOL_NAMES, w as parseEnvKeys, x as fetchSkillMenu } from "./agent-interface-Doo3apDE.js";
4
- import { r as detectNodePackageManagers } from "./package-manager-B6QAvLyt.js";
5
- import { o as withMode } from "./pi-CXhGyUbi.js";
1
+ import { s as logToFile } from "./debug-DaXKSXEy.js";
2
+ import { n as analytics } from "./analytics-Ddf3zJgF.js";
3
+ import { C as parseEnvKeys, E as vaultSensitiveAnswers, S as mergeEnvValues, T as resolveEnvSecretRefs, _ as WIZARD_TOOL_NAMES, b as fetchSkillMenu, g as ENV_FILE_PATH_DESCRIPTION, h as createSecretVault, k as isFullyCancelled, w as resolveEnvPath, x as installSkillById, y as evaluateAskCap } from "./agent-interface-BL2wCV3b.js";
4
+ import { w as createTriageLLMProvider } from "./yara-hooks-CEs3jx7j.js";
5
+ import { r as detectNodePackageManagers } from "./package-manager-DnzNEjci.js";
6
+ import { o as withMode } from "./pi-DE2cAVfO.js";
6
7
  import fs from "fs";
7
8
  import path from "path";
8
9
  import { Type } from "typebox";
@@ -30,7 +31,8 @@ function text(s) {
30
31
  };
31
32
  }
32
33
  function createWizardPiTools(ctx) {
33
- const { workingDirectory, skillsBaseUrl, askBridge, onAskPendingChange } = ctx;
34
+ const { workingDirectory, skillsBaseUrl, askBridge, onAskPendingChange, triageAuth } = ctx;
35
+ const skillScanTriageProvider = createTriageLLMProvider(triageAuth);
34
36
  const detectPackageManager = ctx.detectPackageManager ?? detectNodePackageManagers;
35
37
  const askMaxQuestions = ctx.maxQuestions ?? 10;
36
38
  let askCallCount = 0;
@@ -60,7 +62,7 @@ function createWizardPiTools(ctx) {
60
62
  promptSnippet: "install_skill(skillId) — install a skill, then read its SKILL.md",
61
63
  parameters: Type.Object({ skillId: Type.String({ description: "Skill ID from load_skill_menu" }) }),
62
64
  async execute(_id, args) {
63
- const result = await installSkillById(args.skillId, workingDirectory, skillsBaseUrl);
65
+ const result = await installSkillById(args.skillId, workingDirectory, skillsBaseUrl, void 0, skillScanTriageProvider);
64
66
  if (result.kind !== "ok") {
65
67
  logToFile(`[pi] install_skill ${args.skillId}: ${result.kind}`);
66
68
  return text(`Error installing skill "${args.skillId}": ${result.kind}. Use load_skill_menu to see valid IDs.`);
@@ -196,4 +198,4 @@ function createWizardPiTools(ctx) {
196
198
  //#endregion
197
199
  export { createWizardPiTools };
198
200
 
199
- //# sourceMappingURL=tools-D5pL_r3K.js.map
201
+ //# sourceMappingURL=tools-DwpaEyEv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-DwpaEyEv.js","names":[],"sources":["../src/lib/agent/runner/harness/pi/tools.ts"],"sourcesContent":["/**\n * Wizard capabilities as pi custom tools (#5). pi does not mount MCP servers,\n * so the tools the wizard prompt depends on — skill discovery/install and\n * fenced `.env` edits — are exposed to pi as native `defineTool` tools backed\n * by the same helpers the claude-agent-sdk path uses (`fetchSkillMenu`,\n * `installSkillById`, `parseEnvKeys`, `mergeEnvValues`). Same tool names as the\n * MCP server so the shared prompt is unchanged. `wizard_ask` is wired here too\n * (same schema, caps, and askBridge as the MCP tool) so interactive programs\n * can interview the user on pi; without a bridge (CI) it errors on call.\n * Sensitive answers are vaulted to `{secretRef}` and resolved host-side by\n * set_env_values — the raw value never enters the model conversation.\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport { Type } from 'typebox';\nimport { defineTool } from '@earendil-works/pi-coding-agent';\nimport type { ToolDefinition } from '@earendil-works/pi-coding-agent';\nimport { analytics } from '@utils/analytics';\nimport { logToFile } from '@utils/debug';\nimport {\n DEFAULT_ASK_MAX_QUESTIONS,\n ENV_FILE_PATH_DESCRIPTION,\n WIZARD_TOOL_NAMES,\n evaluateAskCap,\n fetchSkillMenu,\n installSkillById,\n mergeEnvValues,\n parseEnvKeys,\n resolveEnvPath,\n resolveEnvSecretRefs,\n vaultSensitiveAnswers,\n} from '@lib/wizard-tools/tools';\nimport {\n createTriageLLMProvider,\n type TriageGatewayAuth,\n} from '@lib/agent/triage-provider';\nimport { isFullyCancelled, type WizardAskBridge } from '@lib/wizard-ask-bridge';\nimport { createSecretVault } from '@lib/secret-vault';\nimport { withMode } from './index';\nimport {\n detectNodePackageManagers,\n type PackageManagerDetector,\n} from '@lib/detection/package-manager';\n\nfunction text(s: string): {\n content: [{ type: 'text'; text: string }];\n details: unknown;\n} {\n return { content: [{ type: 'text', text: s }], details: {} };\n}\n\nexport interface PiToolsContext {\n workingDirectory: string;\n skillsBaseUrl: string;\n /** Framework's package-manager detector. Defaults to Node detection. */\n detectPackageManager?: PackageManagerDetector;\n /** Drives the `wizard_ask` overlay. Omitted in CI → the tool errors on call. */\n askBridge?: WizardAskBridge;\n /** Per-run cap on wizard_ask calls. Defaults to {@link DEFAULT_ASK_MAX_QUESTIONS}. */\n maxQuestions?: number;\n /** Overlay open/closed signal — the security gate blocks Write/Edit while open. */\n onAskPendingChange?: (pending: boolean) => void;\n /** Program disallow list; gates wizard_ask here since pi tools carry bare names the MCP-prefixed security gate misses. */\n disallowedTools?: readonly string[];\n /**\n * Gateway auth for triaging a freshly installed skill. pi auths the gateway\n * programmatically and never sets the ANTHROPIC_* env vars, so the env\n * fallback in createTriageLLMProvider is empty here — without this the\n * skill-install scan runs untriaged and fails closed, blocking clean\n * first-party skills.\n */\n triageAuth?: TriageGatewayAuth;\n}\n\nexport function createWizardPiTools(ctx: PiToolsContext): ToolDefinition[] {\n const {\n workingDirectory,\n skillsBaseUrl,\n askBridge,\n onAskPendingChange,\n triageAuth,\n } = ctx;\n // Build the triage provider from pi's explicit gateway auth (env fallback is\n // empty on pi) so install_skill can triage rather than block untriaged.\n const skillScanTriageProvider = createTriageLLMProvider(triageAuth);\n const detectPackageManager =\n ctx.detectPackageManager ?? detectNodePackageManagers;\n const askMaxQuestions = ctx.maxQuestions ?? DEFAULT_ASK_MAX_QUESTIONS;\n // Per-run wizard_ask accounting (total cap + one-time adjacency nudge),\n // mirroring the MCP server's counters.\n let askCallCount = 0;\n let askAdjacencyNudged = false;\n // Session-scoped secret vault, same contract as the MCP server: wizard_ask\n // mints `{secretRef}` for sensitive answers, set_env_values resolves them.\n const secretVault = createSecretVault();\n\n // Fetch the skill menu at most once per run — the agent calls load_skill_menu\n // 2-3× otherwise, each a fresh HTTP round-trip (profiled slowness).\n let menuPromise: ReturnType<typeof fetchSkillMenu> | undefined;\n const getSkillMenu = () => (menuPromise ??= fetchSkillMenu(skillsBaseUrl));\n\n const loadSkillMenu = defineTool({\n name: 'load_skill_menu',\n label: 'Load skill menu',\n description:\n 'Load available PostHog skills for a category. Returns skill IDs and names. Call this first, then install_skill with the chosen ID.',\n promptSnippet:\n 'load_skill_menu(category) — list installable PostHog skills',\n parameters: Type.Object({\n category: Type.String({\n description: 'Skill category, e.g. \"integration\"',\n }),\n }),\n async execute(_id, args) {\n const menu = await getSkillMenu();\n if (!menu) return text('Error: could not load the skill menu.');\n const skills = menu.categories[args.category] ?? [];\n if (skills.length === 0) {\n return text(`No skills found for category \"${args.category}\".`);\n }\n logToFile(`[pi] load_skill_menu: ${skills.length} skills`);\n return text(skills.map((s) => `- ${s.id}: ${s.name}`).join('\\n'));\n },\n });\n\n const installSkill = defineTool({\n name: 'install_skill',\n label: 'Install skill',\n description:\n 'Download and install a PostHog skill by ID into .claude/skills/<skillId>/. Call load_skill_menu first. Then read the installed SKILL.md and follow it.',\n promptSnippet:\n 'install_skill(skillId) — install a skill, then read its SKILL.md',\n parameters: Type.Object({\n skillId: Type.String({ description: 'Skill ID from load_skill_menu' }),\n }),\n async execute(_id, args) {\n const result = await installSkillById(\n args.skillId,\n workingDirectory,\n skillsBaseUrl,\n undefined,\n skillScanTriageProvider,\n );\n if (result.kind !== 'ok') {\n logToFile(`[pi] install_skill ${args.skillId}: ${result.kind}`);\n return text(\n `Error installing skill \"${args.skillId}\": ${result.kind}. Use load_skill_menu to see valid IDs.`,\n );\n }\n logToFile(`[pi] install_skill ${args.skillId} -> ${result.path}`);\n return text(\n `Installed \"${args.skillId}\" at ${result.path}. Read ${result.path}/SKILL.md and follow it.`,\n );\n },\n });\n\n const checkEnvKeys = defineTool({\n name: 'check_env_keys',\n label: 'Check env keys',\n description:\n 'Check which environment variable keys are present or missing in a .env file. Never reveals values.',\n promptSnippet: 'check_env_keys(filePath, keys) — see which .env keys exist',\n parameters: Type.Object({\n filePath: Type.String({\n description: ENV_FILE_PATH_DESCRIPTION,\n }),\n keys: Type.Array(Type.String(), {\n description: 'Environment variable key names to check',\n }),\n }),\n async execute(_id, args) {\n const resolved = resolveEnvPath(workingDirectory, args.filePath);\n const existing = fs.existsSync(resolved)\n ? parseEnvKeys(await fs.promises.readFile(resolved, 'utf8'))\n : new Set<string>();\n const results: Record<string, 'present' | 'missing'> = {};\n for (const key of args.keys) {\n results[key] = existing.has(key) ? 'present' : 'missing';\n }\n return text(JSON.stringify(results, null, 2));\n },\n });\n\n const setEnvValues = defineTool({\n name: 'set_env_values',\n label: 'Set env values',\n description:\n 'Create or update environment variable keys in a .env file (creates the file if missing). Each value is either a literal string or a secret reference `{ \"secretRef\": \"secret:...\" }` returned by wizard_ask — refs are resolved locally, so the actual value is written to the file but never returned to the agent.',\n promptSnippet:\n 'set_env_values(filePath, values) — write .env keys (never hardcode secrets in source)',\n parameters: Type.Object({\n filePath: Type.String({\n description: ENV_FILE_PATH_DESCRIPTION,\n }),\n values: Type.Record(\n Type.String(),\n Type.Union([Type.String(), Type.Object({ secretRef: Type.String() })]),\n {\n description:\n 'Key → (literal string OR { secretRef } pointing to a vaulted secret)',\n },\n ),\n }),\n async execute(_id, args) {\n const forbidden = Object.keys(args.values).find(\n (k) => k.toUpperCase() === 'POSTHOG_KEY',\n );\n if (forbidden) {\n return text(\n `Error: \"${forbidden}\" is not a valid PostHog env var name. Use the framework-specific key (e.g. NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN).`,\n );\n }\n // Resolve secret refs host-side; the value never reaches the agent.\n const resolution = resolveEnvSecretRefs(args.values, secretVault);\n if (!resolution.ok) {\n return text(\n `Error: secret reference \"${resolution.secretRef}\" for key \"${resolution.key}\" is not known to the vault. The ref may have expired, been minted in a different run, or been mistyped.`,\n );\n }\n const resolved = resolveEnvPath(workingDirectory, args.filePath);\n const existing = fs.existsSync(resolved)\n ? await fs.promises.readFile(resolved, 'utf8')\n : '';\n const merged = mergeEnvValues(existing, resolution.values);\n const dir = path.dirname(resolved);\n if (!fs.existsSync(dir))\n await fs.promises.mkdir(dir, { recursive: true });\n await fs.promises.writeFile(resolved, merged, 'utf8');\n logToFile(\n `[pi] set_env_values: ${resolved} keys=${Object.keys(args.values).join(\n ',',\n )}`,\n );\n return text(\n `Wrote ${Object.keys(args.values).length} key(s) to ${args.filePath}.`,\n );\n },\n });\n\n const detectPm = defineTool({\n name: 'detect_package_manager',\n label: 'Detect package manager',\n description:\n \"Detect the project's package manager(s). Returns the name and the install command for each. Call this before installing a dependency, then RUN the returned install command (with the posthog package) via bash — the SDK package must end up in the project manifest, or the app will not build.\",\n promptSnippet:\n 'detect_package_manager() — find the PM + install command, then run it via bash to add the SDK',\n parameters: Type.Object({}),\n async execute() {\n const result = await detectPackageManager(workingDirectory);\n logToFile(\n `[pi] detect_package_manager: ${result.detected.length} detected`,\n );\n return text(JSON.stringify(result, null, 2));\n },\n });\n\n // Native mirror of the MCP `wizard_ask` tool: same name, schema, and\n // askBridge, so the shared prompt is unchanged.\n const wizardAsk = defineTool({\n name: 'wizard_ask',\n label: 'Ask the user',\n description:\n 'Ask the user one or more structured questions and wait for their answers. ' +\n 'Use this whenever you would otherwise inline a question in your text output. ' +\n 'Batch related questions into a single call (up to 8) rather than asking one at ' +\n 'a time; sequential calls are fine when later questions genuinely depend on ' +\n 'earlier answers. A fully cancelled or timed-out response does NOT count against ' +\n 'the per-run cap — treat it as \"the user declined\" and fall back gracefully.',\n promptSnippet:\n 'wizard_ask(questions) — ask the user structured questions and wait for answers',\n parameters: Type.Object({\n questions: Type.Array(\n Type.Object({\n id: Type.String({\n description: 'Stable key for the answer in the response map',\n }),\n prompt: Type.String({\n description: 'Question text shown to the user',\n }),\n kind: Type.Union(\n [\n Type.Literal('single'),\n Type.Literal('multi'),\n Type.Literal('text'),\n ],\n {\n description:\n \"'single' = pick one option, 'multi' = pick any, 'text' = free-form single-line answer\",\n },\n ),\n options: Type.Optional(\n Type.Array(\n Type.Object({\n label: Type.String(),\n value: Type.String(),\n description: Type.Optional(Type.String()),\n }),\n {\n description:\n 'Required for kind=single|multi; ignored for kind=text',\n },\n ),\n ),\n required: Type.Optional(\n Type.Boolean({ description: 'Defaults to true' }),\n ),\n sensitive: Type.Optional(\n Type.Boolean({\n description:\n \"Only valid for kind='text'. The answer is stored in the wizard's secret vault and returned as { secretRef: 'secret:...' } instead of the raw string. Use for API keys and tokens; the ref is resolved only by tools that accept it (e.g. set_env_values).\",\n }),\n ),\n }),\n { minItems: 1, maxItems: 8 },\n ),\n }),\n async execute(_id, args) {\n if (!askBridge) {\n return text(\n 'Error: wizard_ask is not available in this environment (CI / non-interactive). Proceed with sensible defaults or emit [ABORT] requirements-incomplete.',\n );\n }\n\n const cap = evaluateAskCap(\n askCallCount,\n askMaxQuestions,\n askAdjacencyNudged,\n );\n if (cap.kind === 'capped') {\n if (cap.reason === 'adjacency') askAdjacencyNudged = true;\n logToFile(\n `[pi] wizard_ask capped: reason=${cap.reason} count=${askCallCount}`,\n );\n analytics.wizardCapture('wizard_ask capped', {\n reason: cap.reason,\n call_count: askCallCount,\n max_questions: askMaxQuestions,\n });\n return text(cap.message);\n }\n\n // The schema can't enforce per-kind requirements or unique ids.\n const ids = new Set<string>();\n for (const q of args.questions) {\n if ((q.kind === 'single' || q.kind === 'multi') && !q.options?.length) {\n return text(\n `Error: question \"${q.id}\" has kind=\"${q.kind}\" but no options. Provide at least one { label, value }, or use kind=\"text\".`,\n );\n }\n if (q.sensitive && q.kind !== 'text') {\n return text(\n `Error: question \"${q.id}\" sets sensitive=true but kind=\"${q.kind}\". Only kind=\"text\" answers can be sensitive.`,\n );\n }\n if (ids.has(q.id)) {\n return text(\n `Error: duplicate question id \"${q.id}\". Each question needs a unique id.`,\n );\n }\n ids.add(q.id);\n }\n\n // Optimistically take the slot; refund it on a cancellation or a bridge\n // error so a declined/failed ask doesn't burn the budget for later ones.\n askCallCount += 1;\n // Block Write/Edit for as long as the overlay is open, so the agent can't\n // mutate files while it's waiting on the user's answer.\n onAskPendingChange?.(true);\n try {\n const answers = await askBridge.request({ questions: args.questions });\n if (isFullyCancelled(answers)) askCallCount -= 1;\n // Sensitive answers go to the vault; the agent sees an opaque ref\n // (same contract as the MCP wizard_ask).\n const sanitised = vaultSensitiveAnswers(\n args.questions,\n answers,\n secretVault,\n );\n logToFile(\n `[pi] wizard_ask: resolved ${\n Object.keys(answers).length\n } answer(s) for ${args.questions.length} question(s)`,\n );\n return text(JSON.stringify({ answers: sanitised }, null, 2));\n } catch (err) {\n askCallCount -= 1;\n const message = err instanceof Error ? err.message : String(err);\n logToFile(`[pi] wizard_ask: error: ${message}`);\n return text(`Error: wizard_ask failed: ${message}`);\n } finally {\n onAskPendingChange?.(false);\n }\n },\n });\n\n const tools = [\n loadSkillMenu,\n installSkill,\n checkEnvKeys,\n setEnvValues,\n detectPm,\n ];\n // Register wizard_ask only when the program allows it. posthog-integration\n // disallows it (runs without structured user input); self-driving keeps it.\n // Sequential: the ask bridge holds a single in-flight question slot, so a\n // batched turn must never dispatch two asks (or an ask + a write) at once.\n const askDisallowed =\n ctx.disallowedTools?.includes(WIZARD_TOOL_NAMES.wizardAsk) ?? false;\n if (!askDisallowed) tools.push(withMode(wizardAsk, 'sequential'));\n return tools;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,KAAK,GAGZ;AACA,QAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAG,CAAC;EAAE,SAAS,EAAE;EAAE;;AA0B9D,SAAgB,oBAAoB,KAAuC;CACzE,MAAM,EACJ,kBACA,eACA,WACA,oBACA,eACE;CAGJ,MAAM,0BAA0B,wBAAwB,WAAW;CACnE,MAAM,uBACJ,IAAI,wBAAwB;CAC9B,MAAM,kB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AU,OAAO,cACzC;AACD,WAAO,KAAK,KAAK,UAAU,EAAE,SAAS,WAAW,EAAE,MAAM,EAAE,CAAC;YACrD,KAAK;AACZ,oBAAgB;IAChB,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAChE,cAAU,2BAA2B,UAAU;AAC/C,WAAO,KAAK,6BAA6B,UAAU;aAC3C;AACR,yBAAqB,MAAM;;;EAGhC,CAAC;CAEF,MAAM,QAAQ;EACZ;EACA;EACA;EACA;EACA;EACD;AAOD,KAAI,EADF,IAAI,iBAAiB,SAAS,kBAAkB,UAAU,IAAI,OAC5C,OAAM,KAAK,SAAS,WAAW,aAAa,CAAC;AACjE,QAAO"}
@@ -1,6 +1,6 @@
1
- import { f as getUI, s as logToFile } from "./debug-DF51kDvZ.js";
2
- import { n as analytics } from "./analytics-D6gRGiqt.js";
3
- import "./wizard-session-tp4Zdbwl.js";
1
+ import { f as getUI, s as logToFile } from "./debug-DaXKSXEy.js";
2
+ import { n as analytics } from "./analytics-Ddf3zJgF.js";
3
+ import "./wizard-session-BAZql11N.js";
4
4
  //#region src/utils/wizard-abort.ts
5
5
  /**
6
6
  * Single exit point for the wizard. Use instead of process.exit() directly.
@@ -46,4 +46,4 @@ async function wizardAbort(options) {
46
46
  //#endregion
47
47
  export { wizardAbort as i, registerCleanup as n, runCleanups as r, WizardError as t };
48
48
 
49
- //# sourceMappingURL=wizard-abort-Br1Dps20.js.map
49
+ //# sourceMappingURL=wizard-abort-B1iPXM3K.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"wizard-abort-Br1Dps20.js","names":[],"sources":["../src/utils/wizard-abort.ts"],"sourcesContent":["/**\n * Single exit point for the wizard. Use instead of process.exit() directly.\n *\n * Sequence: cleanup -> error capture (optional) -> analytics shutdown -> outro -> process.exit\n *\n * WizardError is a data carrier passed to wizardAbort() for analytics context, never thrown.\n * The legacy abort() in setup-utils.ts delegates here.\n */\nimport { analytics } from './analytics';\nimport { logToFile } from './debug';\nimport { getUI } from '@ui';\nimport { OutroKind, type OutroData } from '@lib/wizard-session';\n\nexport class WizardError extends Error {\n constructor(\n message: string,\n public readonly context?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'WizardError';\n }\n}\n\ninterface WizardAbortOptions {\n message?: string;\n /** Structured error data. Renders via `outroError` instead of `outro`. */\n outroData?: OutroData;\n error?: Error | WizardError;\n exitCode?: number;\n}\n\nconst cleanupFns: Array<() => void> = [];\n\nexport function registerCleanup(fn: () => void): void {\n cleanupFns.push(fn);\n}\n\nexport function clearCleanup(): void {\n cleanupFns.length = 0;\n}\n\n/** Runs all registered cleanup functions and drains the array. */\nexport function runCleanups(): void {\n const fns = cleanupFns.splice(0);\n for (const fn of fns) {\n try {\n fn();\n } catch {\n /* cleanup should not prevent exit */\n }\n }\n}\n\nexport async function wizardAbort(\n options?: WizardAbortOptions,\n): Promise<never> {\n const {\n message = 'Wizard setup cancelled.',\n outroData,\n error,\n exitCode = 1,\n } = options ?? {};\n\n logToFile(`[wizard-abort] exitCode=${exitCode}, message: ${message}`);\n if (error) {\n logToFile('[wizard-abort] error:', error);\n }\n\n // 1. Run registered cleanup functions\n runCleanups();\n\n // 2. Capture error in analytics (if provided)\n if (error) {\n analytics.captureException(error, {\n ...((error instanceof WizardError && error.context) || {}),\n });\n }\n\n // 3. Shutdown analytics\n await analytics.shutdown(error ? 'error' : 'cancelled');\n\n // 4. Render the error outro. Synthesize OutroData from `message`\n // when the caller didn't provide structured data.\n const ui = getUI();\n ui.outroError(outroData ?? { kind: OutroKind.Error, message });\n\n // 5. Wait for the user to dismiss the outro screen. In a TUI this gives\n // them time to read the error; in non-TUI environments it resolves\n // immediately.\n await ui.waitForOutroDismissed();\n\n // 6. Exit (fires 'exit' event so TUI cleanup runs)\n return process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,cAAb,cAAiC,MAAM;CACrC,YACE,SACA,SACA;AACA,QAAM,QAAQ;AAFE,OAAA,UAAA;AAGhB,OAAK,OAAO;;;AAYhB,MAAM,aAAgC,EAAE;AAExC,SAAgB,gBAAgB,IAAsB;AACpD,YAAW,KAAK,GAAG;;;AAQrB,SAAgB,cAAoB;CAClC,MAAM,MAAM,WAAW,OAAO,EAAE;AAChC,MAAK,MAAM,MAAM,IACf,KAAI;AACF,MAAI;SACE;;AAMZ,eAAsB,YACpB,SACgB;CAChB,MAAM,EACJ,UAAU,2BACV,WACA,OACA,WAAW,MACT,WAAW,EAAE;AAEjB,WAAU,2BAA2B,SAAS,aAAa,UAAU;AACrE,KAAI,MACF,WAAU,yBAAyB,MAAM;AAI3C,cAAa;AAGb,KAAI,MACF,WAAU,iBAAiB,OAAO,EAChC,GAAK,iBAAiB,eAAe,MAAM,WAAY,EAAE,EAC1D,CAAC;AAIJ,OAAM,UAAU,SAAS,QAAQ,UAAU,YAAY;CAIvD,MAAM,KAAK,OAAO;AAClB,IAAG,WAAW,aAAa;EAAE,MAAA;EAAuB;EAAS,CAAC;AAK9D,OAAM,GAAG,uBAAuB;AAGhC,QAAO,QAAQ,KAAK,SAAS"}
1
+ {"version":3,"file":"wizard-abort-B1iPXM3K.js","names":[],"sources":["../src/utils/wizard-abort.ts"],"sourcesContent":["/**\n * Single exit point for the wizard. Use instead of process.exit() directly.\n *\n * Sequence: cleanup -> error capture (optional) -> analytics shutdown -> outro -> process.exit\n *\n * WizardError is a data carrier passed to wizardAbort() for analytics context, never thrown.\n * The legacy abort() in setup-utils.ts delegates here.\n */\nimport { analytics } from './analytics';\nimport { logToFile } from './debug';\nimport { getUI } from '@ui';\nimport { OutroKind, type OutroData } from '@lib/wizard-session';\n\nexport class WizardError extends Error {\n constructor(\n message: string,\n public readonly context?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'WizardError';\n }\n}\n\ninterface WizardAbortOptions {\n message?: string;\n /** Structured error data. Renders via `outroError` instead of `outro`. */\n outroData?: OutroData;\n error?: Error | WizardError;\n exitCode?: number;\n}\n\nconst cleanupFns: Array<() => void> = [];\n\nexport function registerCleanup(fn: () => void): void {\n cleanupFns.push(fn);\n}\n\nexport function clearCleanup(): void {\n cleanupFns.length = 0;\n}\n\n/** Runs all registered cleanup functions and drains the array. */\nexport function runCleanups(): void {\n const fns = cleanupFns.splice(0);\n for (const fn of fns) {\n try {\n fn();\n } catch {\n /* cleanup should not prevent exit */\n }\n }\n}\n\nexport async function wizardAbort(\n options?: WizardAbortOptions,\n): Promise<never> {\n const {\n message = 'Wizard setup cancelled.',\n outroData,\n error,\n exitCode = 1,\n } = options ?? {};\n\n logToFile(`[wizard-abort] exitCode=${exitCode}, message: ${message}`);\n if (error) {\n logToFile('[wizard-abort] error:', error);\n }\n\n // 1. Run registered cleanup functions\n runCleanups();\n\n // 2. Capture error in analytics (if provided)\n if (error) {\n analytics.captureException(error, {\n ...((error instanceof WizardError && error.context) || {}),\n });\n }\n\n // 3. Shutdown analytics\n await analytics.shutdown(error ? 'error' : 'cancelled');\n\n // 4. Render the error outro. Synthesize OutroData from `message`\n // when the caller didn't provide structured data.\n const ui = getUI();\n ui.outroError(outroData ?? { kind: OutroKind.Error, message });\n\n // 5. Wait for the user to dismiss the outro screen. In a TUI this gives\n // them time to read the error; in non-TUI environments it resolves\n // immediately.\n await ui.waitForOutroDismissed();\n\n // 6. Exit (fires 'exit' event so TUI cleanup runs)\n return process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,cAAb,cAAiC,MAAM;CACrC,YACE,SACA,SACA;AACA,QAAM,QAAQ;AAFE,OAAA,UAAA;AAGhB,OAAK,OAAO;;;AAYhB,MAAM,aAAgC,EAAE;AAExC,SAAgB,gBAAgB,IAAsB;AACpD,YAAW,KAAK,GAAG;;;AAQrB,SAAgB,cAAoB;CAClC,MAAM,MAAM,WAAW,OAAO,EAAE;AAChC,MAAK,MAAM,MAAM,IACf,KAAI;AACF,MAAI;SACE;;AAMZ,eAAsB,YACpB,SACgB;CAChB,MAAM,EACJ,UAAU,2BACV,WACA,OACA,WAAW,MACT,WAAW,EAAE;AAEjB,WAAU,2BAA2B,SAAS,aAAa,UAAU;AACrE,KAAI,MACF,WAAU,yBAAyB,MAAM;AAI3C,cAAa;AAGb,KAAI,MACF,WAAU,iBAAiB,OAAO,EAChC,GAAK,iBAAiB,eAAe,MAAM,WAAY,EAAE,EAC1D,CAAC;AAIJ,OAAM,UAAU,SAAS,QAAQ,UAAU,YAAY;CAIvD,MAAM,KAAK,OAAO;AAClB,IAAG,WAAW,aAAa;EAAE,MAAA;EAAuB;EAAS,CAAC;AAK9D,OAAM,GAAG,uBAAuB;AAGhC,QAAO,QAAQ,KAAK,SAAS"}
@@ -1,2 +1,2 @@
1
- import { i as wizardAbort, t as WizardError } from "./wizard-abort-Br1Dps20.js";
1
+ import { i as wizardAbort, t as WizardError } from "./wizard-abort-B1iPXM3K.js";
2
2
  export { WizardError, wizardAbort };
@@ -95,4 +95,4 @@ function buildSession(args) {
95
95
  //#endregion
96
96
  export { buildSession as a, RunPhase as i, ADDITIONAL_FEATURE_PROMPTS as n, OutroKind as r, ADDITIONAL_FEATURE_LABELS as t };
97
97
 
98
- //# sourceMappingURL=wizard-session-tp4Zdbwl.js.map
98
+ //# sourceMappingURL=wizard-session-BAZql11N.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"wizard-session-tp4Zdbwl.js","names":[],"sources":["../src/lib/wizard-session.ts"],"sourcesContent":["/**\n * WizardSession — single source of truth for every decision the wizard needs.\n *\n * Populated in layers:\n * CLI args / env vars → populate fields directly\n * Auto-detection → framework, typescript, package manager\n * TUI screens → region, framework disambiguation, etc.\n * OAuth → credentials\n *\n * Business logic reads from the session. Never calls a prompt.\n */\n\nimport type { Harness, Integration, Sequence } from './constants';\nimport type { FrameworkConfig } from './framework-config';\nimport type { WizardReadinessResult } from './health-checks/readiness';\nimport type { SettingsConflict } from './agent/claude-settings';\nimport type { ApiUser, ApiProject } from './api';\nimport type { HostResolution } from './host-resolution';\n\nexport interface Credentials {\n accessToken: string;\n projectApiKey: string;\n /** Resolved at auth time and immutable thereafter — see {@link HostResolution}. */\n host: HostResolution;\n projectId: number;\n}\n\nfunction parseProjectIdArg(value: string | undefined): number | undefined {\n if (value === undefined || value === '') return undefined;\n const n = Number(value);\n return Number.isInteger(n) && n > 0 ? n : undefined;\n}\n\nexport type CloudRegion = 'us' | 'eu';\n\n/** Lifecycle phase of the main work (agent run, MCP install, etc.) */\nexport enum RunPhase {\n /** Still gathering input (intro, setup screens) */\n Idle = 'idle',\n /** Main work is in progress */\n Running = 'running',\n /** Main work finished successfully */\n Completed = 'completed',\n /** Main work finished with an error */\n Error = 'error',\n}\n\n/** Features discovered by the feature-discovery subagent */\nexport enum DiscoveredFeature {\n Stripe = 'stripe',\n LLM = 'llm',\n}\n\n/** Additional features the agent can integrate after the main setup */\nexport enum AdditionalFeature {\n LLM = 'llm',\n}\n\n/** Human-readable labels for additional features (used in TUI progress) */\nexport const ADDITIONAL_FEATURE_LABELS: Record<AdditionalFeature, string> = {\n [AdditionalFeature.LLM]: 'AI observability',\n};\n\n/** Agent prompts for each additional feature, injected via the stop hook */\nexport const ADDITIONAL_FEATURE_PROMPTS: Record<AdditionalFeature, string> = {\n [AdditionalFeature.LLM]: `Now integrate AI observability with PostHog. Use the PostHog MCP server to find the appropriate AI observability skill, install it, and follow its workflow. PostHog basics are already installed. Update the setup report markdown file when complete with additions from this task. `,\n};\n\n/** Outcome of the MCP server installation step */\nexport enum McpOutcome {\n NoClients = 'no_clients',\n Skipped = 'skipped',\n Installed = 'installed',\n Failed = 'failed',\n}\n\n/** Outcome kind for the outro screen */\nexport enum OutroKind {\n Success = 'success',\n Error = 'error',\n Cancel = 'cancel',\n}\n\nexport interface OutroData {\n kind: OutroKind;\n /** Main headline (green check for Success, red X for Error, etc.) */\n message?: string;\n /** Free-form body text shown under the headline. Use \\n for paragraph breaks. */\n body?: string;\n /** Success-only: bulleted list of \"what the agent did\" */\n changes?: string[];\n /**\n * Success-only: a prominent, labeled link to where the user should go\n * next (e.g. an inbox the program just configured). Rendered right under\n * the headline and shown verbatim — no UTM tagging — so the URL stays\n * clean and copy-pasteable. Set per-program in buildOutroData.\n */\n primaryLink?: { label: string; url: string };\n /**\n * Success-only: a short \"what to do next\" checklist with its own heading,\n * rendered as a bulleted list. Distinct from `changes`, which recaps what\n * the agent already did.\n */\n nextSteps?: { heading: string; items: string[] };\n docsUrl?: string;\n continueUrl?: string;\n /** Report file the agent wrote (e.g. \"posthog-setup-report.md\") */\n reportFile?: string;\n /** PostHog dashboard URL the program created on the user's behalf. */\n dashboardUrl?: string;\n /** PostHog notebook URL the program uploaded the report to. */\n notebookUrl?: string;\n /**\n * Copy-paste prompt the operator hands to their coding agent to finish the\n * job (work the report's checklist). Printed to the terminal's main buffer on\n * exit (see getExitLine in start-tui.ts) — the TUI's alternate screen is wiped\n * on exit, so the scrollback line is where it survives and can be\n * triple-click-selected. Set per-program in buildOutroData.\n */\n handoffPrompt?: string;\n}\n\n/** A single question rendered by the WizardAsk overlay. */\nexport interface AskQuestion {\n /** Key for the response map */\n id: string;\n prompt: string;\n /** text = single-line free input; single/multi = picker */\n kind: 'single' | 'multi' | 'text';\n /** Required for `single` and `multi`. Ignored for `text`. */\n options?: { label: string; value: string; description?: string }[];\n /** Defaults to true */\n required?: boolean;\n /**\n * Only meaningful for kind='text'. When true, the wizard-tools `wizard_ask`\n * tool stores the user's answer in the session secret vault and returns\n * `{ secretRef }` to the agent instead of the plain string — so the value\n * never enters the LLM conversation. The TUI may also mask input\n * accordingly. See `secret-vault.ts`.\n */\n sensitive?: boolean;\n}\n\n/** Map of question id → answer (string for single/text, string[] for multi). */\nexport type AskAnswers = Record<string, string | string[]>;\n\n/** A pending wizard_ask request held by the store. */\nexport interface PendingQuestion {\n id: string;\n questions: AskQuestion[];\n /** Skill id of the caller. Set by the wizard from session.skillId. */\n source: string;\n /**\n * When true, the ask overlay renders standalone URLs in prompt text as\n * OSC 8 hyperlinks and copies a lone URL to the clipboard. Opt-in per\n * program (set from `ProgramRun.richLinks` via the ask bridge); defaults\n * to false so existing flows render prompts exactly as before. See\n * `LinkText` / `link-helpers`.\n */\n richLinks?: boolean;\n}\n\n/**\n * PostHog dashboard URL emitted by the agent during a program run.\n * Populated via the `[DASHBOARD_URL]` text marker in agent assistant messages\n * — see `handleSDKMessage` in `agent/agent-interface.ts`. Read by programs\n * (e.g. events-audit) inside `buildOutroData` to surface a dashboard link\n * the agent actually created.\n */\n\nexport interface WizardSession {\n // From CLI args\n debug: boolean;\n installDir: string;\n ci: boolean;\n signup: boolean;\n localMcp: boolean;\n mcpFeatures?: string[];\n apiKey?: string;\n email?: string;\n region?: CloudRegion;\n /**\n * Explicit PostHog base URL (`--base-url`). When set, it pins every PostHog\n * origin — API host, cloud/app URL, OAuth server — and `region` is ignored.\n * The runtime equivalent of the dev-build localhost routing; lets the shipped\n * wizard target a local/self-hosted stack. Threaded into the URL helpers in\n * `@utils/urls`. Empty/unset → region-based resolution.\n */\n baseUrl?: string;\n benchmark: boolean;\n yaraReport: boolean;\n projectId?: number;\n noTelemetry: boolean;\n\n /** `--harness` override, read by `resolveHarness`. Wins over the runner flag. */\n harness?: Harness;\n /** `--sequence` override, read in `runProgram`. Wins over the orchestrator flag. */\n sequence?: Sequence;\n /** `--model` override (gateway id), read by `resolveHarness`. Wins over the binding's model. */\n model?: string;\n\n // From detection + screens\n setupConfirmed: boolean;\n integration: Integration | null;\n frameworkContext: Record<string, unknown>;\n typescript: boolean;\n\n /** Human-readable label for the detected framework variant (e.g., \"Django with Wagtail CMS\") */\n detectedFrameworkLabel: string | null;\n\n /** True once framework detection has run (whether it found something or not) */\n detectionComplete: boolean;\n\n /** Set when the detected framework version is too old for the wizard */\n unsupportedVersion: {\n current: string;\n minimum: string;\n docsUrl: string;\n } | null;\n\n // From OAuth\n credentials: Credentials | null;\n\n /**\n * `role_at_organization` from `/api/users/@me/`. Null when the upstream\n * value is missing (older accounts, fresh signups before onboarding).\n * Drives role-tailored MCP prompt suggestions on the McpSuggestedPromptsScreen.\n *\n * Mirrors `apiUser?.role_at_organization` — kept as a top-level convenience\n * because it has dedicated UI semantics (role-tailored kits) and pre-dates\n * the broader `apiUser` plumbing.\n */\n roleAtOrganization: string | null;\n\n /**\n * Full user payload from `/api/users/@me/` — identifiers, profile,\n * current team + organization, preferences, etc. Null until OAuth /\n * CI-key auth populates it. Schema lives in `src/lib/api.ts` and\n * passes through unknown upstream fields so downstream features can\n * read account context (plan, org name, email, etc.) without\n * re-fetching.\n */\n apiUser: ApiUser | null;\n\n /**\n * Project payload resolved at authentication, kept so a second agent run in\n * the same invocation (e.g. self-driving's integration phase) reuses the\n * first login wholesale instead of re-authenticating. The resolved region\n * lives on `credentials.host.region`.\n */\n apiProject: ApiProject | null;\n\n // Lifecycle\n runPhase: RunPhase;\n loginUrl: string | null;\n // Direct PostHog authorize URL, shown in the manual-paste modal for\n // headless/remote shells (the localhost loginUrl is unreachable there).\n authorizeUrl: string | null;\n\n // Feature discovery\n discoveredFeatures: DiscoveredFeature[];\n llmOptIn: boolean;\n\n // ScreenId completion\n mcpComplete: boolean;\n mcpOutcome: McpOutcome | null;\n mcpInstalledClients: string[];\n mcpSuggestedPromptsDismissed: boolean;\n /** True once the user has acted on (opened or skipped) the Connect-Slack step. */\n slackStepDismissed: boolean;\n /**\n * Whether the project already has a Slack integration connected.\n * `null` until detected. Prefetched by the tutorial screen as soon as\n * credentials exist so the Connect-Slack step renders the right\n * variant immediately instead of flashing the nudge first.\n */\n slackConnected: boolean | null;\n skillsComplete: boolean;\n outroDismissed: boolean;\n\n /**\n * Self-driving only: whether to integrate PostHog as part of this run.\n * `null` until decided. When detection finds no PostHog SDK, the\n * integration-check screen sets this to `true` (Self-driving needs an SDK,\n * so we always integrate in that case) — and, on the same screen, asks\n * whether the user already has a PostHog account: \"yes\" leaves `signup`\n * false (OAuth login); \"no\" flips `signup` and collects `email`/`region`\n * so auth provisions a new account. The `--integrate` flag pre-sets this to\n * `true`, skipping the screen entirely and defaulting to the OAuth login.\n * When `true`, the self-driving prompt has the agent set up the SDK before\n * the Self-driving steps. Unused by other programs.\n */\n integrate: boolean | null;\n\n /**\n * Ids of composed run steps that have completed — e.g. self-driving's\n * `integrate-run`. Lets a run step's `isComplete` hold after it ran,\n * independent of the shared `runPhase`.\n */\n completedRuns: string[];\n\n /**\n * Self-driving only: whether the user confirmed the handoff screen shown\n * after the integration run (\"PostHog is installed — now set up Self-driving\").\n * Gates the Self-driving run so it doesn't start until acknowledged. Only\n * reached in the integrate path; the already-has-PostHog path skips it.\n */\n selfDrivingHandoffConfirmed: boolean;\n\n // Runtime\n readinessResult: WizardReadinessResult | null;\n outageDismissed: boolean;\n settingsOverrideKeys: string[] | null;\n settingsConflicts: SettingsConflict[] | null;\n authErrorDetail: {\n hasSettingsConflict: boolean;\n conflicts?: SettingsConflict[];\n logFilePath: string;\n } | null;\n portConflictProcess: {\n command: string;\n pid: string;\n port: number;\n user: string;\n } | null;\n outroData: OutroData | null;\n dashboardUrl: string | null;\n notebookUrl: string | null;\n\n // Additional features queue (drained via stop hook after main integration)\n additionalFeatureQueue: AdditionalFeature[];\n\n // Program metadata (set by runWizard in bin.ts)\n programLabel: string | null;\n skillId: string | null;\n\n // Resolved framework config (set after integration is known)\n frameworkConfig: FrameworkConfig | null;\n\n /** Active wizard_ask request, set by the bridge when the agent calls the tool. */\n pendingQuestion: PendingQuestion | null;\n}\n\n/**\n * Build a WizardSession from CLI args, pre-populating whatever is known.\n */\nexport function buildSession(args: {\n debug?: boolean;\n installDir?: string;\n ci?: boolean;\n signup?: boolean;\n localMcp?: boolean;\n mcpFeatures?: string[];\n apiKey?: string;\n email?: string;\n region?: CloudRegion;\n baseUrl?: string;\n integration?: Integration;\n benchmark?: boolean;\n yaraReport?: boolean;\n projectId?: string;\n noTelemetry?: boolean;\n harness?: Harness;\n sequence?: Sequence;\n model?: string;\n integrate?: boolean;\n}): WizardSession {\n return {\n debug: args.debug ?? false,\n installDir: args.installDir ?? process.cwd(),\n ci: args.ci ?? false,\n signup: args.signup ?? false,\n localMcp: args.localMcp ?? false,\n mcpFeatures: args.mcpFeatures,\n apiKey: args.apiKey,\n email: args.email,\n region: args.region,\n baseUrl: args.baseUrl,\n benchmark: args.benchmark ?? false,\n yaraReport: args.yaraReport ?? false,\n projectId: parseProjectIdArg(args.projectId),\n noTelemetry: args.noTelemetry ?? false,\n harness: args.harness,\n sequence: args.sequence,\n model: args.model,\n\n setupConfirmed: false,\n integration: args.integration ?? null,\n frameworkContext: {},\n typescript: false,\n detectedFrameworkLabel: null,\n detectionComplete: false,\n unsupportedVersion: null,\n\n runPhase: RunPhase.Idle,\n discoveredFeatures: [],\n llmOptIn: false,\n mcpComplete: false,\n mcpOutcome: null,\n mcpInstalledClients: [],\n mcpSuggestedPromptsDismissed: false,\n slackStepDismissed: false,\n slackConnected: null,\n skillsComplete: false,\n outroDismissed: false,\n // `--integrate` forces integration (skip the question); otherwise the\n // integration-check screen resolves it from null.\n integrate: args.integrate === true ? true : null,\n completedRuns: [],\n selfDrivingHandoffConfirmed: false,\n loginUrl: null,\n authorizeUrl: null,\n credentials: null,\n roleAtOrganization: null,\n apiUser: null,\n apiProject: null,\n readinessResult: null,\n outageDismissed: false,\n settingsOverrideKeys: null,\n settingsConflicts: null,\n authErrorDetail: null,\n portConflictProcess: null,\n outroData: null,\n dashboardUrl: null,\n notebookUrl: null,\n additionalFeatureQueue: [],\n programLabel: null,\n skillId: null,\n frameworkConfig: null,\n pendingQuestion: null,\n };\n}\n"],"mappings":";AA2BA,SAAS,kBAAkB,OAA+C;AACxE,KAAI,UAAU,KAAA,KAAa,UAAU,GAAI,QAAO,KAAA;CAChD,MAAM,IAAI,OAAO,MAAM;AACvB,QAAO,OAAO,UAAU,EAAE,IAAI,IAAI,IAAI,IAAI,KAAA;;;AAM5C,IAAY,WAAL,yBAAA,UAAA;;AAEL,UAAA,UAAA;;AAEA,UAAA,aAAA;;AAEA,UAAA,eAAA;;AAEA,UAAA,WAAA;;KACD;;AAcD,MAAa,4BAA+D,GAAA,QACjD,o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lib/wizard-session.ts"],"sourcesContent":["/**\n * WizardSession — single source of truth for every decision the wizard needs.\n *\n * Populated in layers:\n * CLI args / env vars → populate fields directly\n * Auto-detection → framework, typescript, package manager\n * TUI screens → region, framework disambiguation, etc.\n * OAuth → credentials\n *\n * Business logic reads from the session. Never calls a prompt.\n */\n\nimport type { Harness, Integration, Sequence } from './constants';\nimport type { FrameworkConfig } from './framework-config';\nimport type { WizardReadinessResult } from './health-checks/readiness';\nimport type { SettingsConflict } from './agent/claude-settings';\nimport type { ApiUser, ApiProject } from './api';\nimport type { HostResolution } from './host-resolution';\n\nexport interface Credentials {\n accessToken: string;\n projectApiKey: string;\n /** Resolved at auth time and immutable thereafter — see {@link HostResolution}. */\n host: HostResolution;\n projectId: number;\n}\n\nfunction parseProjectIdArg(value: string | undefined): number | undefined {\n if (value === undefined || value === '') return undefined;\n const n = Number(value);\n return Number.isInteger(n) && n > 0 ? n : undefined;\n}\n\nexport type CloudRegion = 'us' | 'eu';\n\n/** Lifecycle phase of the main work (agent run, MCP install, etc.) */\nexport enum RunPhase {\n /** Still gathering input (intro, setup screens) */\n Idle = 'idle',\n /** Main work is in progress */\n Running = 'running',\n /** Main work finished successfully */\n Completed = 'completed',\n /** Main work finished with an error */\n Error = 'error',\n}\n\n/** Features discovered by the feature-discovery subagent */\nexport enum DiscoveredFeature {\n Stripe = 'stripe',\n LLM = 'llm',\n}\n\n/** Additional features the agent can integrate after the main setup */\nexport enum AdditionalFeature {\n LLM = 'llm',\n}\n\n/** Human-readable labels for additional features (used in TUI progress) */\nexport const ADDITIONAL_FEATURE_LABELS: Record<AdditionalFeature, string> = {\n [AdditionalFeature.LLM]: 'AI observability',\n};\n\n/** Agent prompts for each additional feature, injected via the stop hook */\nexport const ADDITIONAL_FEATURE_PROMPTS: Record<AdditionalFeature, string> = {\n [AdditionalFeature.LLM]: `Now integrate AI observability with PostHog. Use the PostHog MCP server to find the appropriate AI observability skill, install it, and follow its workflow. PostHog basics are already installed. Update the setup report markdown file when complete with additions from this task. `,\n};\n\n/** Outcome of the MCP server installation step */\nexport enum McpOutcome {\n NoClients = 'no_clients',\n Skipped = 'skipped',\n Installed = 'installed',\n Failed = 'failed',\n}\n\n/** Outcome kind for the outro screen */\nexport enum OutroKind {\n Success = 'success',\n Error = 'error',\n Cancel = 'cancel',\n}\n\nexport interface OutroData {\n kind: OutroKind;\n /** Main headline (green check for Success, red X for Error, etc.) */\n message?: string;\n /** Free-form body text shown under the headline. Use \\n for paragraph breaks. */\n body?: string;\n /** Success-only: bulleted list of \"what the agent did\" */\n changes?: string[];\n /**\n * Success-only: a prominent, labeled link to where the user should go\n * next (e.g. an inbox the program just configured). Rendered right under\n * the headline and shown verbatim — no UTM tagging — so the URL stays\n * clean and copy-pasteable. Set per-program in buildOutroData.\n */\n primaryLink?: { label: string; url: string };\n /**\n * Success-only: a short \"what to do next\" checklist with its own heading,\n * rendered as a bulleted list. Distinct from `changes`, which recaps what\n * the agent already did.\n */\n nextSteps?: { heading: string; items: string[] };\n docsUrl?: string;\n continueUrl?: string;\n /** Report file the agent wrote (e.g. \"posthog-setup-report.md\") */\n reportFile?: string;\n /** PostHog dashboard URL the program created on the user's behalf. */\n dashboardUrl?: string;\n /** PostHog notebook URL the program uploaded the report to. */\n notebookUrl?: string;\n /**\n * Copy-paste prompt the operator hands to their coding agent to finish the\n * job (work the report's checklist). Printed to the terminal's main buffer on\n * exit (see getExitLine in start-tui.ts) — the TUI's alternate screen is wiped\n * on exit, so the scrollback line is where it survives and can be\n * triple-click-selected. Set per-program in buildOutroData.\n */\n handoffPrompt?: string;\n}\n\n/** A single question rendered by the WizardAsk overlay. */\nexport interface AskQuestion {\n /** Key for the response map */\n id: string;\n prompt: string;\n /** text = single-line free input; single/multi = picker */\n kind: 'single' | 'multi' | 'text';\n /** Required for `single` and `multi`. Ignored for `text`. */\n options?: { label: string; value: string; description?: string }[];\n /** Defaults to true */\n required?: boolean;\n /**\n * Only meaningful for kind='text'. When true, the wizard-tools `wizard_ask`\n * tool stores the user's answer in the session secret vault and returns\n * `{ secretRef }` to the agent instead of the plain string — so the value\n * never enters the LLM conversation. The TUI may also mask input\n * accordingly. See `secret-vault.ts`.\n */\n sensitive?: boolean;\n}\n\n/** Map of question id → answer (string for single/text, string[] for multi). */\nexport type AskAnswers = Record<string, string | string[]>;\n\n/** A pending wizard_ask request held by the store. */\nexport interface PendingQuestion {\n id: string;\n questions: AskQuestion[];\n /** Skill id of the caller. Set by the wizard from session.skillId. */\n source: string;\n /**\n * When true, the ask overlay renders standalone URLs in prompt text as\n * OSC 8 hyperlinks and copies a lone URL to the clipboard. Opt-in per\n * program (set from `ProgramRun.richLinks` via the ask bridge); defaults\n * to false so existing flows render prompts exactly as before. See\n * `LinkText` / `link-helpers`.\n */\n richLinks?: boolean;\n}\n\n/**\n * PostHog dashboard URL emitted by the agent during a program run.\n * Populated via the `[DASHBOARD_URL]` text marker in agent assistant messages\n * — see `handleSDKMessage` in `agent/agent-interface.ts`. Read by programs\n * (e.g. events-audit) inside `buildOutroData` to surface a dashboard link\n * the agent actually created.\n */\n\nexport interface WizardSession {\n // From CLI args\n debug: boolean;\n installDir: string;\n ci: boolean;\n signup: boolean;\n localMcp: boolean;\n mcpFeatures?: string[];\n apiKey?: string;\n email?: string;\n region?: CloudRegion;\n /**\n * Explicit PostHog base URL (`--base-url`). When set, it pins every PostHog\n * origin — API host, cloud/app URL, OAuth server — and `region` is ignored.\n * The runtime equivalent of the dev-build localhost routing; lets the shipped\n * wizard target a local/self-hosted stack. Threaded into the URL helpers in\n * `@utils/urls`. Empty/unset → region-based resolution.\n */\n baseUrl?: string;\n benchmark: boolean;\n yaraReport: boolean;\n projectId?: number;\n noTelemetry: boolean;\n\n /** `--harness` override, read by `resolveHarness`. Wins over the runner flag. */\n harness?: Harness;\n /** `--sequence` override, read in `runProgram`. Wins over the orchestrator flag. */\n sequence?: Sequence;\n /** `--model` override (gateway id), read by `resolveHarness`. Wins over the binding's model. */\n model?: string;\n\n // From detection + screens\n setupConfirmed: boolean;\n integration: Integration | null;\n frameworkContext: Record<string, unknown>;\n typescript: boolean;\n\n /** Human-readable label for the detected framework variant (e.g., \"Django with Wagtail CMS\") */\n detectedFrameworkLabel: string | null;\n\n /** True once framework detection has run (whether it found something or not) */\n detectionComplete: boolean;\n\n /** Set when the detected framework version is too old for the wizard */\n unsupportedVersion: {\n current: string;\n minimum: string;\n docsUrl: string;\n } | null;\n\n // From OAuth\n credentials: Credentials | null;\n\n /**\n * `role_at_organization` from `/api/users/@me/`. Null when the upstream\n * value is missing (older accounts, fresh signups before onboarding).\n * Drives role-tailored MCP prompt suggestions on the McpSuggestedPromptsScreen.\n *\n * Mirrors `apiUser?.role_at_organization` — kept as a top-level convenience\n * because it has dedicated UI semantics (role-tailored kits) and pre-dates\n * the broader `apiUser` plumbing.\n */\n roleAtOrganization: string | null;\n\n /**\n * Full user payload from `/api/users/@me/` — identifiers, profile,\n * current team + organization, preferences, etc. Null until OAuth /\n * CI-key auth populates it. Schema lives in `src/lib/api.ts` and\n * passes through unknown upstream fields so downstream features can\n * read account context (plan, org name, email, etc.) without\n * re-fetching.\n */\n apiUser: ApiUser | null;\n\n /**\n * Project payload resolved at authentication, kept so a second agent run in\n * the same invocation (e.g. self-driving's integration phase) reuses the\n * first login wholesale instead of re-authenticating. The resolved region\n * lives on `credentials.host.region`.\n */\n apiProject: ApiProject | null;\n\n // Lifecycle\n runPhase: RunPhase;\n loginUrl: string | null;\n // Direct PostHog authorize URL, shown in the manual-paste modal for\n // headless/remote shells (the localhost loginUrl is unreachable there).\n authorizeUrl: string | null;\n\n // Feature discovery\n discoveredFeatures: DiscoveredFeature[];\n llmOptIn: boolean;\n\n // ScreenId completion\n mcpComplete: boolean;\n mcpOutcome: McpOutcome | null;\n mcpInstalledClients: string[];\n mcpSuggestedPromptsDismissed: boolean;\n /** True once the user has acted on (opened or skipped) the Connect-Slack step. */\n slackStepDismissed: boolean;\n /**\n * Whether the project already has a Slack integration connected.\n * `null` until detected. Prefetched by the tutorial screen as soon as\n * credentials exist so the Connect-Slack step renders the right\n * variant immediately instead of flashing the nudge first.\n */\n slackConnected: boolean | null;\n skillsComplete: boolean;\n outroDismissed: boolean;\n\n /**\n * Self-driving only: whether to integrate PostHog as part of this run.\n * `null` until decided. When detection finds no PostHog SDK, the\n * integration-check screen sets this to `true` (Self-driving needs an SDK,\n * so we always integrate in that case) — and, on the same screen, asks\n * whether the user already has a PostHog account: \"yes\" leaves `signup`\n * false (OAuth login); \"no\" flips `signup` and collects `email`/`region`\n * so auth provisions a new account. The `--integrate` flag pre-sets this to\n * `true`, skipping the screen entirely and defaulting to the OAuth login.\n * When `true`, the self-driving prompt has the agent set up the SDK before\n * the Self-driving steps. Unused by other programs.\n */\n integrate: boolean | null;\n\n /**\n * Ids of composed run steps that have completed — e.g. self-driving's\n * `integrate-run`. Lets a run step's `isComplete` hold after it ran,\n * independent of the shared `runPhase`.\n */\n completedRuns: string[];\n\n /**\n * Self-driving only: whether the user confirmed the handoff screen shown\n * after the integration run (\"PostHog is installed — now set up Self-driving\").\n * Gates the Self-driving run so it doesn't start until acknowledged. Only\n * reached in the integrate path; the already-has-PostHog path skips it.\n */\n selfDrivingHandoffConfirmed: boolean;\n\n // Runtime\n readinessResult: WizardReadinessResult | null;\n outageDismissed: boolean;\n settingsOverrideKeys: string[] | null;\n settingsConflicts: SettingsConflict[] | null;\n authErrorDetail: {\n hasSettingsConflict: boolean;\n conflicts?: SettingsConflict[];\n logFilePath: string;\n } | null;\n portConflictProcess: {\n command: string;\n pid: string;\n port: number;\n user: string;\n } | null;\n outroData: OutroData | null;\n dashboardUrl: string | null;\n notebookUrl: string | null;\n\n // Additional features queue (drained via stop hook after main integration)\n additionalFeatureQueue: AdditionalFeature[];\n\n // Program metadata (set by runWizard in bin.ts)\n programLabel: string | null;\n skillId: string | null;\n\n // Resolved framework config (set after integration is known)\n frameworkConfig: FrameworkConfig | null;\n\n /** Active wizard_ask request, set by the bridge when the agent calls the tool. */\n pendingQuestion: PendingQuestion | null;\n}\n\n/**\n * Build a WizardSession from CLI args, pre-populating whatever is known.\n */\nexport function buildSession(args: {\n debug?: boolean;\n installDir?: string;\n ci?: boolean;\n signup?: boolean;\n localMcp?: boolean;\n mcpFeatures?: string[];\n apiKey?: string;\n email?: string;\n region?: CloudRegion;\n baseUrl?: string;\n integration?: Integration;\n benchmark?: boolean;\n yaraReport?: boolean;\n projectId?: string;\n noTelemetry?: boolean;\n harness?: Harness;\n sequence?: Sequence;\n model?: string;\n integrate?: boolean;\n}): WizardSession {\n return {\n debug: args.debug ?? false,\n installDir: args.installDir ?? process.cwd(),\n ci: args.ci ?? false,\n signup: args.signup ?? false,\n localMcp: args.localMcp ?? false,\n mcpFeatures: args.mcpFeatures,\n apiKey: args.apiKey,\n email: args.email,\n region: args.region,\n baseUrl: args.baseUrl,\n benchmark: args.benchmark ?? false,\n yaraReport: args.yaraReport ?? false,\n projectId: parseProjectIdArg(args.projectId),\n noTelemetry: args.noTelemetry ?? false,\n harness: args.harness,\n sequence: args.sequence,\n model: args.model,\n\n setupConfirmed: false,\n integration: args.integration ?? null,\n frameworkContext: {},\n typescript: false,\n detectedFrameworkLabel: null,\n detectionComplete: false,\n unsupportedVersion: null,\n\n runPhase: RunPhase.Idle,\n discoveredFeatures: [],\n llmOptIn: false,\n mcpComplete: false,\n mcpOutcome: null,\n mcpInstalledClients: [],\n mcpSuggestedPromptsDismissed: false,\n slackStepDismissed: false,\n slackConnected: null,\n skillsComplete: false,\n outroDismissed: false,\n // `--integrate` forces integration (skip the question); otherwise the\n // integration-check screen resolves it from null.\n integrate: args.integrate === true ? true : null,\n completedRuns: [],\n selfDrivingHandoffConfirmed: false,\n loginUrl: null,\n authorizeUrl: null,\n credentials: null,\n roleAtOrganization: null,\n apiUser: null,\n apiProject: null,\n readinessResult: null,\n outageDismissed: false,\n settingsOverrideKeys: null,\n settingsConflicts: null,\n authErrorDetail: null,\n portConflictProcess: null,\n outroData: null,\n dashboardUrl: null,\n notebookUrl: null,\n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AgB;EAChB,gBAAgB;EAGhB,WAAW,KAAK,cAAc,OAAO,OAAO;EAC5C,eAAe,EAAE;EACjB,6BAA6B;EAC7B,UAAU;EACV,cAAc;EACd,aAAa;EACb,oBAAoB;EACpB,SAAS;EACT,YAAY;EACZ,iBAAiB;EACjB,iBAAiB;EACjB,sBAAsB;EACtB,mBAAmB;EACnB,iBAAiB;EACjB,qBAAqB;EACrB,WAAW;EACX,cAAc;EACd,aAAa;EACb,wBAAwB,EAAE;EAC1B,cAAc;EACd,SAAS;EACT,iBAAiB;EACjB,iBAAiB;EAClB"}
@@ -1,2 +1,2 @@
1
- import { a as buildSession, i as RunPhase, r as OutroKind } from "./wizard-session-tp4Zdbwl.js";
1
+ import { a as buildSession, i as RunPhase, r as OutroKind } from "./wizard-session-BAZql11N.js";
2
2
  export { OutroKind, RunPhase, buildSession };
@@ -1,52 +1,11 @@
1
- import { f as getUI, s as logToFile, u as WIZARD_YARA_REPORT_FILE } from "./debug-DF51kDvZ.js";
2
- import { n as analytics } from "./analytics-D6gRGiqt.js";
1
+ import { f as getUI, s as logToFile, u as WIZARD_YARA_REPORT_FILE } from "./debug-DaXKSXEy.js";
2
+ import { n as analytics } from "./analytics-Ddf3zJgF.js";
3
+ import { n as readFileHead } from "./bounded-fs-d0dw1Qv5.js";
3
4
  import fs from "fs";
4
5
  import path from "path";
5
6
  import fg from "fast-glob";
7
+ import axios from "axios";
6
8
  import { createHash } from "crypto";
7
- //#region src/lib/programs/audit/types.ts
8
- /** Single source of truth for status glyph + color across audit views. */
9
- const AUDIT_SEVERITY_STYLE = {
10
- pending: {
11
- glyph: "◌",
12
- color: "gray"
13
- },
14
- pass: {
15
- glyph: "✔",
16
- color: "green"
17
- },
18
- error: {
19
- glyph: "✘",
20
- color: "red"
21
- },
22
- warning: {
23
- glyph: "⚠",
24
- color: "yellow"
25
- },
26
- suggestion: {
27
- glyph: "•",
28
- color: "cyan"
29
- }
30
- };
31
- const AUDIT_CHECKS_FILE = ".posthog-audit-checks.json";
32
- const AUDIT_REPORT_FILE = "posthog-audit-report.md";
33
- const AUDIT_CHECKS_KEY = "auditChecks";
34
- function getAuditChecks(session) {
35
- const raw = session.frameworkContext[AUDIT_CHECKS_KEY];
36
- return Array.isArray(raw) ? raw : [];
37
- }
38
- /**
39
- * Read the audit checks ledger off disk. Validation lives at write time —
40
- * every writer (`audit_seed_checks` / `audit_add_checks` / `audit_resolve_checks`
41
- * MCP tools, `seedAuditLedger`) zod-parses entries before the atomic write,
42
- * so by the time the file watcher fires we trust the shape and only guard
43
- * against the file not being a JSON array (corrupted / hand-edited / not yet
44
- * seeded).
45
- */
46
- function coerceAuditChecks(parsed) {
47
- return Array.isArray(parsed) ? parsed : [];
48
- }
49
- //#endregion
50
9
  //#region src/lib/skill-install.ts
51
10
  /**
52
11
  * Check if command is a PostHog skill installation from MCP.
@@ -65,6 +24,62 @@ function isSkillInstallCommand(command) {
65
24
  return url.startsWith("https://github.com/PostHog/context-mill/releases/") || /^http:\/\/localhost:\d+\//.test(url);
66
25
  }
67
26
  //#endregion
27
+ //#region src/lib/agent/triage-provider.ts
28
+ /**
29
+ * LLM provider for warlock security-scan triage.
30
+ *
31
+ * Warlock's triageMatches() takes a consumer-supplied `(prompt) => Promise<string>`
32
+ * to run a second pass that filters false positives out of YARA matches. This
33
+ * builds that provider on top of the wizard's existing PostHog LLM gateway auth
34
+ * — the same ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN that initializeAgent()
35
+ * sets for the agent SDK. The gateway speaks the standard Anthropic Messages API,
36
+ * so we POST to it directly with axios (the plain @anthropic-ai/sdk isn't a dep).
37
+ */
38
+ const TRIAGE_MODEL = "claude-haiku-4-5";
39
+ const TRIAGE_MAX_TOKENS = 16384;
40
+ const TRIAGE_TIMEOUT_MS = 2e4;
41
+ /**
42
+ * Build the triage LLM provider. Auth comes from the explicit `auth` param
43
+ * when given (the pi harness — it auths the gateway programmatically and never
44
+ * sets the env vars), otherwise from the gateway auth on process.env (set by
45
+ * initializeAgent on the anthropic path). Returns undefined if neither is
46
+ * configured — callers then skip triage and fail closed (act on every flagged
47
+ * match), so a missing key never silently disables the scanner.
48
+ *
49
+ * The triage model is independent of the agent's model: it is a classifier
50
+ * judging scan matches, and the gateway routes it by model id regardless of
51
+ * which model runs the coding agent.
52
+ */
53
+ function createTriageLLMProvider(auth) {
54
+ const baseURL = auth?.baseURL ?? process.env.ANTHROPIC_BASE_URL;
55
+ const authToken = auth?.authToken ?? process.env.ANTHROPIC_AUTH_TOKEN;
56
+ if (!baseURL || !authToken) {
57
+ logToFile("[YARA] triage provider unavailable (no gateway auth) — flagged scans will fail closed");
58
+ return;
59
+ }
60
+ logToFile(`[YARA] triage provider ready (model: ${TRIAGE_MODEL})`);
61
+ return async (prompt) => {
62
+ const content = (await axios.post(`${baseURL}/v1/messages`, {
63
+ model: TRIAGE_MODEL,
64
+ max_tokens: TRIAGE_MAX_TOKENS,
65
+ temperature: 0,
66
+ messages: [{
67
+ role: "user",
68
+ content: prompt
69
+ }]
70
+ }, {
71
+ headers: {
72
+ Authorization: `Bearer ${authToken}`,
73
+ "anthropic-version": "2023-06-01",
74
+ "content-type": "application/json"
75
+ },
76
+ timeout: TRIAGE_TIMEOUT_MS
77
+ })).data?.content;
78
+ if (Array.isArray(content)) return content.filter((b) => b?.type === "text" && typeof b.text === "string").map((b) => b.text).join("");
79
+ return "";
80
+ };
81
+ }
82
+ //#endregion
68
83
  //#region src/lib/yara-policy.ts
69
84
  /** Severity order, highest first, for picking the match worth reporting. */
70
85
  const SEVERITY_RANK = {
@@ -108,6 +123,49 @@ const EVENT_INVENTORY_FILE = ".posthog-events-inventory.json";
108
123
  /** Per-part filename pattern emitted by events-audit subagents (e.g. `.posthog-events-inventory.part-3.json`). */
109
124
  const EVENT_INVENTORY_PART_PATTERN = /^\.posthog-events-inventory\.part-\d+\.json$/;
110
125
  //#endregion
126
+ //#region src/lib/programs/audit/types.ts
127
+ /** Single source of truth for status glyph + color across audit views. */
128
+ const AUDIT_SEVERITY_STYLE = {
129
+ pending: {
130
+ glyph: "◌",
131
+ color: "gray"
132
+ },
133
+ pass: {
134
+ glyph: "✔",
135
+ color: "green"
136
+ },
137
+ error: {
138
+ glyph: "✘",
139
+ color: "red"
140
+ },
141
+ warning: {
142
+ glyph: "⚠",
143
+ color: "yellow"
144
+ },
145
+ suggestion: {
146
+ glyph: "•",
147
+ color: "cyan"
148
+ }
149
+ };
150
+ const AUDIT_CHECKS_FILE = ".posthog-audit-checks.json";
151
+ const AUDIT_REPORT_FILE = "posthog-audit-report.md";
152
+ const AUDIT_CHECKS_KEY = "auditChecks";
153
+ function getAuditChecks(session) {
154
+ const raw = session.frameworkContext[AUDIT_CHECKS_KEY];
155
+ return Array.isArray(raw) ? raw : [];
156
+ }
157
+ /**
158
+ * Read the audit checks ledger off disk. Validation lives at write time —
159
+ * every writer (`audit_seed_checks` / `audit_add_checks` / `audit_resolve_checks`
160
+ * MCP tools, `seedAuditLedger`) zod-parses entries before the atomic write,
161
+ * so by the time the file watcher fires we trust the shape and only guard
162
+ * against the file not being a JSON array (corrupted / hand-edited / not yet
163
+ * seeded).
164
+ */
165
+ function coerceAuditChecks(parsed) {
166
+ return Array.isArray(parsed) ? parsed : [];
167
+ }
168
+ //#endregion
111
169
  //#region src/lib/programs/posthog-integration/constants.ts
112
170
  /**
113
171
  * Leaf-level constants for the posthog-integration program.
@@ -285,6 +343,7 @@ const SKILL_SCAN_HOOK_TIMEOUT_MS = 3e4;
285
343
  * (~25K tokens), so triage always sees the chunk its matches came from.
286
344
  */
287
345
  const SCAN_CHUNK_SIZE = 1e5;
346
+ const SKILL_FILE_SCAN_BYTES = 10 * 1024 * 1024;
288
347
  /**
289
348
  * Overlap between adjacent chunks so a pattern straddling a chunk boundary
290
349
  * still lands whole inside at least one chunk. YARA rule strings are at most
@@ -660,6 +719,24 @@ function createPostToolUseYaraHooks(llmProvider, onTerminate) {
660
719
  ];
661
720
  }
662
721
  /**
722
+ * Scan a freshly installed skill directory (any root — .claude/skills or the
723
+ * orchestrator's run cache) and return a terminate reason when it is
724
+ * poisoned, else null. The choke point for TS-path installs (downloadSkill);
725
+ * agent Bash installs are covered by the PostToolUse matcher above. Runs the
726
+ * same LLM triage as the tool-use scans (default provider from gateway auth on
727
+ * the env); fail-closed to treating every match as real when no provider is
728
+ * configured, so a missing key never weakens the check. `llmProvider` is
729
+ * injectable for tests.
730
+ */
731
+ async function scanInstalledSkill(absoluteSkillDir, llmProvider = createTriageLLMProvider()) {
732
+ recordScan();
733
+ const matches = await scanSkillFiles(absoluteSkillDir, ".", llmProvider);
734
+ if (matches.length === 0) return null;
735
+ const match = highestSeverityMatch(matches);
736
+ recordMatch("skill-install", "installSkillById", match, "terminated");
737
+ return `Poisoned skill detected: ${match.rule} (${match.metadata.severity ?? "unknown"}) in ${absoluteSkillDir}`;
738
+ }
739
+ /**
663
740
  * Read and scan all text files in a skill directory for prompt injection.
664
741
  * Scans each file sequentially (single-threaded WASM — parallelism buys
665
742
  * nothing), unions the 'input'-context matches, then triages once across the
@@ -675,22 +752,28 @@ async function scanSkillFiles(cwd, skillDir, llmProvider) {
675
752
  cwd: absoluteDir,
676
753
  absolute: true
677
754
  });
678
- const fileContents = [];
679
- for (const filePath of files) try {
680
- fileContents.push(fs.readFileSync(filePath, "utf-8"));
681
- } catch (err) {
682
- logToFile(`[YARA] Could not read skill file ${filePath}:`, err);
683
- }
684
- if (fileContents.length === 0) {
755
+ if (files.length === 0) {
685
756
  logToFile(`[YARA] No text files found in skill directory: ${absoluteDir}`);
686
757
  return [];
687
758
  }
688
- logToFile(`[YARA] Scanning ${fileContents.length} files in skill directory: ${skillDir}`);
759
+ logToFile(`[YARA] Scanning ${files.length} files in skill directory: ${skillDir}`);
689
760
  const flagged = [];
690
- for (const content of fileContents) flagged.push(...await scanForContext(content, "input"));
761
+ for (const filePath of files) {
762
+ let content;
763
+ try {
764
+ if (fs.statSync(filePath).size > SKILL_FILE_SCAN_BYTES) {
765
+ logToFile(`[YARA] Skill file over ${SKILL_FILE_SCAN_BYTES} bytes; scanning its head only: ${filePath}`);
766
+ content = readFileHead(filePath, SKILL_FILE_SCAN_BYTES);
767
+ } else content = fs.readFileSync(filePath, "utf-8");
768
+ } catch (err) {
769
+ logToFile(`[YARA] Could not read skill file ${filePath}:`, err);
770
+ continue;
771
+ }
772
+ if (content) flagged.push(...await scanForContext(content, "input"));
773
+ }
691
774
  return triageFlagged(flagged, "input", llmProvider);
692
775
  }
693
776
  //#endregion
694
- export { getAuditChecks as S, AUDIT_CHECKS_FILE as _, flushScanReport as a, AUDIT_SEVERITY_STYLE as b, isWizardDocumentationPath as c, repeatBlockReason as d, scanAndTriage as f, scanVerdict as g, SETUP_REPORT_FILE as h, createRepeatBlockTracker as i, prewarmYaraScanner as l, EVENT_PLAN_FILE as m, createPostToolUseYaraHooks as n, formatScanReport as o, writeScanReport as p, createPreToolUseYaraHooks as r, formatYaraAbortMessage as s, captureScanReport as t, recordExternalScan as u, AUDIT_CHECKS_KEY as v, coerceAuditChecks as x, AUDIT_REPORT_FILE as y };
777
+ export { scanVerdict as C, SETUP_REPORT_FILE as S, AUDIT_CHECKS_KEY as _, flushScanReport as a, coerceAuditChecks as b, isWizardDocumentationPath as c, repeatBlockReason as d, scanAndTriage as f, AUDIT_CHECKS_FILE as g, EVENT_PLAN_FILE as h, createRepeatBlockTracker as i, prewarmYaraScanner as l, writeScanReport as m, createPostToolUseYaraHooks as n, formatScanReport as o, scanInstalledSkill as p, createPreToolUseYaraHooks as r, formatYaraAbortMessage as s, captureScanReport as t, recordExternalScan as u, AUDIT_REPORT_FILE as v, createTriageLLMProvider as w, getAuditChecks as x, AUDIT_SEVERITY_STYLE as y };
695
778
 
696
- //# sourceMappingURL=yara-hooks-DEHfsDSF.js.map
779
+ //# sourceMappingURL=yara-hooks-CEs3jx7j.js.map