@posthog/wizard 2.38.1 → 2.38.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{add-mcp-server-to-clients-BB1_aH5M.js → add-mcp-server-to-clients-CHSzsAG8.js} +5 -5
- package/dist/{add-mcp-server-to-clients-BB1_aH5M.js.map → add-mcp-server-to-clients-CHSzsAG8.js.map} +1 -1
- package/dist/{agent-interface-kOuzXg84.js → agent-interface-DExARWay.js} +6 -6
- package/dist/{agent-interface-kOuzXg84.js.map → agent-interface-DExARWay.js.map} +1 -1
- package/dist/{agent-runner-DZhaiwD5.js → agent-runner-CMfTmM3B.js} +16 -16
- package/dist/{agent-runner-DZhaiwD5.js.map → agent-runner-CMfTmM3B.js.map} +1 -1
- package/dist/{analytics-Z_2kCTpB.js → analytics-Ciob-x8a.js} +2 -2
- package/dist/{analytics-Z_2kCTpB.js.map → analytics-Ciob-x8a.js.map} +1 -1
- package/dist/analytics-DbfiRvPS.js +2 -0
- package/dist/{api-CwhOyprf.js → api-T_WHs3qZ.js} +3 -3
- package/dist/{api-CwhOyprf.js.map → api-T_WHs3qZ.js.map} +1 -1
- package/dist/bin.js +163 -69
- package/dist/bin.js.map +1 -1
- package/dist/{ci-install-CWDY86uB.js → ci-install-DJN5aT7W.js} +4 -4
- package/dist/{ci-install-CWDY86uB.js.map → ci-install-DJN5aT7W.js.map} +1 -1
- package/dist/{debug-BmdpjMub.js → debug-Cne-cLxd.js} +1 -1
- package/dist/{debug-CaRHQrDY.js → debug-D1lORUFs.js} +6 -10
- package/dist/debug-D1lORUFs.js.map +1 -0
- package/dist/{environment-knibpXF2.js → environment-BEsDCA2q.js} +3 -3
- package/dist/{environment-knibpXF2.js.map → environment-BEsDCA2q.js.map} +1 -1
- package/dist/{file-utils-DWYX_G1o.js → file-utils-Cn3dzlo-.js} +2 -2
- package/dist/{file-utils-DWYX_G1o.js.map → file-utils-Cn3dzlo-.js.map} +1 -1
- package/dist/{headless-ui-C4JCi9Zz.js → headless-ui-DGunpK-s.js} +2 -2
- package/dist/{headless-ui-C4JCi9Zz.js.map → headless-ui-DGunpK-s.js.map} +1 -1
- package/dist/{host-resolution-C18FwVrM.js → host-resolution-BnUJZKId.js} +3 -3
- package/dist/{host-resolution-C18FwVrM.js.map → host-resolution-BnUJZKId.js.map} +1 -1
- package/dist/{interactive-46qgS-UA.js → interactive-BB2IDSWP.js} +2 -2
- package/dist/{interactive-46qgS-UA.js.map → interactive-BB2IDSWP.js.map} +1 -1
- package/dist/{mcp-QWL5Obf3.js → mcp-CgA5vyiS.js} +2 -2
- package/dist/{mcp-QWL5Obf3.js.map → mcp-CgA5vyiS.js.map} +1 -1
- package/dist/{mcp-prompt-streaming-BpNkFksF.js → mcp-prompt-streaming-CGAkq9qR.js} +4 -4
- package/dist/{mcp-prompt-streaming-BpNkFksF.js.map → mcp-prompt-streaming-CGAkq9qR.js.map} +1 -1
- package/dist/{non-interactive-3_T1d0cj.js → non-interactive-Dko5F3vh.js} +2 -2
- package/dist/{non-interactive-3_T1d0cj.js.map → non-interactive-Dko5F3vh.js.map} +1 -1
- package/dist/{package-manager-C5VVQHQ-.js → package-manager-WKKQADHM.js} +2 -2
- package/dist/{package-manager-C5VVQHQ-.js.map → package-manager-WKKQADHM.js.map} +1 -1
- package/dist/{playground-CbzUpMuN.js → playground-UtT6zbjE.js} +5 -5
- package/dist/{playground-CbzUpMuN.js.map → playground-UtT6zbjE.js.map} +1 -1
- package/dist/{posthog-integration-6vdi4wRB.js → posthog-integration-CWXSng0W.js} +39 -20
- package/dist/posthog-integration-CWXSng0W.js.map +1 -0
- package/dist/{provisioning-DK0tS98H.js → provisioning-CgomM26T.js} +4 -4
- package/dist/{provisioning-DK0tS98H.js.map → provisioning-CgomM26T.js.map} +1 -1
- package/dist/{registry-DfXVjxsP.js → registry-BQIX-25O.js} +11 -8
- package/dist/{registry-DfXVjxsP.js.map → registry-BQIX-25O.js.map} +1 -1
- package/dist/{security-BMVH_bjk.js → security-pJOYY5LO.js} +3 -3
- package/dist/{security-BMVH_bjk.js.map → security-pJOYY5LO.js.map} +1 -1
- package/dist/{setup-utils-v9I6PQyP.js → setup-utils-DLGNk8T6.js} +9 -9
- package/dist/{setup-utils-v9I6PQyP.js.map → setup-utils-DLGNk8T6.js.map} +1 -1
- package/dist/{start-tui-CylEL6i_.js → start-tui-BjCKghQq.js} +131 -71
- package/dist/start-tui-BjCKghQq.js.map +1 -0
- package/dist/{steps-DQdpexNM.js → steps-XjV9CiqH.js} +7 -7
- package/dist/{steps-DQdpexNM.js.map → steps-XjV9CiqH.js.map} +1 -1
- package/dist/{store-Db0X2V5D.js → store-CDIxU0rr.js} +7 -5
- package/dist/{store-Db0X2V5D.js.map → store-CDIxU0rr.js.map} +1 -1
- package/dist/{subagent-Pk9jRXRf.js → subagent-S5Yh16IJ.js} +2 -2
- package/dist/{subagent-Pk9jRXRf.js.map → subagent-S5Yh16IJ.js.map} +1 -1
- package/dist/{tasks-B46phMJu.js → tasks-wbjOdifO.js} +2 -2
- package/dist/{tasks-B46phMJu.js.map → tasks-wbjOdifO.js.map} +1 -1
- package/dist/{telemetry-BJAHymMq.js → telemetry-BfnR7gtf.js} +3 -3
- package/dist/{telemetry-BJAHymMq.js.map → telemetry-BfnR7gtf.js.map} +1 -1
- package/dist/{terminal-BTQSAkC-.js → terminal-BvRwVeQp.js} +11 -11
- package/dist/{terminal-BTQSAkC-.js.map → terminal-BvRwVeQp.js.map} +1 -1
- package/dist/{tools-C_m5knXt.js → tools-CbtYlZV4.js} +4 -4
- package/dist/{tools-C_m5knXt.js.map → tools-CbtYlZV4.js.map} +1 -1
- package/dist/{urls-BCmeQMIb.js → urls-CilgPbS-.js} +2 -2
- package/dist/{urls-BCmeQMIb.js.map → urls-CilgPbS-.js.map} +1 -1
- package/dist/{wizard-abort-DkngXmxN.js → wizard-abort-Cp5Y7f8C.js} +3 -3
- package/dist/{wizard-abort-DkngXmxN.js.map → wizard-abort-Cp5Y7f8C.js.map} +1 -1
- package/dist/{wizard-abort-CMzW4LVM.js → wizard-abort-DHrEGqaC.js} +1 -1
- package/dist/{wizard-tools-C8nVWLeI.js → wizard-tools-DQTfAzSV.js} +28 -62
- package/dist/wizard-tools-DQTfAzSV.js.map +1 -0
- package/package.json +2 -1
- package/dist/analytics-B1SC2jaf.js +0 -2
- package/dist/debug-CaRHQrDY.js.map +0 -1
- package/dist/posthog-integration-6vdi4wRB.js.map +0 -1
- package/dist/start-tui-CylEL6i_.js.map +0 -1
- package/dist/wizard-tools-C8nVWLeI.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { s as logToFile } from "./debug-
|
|
2
|
-
import { a as installSkillById, c as resolveEnvPath, i as fetchSkillMenu, o as mergeEnvValues, s as parseEnvKeys } from "./wizard-tools-
|
|
3
|
-
import { r as detectNodePackageManagers } from "./package-manager-
|
|
1
|
+
import { s as logToFile } from "./debug-D1lORUFs.js";
|
|
2
|
+
import { a as installSkillById, c as resolveEnvPath, i as fetchSkillMenu, o as mergeEnvValues, s as parseEnvKeys } from "./wizard-tools-DQTfAzSV.js";
|
|
3
|
+
import { r as detectNodePackageManagers } from "./package-manager-WKKQADHM.js";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { Type } from "typebox";
|
|
@@ -119,4 +119,4 @@ function createWizardPiTools(ctx) {
|
|
|
119
119
|
//#endregion
|
|
120
120
|
export { createWizardPiTools };
|
|
121
121
|
|
|
122
|
-
//# sourceMappingURL=tools-
|
|
122
|
+
//# sourceMappingURL=tools-CbtYlZV4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools-C_m5knXt.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.\n *\n * v1 covers the four tools a framework integration needs. `wizard_ask` is\n * interactive-only (disabled in CI) and the secret-vault `secretRef` path is a\n * follow-up — CI passes literal values.\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 { logToFile } from '@utils/debug';\nimport {\n fetchSkillMenu,\n installSkillById,\n mergeEnvValues,\n parseEnvKeys,\n resolveEnvPath,\n} from '@lib/wizard-tools';\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}\n\nexport function createWizardPiTools(ctx: PiToolsContext): ToolDefinition[] {\n const { workingDirectory, skillsBaseUrl } = ctx;\n const detectPackageManager =\n ctx.detectPackageManager ?? detectNodePackageManagers;\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 );\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: 'Path to the .env file, relative to the project root',\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). Pass literal string values.',\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: 'Path to the .env file, relative to the project root',\n }),\n values: Type.Record(Type.String(), Type.String(), {\n description: 'Key → literal value',\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 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, args.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 return [loadSkillMenu, installSkill, checkEnvKeys, setEnvValues, detectPm];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,KAAK,GAGZ;AAC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,IAAI,CACrB,OAAM,GAAG,SAAS,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC;AACnD,UAAM,GAAG,SAAS,UAAU,UAAU,QAAQ,OAAO;AACrD,cACE,wBAAwB,SAAS,QAAQ,OAAO,KAAK,KAAK,OAAO,CAAC,KAChE,IACD,GACF;AACD,WAAO,KACL,SAAS,OAAO,KAAK,KAAK,OAAO,CAAC,OAAO,aAAa,KAAK,SAAS,GACrE;;GAEJ,CAAC;EAEe,WAAW;GAC1B,MAAM;GACN,OAAO;GACP,aACE;GACF,eACE;GACF,YAAY,KAAK,OAAO,EAAE,CAAC;GAC3B,MAAM,UAAU;IACd,MAAM,SAAS,MAAM,qBAAqB,iBAAiB;AAC3D,cACE,gCAAgC,OAAO,SAAS,OAAO,WACxD;AACD,WAAO,KAAK,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;;GAE/C,CAAC;EAEwE"}
|
|
1
|
+
{"version":3,"file":"tools-CbtYlZV4.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.\n *\n * v1 covers the four tools a framework integration needs. `wizard_ask` is\n * interactive-only (disabled in CI) and the secret-vault `secretRef` path is a\n * follow-up — CI passes literal values.\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 { logToFile } from '@utils/debug';\nimport {\n fetchSkillMenu,\n installSkillById,\n mergeEnvValues,\n parseEnvKeys,\n resolveEnvPath,\n} from '@lib/wizard-tools';\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}\n\nexport function createWizardPiTools(ctx: PiToolsContext): ToolDefinition[] {\n const { workingDirectory, skillsBaseUrl } = ctx;\n const detectPackageManager =\n ctx.detectPackageManager ?? detectNodePackageManagers;\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 );\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: 'Path to the .env file, relative to the project root',\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). Pass literal string values.',\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: 'Path to the .env file, relative to the project root',\n }),\n values: Type.Record(Type.String(), Type.String(), {\n description: 'Key → literal value',\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 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, args.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 return [loadSkillMenu, installSkill, checkEnvKeys, setEnvValues, detectPm];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,KAAK,GAGZ;AACA,QAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAG,CAAC;EAAE,SAAS,EAAE;EAAE;;AAU9D,SAAgB,oBAAoB,KAAuC;CACzE,MAAM,EAAE,kBAAkB,kBAAkB;CAC5C,MAAM,uBACJ,IAAI,wBAAwB;CAI9B,IAAI;CACJ,MAAM,qBAAsB,gBAAgB,eAAe,cAAc;AA+IzE,QAAO;EA7Ie,WAAW;GAC/B,MAAM;GACN,OAAO;GACP,aACE;GACF,eACE;GACF,YAAY,KAAK,OAAO,EACtB,UAAU,KAAK,OAAO,EACpB,aAAa,wCACd,CAAC,EACH,CAAC;GACF,MAAM,QAAQ,KAAK,MAAM;IACvB,MAAM,OAAO,MAA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ACE,gCAAgC,OAAO,SAAS,OAAO,WACxD;AACD,WAAO,KAAK,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;;GAE/C,CAAC;EAEwE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { st as WIZARD_USER_AGENT } from "./debug-D1lORUFs.js";
|
|
2
2
|
import axios from "axios";
|
|
3
3
|
//#region src/utils/urls.ts
|
|
4
4
|
/**
|
|
@@ -64,4 +64,4 @@ const getOAuthUrl = (baseUrl) => resolveBaseUrl(baseUrl) ?? PROD_OAUTH_URL;
|
|
|
64
64
|
//#endregion
|
|
65
65
|
export { getOAuthUrl as a, getLlmGatewayUrl as i, getCloudUrl as n, getUiHostFromHost as o, getHost as r, resolveBaseUrl as s, detectRegion as t };
|
|
66
66
|
|
|
67
|
-
//# sourceMappingURL=urls-
|
|
67
|
+
//# sourceMappingURL=urls-CilgPbS-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"urls-
|
|
1
|
+
{"version":3,"file":"urls-CilgPbS-.js","names":[],"sources":["../src/utils/urls.ts"],"sourcesContent":["import axios from 'axios';\nimport { IS_DEV, WIZARD_USER_AGENT } from '@lib/constants';\nimport type { CloudRegion } from './types';\n\n/**\n * Resolve a pinned PostHog base URL from an optional override. When present, it\n * becomes the single source of truth for every PostHog origin — the\n * API/ingestion host, the cloud/app URL, and the OAuth server — bypassing\n * region resolution entirely.\n *\n * The override lives on the session (`session.baseUrl`, set by `--base-url`) and\n * is threaded in by callers, so there is no hidden module-level state. A `--base-url`\n * value wins; otherwise a dev/test build implies `localhost:8010`; otherwise the\n * result is `undefined`, meaning region-based resolution applies.\n *\n * This is the runtime equivalent of the `IS_DEV` localhost routing: `IS_DEV` is a\n * build-time constant that tsdown compiles out of production builds, so it can't\n * point a shipped wizard at a local stack — `--base-url` can. Both feed this one\n * resolver so every URL helper only asks the question once.\n */\nexport const resolveBaseUrl = (override?: string): string | undefined => {\n return override?.trim() || (IS_DEV ? 'http://localhost:8010' : undefined);\n};\n\nexport const getUiHostFromHost = (host: string) => {\n if (host.includes('us.i.posthog.com')) {\n return 'https://us.posthog.com';\n }\n\n if (host.includes('eu.i.posthog.com')) {\n return 'https://eu.posthog.com';\n }\n\n return host;\n};\n\nexport const getHost = (region: CloudRegion, baseUrl?: string) => {\n const override = resolveBaseUrl(baseUrl);\n if (override) {\n return override;\n }\n\n if (region === 'eu') {\n return 'https://eu.i.posthog.com';\n }\n\n return 'https://us.i.posthog.com';\n};\n\nexport const getCloudUrl = (region: CloudRegion, baseUrl?: string) => {\n const override = resolveBaseUrl(baseUrl);\n if (override) {\n return override;\n }\n\n if (region === 'eu') {\n return 'https://eu.posthog.com';\n }\n\n return 'https://us.posthog.com';\n};\n\nexport async function detectRegion(\n accessToken: string,\n baseUrl?: string,\n): Promise<CloudRegion> {\n // With a pinned base URL there is only one instance to talk to — skip the\n // us/eu probe and default the region label to 'us'. (Covers IS_DEV too, via\n // resolveBaseUrl.) The URLs themselves come from the override, not this label.\n if (resolveBaseUrl(baseUrl)) {\n return 'us';\n }\n\n const headers = {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': WIZARD_USER_AGENT,\n };\n\n const [usResult, euResult] = await Promise.allSettled([\n axios.get('https://us.posthog.com/api/users/@me/', { headers }),\n axios.get('https://eu.posthog.com/api/users/@me/', { headers }),\n ]);\n\n if (usResult.status === 'fulfilled') return 'us';\n if (euResult.status === 'fulfilled') return 'eu';\n\n throw new Error(\n 'Could not determine cloud region from access token. Please check your PostHog account.',\n );\n}\n\nexport const getLlmGatewayUrl = (host: string) => {\n if (host.includes('host.docker.internal')) {\n return 'http://host.docker.internal:3308/wizard';\n }\n\n if (host.includes('localhost')) {\n return 'http://localhost:3308/wizard';\n }\n\n if (host.includes('eu.posthog.com') || host.includes('eu.i.posthog.com')) {\n return 'https://gateway.eu.posthog.com/wizard';\n }\n\n return 'https://gateway.us.posthog.com/wizard';\n};\n\n/** Region-agnostic prod OAuth server. Resolves to the right region server-side. */\nconst PROD_OAUTH_URL = 'https://oauth.posthog.com';\n\n/**\n * OAuth server URL. Follows the base-URL override (and thus IS_DEV → localhost),\n * otherwise the region-agnostic prod OAuth host.\n */\nexport const getOAuthUrl = (baseUrl?: string): string =>\n resolveBaseUrl(baseUrl) ?? PROD_OAUTH_URL;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,MAAa,kBAAkB,aAA0C;AACvE,QAAO,UAAU,MAAM,IAAwC,KAAA;;AAGjE,MAAa,qBAAqB,SAAiB;AACjD,KAAI,KAAK,SAAS,mBAAmB,CACnC,QAAO;AAGT,KAAI,KAAK,SAAS,mBAAmB,CACnC,QAAO;AAGT,QAAO;;AAGT,MAAa,WAAW,QAAqB,YAAqB;CAChE,MAAM,WAAW,eAAe,QAAQ;AACxC,KAAI,SACF,QAAO;AAGT,KAAI,WAAW,KACb,QAAO;AAGT,QAAO;;AAGT,MAAa,eAAe,QAAqB,YAAqB;CACpE,MAAM,WAAW,eAAe,QAAQ;AACxC,KAAI,SACF,QAAO;AAGT,KAAI,WAAW,KACb,QAAO;AAGT,QAAO;;AAGT,eAAsB,aACpB,aACA,SACsB;AAItB,KAAI,eAAe,QAAQ,CACzB,QAAO;CAGT,MAAM,UAAU;EACd,eAAe,UAAU;EACzB,cAAc;EACf;CAED,MAAM,CAAC,UAAU,YAAY,MAAM,QAAQ,WAAW,CACpD,MAAM,IAAI,yCAAyC,EAAE,SAAS,CAAC,EAC/D,MAAM,IAAI,yCAAyC,EAAE,SAAS,CAAC,CAChE,CAAC;AAEF,KAAI,SAAS,WAAW,YAAa,QAAO;AAC5C,KAAI,SAAS,WAAW,YAAa,QAAO;AAE5C,OAAM,IAAI,MACR,yFACD;;AAGH,MAAa,oBAAoB,SAAiB;AAChD,KAAI,KAAK,SAAS,uBAAuB,CACvC,QAAO;AAGT,KAAI,KAAK,SAAS,YAAY,CAC5B,QAAO;AAGT,KAAI,KAAK,SAAS,iBAAiB,IAAI,KAAK,SAAS,mBAAmB,CACtE,QAAO;AAGT,QAAO;;;AAIT,MAAM,iBAAiB;;;;;AAMvB,MAAa,eAAe,YAC1B,eAAe,QAAQ,IAAI"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
1
|
+
import { f as getUI, s as logToFile } from "./debug-D1lORUFs.js";
|
|
2
|
+
import { n as analytics } from "./analytics-Ciob-x8a.js";
|
|
3
3
|
import "./wizard-session-BoXAZEOf.js";
|
|
4
4
|
//#region src/utils/wizard-abort.ts
|
|
5
5
|
/**
|
|
@@ -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-
|
|
49
|
+
//# sourceMappingURL=wizard-abort-Cp5Y7f8C.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wizard-abort-
|
|
1
|
+
{"version":3,"file":"wizard-abort-Cp5Y7f8C.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-
|
|
1
|
+
import { i as wizardAbort, t as WizardError } from "./wizard-abort-Cp5Y7f8C.js";
|
|
2
2
|
export { WizardError, wizardAbort };
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
1
|
+
import { s as logToFile } from "./debug-D1lORUFs.js";
|
|
2
|
+
import { n as analytics } from "./analytics-Ciob-x8a.js";
|
|
3
3
|
import * as fs$1 from "fs";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import * as path$1 from "path";
|
|
6
6
|
import path from "path";
|
|
7
7
|
import { z } from "zod";
|
|
8
|
-
import {
|
|
8
|
+
import { unzipSync } from "fflate";
|
|
9
9
|
import { randomUUID } from "crypto";
|
|
10
10
|
//#region src/utils/atomic-ledger.ts
|
|
11
11
|
/**
|
|
@@ -554,74 +554,40 @@ async function fetchSkillMenu(skillsBaseUrl) {
|
|
|
554
554
|
return null;
|
|
555
555
|
}
|
|
556
556
|
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
"-C",
|
|
572
|
-
destDir
|
|
573
|
-
]
|
|
574
|
-
}];
|
|
575
|
-
if (process.platform === "win32") {
|
|
576
|
-
const quote = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
577
|
-
attempts.push({
|
|
578
|
-
tool: "powershell.exe",
|
|
579
|
-
args: [
|
|
580
|
-
"-NoProfile",
|
|
581
|
-
"-NonInteractive",
|
|
582
|
-
"-Command",
|
|
583
|
-
`Expand-Archive -LiteralPath ${quote(zipFile)} -DestinationPath ${quote(destDir)} -Force`
|
|
584
|
-
]
|
|
585
|
-
});
|
|
586
|
-
}
|
|
587
|
-
return attempts;
|
|
588
|
-
}
|
|
589
|
-
/** Extract with the first tool that works; throws naming every failure. */
|
|
590
|
-
function extractZip(zipFile, destDir, exec = execFileSync) {
|
|
591
|
-
const failures = [];
|
|
592
|
-
for (const { tool, args } of zipExtractionAttempts(zipFile, destDir)) try {
|
|
593
|
-
exec(tool, args, { timeout: 3e4 });
|
|
594
|
-
return tool;
|
|
595
|
-
} catch (err) {
|
|
596
|
-
failures.push(`${tool}: ${err.message}`);
|
|
557
|
+
/** Extract a zip buffer, refusing entries that escape destDir (zip-slip). */
|
|
558
|
+
function extractZipArchive(zip, destDir) {
|
|
559
|
+
const root = path.resolve(destDir);
|
|
560
|
+
let written = 0;
|
|
561
|
+
for (const [entryPath, data] of Object.entries(unzipSync(zip))) {
|
|
562
|
+
const target = path.resolve(root, entryPath);
|
|
563
|
+
if (target !== root && !target.startsWith(root + path.sep)) throw new Error(`zip entry escapes destination: ${entryPath}`);
|
|
564
|
+
if (entryPath.endsWith("/")) {
|
|
565
|
+
fs.mkdirSync(target, { recursive: true });
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
569
|
+
fs.writeFileSync(target, data);
|
|
570
|
+
written++;
|
|
597
571
|
}
|
|
598
|
-
|
|
572
|
+
return written;
|
|
599
573
|
}
|
|
600
574
|
/**
|
|
601
575
|
* Download and extract a skill.
|
|
602
576
|
* By default installs to `<installDir>/.claude/skills/<id>/`.
|
|
603
577
|
* Pass `skillsRoot` to override the base directory (e.g. `.posthog/skills`).
|
|
604
578
|
*/
|
|
605
|
-
function downloadSkill(skillEntry, installDir, skillsRoot) {
|
|
579
|
+
async function downloadSkill(skillEntry, installDir, skillsRoot) {
|
|
606
580
|
const skillDir = skillsRoot ? path.join(installDir, skillsRoot, skillEntry.id) : path.join(installDir, ".claude", "skills", skillEntry.id);
|
|
607
|
-
const tmpFile = skillTmpPath(skillEntry.id);
|
|
608
581
|
let step = "download";
|
|
609
582
|
try {
|
|
610
583
|
fs.mkdirSync(skillDir, { recursive: true });
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
skillEntry.downloadUrl,
|
|
615
|
-
"-o",
|
|
616
|
-
tmpFile
|
|
617
|
-
], { timeout: 3e4 });
|
|
584
|
+
const resp = await fetch(skillEntry.downloadUrl, { signal: AbortSignal.timeout(3e4) });
|
|
585
|
+
if (!resp.ok) throw new Error(`download failed with HTTP ${resp.status}`);
|
|
586
|
+
const zip = new Uint8Array(await resp.arrayBuffer());
|
|
618
587
|
step = "extract";
|
|
619
|
-
const
|
|
588
|
+
const fileCount = extractZipArchive(zip, skillDir);
|
|
620
589
|
fs.writeFileSync(path.join(skillDir, ".posthog-wizard"), "");
|
|
621
|
-
|
|
622
|
-
fs.unlinkSync(tmpFile);
|
|
623
|
-
} catch {}
|
|
624
|
-
logToFile(`downloadSkill: installed ${skillEntry.id} from ${skillEntry.downloadUrl} (extracted via ${extractedWith})`);
|
|
590
|
+
logToFile(`downloadSkill: installed ${skillEntry.id} from ${skillEntry.downloadUrl} (${fileCount} files)`);
|
|
625
591
|
return { success: true };
|
|
626
592
|
} catch (err) {
|
|
627
593
|
logToFile(`downloadSkill: error: ${err.message}`);
|
|
@@ -650,7 +616,7 @@ async function installSkillById(skillId, installDir, skillsBaseUrl, skillsRoot)
|
|
|
650
616
|
kind: "skill-not-found",
|
|
651
617
|
skillId
|
|
652
618
|
};
|
|
653
|
-
const result = downloadSkill(skill, installDir, skillsRoot);
|
|
619
|
+
const result = await downloadSkill(skill, installDir, skillsRoot);
|
|
654
620
|
if (!result.success) return {
|
|
655
621
|
kind: "download-failed",
|
|
656
622
|
message: result.error ?? "unknown"
|
|
@@ -932,7 +898,7 @@ async function createWizardToolsServer(options) {
|
|
|
932
898
|
text: menuText
|
|
933
899
|
}] };
|
|
934
900
|
});
|
|
935
|
-
const installSkill = tool("install_skill", "Download and install a PostHog skill by ID. Call load_skill_menu first to see available skills. Extracts the skill to .claude/skills/<skillId>/.", { skillId: z.string().describe("Skill ID from the skill menu (e.g., \"integration-nextjs-app-router\")") }, (args) => {
|
|
901
|
+
const installSkill = tool("install_skill", "Download and install a PostHog skill by ID. Call load_skill_menu first to see available skills. Extracts the skill to .claude/skills/<skillId>/.", { skillId: z.string().describe("Skill ID from the skill menu (e.g., \"integration-nextjs-app-router\")") }, async (args) => {
|
|
936
902
|
if (!/^[a-z0-9][a-z0-9_-]*$/.test(args.skillId)) return {
|
|
937
903
|
content: [{
|
|
938
904
|
type: "text",
|
|
@@ -948,7 +914,7 @@ async function createWizardToolsServer(options) {
|
|
|
948
914
|
}],
|
|
949
915
|
isError: true
|
|
950
916
|
};
|
|
951
|
-
const result = downloadSkill(skill, workingDirectory);
|
|
917
|
+
const result = await downloadSkill(skill, workingDirectory);
|
|
952
918
|
if (result.success) return { content: [{
|
|
953
919
|
type: "text",
|
|
954
920
|
text: `Skill installed to .claude/skills/${args.skillId}/`
|
|
@@ -1159,4 +1125,4 @@ const WIZARD_TOOL_NAMES = {
|
|
|
1159
1125
|
//#endregion
|
|
1160
1126
|
export { coerceAuditChecks as _, installSkillById as a, resolveEnvPath as c, TaskStatus as d, createWizardAskBridge as f, AUDIT_SEVERITY_STYLE as g, AUDIT_REPORT_FILE as h, fetchSkillMenu as i, QUEUE_DIR_NAME as l, AUDIT_CHECKS_KEY as m, createWizardToolsServer as n, mergeEnvValues as o, AUDIT_CHECKS_FILE as p, downloadSkill as r, parseEnvKeys as s, WIZARD_TOOL_NAMES as t, QueueStore as u, getAuditChecks as v };
|
|
1161
1127
|
|
|
1162
|
-
//# sourceMappingURL=wizard-tools-
|
|
1128
|
+
//# sourceMappingURL=wizard-tools-DQTfAzSV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wizard-tools-DQTfAzSV.js","names":["path"],"sources":["../src/utils/atomic-ledger.ts","../src/lib/programs/audit/types.ts","../src/lib/wizard-ask-bridge.ts","../src/lib/secret-vault.ts","../src/lib/agent/runner/sequence/orchestrator/queue.ts","../src/lib/agent/runner/sequence/orchestrator/queue-tools.ts","../src/lib/wizard-tools.ts"],"sourcesContent":["/**\n * Small shared primitives for on-disk ledgers: an atomic JSON writer and a\n * single-chain async mutex. Used by the audit tools and by the orchestrator\n * queue. Lifted here so both share one implementation.\n */\nimport * as fs from 'fs';\n\n/**\n * Atomically write JSON: write to a `.tmp` file then rename over the target. The\n * rename bumps the file's mtime in one step, which is what a file watcher polls.\n */\nexport function writeJsonAtomic(targetPath: string, data: unknown): void {\n const tmpPath = `${targetPath}.tmp`;\n fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8');\n fs.renameSync(tmpPath, targetPath);\n}\n\n/**\n * A single async mutex. Serializes read-modify-write cycles so concurrent callers\n * (parallel task agents, audit tool calls) never interleave a mutation.\n */\nexport function makeMutex() {\n let chain: Promise<unknown> = Promise.resolve();\n return async function run<T>(fn: () => Promise<T> | T): Promise<T> {\n const next = chain.then(() => fn());\n chain = next.catch(() => undefined);\n return next;\n };\n}\n","import type { WizardSession } from '@lib/wizard-session';\n\nexport type AuditStatus =\n | 'pending'\n | 'pass'\n | 'error'\n | 'warning'\n | 'suggestion';\n\nexport interface AuditCheck {\n id: string;\n area: string;\n label: string;\n status: AuditStatus;\n file?: string;\n details?: string;\n}\n\nexport interface AuditSeverityStyle {\n glyph: string;\n color: string;\n}\n\n/** Single source of truth for status glyph + color across audit views. */\nexport const AUDIT_SEVERITY_STYLE: Record<AuditStatus, AuditSeverityStyle> = {\n pending: { glyph: '◌', color: 'gray' },\n pass: { glyph: '✔', color: 'green' },\n error: { glyph: '✘', color: 'red' },\n warning: { glyph: '⚠', color: 'yellow' },\n suggestion: { glyph: '•', color: 'cyan' },\n};\n\nexport const AUDIT_CHECKS_FILE = '.posthog-audit-checks.json';\nexport const AUDIT_REPORT_FILE = 'posthog-audit-report.md';\nexport const AUDIT_CHECKS_KEY = 'auditChecks';\n\nexport function getAuditChecks(session: WizardSession): AuditCheck[] {\n const raw = session.frameworkContext[AUDIT_CHECKS_KEY];\n return Array.isArray(raw) ? (raw as AuditCheck[]) : [];\n}\n\n/**\n * Read the audit checks ledger off disk. Validation lives at write time —\n * every writer (`audit_seed_checks` / `audit_add_checks` / `audit_resolve_checks`\n * MCP tools, `seedAuditLedger`) zod-parses entries before the atomic write,\n * so by the time the file watcher fires we trust the shape and only guard\n * against the file not being a JSON array (corrupted / hand-edited / not yet\n * seeded).\n */\nexport function coerceAuditChecks(parsed: unknown): AuditCheck[] {\n return Array.isArray(parsed) ? (parsed as AuditCheck[]) : [];\n}\n","/**\n * WizardAskBridge — host-side promise broker for the `wizard_ask` MCP tool.\n *\n * The `wizard_ask` tool needs to (a) read information from the wizard\n * session (the active skill id, used as the analytics `source`) and\n * (b) drive the TUI overlay. Wiring `wizard-tools.ts` directly to either\n * would couple our pure-data MCP server to the runtime UI layer.\n *\n * The bridge is the seam: `wizard-tools.ts` depends on this interface,\n * and `agent-runner.ts` constructs an implementation that knows about\n * both the session and `getUI()`.\n */\nimport { randomUUID } from 'crypto';\n\nimport { analytics } from '@utils/analytics';\nimport type {\n AskAnswers,\n AskQuestion,\n PendingQuestion,\n} from './wizard-session';\n\nexport interface WizardAskRequest {\n questions: AskQuestion[];\n}\n\nexport interface WizardAskBridge {\n /**\n * Open the WizardAsk overlay and resolve with the user's answers.\n * One answer per question id (string for `single`/`text`, string[] for\n * `multi`). Cancelled fields come back as the literal `\"__cancelled__\"`.\n */\n request(req: WizardAskRequest): Promise<AskAnswers>;\n}\n\nexport interface WizardAskBridgeOptions {\n /** Returns the active skill id, used as the analytics `source` on the request. */\n getSource: () => string;\n /** Opens the overlay and resolves once the user submits or cancels. */\n showQuestion: (question: PendingQuestion) => Promise<AskAnswers>;\n /**\n * Per-question timeout in milliseconds. When the user takes longer than\n * this to answer, every unanswered field resolves with the\n * {@link CANCELLED_SENTINEL} value. Defaults to {@link DEFAULT_ASK_TIMEOUT_MS}.\n */\n timeoutMs?: number;\n /**\n * Opt the rendered overlay into rich link handling (OSC 8 hyperlinks +\n * clipboard copy for prompt URLs). Set per program; defaults to false.\n * Propagated onto every {@link PendingQuestion} this bridge creates.\n */\n richLinks?: boolean;\n}\n\n/** Sentinel returned for unanswered fields on cancellation or timeout. */\nexport const CANCELLED_SENTINEL = '__cancelled__';\n\n/** Default per-question timeout (5 minutes). */\nexport const DEFAULT_ASK_TIMEOUT_MS = 5 * 60 * 1000;\n\nfunction buildCancelledAnswers(questions: AskQuestion[]): AskAnswers {\n const out: AskAnswers = {};\n for (const q of questions) {\n out[q.id] = CANCELLED_SENTINEL;\n }\n return out;\n}\n\nexport function isFullyCancelled(answers: AskAnswers): boolean {\n const values = Object.values(answers);\n if (values.length === 0) return false;\n return values.every((v) => v === CANCELLED_SENTINEL);\n}\n\nexport function createWizardAskBridge(\n opts: WizardAskBridgeOptions,\n): WizardAskBridge {\n const timeoutMs = opts.timeoutMs ?? DEFAULT_ASK_TIMEOUT_MS;\n\n return {\n async request({ questions }) {\n const pending: PendingQuestion = {\n id: randomUUID(),\n questions,\n source: opts.getSource(),\n richLinks: opts.richLinks ?? false,\n };\n\n const startedAt = Date.now();\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n // Race the user against the timeout. Whichever fires first wins; the\n // other branch is harmless because the overlay still resolves via the\n // store when the user eventually submits (and the answers are simply\n // discarded).\n const timeoutPromise = new Promise<AskAnswers>((resolve) => {\n timer = setTimeout(() => {\n resolve(buildCancelledAnswers(questions));\n }, timeoutMs);\n });\n\n try {\n const answers = await Promise.race([\n opts.showQuestion(pending),\n timeoutPromise,\n ]);\n const durationMs = Date.now() - startedAt;\n\n if (isFullyCancelled(answers)) {\n analytics.wizardCapture('wizard_ask cancelled', {\n source: pending.source,\n question_count: questions.length,\n duration_ms: durationMs,\n timed_out: durationMs >= timeoutMs,\n });\n } else {\n analytics.wizardCapture('wizard_ask answered', {\n source: pending.source,\n question_count: questions.length,\n duration_ms: durationMs,\n });\n }\n\n return answers;\n } finally {\n if (timer) clearTimeout(timer);\n }\n },\n };\n}\n","/**\n * Session-scoped secret vault.\n *\n * Tools that handle sensitive values (personal API keys pasted by the user\n * or minted by the wizard, OAuth tokens, etc.) store them here and return\n * an opaque `secret:<uuid>` ref to the agent. The agent passes the ref\n * around to subsequent tools — `set_env_values` resolves it host-side\n * before writing — but the raw value never enters the LLM conversation.\n *\n * The vault is created once per `createWizardToolsServer` call and lives\n * for the duration of a single wizard run. There is no persistence and\n * no cross-session sharing; refs minted in one run cannot be resolved in\n * another.\n */\n\nimport { randomUUID } from 'crypto';\n\nconst REF_PREFIX = 'secret:';\n\nexport interface SecretMeta {\n /** Opaque reference handed to the agent. */\n ref: string;\n /** Human-readable label shown to the user (e.g. \"Personal API key\"). */\n label: string;\n /** Where the secret came from (e.g. \"wizard_ask\"). */\n source: string;\n /** ms epoch when the secret was stored. */\n createdAt: number;\n}\n\nexport interface SecretVault {\n /** Store a value and return its ref. */\n put(value: string, meta: Omit<SecretMeta, 'ref' | 'createdAt'>): string;\n /** Resolve a ref to its value, or undefined if unknown. */\n get(ref: string): string | undefined;\n /** Whether the vault knows about this ref. */\n has(ref: string): boolean;\n /** Metadata for every stored secret (never the values). */\n list(): SecretMeta[];\n /** Drop every secret. Call at session teardown. */\n clear(): void;\n}\n\n/** True when the value looks like a secret ref. Does not assert resolvability. */\nexport function isSecretRef(value: unknown): value is string {\n return typeof value === 'string' && value.startsWith(REF_PREFIX);\n}\n\nexport function createSecretVault(): SecretVault {\n const store = new Map<string, { value: string; meta: SecretMeta }>();\n\n return {\n put(value, meta) {\n const ref = `${REF_PREFIX}${randomUUID()}`;\n store.set(ref, {\n value,\n meta: {\n ref,\n label: meta.label,\n source: meta.source,\n createdAt: Date.now(),\n },\n });\n return ref;\n },\n get(ref) {\n return store.get(ref)?.value;\n },\n has(ref) {\n return store.has(ref);\n },\n list() {\n return [...store.values()].map((s) => s.meta);\n },\n clear() {\n store.clear();\n },\n };\n}\n","/**\n * The orchestrator task queue.\n *\n * In memory, synchronous, single-owner: one Node process drives the run, so\n * there is no locking. The queue imposes no execution policy — `nextRunnable`\n * returns every pending task whose dependencies are satisfied, and how many of\n * those run at once is decided by the task graph, not the queue.\n *\n * Every transition rewrites `<installDir>/.posthog-wizard-cache/queue.json`, a\n * small file holding the whole queue, handoffs included. It is the run's log\n * and the report's source. The whole cache folder is run-scoped and wiped when\n * the run ends.\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { randomUUID } from 'crypto';\nimport { writeJsonAtomic } from '@utils/atomic-ledger';\nimport { analytics } from '@utils/analytics';\n\nexport const TaskStatus = {\n Pending: 'pending',\n Running: 'running',\n Done: 'done',\n Skipped: 'skipped',\n Failed: 'failed',\n} as const;\n\nexport type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus];\n\nexport interface QueuedTask {\n id: string;\n type: string;\n /** Human-readable label for the TUI, set by the enqueuing agent. */\n label?: string;\n status: TaskStatus;\n /**\n * Ids of tasks that must finish before this one runs. Ids are generated at\n * enqueue and dependsOn is never mutated, so a task can only depend on tasks\n * created before it — the graph is a DAG by construction, cycles cannot\n * form. Unknown ids are rejected by the enqueue_task guard.\n */\n dependsOn: string[];\n inputs: Record<string, unknown>;\n model?: string;\n attempts: number;\n maxAttempts: number;\n /** The structured handoff the task reported on completion. */\n handoff?: TaskHandoff;\n /** 'orchestrator' for seeded tasks, or the id of the task that enqueued this one. */\n enqueuedBy: string;\n createdAt: string;\n startedAt?: string;\n finishedAt?: string;\n error?: { type: string; message: string };\n}\n\nexport interface QueueFile {\n version: 1;\n runId: string;\n tasks: QueuedTask[];\n}\n\n/** The structured handoff a task leaves for the next agent. */\nexport interface TaskHandoff {\n goals: string;\n did: string;\n forNextAgent: string;\n filesTouched?: string[];\n /** A one-line summary of any unresolved conflict, surfaced in the outro. */\n conflict?: string;\n}\n\nexport interface EnqueueInput {\n type: string;\n label?: string;\n inputs?: Record<string, unknown>;\n dependsOn?: string[];\n model?: string;\n maxAttempts?: number;\n enqueuedBy?: string;\n}\n\nexport const QUEUE_DIR_NAME = '.posthog-wizard-cache';\nconst DEFAULT_MAX_ATTEMPTS = 2;\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\n/** Dropped in the cache folder so an orphaned copy explains itself. */\nconst DELETE_ME_FILE = '.DELETE-ME.md';\nconst DELETE_ME_BODY = `# Safe to delete\n\nThis folder contains run artifacts from the PostHog Wizard. This should have\nbeen deleted if the Wizard has finished running. If this wasn't deleted for\nsome reason, you can safely delete the entire \\`${QUEUE_DIR_NAME}/\\` folder.\n`;\n\n/** Every queue transition, in the order it is reflected. */\nexport type TransitionEvent =\n | 'enqueue'\n | 'start'\n | 'complete'\n | 'skip'\n | 'fail'\n | 'requeue';\n\nexport interface QueueStoreOptions {\n /**\n * Called on every transition with the task's post-transition state. The\n * runner uses it for telemetry; the store itself stays analytics-free.\n * Listener errors are reported but cannot break a transition.\n */\n onTransition?: (event: TransitionEvent, task: QueuedTask) => void;\n}\n\nexport class QueueStore {\n private tasks: QueuedTask[] = [];\n private readonly onTransition?: (\n event: TransitionEvent,\n task: QueuedTask,\n ) => void;\n\n readonly runId: string;\n readonly queuePath: string;\n\n constructor(installDir: string, runId: string, opts?: QueueStoreOptions) {\n this.onTransition = opts?.onTransition;\n this.runId = runId;\n const dir = path.join(installDir, QUEUE_DIR_NAME);\n this.queuePath = path.join(dir, 'queue.json');\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(path.join(dir, DELETE_ME_FILE), DELETE_ME_BODY);\n }\n\n // ── Reads ───────────────────────────────────────────────────────────\n\n list(): readonly QueuedTask[] {\n return this.tasks;\n }\n\n get(id: string): QueuedTask | undefined {\n return this.tasks.find((t) => t.id === id);\n }\n\n /**\n * Every pending task whose dependencies are all satisfied (`done` or\n * `skipped`). A skipped dependency does not block downstream work.\n */\n nextRunnable(): QueuedTask[] {\n const doneIds = new Set(\n this.tasks\n .filter(\n (t) =>\n t.status === TaskStatus.Done || t.status === TaskStatus.Skipped,\n )\n .map((t) => t.id),\n );\n return this.tasks.filter(\n (t) =>\n t.status === TaskStatus.Pending &&\n t.dependsOn.every((d) => doneIds.has(d)),\n );\n }\n\n /**\n * True when no task is running and none can be started. Either everything\n * is terminal, or the only pending tasks are blocked by a failed dependency.\n */\n isDrained(): boolean {\n if (this.tasks.some((t) => t.status === TaskStatus.Running)) return false;\n return this.nextRunnable().length === 0;\n }\n\n summary(): Record<TaskStatus, number> & { total: number } {\n const counts: Record<TaskStatus, number> = {\n [TaskStatus.Pending]: 0,\n [TaskStatus.Running]: 0,\n [TaskStatus.Done]: 0,\n [TaskStatus.Skipped]: 0,\n [TaskStatus.Failed]: 0,\n };\n for (const t of this.tasks) counts[t.status] += 1;\n return { ...counts, total: this.tasks.length };\n }\n\n readHandoff(id: string): TaskHandoff | null {\n return this.get(id)?.handoff ?? null;\n }\n\n /** Handoffs of completed tasks of a given type, oldest first. */\n readHandoffsByType(type: string): TaskHandoff[] {\n return this.tasks\n .filter((t) => t.type === type && t.handoff)\n .map((t) => t.handoff as TaskHandoff);\n }\n\n // ── Transitions (each one reflected to queue.json) ──────────────────\n\n enqueue(input: EnqueueInput): QueuedTask {\n const task: QueuedTask = {\n id: randomUUID(),\n type: input.type,\n label: input.label,\n status: TaskStatus.Pending,\n dependsOn: input.dependsOn ?? [],\n inputs: input.inputs ?? {},\n model: input.model,\n attempts: 0,\n maxAttempts: input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n enqueuedBy: input.enqueuedBy ?? 'orchestrator',\n createdAt: nowIso(),\n };\n this.tasks.push(task);\n this.reflect();\n this.notify('enqueue', task);\n return task;\n }\n\n start(id: string): QueuedTask {\n const t = this.require(id);\n t.status = TaskStatus.Running;\n t.startedAt = nowIso();\n t.attempts += 1;\n this.reflect();\n this.notify('start', t);\n return t;\n }\n\n complete(id: string, handoff?: TaskHandoff): QueuedTask {\n return this.finish(id, TaskStatus.Done, handoff);\n }\n\n /** Terminal: the agent could not do the task. Not done, not failed. */\n skip(id: string, handoff?: TaskHandoff): QueuedTask {\n return this.finish(id, TaskStatus.Skipped, handoff);\n }\n\n fail(\n id: string,\n error: { type: string; message: string },\n handoff?: TaskHandoff,\n ): QueuedTask {\n const t = this.require(id);\n t.error = error;\n return this.finish(id, TaskStatus.Failed, handoff);\n }\n\n /** Put a failed/running task back to pending for a retry within the run. */\n requeue(id: string): QueuedTask {\n const t = this.require(id);\n t.status = TaskStatus.Pending;\n t.startedAt = undefined;\n t.finishedAt = undefined;\n this.reflect();\n this.notify('requeue', t);\n return t;\n }\n\n // ── Internals ───────────────────────────────────────────────────────\n\n private finish(\n id: string,\n status: 'done' | 'skipped' | 'failed',\n handoff?: TaskHandoff,\n ): QueuedTask {\n const t = this.require(id);\n if (handoff) t.handoff = handoff;\n t.status = status;\n t.finishedAt = nowIso();\n this.reflect();\n this.notify(\n status === TaskStatus.Done\n ? 'complete'\n : status === TaskStatus.Skipped\n ? 'skip'\n : 'fail',\n t,\n );\n return t;\n }\n\n private reflect(): void {\n const file: QueueFile = {\n version: 1,\n runId: this.runId,\n tasks: this.tasks,\n };\n writeJsonAtomic(this.queuePath, file);\n }\n\n private notify(event: TransitionEvent, task: QueuedTask): void {\n try {\n this.onTransition?.(event, task);\n } catch (error) {\n // A listener must never break a transition, but its failure is a bug.\n analytics.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'orchestrator_queue_listener', event },\n );\n }\n }\n\n private require(id: string): QueuedTask {\n const t = this.get(id);\n if (!t) throw new Error(`No task ${id} in the queue`);\n return t;\n }\n}\n","/**\n * Orchestrator MCP tools, registered into the existing `wizard-tools` server when\n * a queue is present. They let the orchestrator agent and task agents grow the\n * queue, report completion with a structured handoff, and read prior handoffs.\n *\n * The guard logic and the apply functions are plain, exported, and unit-tested.\n * `buildOrchestratorTools` wraps them in the SDK `tool()` shape.\n */\nimport { z } from 'zod';\nimport { analytics } from '@utils/analytics';\nimport {\n TaskStatus,\n type QueueStore,\n type QueuedTask,\n type TaskHandoff,\n} from './queue';\n\nexport interface OrchestratorToolsContext {\n store: QueueStore;\n /** Task types the registry knows about. enqueue_task rejects anything else. */\n validTypes: readonly string[];\n /**\n * The id of the task this tool server is bound to. Each task agent gets its\n * own wizard-tools server, so attribution holds when independent tasks run\n * in parallel. Absent for the seed, which is not a task.\n */\n currentTaskId?: string;\n}\n\nexport interface EnqueueArgs {\n type: string;\n label?: string;\n inputs?: Record<string, unknown>;\n dependsOn?: string[];\n model?: string;\n reason: string;\n}\n\nexport type GuardResult =\n | { ok: true }\n | { ok: false; guard: string; message: string };\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>).sort(\n ([a], [b]) => a.localeCompare(b),\n );\n return `{${entries\n .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)\n .join(',')}}`;\n}\n\nfunction dedupKey(type: string, inputs: Record<string, unknown>): string {\n return `${type}::${stableStringify(inputs)}`;\n}\n\n/**\n * A backstop on total queue size. Tasks can enqueue tasks, so a misbehaving\n * type could grow the queue without bound. Keeping the graph small is the job\n * of good agent and skill design, not this number — it only stops a runaway.\n * The real flow is ~9 tasks, so this sits well clear of it.\n */\nconst MAX_QUEUE_TASKS = 30;\n\n/**\n * Validate an enqueue. Structural checks only — a real type, real dependencies,\n * not a literal duplicate, and not past the runaway backstop. How much runs,\n * and in what shape, is the task graph's business, not a knob's.\n */\nexport function checkEnqueueGuards(\n ctx: OrchestratorToolsContext,\n args: EnqueueArgs,\n): GuardResult {\n const tasks = ctx.store.list();\n\n if (tasks.length >= MAX_QUEUE_TASKS) {\n return {\n ok: false,\n guard: 'queue-full',\n message: `The queue already holds ${tasks.length} tasks (cap ${MAX_QUEUE_TASKS}). Refine the existing tasks rather than adding more.`,\n };\n }\n\n if (!ctx.validTypes.includes(args.type)) {\n return {\n ok: false,\n guard: 'unknown-type',\n message: `Unknown task type \"${\n args.type\n }\". Valid types: ${ctx.validTypes.join(', ')}.`,\n };\n }\n\n for (const dep of args.dependsOn ?? []) {\n if (!ctx.store.get(dep)) {\n return {\n ok: false,\n guard: 'unknown-dep',\n message: `Dependency \"${dep}\" is not a known task id.`,\n };\n }\n }\n\n const key = dedupKey(args.type, args.inputs ?? {});\n if (\n tasks.some(\n (t) =>\n t.status !== TaskStatus.Failed && dedupKey(t.type, t.inputs) === key,\n )\n ) {\n return {\n ok: false,\n guard: 'dedup',\n message: `A \"${args.type}\" task with these inputs already exists.`,\n };\n }\n\n return { ok: true };\n}\n\nexport type EnqueueResult =\n | { ok: true; task: QueuedTask }\n | { ok: false; guard: string; message: string };\n\nexport function applyEnqueue(\n ctx: OrchestratorToolsContext,\n args: EnqueueArgs,\n): EnqueueResult {\n const guard = checkEnqueueGuards(ctx, args);\n if (!guard.ok) return guard;\n\n const task = ctx.store.enqueue({\n type: args.type,\n label: args.label,\n inputs: args.inputs ?? {},\n dependsOn: args.dependsOn ?? [],\n model: args.model,\n enqueuedBy: ctx.currentTaskId ?? 'orchestrator',\n });\n return { ok: true, task };\n}\n\nexport type CompleteResult = { ok: true } | { ok: false; message: string };\n\nexport function applyComplete(\n ctx: OrchestratorToolsContext,\n args: { status: 'done' | 'failed' | 'skipped'; handoff: TaskHandoff },\n): CompleteResult {\n const id = ctx.currentTaskId;\n if (!id) {\n return {\n ok: false,\n message: 'complete_task can only be called by a running task agent.',\n };\n }\n if (args.status === TaskStatus.Failed) {\n ctx.store.fail(\n id,\n { type: 'self-reported', message: args.handoff.forNextAgent },\n args.handoff,\n );\n } else if (args.status === TaskStatus.Skipped) {\n ctx.store.skip(id, args.handoff);\n } else {\n ctx.store.complete(id, args.handoff);\n }\n return { ok: true };\n}\n\nexport function applyReadHandoffs(\n ctx: OrchestratorToolsContext,\n args: { type?: string; taskId?: string },\n): TaskHandoff[] {\n if (args.taskId) {\n const h = ctx.store.readHandoff(args.taskId);\n return h ? [h] : [];\n }\n if (args.type) {\n return ctx.store.readHandoffsByType(args.type);\n }\n // No filter: every handoff of a dependency of the current task.\n const currentId = ctx.currentTaskId;\n const current = currentId ? ctx.store.get(currentId) : undefined;\n if (!current) return [];\n return current.dependsOn\n .map((depId) => ctx.store.readHandoff(depId))\n .filter((h): h is TaskHandoff => h !== null);\n}\n\nconst HANDOFF_SHAPE = {\n goals: z.string().describe('What this task was asked to achieve.'),\n did: z.string().describe('What you actually did.'),\n forNextAgent: z.string().describe('What the next agent should know.'),\n filesTouched: z.array(z.string()).optional(),\n conflict: z\n .string()\n .optional()\n .describe(\n 'A one-line summary of any conflict you could not cleanly resolve (e.g. a dependency or build conflict). Put full detail in your work; this line is surfaced to the user.',\n ),\n};\n\ntype SdkTool = (\n name: string,\n description: string,\n // The SDK accepts a plain object of zod fields as the schema.\n schema: Record<string, z.ZodTypeAny>,\n handler: (args: never) => unknown,\n) => unknown;\n\nfunction textResult(text: string, isError = false) {\n return { isError, content: [{ type: 'text' as const, text }] };\n}\n\n/**\n * Build the orchestrator tools in the SDK `tool()` shape. Called from\n * createWizardToolsServer only when a queue context is present.\n */\nexport function buildOrchestratorTools(\n tool: SdkTool,\n ctx: OrchestratorToolsContext,\n): unknown[] {\n const enqueueTask = tool(\n 'enqueue_task',\n 'Add a task to the orchestrator queue. Use it to seed work and to enqueue follow-up work you discover. Keep tasks small and discrete.',\n {\n type: z\n .string()\n .describe(`The task type. One of: ${ctx.validTypes.join(', ')}.`),\n label: z\n .string()\n .optional()\n .describe(\n 'A short label for the UI — the action in a few words (e.g. \"Add the PostHog SDK\", \"Initialize PostHog\"). Leave out file names, class names, and other specifics.',\n ),\n inputs: z.record(z.unknown()).optional(),\n dependsOn: z\n .array(z.string())\n .optional()\n .describe('Task ids that must be done before this task runs.'),\n model: z.string().optional(),\n reason: z.string().describe('One line on why this task is needed.'),\n },\n ((args: EnqueueArgs) => {\n const res = applyEnqueue(ctx, args);\n if (!res.ok) {\n analytics.wizardCapture('orchestrator guard tripped', {\n guard: res.guard,\n type: args.type,\n });\n return textResult(res.message, true);\n }\n return textResult(JSON.stringify({ id: res.task.id }));\n }) as (args: never) => unknown,\n );\n\n const completeTask = tool(\n 'complete_task',\n \"Report the outcome of your task. Always call this exactly once when you finish, with a structured handoff for the next agent. Use status 'skipped' when the task does not apply to this project and you cannot do it (say why in the handoff) — not 'done'.\",\n {\n status: z.enum(['done', 'failed', 'skipped']),\n handoff: z.object(HANDOFF_SHAPE),\n },\n ((args: {\n status: 'done' | 'failed' | 'skipped';\n handoff: TaskHandoff;\n }) => {\n const res = applyComplete(ctx, args);\n if (!res.ok) return textResult(res.message, true);\n return textResult('ok');\n }) as (args: never) => unknown,\n );\n\n const readHandoffs = tool(\n 'read_handoffs',\n 'Read structured handoffs from earlier tasks. With no argument, returns the handoffs of your dependencies.',\n {\n type: z.string().optional(),\n taskId: z.string().optional(),\n },\n ((args: { type?: string; taskId?: string }) => {\n const handoffs = applyReadHandoffs(ctx, args);\n return textResult(JSON.stringify(handoffs, null, 2));\n }) as (args: never) => unknown,\n );\n\n return [enqueueTask, completeTask, readHandoffs];\n}\n","/**\n * Unified in-process MCP server for the PostHog wizard.\n *\n * Provides tools that run locally (secret values never leave the machine):\n * - check_env_keys: Check which env var keys exist in a .env file\n * - set_env_values: Create/update env vars in a .env file\n * - detect_package_manager: Detect the project's package manager(s)\n * - load_skill_menu / install_skill: Skill installation\n * - audit_seed_checks / audit_add_checks / audit_resolve_checks: Audit ledger ownership\n */\n\nimport path from 'path';\nimport fs from 'fs';\nimport { unzipSync } from 'fflate';\nimport { z } from 'zod';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport { writeJsonAtomic, makeMutex } from '@utils/atomic-ledger';\nimport type { PackageManagerDetector } from './detection/package-manager';\nimport {\n AUDIT_CHECKS_FILE,\n coerceAuditChecks,\n type AuditCheck,\n type AuditStatus,\n} from './programs/audit/types';\nimport { type WizardAskBridge, isFullyCancelled } from './wizard-ask-bridge';\nimport { createSecretVault, type SecretVault } from './secret-vault';\nimport {\n buildOrchestratorTools,\n type OrchestratorToolsContext,\n} from './agent/runner/sequence/orchestrator/queue-tools';\n\n// ---------------------------------------------------------------------------\n// SDK dynamic import (ESM module loaded once, cached)\n// ---------------------------------------------------------------------------\n\nlet _sdkModule: any = null;\nasync function getSDKModule(): Promise<any> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\n// ---------------------------------------------------------------------------\n// Skill types\n// ---------------------------------------------------------------------------\n\nexport type SkillEntry = { id: string; name: string; downloadUrl: string };\n\n/**\n * Entry in the wizard's runtime CLI registry. Mirrors the shape context-mill\n * publishes under `cliEntries` inside `skill-menu.json`. The wizard uses these\n * to register skill-backed subcommands at runtime instead of from a baked\n * build-time snapshot.\n */\nexport type CliEntry = {\n skillId: string;\n role: 'command' | 'skill' | 'internal';\n command?: string;\n parentCommand?: string;\n default?: boolean;\n displayName: string;\n description: string;\n};\n\nexport interface SkillMenu {\n categories: Record<string, SkillEntry[]>;\n /**\n * Skills exposed as CLI commands. Optional because context-mill releases\n * older than the runtime-resolver cutover don't emit this field.\n */\n cliEntries?: CliEntry[];\n}\n\n// ---------------------------------------------------------------------------\n// Standalone skill helpers (usable before the MCP server is created)\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch the skill menu from the skills server.\n * Returns parsed data on success, `null` on failure.\n */\nexport async function fetchSkillMenu(\n skillsBaseUrl: string,\n): Promise<SkillMenu | null> {\n try {\n const menuUrl = `${skillsBaseUrl}/skill-menu.json`;\n logToFile(`fetchSkillMenu: fetching from ${menuUrl}`);\n const resp = await fetch(menuUrl);\n if (resp.ok) {\n const data = (await resp.json()) as SkillMenu;\n logToFile(\n `fetchSkillMenu: loaded (${\n Object.keys(data.categories).length\n } categories)`,\n );\n return data;\n }\n logToFile(`fetchSkillMenu: failed with HTTP ${resp.status}`);\n return null;\n } catch (err: any) {\n logToFile(`fetchSkillMenu: error: ${err.message}`);\n return null;\n }\n}\n\n/** Extract a zip buffer, refusing entries that escape destDir (zip-slip). */\nfunction extractZipArchive(zip: Uint8Array, destDir: string): number {\n const root = path.resolve(destDir);\n let written = 0;\n for (const [entryPath, data] of Object.entries(unzipSync(zip))) {\n const target = path.resolve(root, entryPath);\n if (target !== root && !target.startsWith(root + path.sep)) {\n throw new Error(`zip entry escapes destination: ${entryPath}`);\n }\n if (entryPath.endsWith('/')) {\n fs.mkdirSync(target, { recursive: true });\n continue;\n }\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, data);\n written++;\n }\n return written;\n}\n\n/**\n * Download and extract a skill.\n * By default installs to `<installDir>/.claude/skills/<id>/`.\n * Pass `skillsRoot` to override the base directory (e.g. `.posthog/skills`).\n */\nexport async function downloadSkill(\n skillEntry: SkillEntry,\n installDir: string,\n skillsRoot?: string,\n): Promise<{ success: boolean; error?: string }> {\n const skillDir = skillsRoot\n ? path.join(installDir, skillsRoot, skillEntry.id)\n : path.join(installDir, '.claude', 'skills', skillEntry.id);\n let step: 'download' | 'extract' = 'download';\n\n try {\n fs.mkdirSync(skillDir, { recursive: true });\n const resp = await fetch(skillEntry.downloadUrl, {\n signal: AbortSignal.timeout(30000),\n });\n if (!resp.ok) throw new Error(`download failed with HTTP ${resp.status}`);\n const zip = new Uint8Array(await resp.arrayBuffer());\n step = 'extract';\n const fileCount = extractZipArchive(zip, skillDir);\n fs.writeFileSync(path.join(skillDir, '.posthog-wizard'), '');\n\n logToFile(\n `downloadSkill: installed ${skillEntry.id} from ${skillEntry.downloadUrl} (${fileCount} files)`,\n );\n return { success: true };\n } catch (err: any) {\n logToFile(`downloadSkill: error: ${err.message}`);\n // A skill-less run still reports success — keep the failure visible.\n analytics.wizardCapture('skill install failed', {\n skill_id: skillEntry.id,\n step,\n platform: process.platform,\n error: String(err.message).slice(0, 500),\n });\n return { success: false, error: err.message };\n }\n}\n\n/**\n * Structured result for installSkillById.\n * - `ok`: the skill was fetched and extracted; `path` is where it lives\n * relative to installDir.\n * - `menu-fetch-failed`: couldn't fetch or parse the skill menu.\n * - `skill-not-found`: the menu didn't contain a skill with this id.\n * - `download-failed`: found the skill but download/extract failed;\n * `message` has the underlying error.\n */\nexport type InstallSkillResult =\n | { kind: 'ok'; path: string }\n | { kind: 'menu-fetch-failed' }\n | { kind: 'skill-not-found'; skillId: string }\n | { kind: 'download-failed'; message: string };\n\n/**\n * High-level \"install a skill by ID\" helper. Fetches the skill menu,\n * finds the skill, downloads and extracts it. Programs should use this\n * instead of composing fetchSkillMenu + downloadSkill themselves.\n */\nexport async function installSkillById(\n skillId: string,\n installDir: string,\n skillsBaseUrl: string,\n skillsRoot?: string,\n): Promise<InstallSkillResult> {\n const menu = await fetchSkillMenu(skillsBaseUrl);\n if (!menu) return { kind: 'menu-fetch-failed' };\n\n const skill = Object.values(menu.categories)\n .flat()\n .find((s) => s.id === skillId);\n if (!skill) return { kind: 'skill-not-found', skillId };\n\n const result = await downloadSkill(skill, installDir, skillsRoot);\n if (!result.success) {\n return { kind: 'download-failed', message: result.error ?? 'unknown' };\n }\n\n const relPath = skillsRoot\n ? `${skillsRoot}/${skillId}`\n : `.claude/skills/${skillId}`;\n return { kind: 'ok', path: relPath };\n}\n\n// ---------------------------------------------------------------------------\n// Options for creating the wizard tools server\n// ---------------------------------------------------------------------------\n\nexport interface WizardToolsOptions {\n /** Root directory of the project being analyzed */\n workingDirectory: string;\n\n /** Framework-specific package manager detector */\n detectPackageManager: PackageManagerDetector;\n\n /** Base URL for the skills server (e.g. http://localhost:8765 or GitHub releases URL) */\n skillsBaseUrl: string;\n\n /**\n * Bridge that drives the `wizard_ask` overlay. When omitted, the\n * `wizard_ask` tool is still registered but returns an error explaining\n * the host is non-interactive — keeps the tool surface stable across\n * CI/dev environments.\n */\n askBridge?: WizardAskBridge;\n\n /**\n * Per-run cap on `wizard_ask` invocations. Defaults to {@link DEFAULT_ASK_MAX_QUESTIONS}.\n * The 4th call always returns a \"batch your questions\" error regardless\n * of this cap — see {@link ASK_BATCH_THRESHOLD}.\n */\n askMaxQuestions?: number;\n\n /**\n * Optional secret vault. When provided, tools that handle sensitive\n * values (wizard_ask with `sensitive: true`, set_env_values) route\n * those values through the vault and return opaque refs to the agent\n * instead of raw strings — so the LLM never sees them. When omitted\n * (e.g. in unit tests), a fresh vault is created internally.\n */\n secretVault?: SecretVault;\n\n /**\n * Orchestrator queue context. Present only when the `wizard-orchestrator`\n * flag routes the run to the orchestrator; when set, the orchestrator tools\n * (enqueue_task, complete_task, read_handoffs) are registered. Absent on the\n * linear path.\n */\n orchestrator?: OrchestratorToolsContext;\n}\n\n/** Default per-run cap on wizard_ask calls when no override is provided. */\nexport const DEFAULT_ASK_MAX_QUESTIONS = 10;\n/** The call after this many returns a one-time batch-your-questions nudge. */\nexport const ASK_BATCH_THRESHOLD = 3;\n\nexport type AskCapDecision =\n | { kind: 'ok' }\n | {\n kind: 'capped';\n reason: 'max_questions' | 'adjacency';\n message: string;\n };\n\n/**\n * Pure decision function for the wizard_ask caps. Returns whether the\n * upcoming call should proceed and, if not, the error message to surface\n * to the agent. Extracted so the policy can be unit-tested without\n * spinning up an MCP server.\n *\n * The adjacency nudge fires exactly once per run (the caller records it\n * via `adjacencyNudged`) — flows that legitimately need several\n * sequential, answer-dependent asks then proceed up to `maxQuestions`.\n * Without the flag the rejected call would never advance the counter and\n * every later call would be rejected, making caps above the threshold\n * unreachable.\n */\nexport function evaluateAskCap(\n callCount: number,\n maxQuestions: number,\n adjacencyNudged = false,\n): AskCapDecision {\n if (callCount >= maxQuestions) {\n return {\n kind: 'capped',\n reason: 'max_questions',\n message: `Error: wizard_ask cap reached (${maxQuestions} calls in this run). Proceed with sensible defaults using the answers you already have, or emit [ABORT] requirements-incomplete.`,\n };\n }\n if (!adjacencyNudged && callCount >= ASK_BATCH_THRESHOLD) {\n return {\n kind: 'capped',\n reason: 'adjacency',\n message: `Error: too many wizard_ask calls in a row (${callCount} so far). Batch the remaining questions into a single call — the schema accepts up to 8 questions per invocation. If the remaining questions truly depend on earlier answers, ask again and they will go through.`,\n };\n }\n return { kind: 'ok' };\n}\n\n// ---------------------------------------------------------------------------\n// Env file helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve filePath relative to workingDirectory, rejecting path traversal.\n */\nexport function resolveEnvPath(\n workingDirectory: string,\n filePath: string,\n): string {\n const resolved = path.resolve(workingDirectory, filePath);\n if (\n !resolved.startsWith(workingDirectory + path.sep) &&\n resolved !== workingDirectory\n ) {\n throw new Error(\n `Path traversal rejected: \"${filePath}\" resolves outside working directory`,\n );\n }\n return resolved;\n}\n\n/**\n * Ensure the given env file basename is covered by .gitignore in the working directory.\n * Creates .gitignore if it doesn't exist; appends the entry if missing.\n */\nexport function ensureGitignoreCoverage(\n workingDirectory: string,\n envFileName: string,\n): void {\n const gitignorePath = path.join(workingDirectory, '.gitignore');\n\n if (fs.existsSync(gitignorePath)) {\n const content = fs.readFileSync(gitignorePath, 'utf8');\n // Check if the file (or a glob covering it) is already listed\n if (content.split('\\n').some((line) => line.trim() === envFileName)) {\n return;\n }\n const newContent = content.endsWith('\\n')\n ? `${content}${envFileName}\\n`\n : `${content}\\n${envFileName}\\n`;\n fs.writeFileSync(gitignorePath, newContent, 'utf8');\n } else {\n fs.writeFileSync(gitignorePath, `${envFileName}\\n`, 'utf8');\n }\n}\n\n/**\n * Parse a .env file's content and return the set of defined key names.\n */\nexport function parseEnvKeys(content: string): Set<string> {\n const keys = new Set<string>();\n for (const line of content.split('\\n')) {\n const match = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=/);\n if (match) {\n keys.add(match[1]);\n }\n }\n return keys;\n}\n\n/**\n * Merge key-value pairs into existing .env content.\n * Updates existing keys in-place, appends new keys at the end.\n */\nexport function mergeEnvValues(\n content: string,\n values: Record<string, string>,\n): string {\n let result = content;\n const updatedKeys = new Set<string>();\n\n for (const [key, value] of Object.entries(values)) {\n const regex = new RegExp(`^(\\\\s*${key}\\\\s*=).*$`, 'm');\n if (regex.test(result)) {\n result = result.replace(regex, `$1${value}`);\n updatedKeys.add(key);\n }\n }\n\n const newKeys = Object.entries(values).filter(\n ([key]) => !updatedKeys.has(key),\n );\n if (newKeys.length > 0) {\n if (result.length > 0 && !result.endsWith('\\n')) {\n result += '\\n';\n }\n for (const [key, value] of newKeys) {\n result += `${key}=${value}\\n`;\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Audit ledger helpers\n// ---------------------------------------------------------------------------\n\nconst AUDIT_STATUSES: readonly AuditStatus[] = [\n 'pending',\n 'pass',\n 'error',\n 'warning',\n 'suggestion',\n];\n\nconst auditCheckSchema = z.object({\n id: z.string().min(1),\n area: z.string().min(1),\n label: z.string().min(1),\n status: z.enum(AUDIT_STATUSES as [AuditStatus, ...AuditStatus[]]),\n file: z.string().optional(),\n details: z.string().optional(),\n});\n\nconst auditUpdateSchema = z.object({\n id: z.string().min(1),\n status: z.enum(AUDIT_STATUSES as [AuditStatus, ...AuditStatus[]]),\n file: z.string().optional(),\n details: z.string().optional(),\n});\n\n/** Atomically write the audit ledger. Thin typed wrapper over writeJsonAtomic. */\nfunction writeLedgerAtomic(targetPath: string, checks: AuditCheck[]): void {\n writeJsonAtomic(targetPath, checks);\n}\n\n/**\n * Apply a batch of patches to the ledger by id. Returns the new array and the\n * list of update ids that didn't match any existing check.\n */\nfunction applyAuditUpdates(\n current: AuditCheck[],\n updates: Array<{\n id: string;\n status: AuditStatus;\n file?: string;\n details?: string;\n }>,\n): { next: AuditCheck[]; unknown: string[] } {\n const byId = new Map(current.map((c) => [c.id, c]));\n const unknown: string[] = [];\n\n for (const u of updates) {\n const existing = byId.get(u.id);\n if (!existing) {\n unknown.push(u.id);\n continue;\n }\n byId.set(u.id, {\n ...existing,\n status: u.status,\n ...(u.file !== undefined ? { file: u.file } : {}),\n ...(u.details !== undefined ? { details: u.details } : {}),\n });\n }\n\n return {\n next: current.map((c) => byId.get(c.id) ?? c),\n unknown,\n };\n}\n\n/**\n * Append new checks to a seeded ledger. Duplicate ids are reported without\n * mutating the current ledger, including duplicates inside the additions.\n */\nfunction applyAuditAdditions(\n current: AuditCheck[],\n additions: AuditCheck[],\n): { next: AuditCheck[]; duplicates: string[] } {\n const existingIds = new Set(current.map((c) => c.id));\n const additionIds = new Set<string>();\n const duplicates: string[] = [];\n\n for (const check of additions) {\n if (existingIds.has(check.id) || additionIds.has(check.id)) {\n duplicates.push(check.id);\n continue;\n }\n additionIds.add(check.id);\n }\n\n if (duplicates.length > 0) {\n return { next: current, duplicates };\n }\n\n return { next: [...current, ...additions], duplicates: [] };\n}\n\nfunction readLedger(targetPath: string): AuditCheck[] {\n if (!fs.existsSync(targetPath)) return [];\n try {\n const parsed = JSON.parse(fs.readFileSync(targetPath, 'utf8'));\n return coerceAuditChecks(parsed);\n } catch {\n return [];\n }\n}\n\ntype AppendAuditChecksResult =\n | { ok: true; added: number }\n | { ok: false; reason: 'missing-ledger' }\n | { ok: false; reason: 'duplicate-ids'; ids: string[] };\n\nfunction appendAuditChecksToLedger(\n targetPath: string,\n additions: AuditCheck[],\n): AppendAuditChecksResult {\n if (!fs.existsSync(targetPath)) {\n return { ok: false, reason: 'missing-ledger' };\n }\n\n const current = readLedger(targetPath);\n const { next, duplicates } = applyAuditAdditions(current, additions);\n if (duplicates.length > 0) {\n return { ok: false, reason: 'duplicate-ids', ids: duplicates };\n }\n\n writeLedgerAtomic(targetPath, next);\n return { ok: true, added: additions.length };\n}\n\n// ---------------------------------------------------------------------------\n// Server factory\n// ---------------------------------------------------------------------------\n\nconst SERVER_NAME = 'wizard-tools';\n\n/**\n * Create the unified in-process MCP server with all wizard tools.\n * Must be called asynchronously because the SDK is an ESM module loaded via dynamic import.\n */\nexport async function createWizardToolsServer(options: WizardToolsOptions) {\n const {\n workingDirectory,\n detectPackageManager,\n skillsBaseUrl,\n askBridge,\n askMaxQuestions = DEFAULT_ASK_MAX_QUESTIONS,\n secretVault = createSecretVault(),\n orchestrator,\n } = options;\n const sdk = await getSDKModule();\n const { tool, createSdkMcpServer } = sdk;\n\n // Per-server counter for wizard_ask call accounting (adjacency + total cap).\n let askCallCount = 0;\n // The adjacency nudge fires once per run; after that only the total cap applies.\n let askAdjacencyNudged = false;\n\n // Pre-fetch skill menu so category names are available in the tool schema\n let cachedSkillMenu: Record<string, SkillEntry[]> = {};\n let categoryNames: [string, ...string[]] = ['integration'];\n\n const menu = await fetchSkillMenu(skillsBaseUrl);\n if (menu) {\n cachedSkillMenu = menu.categories;\n }\n\n const keys = Object.keys(cachedSkillMenu);\n if (keys.length > 0) {\n categoryNames = keys as [string, ...string[]];\n }\n\n // -- check_env_keys -------------------------------------------------------\n\n const checkEnvKeys = tool(\n 'check_env_keys',\n 'Check which environment variable keys are present or missing in a .env file. Never reveals values.',\n {\n filePath: z\n .string()\n .describe('Path to the .env file, relative to the project root'),\n keys: z\n .array(z.string())\n .describe('Environment variable key names to check'),\n },\n (args: { filePath: string; keys: string[] }) => {\n const resolved = resolveEnvPath(workingDirectory, args.filePath);\n logToFile(`check_env_keys: ${resolved}, keys: ${args.keys.join(', ')}`);\n\n const existingKeys: Set<string> = fs.existsSync(resolved)\n ? parseEnvKeys(fs.readFileSync(resolved, 'utf8'))\n : new Set<string>();\n\n const results: Record<string, 'present' | 'missing'> = {};\n for (const key of args.keys) {\n results[key] = existingKeys.has(key) ? 'present' : 'missing';\n }\n\n return {\n content: [\n { type: 'text' as const, text: JSON.stringify(results, null, 2) },\n ],\n };\n },\n );\n\n // -- set_env_values -------------------------------------------------------\n\n const setEnvValues = tool(\n 'set_env_values',\n 'Create or update environment variable keys in a .env file. Creates the file if it does not exist. Ensures .gitignore coverage. Each value can be either a literal string or a secret reference of the form `{ \"secretRef\": \"secret:...\" }` returned by another tool (e.g. wizard_ask). Secret references are resolved locally — the actual value is written to the file but never returned to the agent.',\n {\n filePath: z\n .string()\n .describe('Path to the .env file, relative to the project root'),\n values: z\n .record(\n z.string(),\n z.union([z.string(), z.object({ secretRef: z.string() })]),\n )\n .describe(\n 'Key → (literal string OR { secretRef } pointing to a vaulted secret)',\n ),\n },\n (args: {\n filePath: string;\n values: Record<string, string | { secretRef: string }>;\n }) => {\n // Block the wrong key name — the correct key is NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN or similar\n const forbidden = Object.keys(args.values).find(\n (k) => k.toUpperCase() === 'POSTHOG_KEY',\n );\n if (forbidden) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: \"${forbidden}\" is not a valid PostHog env var name. Use the project-specific key name from your framework's integration guide (e.g. NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN).`,\n },\n ],\n isError: true,\n };\n }\n\n // Resolve any secret refs from the vault before writing.\n const resolvedValues: Record<string, string> = {};\n const resolvedRefKeys: string[] = [];\n for (const [key, val] of Object.entries(args.values)) {\n if (typeof val === 'string') {\n resolvedValues[key] = val;\n } else {\n const secret = secretVault.get(val.secretRef);\n if (secret === undefined) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: secret reference \"${val.secretRef}\" for key \"${key}\" is not known to the vault. The ref may have expired, been minted in a different run, or been mistyped.`,\n },\n ],\n isError: true,\n };\n }\n resolvedValues[key] = secret;\n resolvedRefKeys.push(key);\n }\n }\n\n const resolved = resolveEnvPath(workingDirectory, args.filePath);\n logToFile(\n `set_env_values: ${resolved}, keys: ${Object.keys(resolvedValues).join(\n ', ',\n )}${\n resolvedRefKeys.length > 0\n ? ` (secret refs: ${resolvedRefKeys.join(', ')})`\n : ''\n }`,\n );\n\n const existing = fs.existsSync(resolved)\n ? fs.readFileSync(resolved, 'utf8')\n : '';\n const content = mergeEnvValues(existing, resolvedValues);\n\n // Ensure parent directory exists\n const dir = path.dirname(resolved);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n fs.writeFileSync(resolved, content, 'utf8');\n\n // Ensure .gitignore coverage for this env file\n const envFileName = path.basename(resolved);\n ensureGitignoreCoverage(workingDirectory, envFileName);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `Updated ${Object.keys(args.values).length} key(s) in ${\n args.filePath\n }`,\n },\n ],\n };\n },\n );\n\n // -- detect_package_manager -----------------------------------------------\n\n const detectPM = tool(\n 'detect_package_manager',\n 'Detect which package manager(s) the project uses. Returns the name, install command, and run command for each detected package manager. Call this before running any install commands.',\n {},\n async () => {\n logToFile(`detect_package_manager: scanning ${workingDirectory}`);\n\n const result = await detectPackageManager(workingDirectory);\n\n logToFile(\n `detect_package_manager: detected ${result.detected.length} package manager(s)`,\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n },\n );\n\n // -- load_skill_menu ------------------------------------------------------\n\n const loadSkillMenu = tool(\n 'load_skill_menu',\n 'Load available PostHog skills for a category. Returns skill IDs and names. Call this first, then use install_skill with the chosen ID.',\n {\n category: z.enum(categoryNames).describe('Skill category'),\n },\n (args: { category: string }) => {\n const skills = cachedSkillMenu[args.category];\n if (!skills || skills.length === 0) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `No skills found for category \"${args.category}\".`,\n },\n ],\n isError: true,\n };\n }\n\n const menuText = skills.map((s) => `- ${s.id}: ${s.name}`).join('\\n');\n\n logToFile(\n `load_skill_menu: returning ${skills.length} skills for \"${args.category}\"`,\n );\n\n return {\n content: [{ type: 'text' as const, text: menuText }],\n };\n },\n );\n\n // -- install_skill --------------------------------------------------------\n\n const installSkill = tool(\n 'install_skill',\n 'Download and install a PostHog skill by ID. Call load_skill_menu first to see available skills. Extracts the skill to .claude/skills/<skillId>/.',\n {\n skillId: z\n .string()\n .describe(\n 'Skill ID from the skill menu (e.g., \"integration-nextjs-app-router\")',\n ),\n },\n async (args: { skillId: string }) => {\n if (!/^[a-z0-9][a-z0-9_-]*$/.test(args.skillId)) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Error: skillId must be lowercase alphanumeric with hyphens.',\n },\n ],\n isError: true,\n };\n }\n\n // Look up download URL from cached menu\n const allSkills: SkillEntry[] = Object.values(cachedSkillMenu).flat();\n const skill = allSkills.find((s) => s.id === args.skillId);\n if (!skill) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: skill \"${args.skillId}\" not found. Use load_skill_menu to see available skills.`,\n },\n ],\n isError: true,\n };\n }\n\n const result = await downloadSkill(skill, workingDirectory);\n if (result.success) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Skill installed to .claude/skills/${args.skillId}/`,\n },\n ],\n };\n } else {\n // The agent only sees a tool-result string — report the failure too.\n analytics.captureException(\n new Error('Skill install failed: download-failed'),\n {\n source: 'install_skill_tool',\n skill_id: args.skillId,\n error_detail: String(result.error).slice(0, 500),\n platform: process.platform,\n },\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error installing skill: ${result.error}`,\n },\n ],\n isError: true,\n };\n }\n },\n );\n\n // -- audit_seed_checks ----------------------------------------------------\n\n const auditLedgerPath = path.join(workingDirectory, AUDIT_CHECKS_FILE);\n const auditMutex = makeMutex();\n\n const auditSeedChecks = tool(\n 'audit_seed_checks',\n 'Seed the audit ledger at .posthog-audit-checks.json with the full set of pending checks. Call this once at the start of the audit. Atomically replaces any existing ledger.',\n {\n checks: z\n .array(auditCheckSchema)\n .describe('Full pending checklist to write to the ledger'),\n },\n async (args: { checks: AuditCheck[] }) => {\n return auditMutex(() => {\n writeLedgerAtomic(auditLedgerPath, args.checks);\n logToFile(`audit_seed_checks: wrote ${args.checks.length} entries`);\n return {\n content: [\n {\n type: 'text' as const,\n text: `Seeded ${args.checks.length} audit checks.`,\n },\n ],\n };\n });\n },\n );\n\n // -- audit_add_checks -----------------------------------------------------\n\n const auditAddChecks = tool(\n 'audit_add_checks',\n 'Append one or more pending checks to the existing audit ledger at .posthog-audit-checks.json. Call audit_seed_checks first. Atomically rejects duplicate ids without changing the ledger.',\n {\n checks: z\n .array(auditCheckSchema)\n .min(1)\n .describe('Additional checks to append to the existing ledger'),\n },\n async (args: { checks: AuditCheck[] }) => {\n return auditMutex(() => {\n const result = appendAuditChecksToLedger(auditLedgerPath, args.checks);\n\n if (!result.ok) {\n if (result.reason === 'missing-ledger') {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Error: audit ledger does not exist. Run audit_seed_checks first.',\n },\n ],\n isError: true,\n };\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: duplicate check id(s): ${result.ids.join(\n ', ',\n )}. Check ids must be unique.`,\n },\n ],\n isError: true,\n };\n }\n\n logToFile(`audit_add_checks: added ${result.added} entries`);\n return {\n content: [\n {\n type: 'text' as const,\n text: `Added ${result.added} audit check(s).`,\n },\n ],\n };\n });\n },\n );\n\n // -- audit_resolve_checks -------------------------------------------------\n\n const auditResolveChecks = tool(\n 'audit_resolve_checks',\n \"Resolve one or more audit checks by id. Patches each entry's status (and optional file/details) and writes the ledger back atomically. Concurrent calls serialize.\",\n {\n updates: z\n .array(auditUpdateSchema)\n .min(1)\n .describe('Patches to apply, keyed by check id'),\n },\n async (args: {\n updates: Array<{\n id: string;\n status: AuditStatus;\n file?: string;\n details?: string;\n }>;\n }) => {\n return auditMutex(() => {\n const current = readLedger(auditLedgerPath);\n const { next, unknown } = applyAuditUpdates(current, args.updates);\n\n if (unknown.length > 0) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: unknown check id(s): ${unknown.join(\n ', ',\n )}. Run audit_seed_checks first or check the id.`,\n },\n ],\n isError: true,\n };\n }\n\n writeLedgerAtomic(auditLedgerPath, next);\n logToFile(\n `audit_resolve_checks: applied ${args.updates.length} update(s)`,\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `Resolved ${args.updates.length} check(s).`,\n },\n ],\n };\n });\n },\n );\n\n // -- wizard_ask -----------------------------------------------------------\n\n const askQuestionSchema = z.object({\n id: z\n .string()\n .min(1)\n .describe('Stable key for the answer in the response map'),\n prompt: z.string().min(1).describe('Question text shown to the user'),\n kind: z\n .enum(['single', 'multi', 'text'])\n .describe(\n \"'single' = pick one option, 'multi' = pick any, 'text' = free-form single-line answer\",\n ),\n options: z\n .array(\n z.object({\n label: z.string(),\n value: z.string(),\n description: z\n .string()\n .optional()\n .describe(\n 'Optional secondary line shown dimmed and wrapped beneath the ' +\n 'label (multi-select only). Use when a choice needs more than a ' +\n 'title — e.g. what a custom scout watches and what makes it speak up.',\n ),\n }),\n )\n .optional()\n .describe('Required for kind=single|multi; ignored for kind=text'),\n required: z.boolean().optional().describe('Defaults to true'),\n sensitive: z\n .boolean()\n .optional()\n .describe(\n \"Only valid for kind='text'. When true, the user's answer is stored in the wizard's secret vault and returned to you as { secretRef: 'secret:...' } instead of the raw string. Use for API keys, tokens, and any other secret the user types in. The secretRef is only resolved by wizard-tools that accept it (e.g. set_env_values) — it is NOT resolved when passed to other MCP tools (e.g. PostHog data-warehouse tools), which will reject it. For a secret that must reach another tool, write it to the env with set_env_values first, or use that tool's own credential-reference flow.\",\n ),\n });\n\n const wizardAsk = tool(\n 'wizard_ask',\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 a ' +\n 'time; sequential calls are fine when later questions genuinely depend on earlier ' +\n 'answers. A fully cancelled or timed-out response does NOT count against the per-run ' +\n 'cap — treat it as \"the user declined\" and fall back gracefully (e.g. hand over a ' +\n 'deep link) without worrying about a wasted call.',\n {\n questions: z.array(askQuestionSchema).min(1).max(8),\n },\n async (args: {\n questions: Array<{\n id: string;\n prompt: string;\n kind: 'single' | 'multi' | 'text';\n options?: { label: string; value: string }[];\n required?: boolean;\n sensitive?: boolean;\n }>;\n }) => {\n if (!askBridge) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Error: wizard_ask is not available in this environment (CI / non-interactive). Proceed with sensible defaults or emit [ABORT] requirements-incomplete.',\n },\n ],\n isError: true,\n };\n }\n\n const capDecision = evaluateAskCap(\n askCallCount,\n askMaxQuestions,\n askAdjacencyNudged,\n );\n if (capDecision.kind === 'capped') {\n if (capDecision.reason === 'adjacency') {\n askAdjacencyNudged = true;\n }\n analytics.wizardCapture('wizard_ask capped', {\n reason: capDecision.reason,\n call_count: askCallCount,\n max_questions: askMaxQuestions,\n });\n return {\n content: [{ type: 'text' as const, text: capDecision.message }],\n isError: true,\n };\n }\n\n // Validate that single/multi questions include options. The schema\n // alone can't enforce a per-kind requirement.\n for (const q of args.questions) {\n if (\n (q.kind === 'single' || q.kind === 'multi') &&\n (!q.options || q.options.length === 0)\n ) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: question \"${q.id}\" has kind=\"${q.kind}\" but no options. Provide at least one { label, value } option, or change kind to \"text\".`,\n },\n ],\n isError: true,\n };\n }\n if (q.sensitive && q.kind !== 'text') {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: question \"${q.id}\" sets sensitive=true but kind=\"${q.kind}\". Only kind=\"text\" answers can be vaulted as secrets.`,\n },\n ],\n isError: true,\n };\n }\n }\n\n const ids = new Set<string>();\n for (const q of args.questions) {\n if (ids.has(q.id)) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: duplicate question id \"${q.id}\". Each question must have a unique id.`,\n },\n ],\n isError: true,\n };\n }\n ids.add(q.id);\n }\n\n askCallCount += 1;\n\n try {\n const answers = await askBridge.request({ questions: args.questions });\n\n // A fully cancelled/timed-out ask (the user dismissed the overlay or let\n // it time out) shouldn't burn the per-run cap. Otherwise one cancellation\n // exhausts the budget for every remaining source and forces a deep-link\n // fallback even when the user was willing to answer. Refund the slot we\n // optimistically took so cancellation is free.\n if (isFullyCancelled(answers)) {\n askCallCount -= 1;\n }\n\n // For any question marked sensitive, move the raw answer into the\n // vault and replace it with an opaque ref before returning to the\n // agent — so the secret never enters the LLM conversation.\n const sensitiveById = new Map(\n args.questions\n .filter((q) => q.sensitive)\n .map((q) => [q.id, q.prompt]),\n );\n const sanitised: Record<\n string,\n string | string[] | { secretRef: string }\n > = {};\n for (const [id, answer] of Object.entries(answers)) {\n const label = sensitiveById.get(id);\n if (\n label !== undefined &&\n typeof answer === 'string' &&\n answer !== '__cancelled__'\n ) {\n const ref = secretVault.put(answer, {\n label,\n source: 'wizard_ask',\n });\n sanitised[id] = { secretRef: ref };\n logToFile(`wizard_ask: vaulted answer for \"${id}\" as ${ref}`);\n } else {\n sanitised[id] = answer;\n }\n }\n\n logToFile(\n `wizard_ask: resolved ${Object.keys(answers).length} answer(s) for ${\n args.questions.length\n } question(s)`,\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ answers: sanitised }, null, 2),\n },\n ],\n };\n } catch (err: any) {\n logToFile(`wizard_ask: error: ${err?.message ?? err}`);\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: wizard_ask failed: ${err?.message ?? String(err)}`,\n },\n ],\n isError: true,\n };\n }\n },\n );\n\n // -- Assemble server ------------------------------------------------------\n\n const orchestratorTools = orchestrator\n ? buildOrchestratorTools(tool, orchestrator)\n : [];\n\n return createSdkMcpServer({\n name: SERVER_NAME,\n version: '1.0.0',\n tools: [\n checkEnvKeys,\n setEnvValues,\n detectPM,\n loadSkillMenu,\n installSkill,\n auditSeedChecks,\n auditAddChecks,\n auditResolveChecks,\n wizardAsk,\n ...orchestratorTools,\n ],\n });\n}\n\n/** Tool names exposed by the wizard-tools server, keyed for selective use. */\n// SDK expects MCP tool names in allowedTools/disallowedTools to be the\n// fully-qualified `mcp__<server>__<tool>` form (sdk.d.ts: \"Fully-qualified\n// MCP tool name, e.g. mcp__server__tool_name.\"). The colon form silently\n// fails to match, which made every program's `disallowedTools` entry a no-op.\nexport const WIZARD_TOOL_NAMES = {\n checkEnvKeys: `mcp__${SERVER_NAME}__check_env_keys`,\n setEnvValues: `mcp__${SERVER_NAME}__set_env_values`,\n detectPackageManager: `mcp__${SERVER_NAME}__detect_package_manager`,\n loadSkillMenu: `mcp__${SERVER_NAME}__load_skill_menu`,\n installSkill: `mcp__${SERVER_NAME}__install_skill`,\n auditSeedChecks: `mcp__${SERVER_NAME}__audit_seed_checks`,\n auditAddChecks: `mcp__${SERVER_NAME}__audit_add_checks`,\n auditResolveChecks: `mcp__${SERVER_NAME}__audit_resolve_checks`,\n wizardAsk: `mcp__${SERVER_NAME}__wizard_ask`,\n enqueueTask: `mcp__${SERVER_NAME}__enqueue_task`,\n completeTask: `mcp__${SERVER_NAME}__complete_task`,\n readHandoffs: `mcp__${SERVER_NAME}__read_handoffs`,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Test-only exports\n// ---------------------------------------------------------------------------\n\nexport const __test = {\n extractZipArchive,\n writeLedgerAtomic,\n readLedger,\n applyAuditAdditions,\n appendAuditChecksToLedger,\n applyAuditUpdates,\n makeMutex,\n AUDIT_CHECKS_FILE,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAWA,SAAgB,gBAAgB,YAAoB,MAAqB;CACvE,MAAM,UAAU,GAAG,WAAW;AAC9B,MAAG,cAAc,SAAS,KAAK,UAAU,MAAM,MAAM,EAAE,EAAE,OAAO;AAChE,MAAG,WAAW,SAAS,WAAW;;;;;;AAOpC,SAAgB,YAAY;CAC1B,IAAI,QAA0B,QAAQ,SAAS;AAC/C,QAAO,eAAe,IAAO,IAAsC;EACjE,MAAM,OAAO,MAAM,WAAW,IAAI,CAAC;AACnC,UAAQ,KAAK,YAAY,KAAA,EAAU;AACnC,SAAO;;;;;;ACFX,MAAa,uBAAgE;CAC3E,SAAS;EAAE,OAAO;EAAK,OAAO;EAAQ;CACtC,MAAM;EAAE,OAAO;EAAK,OAAO;E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AC,OAAO,iBAClD,KAAK,UAAU,OAChB,cACF;AACD,YAAO,EACL,SAAS,CACP;MACE,MAAM;MACN,MAAM,KAAK,UAAU,EAAE,SAAS,WAAW,EAAE,MAAM,EAAE;MACtD,CACF,EACF;aACM,KAAU;AACjB,eAAU,sBAAsB,KAAK,WAAW,MAAM;AACtD,YAAO;MACL,SAAS,CACP;OACE,MAAM;OACN,MAAM,6BAA6B,KAAK,WAAW,OAAO,IAAI;OAC/D,CACF;MACD,SAAS;MACV;;KAGN;GAqBG,GAjBsB,eACtB,uBAAuB,MAAM,aAAa,GAC1C,EAAE;GAgBH;EACF,CAAC;;;AAQJ,MAAa,oBAAoB;CAC/B,cAAc,QAAQ,YAAY;CAClC,cAAc,QAAQ,YAAY;CAClC,sBAAsB,QAAQ,YAAY;CAC1C,eAAe,QAAQ,YAAY;CACnC,cAAc,QAAQ,YAAY;CAClC,iBAAiB,QAAQ,YAAY;CACrC,gBAAgB,QAAQ,YAAY;CACpC,oBAAoB,QAAQ,YAAY;CACxC,WAAW,QAAQ,YAAY;CAC/B,aAAa,QAAQ,YAAY;CACjC,cAAc,QAAQ,YAAY;CAClC,cAAc,QAAQ,YAAY;CACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@posthog/wizard",
|
|
3
|
-
"version": "2.38.
|
|
3
|
+
"version": "2.38.2",
|
|
4
4
|
"homepage": "https://github.com/PostHog/wizard",
|
|
5
5
|
"repository": "https://github.com/PostHog/wizard",
|
|
6
6
|
"description": "The PostHog wizard helps you to configure your project",
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"@posthog/warlock": "0.2.2",
|
|
41
41
|
"axios": "1.7.4",
|
|
42
42
|
"fast-glob": "^3.3.3",
|
|
43
|
+
"fflate": "^0.8.3",
|
|
43
44
|
"glob": "9.3.5",
|
|
44
45
|
"ink": "^6.8.0",
|
|
45
46
|
"inquirer": "^6.2.0",
|