@posthog/wizard 2.66.0 → 2.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/{add-mcp-server-to-clients-DWDEuDUR.js → add-mcp-server-to-clients-y0swAr9I.js} +25 -25
  2. package/dist/{add-mcp-server-to-clients-DWDEuDUR.js.map → add-mcp-server-to-clients-y0swAr9I.js.map} +1 -1
  3. package/dist/{agent-interface-D3MNaDp3.js → agent-interface-CaEptZuu.js} +404 -73
  4. package/dist/agent-interface-CaEptZuu.js.map +1 -0
  5. package/dist/{agent-prompt-loader-D8Bajo-L.js → agent-prompt-loader-DZHc9tIG.js} +5 -5
  6. package/dist/{agent-prompt-loader-D8Bajo-L.js.map → agent-prompt-loader-DZHc9tIG.js.map} +1 -1
  7. package/dist/{agent-runner-DEeMqJxy.js → agent-runner-Do5kyhPo.js} +85 -39
  8. package/dist/agent-runner-Do5kyhPo.js.map +1 -0
  9. package/dist/analytics-BNCWoTKa.js +2 -0
  10. package/dist/{analytics-D8JNuPAT.js → analytics-tF06lcmE.js} +2 -2
  11. package/dist/{analytics-D8JNuPAT.js.map → analytics-tF06lcmE.js.map} +1 -1
  12. package/dist/{api-CemGgyBv.js → api-D7-8R4xx.js} +3 -3
  13. package/dist/{api-CemGgyBv.js.map → api-D7-8R4xx.js.map} +1 -1
  14. package/dist/bin.js +200 -85
  15. package/dist/bin.js.map +1 -1
  16. package/dist/{bounded-fs-C6OjqZst.js → bounded-fs-BwuqKpBH.js} +3 -3
  17. package/dist/{bounded-fs-C6OjqZst.js.map → bounded-fs-BwuqKpBH.js.map} +1 -1
  18. package/dist/{ci-install-DIB2n4Ju.js → ci-install-CrqqhXAw.js} +18 -9
  19. package/dist/ci-install-CrqqhXAw.js.map +1 -0
  20. package/dist/{debug-H-GTKvvU.js → debug-CWn7PsPd.js} +1 -1
  21. package/dist/{debug-BKqv-yfT.js → debug-aA5dm2MR.js} +4 -4
  22. package/dist/debug-aA5dm2MR.js.map +1 -0
  23. package/dist/{defaults-BHhXrX9F.js → defaults-DI642M3n.js} +1 -1
  24. package/dist/{defaults-BHhXrX9F.js.map → defaults-DI642M3n.js.map} +1 -1
  25. package/dist/{env-api-key-CzHDwfV2.js → env-api-key-CwkRyrgi.js} +2 -2
  26. package/dist/{env-api-key-CzHDwfV2.js.map → env-api-key-CwkRyrgi.js.map} +1 -1
  27. package/dist/environment-BGUJxuvj.js +44 -0
  28. package/dist/environment-BGUJxuvj.js.map +1 -0
  29. package/dist/errors-BHervYGs.js +156 -0
  30. package/dist/errors-BHervYGs.js.map +1 -0
  31. package/dist/{file-watcher-Cr-4tA-e.js → file-watcher-Cn7tD95m.js} +2 -2
  32. package/dist/{file-watcher-Cr-4tA-e.js.map → file-watcher-Cn7tD95m.js.map} +1 -1
  33. package/dist/{headless-ui-DT3Db1bk.js → headless-ui-DtIYZNVv.js} +2 -2
  34. package/dist/{headless-ui-DT3Db1bk.js.map → headless-ui-DtIYZNVv.js.map} +1 -1
  35. package/dist/{interactive-D3LdFxZG.js → interactive-BRB6w6KG.js} +2 -2
  36. package/dist/{interactive-D3LdFxZG.js.map → interactive-BRB6w6KG.js.map} +1 -1
  37. package/dist/{local-dev-BN6NKQ0B.js → local-dev-DPZiIPCK.js} +1 -1
  38. package/dist/{local-dev-BN6NKQ0B.js.map → local-dev-DPZiIPCK.js.map} +1 -1
  39. package/dist/{mcp-BjckYQmP.js → mcp-BXdSTZe6.js} +2 -2
  40. package/dist/{mcp-BjckYQmP.js.map → mcp-BXdSTZe6.js.map} +1 -1
  41. package/dist/{mcp-prompt-streaming--sRErHKv.js → mcp-prompt-streaming-DhOT15Jj.js} +13 -12
  42. package/dist/mcp-prompt-streaming-DhOT15Jj.js.map +1 -0
  43. package/dist/{non-interactive-CNoYoEZp.js → non-interactive-ezilF3PY.js} +7 -2
  44. package/dist/non-interactive-ezilF3PY.js.map +1 -0
  45. package/dist/{orchestrator-tools-8bGyDDhn.js → orchestrator-tools-D82843t_.js} +3 -3
  46. package/dist/{orchestrator-tools-8bGyDDhn.js.map → orchestrator-tools-D82843t_.js.map} +1 -1
  47. package/dist/{package-json-D0DCWpe5.js → package-json-GEU2VZlS.js} +1 -1
  48. package/dist/{package-json-D0DCWpe5.js.map → package-json-GEU2VZlS.js.map} +1 -1
  49. package/dist/{package-manager-BQDHm7ER.js → package-manager-BPoVLj7W.js} +4 -4
  50. package/dist/package-manager-BPoVLj7W.js.map +1 -0
  51. package/dist/{pi-W-4RUPFY.js → pi-CKyt4bcu.js} +17 -13
  52. package/dist/pi-CKyt4bcu.js.map +1 -0
  53. package/dist/{playground-uHHgZChe.js → playground-Dnyb4jLu.js} +7 -7
  54. package/dist/{playground-uHHgZChe.js.map → playground-Dnyb4jLu.js.map} +1 -1
  55. package/dist/{posthog-ChzdlmCs.js → posthog-BHyJiU05.js} +2 -2
  56. package/dist/{posthog-ChzdlmCs.js.map → posthog-BHyJiU05.js.map} +1 -1
  57. package/dist/{posthog-integration-LxEBGkoe.js → posthog-integration-DJX4qTDQ.js} +22 -17
  58. package/dist/posthog-integration-DJX4qTDQ.js.map +1 -0
  59. package/dist/{provisioning-BHTl91OZ.js → provisioning-DEEt9xl4.js} +3 -3
  60. package/dist/{provisioning-BHTl91OZ.js.map → provisioning-DEEt9xl4.js.map} +1 -1
  61. package/dist/{queue-tools-DABh1Ssc.js → queue-tools-i_TmeI02.js} +3 -3
  62. package/dist/{queue-tools-DABh1Ssc.js.map → queue-tools-i_TmeI02.js.map} +1 -1
  63. package/dist/{registry-CxNpCNAj.js → registry-CbXqxcX0.js} +81 -81
  64. package/dist/{registry-CxNpCNAj.js.map → registry-CbXqxcX0.js.map} +1 -1
  65. package/dist/{security-B4jU_-7q.js → security-DZ1rkONB.js} +21 -9
  66. package/dist/security-DZ1rkONB.js.map +1 -0
  67. package/dist/{setup-utils-aWZEdfwh.js → setup-utils-BLKhAx6g.js} +13 -13
  68. package/dist/{setup-utils-aWZEdfwh.js.map → setup-utils-BLKhAx6g.js.map} +1 -1
  69. package/dist/{start-tui-BQH4mQIZ.js → start-tui-D1MqJVT1.js} +33 -23
  70. package/dist/start-tui-D1MqJVT1.js.map +1 -0
  71. package/dist/{steps-5HAqjUvn.js → steps-Dsw-zBET.js} +7 -7
  72. package/dist/{steps-5HAqjUvn.js.map → steps-Dsw-zBET.js.map} +1 -1
  73. package/dist/{store-P_7zUfbj.js → store-OGBMWp3H.js} +5 -5
  74. package/dist/{store-P_7zUfbj.js.map → store-OGBMWp3H.js.map} +1 -1
  75. package/dist/{subagent-uGPDXPfS.js → subagent-DrnKYgvu.js} +2 -2
  76. package/dist/{subagent-uGPDXPfS.js.map → subagent-DrnKYgvu.js.map} +1 -1
  77. package/dist/{task-oh8OAnvR.js → task-DyvLyDsO.js} +18 -14
  78. package/dist/task-DyvLyDsO.js.map +1 -0
  79. package/dist/{task-stream-jUARpyB5.js → task-stream-CLXzeuPO.js} +16 -9
  80. package/dist/task-stream-CLXzeuPO.js.map +1 -0
  81. package/dist/{tasks-2mu3lAvm.js → tasks-D77GNdOU.js} +2 -2
  82. package/dist/{tasks-2mu3lAvm.js.map → tasks-D77GNdOU.js.map} +1 -1
  83. package/dist/{telemetry-BllPiBKw.js → telemetry-wp-z9LXH.js} +3 -3
  84. package/dist/{telemetry-BllPiBKw.js.map → telemetry-wp-z9LXH.js.map} +1 -1
  85. package/dist/{terminal-aWQrDy8s.js → terminal-D9j4wbpD.js} +13 -13
  86. package/dist/{terminal-aWQrDy8s.js.map → terminal-D9j4wbpD.js.map} +1 -1
  87. package/dist/{tools-u8TaJFqa.js → tools-D0r4e-Vu.js} +10 -7
  88. package/dist/tools-D0r4e-Vu.js.map +1 -0
  89. package/dist/wizard-abort-Bv87YVSp.js +71 -0
  90. package/dist/wizard-abort-Bv87YVSp.js.map +1 -0
  91. package/dist/{wizard-abort-pFFH7dcx.js → wizard-abort-oazJA1Jb.js} +1 -1
  92. package/dist/{wizard-session-DTyLMPsX.js → wizard-session-C_7r3-rO.js} +3 -2
  93. package/dist/wizard-session-C_7r3-rO.js.map +1 -0
  94. package/dist/{wizard-session-Cw7-_OcZ.js → wizard-session-D1KQqUml.js} +1 -1
  95. package/dist/yara-hooks-Bl-FeANN.js +2 -0
  96. package/dist/{yara-hooks-BXDBIOBq.js → yara-hooks-DeonKbE_.js} +57 -8
  97. package/dist/yara-hooks-DeonKbE_.js.map +1 -0
  98. package/package.json +1 -1
  99. package/dist/agent-interface-D3MNaDp3.js.map +0 -1
  100. package/dist/agent-runner-DEeMqJxy.js.map +0 -1
  101. package/dist/analytics-DN3Kzf7H.js +0 -2
  102. package/dist/ci-install-DIB2n4Ju.js.map +0 -1
  103. package/dist/debug-BKqv-yfT.js.map +0 -1
  104. package/dist/environment-Cl-fIQku.js +0 -22
  105. package/dist/environment-Cl-fIQku.js.map +0 -1
  106. package/dist/mcp-prompt-streaming--sRErHKv.js.map +0 -1
  107. package/dist/non-interactive-CNoYoEZp.js.map +0 -1
  108. package/dist/package-manager-BQDHm7ER.js.map +0 -1
  109. package/dist/pi-W-4RUPFY.js.map +0 -1
  110. package/dist/posthog-integration-LxEBGkoe.js.map +0 -1
  111. package/dist/security-B4jU_-7q.js.map +0 -1
  112. package/dist/start-tui-BQH4mQIZ.js.map +0 -1
  113. package/dist/task-oh8OAnvR.js.map +0 -1
  114. package/dist/task-stream-jUARpyB5.js.map +0 -1
  115. package/dist/tools-u8TaJFqa.js.map +0 -1
  116. package/dist/wizard-abort-D9jiMkZA.js +0 -49
  117. package/dist/wizard-abort-D9jiMkZA.js.map +0 -1
  118. package/dist/wizard-session-DTyLMPsX.js.map +0 -1
  119. package/dist/yara-hooks-BXDBIOBq.js.map +0 -1
  120. package/dist/yara-hooks-i2jOabhI.js +0 -2
@@ -1,7 +1,7 @@
1
- import { s as logToFile } from "./debug-BKqv-yfT.js";
2
- import { n as analytics } from "./analytics-D8JNuPAT.js";
3
- import { h as isThinkingLevel } from "./queue-tools-DABh1Ssc.js";
4
- import { D as WIZARD_TOOL_NAMES, R as fetchWithRetry } from "./agent-interface-D3MNaDp3.js";
1
+ import { s as logToFile } from "./debug-aA5dm2MR.js";
2
+ import { n as analytics } from "./analytics-tF06lcmE.js";
3
+ import { L as fetchWithRetry, T as WIZARD_TOOL_NAMES } from "./agent-interface-CaEptZuu.js";
4
+ import { h as isThinkingLevel } from "./queue-tools-i_TmeI02.js";
5
5
  //#region src/lib/agent/agent-prompt-loader.ts
6
6
  function projectContext(ctx) {
7
7
  return `You have access to the PostHog MCP server and the wizard tools.
@@ -312,4 +312,4 @@ const EMPTY_PROMPT = {};
312
312
  //#endregion
313
313
  export { assembleTaskPrompt as a, queueTools as c, taskModelSpec as d, assembleSeedPrompt as i, renderToolInventory as l, agentRunTools as n, loadAgentRegistry as o, allowsPostHogMcp as r, promptModelFor as s, ASK_TOOL as t, resolveTask as u };
314
314
 
315
- //# sourceMappingURL=agent-prompt-loader-D8Bajo-L.js.map
315
+ //# sourceMappingURL=agent-prompt-loader-DZHc9tIG.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-prompt-loader-D8Bajo-L.js","names":[],"sources":["../src/lib/agent/agent-prompt-loader.ts"],"sourcesContent":["/**\n * Agent-prompt loader + registry.\n *\n * Agent prompts are the WHAT of a task: a markdown file per type, served from\n * context-mill as the `agents` content type (parallel to skills). The frontmatter\n * carries the artifacts the executor needs — model, the mini-skills to load (the\n * HOW), the tools the task may use, and its dependencies — and the body is the\n * instruction the agent reads.\n *\n * The registry is fetched once at startup and scoped to one flow — agents\n * declare `flow` and (for the planner) `seed: true` in frontmatter, so each\n * program (integration, audit, migration, ...) ships its own agent set and the\n * loader stays generic. Every prompt is downloaded and parsed up front, so\n * resolving a task to its run config is synchronous and adds no mid-drain\n * network latency. The registry's type list also drives `enqueue_task`\n * validation.\n */\nimport type {\n QueueStore,\n QueuedTask,\n} from './runner/sequence/orchestrator/queue';\nimport type { ResolvedTask } from './runner/sequence/orchestrator/executor';\nimport type { HostResolution } from '@lib/host-resolution';\nimport {\n isThinkingLevel,\n type ThinkingLevel,\n} from './runner/switchboard/models';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport { fetchWithRetry } from '@lib/fetch-retry';\nimport { WIZARD_TOOL_NAMES } from '@lib/wizard-tools/tools';\n\n/**\n * The basics the client injects around every agent-prompt body. The `/agents/`\n * files carry intent only (goal, success criteria); the wizard owns the I/O\n * contract — who the agent is, how it reports, how it surfaces progress — so the\n * authored prompts never restate it.\n */\nexport interface OrchestratorPromptContext {\n projectId: number;\n projectApiKey: string;\n host: HostResolution;\n /** Path to the framework's reference implementation (EXAMPLE.md), if available. */\n examplePath?: string;\n /** Path to the framework's rules (COMMANDMENTS.md), if available. */\n commandmentsPath?: string;\n}\n\nfunction projectContext(ctx: OrchestratorPromptContext): string {\n // Both hosts, distinctly labelled: `apiHost` is the ingestion/API origin the\n // SDK talks to, `appHost` the user-facing web app. A task that hands the user\n // a link (e.g. the data-warehouse new-source fallback) must build it from the\n // app host — the ingestion host does not serve those pages.\n return `You have access to the PostHog MCP server and the wizard tools.\n\nProject context:\n- PostHog Project ID: ${ctx.projectId}\n- PostHog public token: ${ctx.projectApiKey}\n- PostHog Host: ${ctx.host.apiHost}\n- PostHog app URL (base for any link you show the user in a browser): ${ctx.host.appHost}`;\n}\n\n/** Points the agent at the framework's reference integration to learn patterns from. */\nfunction exampleReference(ctx: OrchestratorPromptContext): string | null {\n if (!ctx.examplePath) return null;\n return `A reference PostHog integration for this framework is at \\`${ctx.examplePath}\\`. It shows the target implementation pattern. Reference its patterns and conventions, adapting them to this codebase.`;\n}\n\n/** The framework's rules ship with the reference skill; every task follows them. */\nfunction commandmentsReference(ctx: OrchestratorPromptContext): string | null {\n if (!ctx.commandmentsPath) return null;\n return `Framework rules for this integration are at \\`${ctx.commandmentsPath}\\`. Read them before you edit and follow them.`;\n}\n\n/**\n * The task's own tool list, injected so an agent never has to discover a tool's\n * absence by trying it — and never reports that absence as a finding. Later\n * tasks hold tools this one does not, so work it cannot do is handed on rather\n * than attempted.\n */\n/** Renders the inventory from the tool names a harness actually registered for\n * the run — the one complete list, in the vocabulary the agent will call. */\nexport function renderToolInventory(toolNames: readonly string[]): string {\n if (toolNames.length === 0) return '';\n return `Your tools for this task: ${toolNames.join(\n ', ',\n )}. Do not look for a tool that is not listed or treat its absence as a problem to report. Later tasks in this run hold tools you do not: when your task needs one, hand that work off in your handoff for the task that can do it, or note it for the final report.`;\n}\n\nconst TASK_BASICS = `You are one step in a larger PostHog workflow made of several tasks, run as a fresh agent with no memory of the other tasks beyond the context you are given. Other tasks — before and after you — own the rest of the work, so stay strictly on your own task: do not do a neighbouring step's job, redo what an upstream handoff already did, or reach beyond what you were asked. Do only your task, then report exactly once by calling complete_task with a structured handoff: what your goal was, what you did, and what the next agent should know. When you are given context from previous steps, trust it — those agents already did their work, so do not re-verify or re-read what their handoffs tell you. Build on it and move fast. Read a file before you edit it, so your own changes do not duplicate what is already there. Work only inside this project's own directory: never read, list, or search (find, ls, grep, glob) outside it — not the OS, not other projects, not global package caches. If your task seems to need something outside this directory, it does not — skip that part and say so in your handoff rather than hunting across the filesystem. If your task does not apply to this project — there is genuinely nothing for it to do — report it with status \\`not needed\\` and say why, rather than marking it done.`;\n\nconst SEED_BASICS = `You are the orchestrator. Plan the work and seed the queue with enqueue_task — each call returns an id you can pass as a dependency to a later task. Give each task a short label for the UI — the action in a few words, not file names, class names, or other specifics. The last task you queue, the one that reports on the run, must depend on every other task in the queue — directly, or through a task it already depends on. You are not a task yourself: do not call complete_task and do not edit the project.`;\n\n/**\n * Tasks the wizard queued before the planner ran. It has to see them: they are\n * part of the run it is planning around, and the task that reports last has to\n * depend on them. Their ids are real, so it can wire the edge directly.\n *\n * The one-way rule matters as much as the sink edge. These tasks are deferred to\n * the end of the drain after planning (`seeded-deps.ts`) and may block on a\n * person, so a task the planner hangs off one would wait on the user too — which\n * is the interruption deferring them removed. The resolver drops such a task\n * from the seeded task's own dependencies to stay acyclic, so the damage is\n * silent; saying so here is what prevents it.\n */\nfunction preQueuedTasks(\n tasks: readonly { id: string; type: string }[],\n): string | null {\n if (tasks.length === 0) return null;\n const lines = tasks.map((t) => `- ${t.type} (id: ${t.id})`);\n return `The queue already holds these tasks, placed by the wizard from what it found in this project. Do not queue them again. They run late — after every task you queue — and one may stop to ask the user for input, so make the reporting task depend on each one and hang nothing else off them: any other task you made depend on one would end up waiting on a person.\\n${lines.join(\n '\\n',\n )}`;\n}\n\n/**\n * Points the agent at its installed task instructions (the HOW). They live under\n * the wizard's run dir, not `.claude/skills/`, so the SDK does not auto-load\n * them — the prompt has to name them.\n */\nfunction skillReference(paths: readonly string[]): string | null {\n if (paths.length === 0) return null;\n const list = paths.map((p) => `\\`${p}\\``).join(', ');\n return `Your task instructions are at ${list}. Read them before you start and follow them. They are wizard scaffolding, not part of the project.`;\n}\n\n/** A task agent's full prompt: injected basics, then the authored intent. */\nexport function assembleTaskPrompt(\n ctx: OrchestratorPromptContext,\n body: string,\n skillPaths: readonly string[] = [],\n): string {\n return [\n projectContext(ctx),\n exampleReference(ctx),\n commandmentsReference(ctx),\n skillReference(skillPaths),\n TASK_BASICS,\n body,\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/** The seed agent's full prompt: injected basics, then the authored intent. */\nexport function assembleSeedPrompt(\n ctx: OrchestratorPromptContext,\n body: string,\n preQueued: readonly { id: string; type: string }[] = [],\n): string {\n return [projectContext(ctx), SEED_BASICS, preQueuedTasks(preQueued), body]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/** Orchestrator tools are MCP tools under the `posthog-wizard` server. Frontmatter\n * names them short (e.g. `enqueue_task`); the SDK gates on the full name. */\nconst ORCHESTRATOR_TOOL_PREFIX = 'mcp__posthog-wizard__';\nconst ORCHESTRATOR_TOOLS = new Set([\n 'enqueue_task',\n 'complete_task',\n 'read_handoffs',\n]);\n\n/** The one tool that stops a task until a person answers. Named short in frontmatter. */\nexport const ASK_TOOL = 'wizard_ask';\n\n/** The skill-menu tools, as agents ask for them in frontmatter. */\nconst SKILL_MENU_TOOL = 'load_skill_menu';\nconst INSTALL_SKILL_TOOL = 'install_skill';\n\n/**\n * The PostHog MCP, as an agent asks for it in frontmatter. Every tool a task\n * gets is granted by its own prompt, this one included: a task that never names\n * it never has the server wired in, and one that does gets it under this name\n * on both harnesses.\n */\nexport const POSTHOG_MCP_TOOL = 'posthog_exec';\n/** The same tool as the anthropic SDK names it, on the hosted PostHog server. */\nconst POSTHOG_MCP_SDK_TOOL = 'mcp__posthog-wizard__exec';\n\n/** Whether a task asked for the PostHog MCP — accepts either spelling. */\nexport function allowsPostHogMcp(\n allowedTools: readonly string[] | undefined,\n): boolean {\n return (allowedTools ?? []).some(\n (name) => name === POSTHOG_MCP_TOOL || name === POSTHOG_MCP_SDK_TOOL,\n );\n}\n\n/** The queue tools a task holds — all of them minus its disallows. Short names.\n * Single source for both the injected inventory and the harness's tool grant. */\nexport function queueTools(disallowedTools: readonly string[]): string[] {\n const disallowed = new Set(\n disallowedTools.map((n) => n.replace(ORCHESTRATOR_TOOL_PREFIX, '')),\n );\n return [...ORCHESTRATOR_TOOLS].filter((t) => !disallowed.has(t));\n}\n\n/** A parsed agent prompt. The frontmatter fields plus the markdown body. */\nexport interface AgentPrompt {\n type: string;\n /** Human-readable title for the TUI; falls back to `type` when absent. */\n label?: string;\n /** The flow this agent belongs to (the program id, e.g. \\`posthog-integration\\`). */\n flow?: string;\n /** Marks the flow's planner: it seeds the queue and is not an enqueueable task. */\n seed: boolean;\n /** Marks a task that runs last: it must depend on every other task in the queue. */\n sink: boolean;\n /**\n * Marks a task only the wizard may queue. The planner never sees the type, so\n * whether it runs is a decision the client makes from what it detected, not\n * one an agent can reach — it can neither invent the task nor forget it.\n */\n runnerSeeded: boolean;\n /** Per-profile model + effort. `pi` = the gpt/pi harness, `sdk` = the anthropic\n * harness. The mapping is not 1:1 across providers, so each agent names both. */\n modelPi?: string;\n effortPi?: ThinkingLevel;\n modelSdk?: string;\n effortSdk?: ThinkingLevel;\n skills: string[];\n allowedTools: string[];\n disallowedTools: string[];\n /**\n * Task types this one runs after. Read differently by the two kinds of task:\n *\n * - **Enqueueable types**: advisory. The planner authors the real graph with\n * `enqueue_task`, passing ids, and its seed prompt describes the shape it\n * should build. Nothing resolves this field for them.\n * - **`runnerSeeded` types**: authoritative. Such a task is queued before the\n * planner runs, so it cannot name ids; the runner resolves these types to\n * the ids the planner produced and applies them (see `seeded-deps.ts`).\n * Empty means \"after everything that is not the sink\".\n */\n dependsOn: string[];\n body: string;\n}\n\n/** The model + effort an agent runs on for a given harness — `pi` picks the gpt\n * column, anything else the sdk (anthropic) column. */\nexport function promptModelFor(\n prompt: AgentPrompt,\n harness: string,\n): { model?: string; effort?: ThinkingLevel } {\n const pi = harness === 'pi';\n return {\n model: pi ? prompt.modelPi : prompt.modelSdk,\n effort: pi ? prompt.effortPi : prompt.effortSdk,\n };\n}\n\nexport interface AgentRegistry {\n /** The flow's task types — every prompt except the seed. */\n readonly types: string[];\n /** The types an agent may enqueue: `types` minus the runner-seeded ones. */\n readonly enqueueableTypes: string[];\n /** The types that run last and must depend on the whole queue. */\n readonly sinkTypes: string[];\n /** The types only the wizard queues, from what it detected before the run. */\n readonly runnerSeededTypes: string[];\n /** The flow's planner, the one prompt marked `seed: true` in its frontmatter. */\n readonly seed?: AgentPrompt;\n get(type: string): AgentPrompt | undefined;\n}\n\n/** The registry for one flow's prompts. Pure; the loader feeds it the fetched set. */\nexport function buildRegistry(\n prompts: readonly AgentPrompt[],\n flow: string,\n opts?: {\n exclude?: readonly string[];\n /** Per-stage pi model/effort overlays, keyed by task type ('seed' for the planner). Applied here — the one place prompts enter the wizard — so every downstream read sees the effective spec. */\n overrides?: Record<\n string,\n { model?: string; effort?: ThinkingLevel } | undefined\n >;\n },\n): AgentRegistry {\n // The harness can exclude task types (CI excludes dashboards). An excluded\n // type does not exist for the run: the seed cannot enqueue it and no agent\n // is ever spun up for it.\n const excluded = new Set(opts?.exclude ?? []);\n const inFlow = prompts\n .filter((p) => p.flow === flow && !excluded.has(p.type))\n .map((p) => {\n const o = opts?.overrides?.[p.seed ? 'seed' : p.type];\n if (!o) return p;\n return {\n ...p,\n modelPi: o.model ?? p.modelPi,\n effortPi: o.effort ?? p.effortPi,\n };\n });\n const byType = new Map(inFlow.map((p) => [p.type, p]));\n const tasks = inFlow.filter((p) => !p.seed);\n return {\n types: tasks.map((p) => p.type),\n enqueueableTypes: tasks.filter((p) => !p.runnerSeeded).map((p) => p.type),\n sinkTypes: tasks.filter((p) => p.sink).map((p) => p.type),\n runnerSeededTypes: tasks.filter((p) => p.runnerSeeded).map((p) => p.type),\n seed: inFlow.find((p) => p.seed),\n get: (type) => byType.get(type),\n };\n}\n\ninterface AgentMenu {\n /** `flow` arrived with context-mill's flow-scoped agents folder; older menus omit it. */\n agents: { id: string; flow?: string; downloadUrl: string }[];\n}\n\n/** A native tool passes through; an MCP tool gets its fully-qualified name. */\nfunction expandToolName(name: string): string {\n if (name === ASK_TOOL) return WIZARD_TOOL_NAMES.wizardAsk;\n if (name === SKILL_MENU_TOOL) return WIZARD_TOOL_NAMES.loadSkillMenu;\n if (name === INSTALL_SKILL_TOOL) return WIZARD_TOOL_NAMES.installSkill;\n if (name === POSTHOG_MCP_TOOL) return POSTHOG_MCP_SDK_TOOL;\n return ORCHESTRATOR_TOOLS.has(name)\n ? `${ORCHESTRATOR_TOOL_PREFIX}${name}`\n : name;\n}\n\n/** A prompt's allow/disallow lists with orchestrator tool names MCP-qualified. */\nexport function agentRunTools(prompt: AgentPrompt): {\n allowedTools: string[];\n disallowedTools: string[];\n} {\n return {\n allowedTools: prompt.allowedTools.map(expandToolName),\n disallowedTools: prompt.disallowedTools.map(expandToolName),\n };\n}\n\nfunction toStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((v): v is string => typeof v === 'string');\n}\n\n/**\n * Parse the leading `---` frontmatter block and the markdown body. The\n * frontmatter is a small, known schema (scalars and inline `[a, b]` arrays), so\n * a tiny parser covers it without a YAML dependency. Inline `# comments` after a\n * value are stripped. `fallbackType` (the menu id) and `fallbackFlow` (the\n * menu entry's flow) apply when the frontmatter omits `type:`/`flow:`.\n */\nexport function parseAgentPrompt(\n text: string,\n fallbackType: string,\n fallbackFlow?: string,\n): AgentPrompt {\n const match = text.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n const frontmatter = match ? match[1] : '';\n const body = (match ? match[2] : text).trim();\n\n const fields: Record<string, unknown> = {};\n for (const rawLine of frontmatter.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\s+#.*$/, '').trim();\n if (!line || line.startsWith('#')) continue;\n const kv = line.match(/^([\\w-]+):\\s*(.*)$/);\n if (!kv) continue;\n const [, key, raw] = kv;\n if (raw.startsWith('[') && raw.endsWith(']')) {\n fields[key] = raw\n .slice(1, -1)\n .split(',')\n .map((s) => s.trim().replace(/^['\"]|['\"]$/g, ''))\n .filter(Boolean);\n } else {\n fields[key] = raw.replace(/^['\"]|['\"]$/g, '');\n }\n }\n\n const str = (v: unknown) => (typeof v === 'string' ? v : undefined);\n // Effort is remote data — reject typos here so downstream carries ThinkingLevel.\n const effort = (v: unknown, key: string): ThinkingLevel | undefined => {\n if (v === undefined) return undefined;\n if (isThinkingLevel(v)) return v;\n logToFile(\n `[agent-prompt] ${fallbackType}: ignoring invalid ${key} \"${String(v)}\"`,\n );\n analytics.wizardCapture('agent prompt invalid effort', {\n task_type: fallbackType,\n key,\n value: String(v),\n });\n return undefined;\n };\n return {\n type: typeof fields.type === 'string' ? fields.type : fallbackType,\n label: typeof fields.label === 'string' ? fields.label : undefined,\n flow: typeof fields.flow === 'string' ? fields.flow : fallbackFlow,\n seed: fields.seed === 'true',\n sink: fields.sink === 'true',\n runnerSeeded: fields.runnerSeeded === 'true',\n modelPi: str(fields.model_pi),\n effortPi: effort(fields.effort_pi, 'effort_pi'),\n modelSdk: str(fields.model_sdk),\n effortSdk: effort(fields.effort_sdk, 'effort_sdk'),\n skills: toStringArray(fields.skills),\n allowedTools: toStringArray(fields.allowedTools),\n disallowedTools: toStringArray(fields.disallowedTools),\n dependsOn: toStringArray(fields.dependsOn),\n body,\n };\n}\n\nasync function fetchText(url: string): Promise<string> {\n const res = await fetchWithRetry(url);\n return res.text();\n}\n\n/**\n * Fetch the agent menu and every agent prompt it lists, parse them, and build\n * the registry for one flow. Throws if the menu cannot be fetched — the\n * orchestrator cannot run without its prompts.\n */\nexport async function loadAgentRegistry(\n skillsBaseUrl: string,\n flow: string,\n opts?: Parameters<typeof buildRegistry>[2],\n): Promise<AgentRegistry> {\n const menuRaw = await fetchText(`${skillsBaseUrl}/agent-menu.json`);\n const menu = JSON.parse(menuRaw) as AgentMenu;\n\n // Menus that carry a flow per entry let us skip other flows' prompts before\n // fetching them; entries without one are fetched and filtered by their\n // frontmatter in buildRegistry, as before.\n const entries = (menu.agents ?? []).filter(\n (entry) => !entry.flow || entry.flow === flow,\n );\n const prompts = await Promise.all(\n entries.map(async (entry) => {\n const text = await fetchText(entry.downloadUrl);\n return parseAgentPrompt(text, entry.id, entry.flow);\n }),\n );\n\n return buildRegistry(prompts, flow, opts);\n}\n\n/**\n * Render a task's own inputs into a section, so a fanned-out task (e.g. one\n * `capture` per event) sees the specific thing it owns. Empty when there are none.\n */\nfunction renderInputs(task: QueuedTask): string {\n const entries = Object.entries(task.inputs ?? {});\n if (entries.length === 0) return '';\n const lines = entries.map(([k, v]) => `- ${k}: ${formatInputValue(v)}`);\n return `## Your task input\\n\\n${lines.join('\\n')}`;\n}\n\nfunction formatInputValue(value: unknown): string {\n if (typeof value === 'string') return value;\n return JSON.stringify(value);\n}\n\n/**\n * The ids of every task `task` transitively depends on — the full upstream\n * chain, not just direct dependencies — ordered roots-first, each once. A `seen`\n * set dedupes diamonds and guards against cycles.\n */\nfunction ancestorIds(task: QueuedTask, store: QueueStore): string[] {\n const seen = new Set<string>();\n const ordered: string[] = [];\n const visit = (id: string): void => {\n if (seen.has(id)) return;\n seen.add(id);\n const t = store.get(id);\n if (!t) return;\n for (const dep of t.dependsOn) visit(dep); // ancestors before dependents\n ordered.push(id);\n };\n for (const dep of task.dependsOn) visit(dep);\n return ordered;\n}\n\n/**\n * Render the handoffs of every step `task` transitively depends on into a context\n * section, so a fresh agent sees the whole upstream chain — not just its direct\n * dependencies. Reliability over token economy: a step must never have to\n * re-discover what any ancestor already established just because an intermediate\n * handoff happened to omit it. Empty when there are no completed ancestors.\n */\nfunction renderHandoffContext(task: QueuedTask, store: QueueStore): string {\n const lines: string[] = [];\n for (const id of ancestorIds(task, store)) {\n const dep = store.get(id);\n const handoff = store.readHandoff(id);\n if (!dep || !handoff) continue;\n lines.push(`### ${dep.type}`);\n lines.push(`- did: ${handoff.did}`);\n lines.push(`- for you: ${handoff.forNextAgent}`);\n if (handoff.filesTouched?.length) {\n lines.push(`- files: ${handoff.filesTouched.join(', ')}`);\n }\n if (handoff.evidence) {\n lines.push(`- evidence: ${handoff.evidence}`);\n }\n if (handoff.assumptions) {\n lines.push(`- assumed: ${handoff.assumptions}`);\n }\n if (handoff.reportSection) {\n lines.push(`- report section:\\n${handoff.reportSection}`);\n }\n lines.push('');\n }\n if (lines.length === 0) return '';\n return `## Context from previous steps\\n\\n${lines.join('\\n')}`.trim();\n}\n\n/**\n * Resolve a queued task to its run config: the prompt body (with upstream\n * handoffs appended), the model, and the tool lists with orchestrator tool names\n * MCP-qualified. The model precedence is enqueue override, then prompt, then\n * default. Throws if no prompt is registered for the task's type.\n */\nexport function resolveTask(\n registry: AgentRegistry,\n task: QueuedTask,\n store: QueueStore,\n): ResolvedTask {\n const prompt = registry.get(task.type);\n if (!prompt) {\n throw new Error(`No agent prompt registered for task type \"${task.type}\"`);\n }\n\n const body = [\n renderInputs(task),\n prompt.body,\n renderHandoffContext(task, store),\n ]\n .filter(Boolean)\n .join('\\n\\n');\n\n return {\n ...agentRunTools(prompt),\n prompt: body,\n skills: prompt.skills,\n };\n}\n\n/** The model + effort a task runs on for a harness: enqueue override, then the\n * prompt's per-profile frontmatter; the caller's switchboard pick is the fallback. */\nexport function taskModelSpec(\n registry: AgentRegistry,\n task: QueuedTask,\n harness: string,\n): { model?: string; effort?: ThinkingLevel } {\n const picked = promptModelFor(\n registry.get(task.type) ?? EMPTY_PROMPT,\n harness,\n );\n return {\n model: task.model ?? picked.model,\n effort: picked.effort,\n };\n}\n\nconst EMPTY_PROMPT = {} as AgentPrompt;\n"],"mappings":";;;;;AAgDA,SAAS,eAAe,KAAwC;AAK9D,QAAO;;;wBAGe,IAAI,UAAU;0BACZ,IAAI,cAAc;kBAC1B,IAAI,KAAK,QAAQ;wEACqC,IAAI,KAAK;;;AAIjF,SAAS,iBAAiB,KAA+C;AACvE,KAAI,CAAC,IAAI,YAAa,QAAO;AAC7B,QAAO,8DAA8D,IAAI,YAAY;;;AAIvF,SAAS,sBAAsB,KAA+C;AAC5E,KAAI,CAAC,IAAI,iBAAkB,QAAO;AAClC,QAAO,iDAAiD,IAAI,iBAAiB;;;;;;;;;;AAW/E,SAAgB,oBAAoB,WAAsC;AACxE,KAAI,UAAU,WAAW,EAAG,QAAO;AACnC,QAAO,6BAA6B,UAAU,KAC5C,KACD,CAAC;;AAGJ,MAAM,cAAc;AAEpB,MAAM,cAAc;;;;;;;;;;;;;AAcpB,SAAS,eACP,OACe;AACf,KAAI,MAAM,WAAW,EAAG,QAAO;AAE/B,QAAO,0WADO,MAAM,KAAK,MAAM,KAAK,EAAE,KAAK,QAAQ,EAAE,GAAG,GAAG,CAC4T,KACrX,KACD;;;;;;;AAQH,SAAS,eAAe,OAAyC;AAC/D,KAAI,MAAM,WAAW,EAAG,QAAO;AAE/B,QAAO,iCADM,MAAM,KAAK,MAAM,KAAK,EAAE,IAAI,CAAC,KAAK,KAAK,CACP;;;AAI/C,SAAgB,mBACd,KACA,MACA,aAAgC,EAAE,EAC1B;AACR,QAAO;EACL,eAAe,IAAI;EACnB,iBAAiB,IAAI;EACrB,sBAAsB,IAAI;EAC1B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,"file":"agent-prompt-loader-DZHc9tIG.js","names":[],"sources":["../src/lib/agent/agent-prompt-loader.ts"],"sourcesContent":["/**\n * Agent-prompt loader + registry.\n *\n * Agent prompts are the WHAT of a task: a markdown file per type, served from\n * context-mill as the `agents` content type (parallel to skills). The frontmatter\n * carries the artifacts the executor needs — model, the mini-skills to load (the\n * HOW), the tools the task may use, and its dependencies — and the body is the\n * instruction the agent reads.\n *\n * The registry is fetched once at startup and scoped to one flow — agents\n * declare `flow` and (for the planner) `seed: true` in frontmatter, so each\n * program (integration, audit, migration, ...) ships its own agent set and the\n * loader stays generic. Every prompt is downloaded and parsed up front, so\n * resolving a task to its run config is synchronous and adds no mid-drain\n * network latency. The registry's type list also drives `enqueue_task`\n * validation.\n */\nimport type {\n QueueStore,\n QueuedTask,\n} from './runner/sequence/orchestrator/queue';\nimport type { ResolvedTask } from './runner/sequence/orchestrator/executor';\nimport type { HostResolution } from '@lib/host-resolution';\nimport {\n isThinkingLevel,\n type ThinkingLevel,\n} from './runner/switchboard/models';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport { fetchWithRetry } from '@lib/fetch-retry';\nimport { WIZARD_TOOL_NAMES } from '@lib/wizard-tools/tools';\n\n/**\n * The basics the client injects around every agent-prompt body. The `/agents/`\n * files carry intent only (goal, success criteria); the wizard owns the I/O\n * contract — who the agent is, how it reports, how it surfaces progress — so the\n * authored prompts never restate it.\n */\nexport interface OrchestratorPromptContext {\n projectId: number;\n projectApiKey: string;\n host: HostResolution;\n /** Path to the framework's reference implementation (EXAMPLE.md), if available. */\n examplePath?: string;\n /** Path to the framework's rules (COMMANDMENTS.md), if available. */\n commandmentsPath?: string;\n}\n\nfunction projectContext(ctx: OrchestratorPromptContext): string {\n // Both hosts, distinctly labelled: `apiHost` is the ingestion/API origin the\n // SDK talks to, `appHost` the user-facing web app. A task that hands the user\n // a link (e.g. the data-warehouse new-source fallback) must build it from the\n // app host — the ingestion host does not serve those pages.\n return `You have access to the PostHog MCP server and the wizard tools.\n\nProject context:\n- PostHog Project ID: ${ctx.projectId}\n- PostHog public token: ${ctx.projectApiKey}\n- PostHog Host: ${ctx.host.apiHost}\n- PostHog app URL (base for any link you show the user in a browser): ${ctx.host.appHost}`;\n}\n\n/** Points the agent at the framework's reference integration to learn patterns from. */\nfunction exampleReference(ctx: OrchestratorPromptContext): string | null {\n if (!ctx.examplePath) return null;\n return `A reference PostHog integration for this framework is at \\`${ctx.examplePath}\\`. It shows the target implementation pattern. Reference its patterns and conventions, adapting them to this codebase.`;\n}\n\n/** The framework's rules ship with the reference skill; every task follows them. */\nfunction commandmentsReference(ctx: OrchestratorPromptContext): string | null {\n if (!ctx.commandmentsPath) return null;\n return `Framework rules for this integration are at \\`${ctx.commandmentsPath}\\`. Read them before you edit and follow them.`;\n}\n\n/**\n * The task's own tool list, injected so an agent never has to discover a tool's\n * absence by trying it — and never reports that absence as a finding. Later\n * tasks hold tools this one does not, so work it cannot do is handed on rather\n * than attempted.\n */\n/** Renders the inventory from the tool names a harness actually registered for\n * the run — the one complete list, in the vocabulary the agent will call. */\nexport function renderToolInventory(toolNames: readonly string[]): string {\n if (toolNames.length === 0) return '';\n return `Your tools for this task: ${toolNames.join(\n ', ',\n )}. Do not look for a tool that is not listed or treat its absence as a problem to report. Later tasks in this run hold tools you do not: when your task needs one, hand that work off in your handoff for the task that can do it, or note it for the final report.`;\n}\n\nconst TASK_BASICS = `You are one step in a larger PostHog workflow made of several tasks, run as a fresh agent with no memory of the other tasks beyond the context you are given. Other tasks — before and after you — own the rest of the work, so stay strictly on your own task: do not do a neighbouring step's job, redo what an upstream handoff already did, or reach beyond what you were asked. Do only your task, then report exactly once by calling complete_task with a structured handoff: what your goal was, what you did, and what the next agent should know. When you are given context from previous steps, trust it — those agents already did their work, so do not re-verify or re-read what their handoffs tell you. Build on it and move fast. Read a file before you edit it, so your own changes do not duplicate what is already there. Work only inside this project's own directory: never read, list, or search (find, ls, grep, glob) outside it — not the OS, not other projects, not global package caches. If your task seems to need something outside this directory, it does not — skip that part and say so in your handoff rather than hunting across the filesystem. If your task does not apply to this project — there is genuinely nothing for it to do — report it with status \\`not needed\\` and say why, rather than marking it done.`;\n\nconst SEED_BASICS = `You are the orchestrator. Plan the work and seed the queue with enqueue_task — each call returns an id you can pass as a dependency to a later task. Give each task a short label for the UI — the action in a few words, not file names, class names, or other specifics. The last task you queue, the one that reports on the run, must depend on every other task in the queue — directly, or through a task it already depends on. You are not a task yourself: do not call complete_task and do not edit the project.`;\n\n/**\n * Tasks the wizard queued before the planner ran. It has to see them: they are\n * part of the run it is planning around, and the task that reports last has to\n * depend on them. Their ids are real, so it can wire the edge directly.\n *\n * The one-way rule matters as much as the sink edge. These tasks are deferred to\n * the end of the drain after planning (`seeded-deps.ts`) and may block on a\n * person, so a task the planner hangs off one would wait on the user too — which\n * is the interruption deferring them removed. The resolver drops such a task\n * from the seeded task's own dependencies to stay acyclic, so the damage is\n * silent; saying so here is what prevents it.\n */\nfunction preQueuedTasks(\n tasks: readonly { id: string; type: string }[],\n): string | null {\n if (tasks.length === 0) return null;\n const lines = tasks.map((t) => `- ${t.type} (id: ${t.id})`);\n return `The queue already holds these tasks, placed by the wizard from what it found in this project. Do not queue them again. They run late — after every task you queue — and one may stop to ask the user for input, so make the reporting task depend on each one and hang nothing else off them: any other task you made depend on one would end up waiting on a person.\\n${lines.join(\n '\\n',\n )}`;\n}\n\n/**\n * Points the agent at its installed task instructions (the HOW). They live under\n * the wizard's run dir, not `.claude/skills/`, so the SDK does not auto-load\n * them — the prompt has to name them.\n */\nfunction skillReference(paths: readonly string[]): string | null {\n if (paths.length === 0) return null;\n const list = paths.map((p) => `\\`${p}\\``).join(', ');\n return `Your task instructions are at ${list}. Read them before you start and follow them. They are wizard scaffolding, not part of the project.`;\n}\n\n/** A task agent's full prompt: injected basics, then the authored intent. */\nexport function assembleTaskPrompt(\n ctx: OrchestratorPromptContext,\n body: string,\n skillPaths: readonly string[] = [],\n): string {\n return [\n projectContext(ctx),\n exampleReference(ctx),\n commandmentsReference(ctx),\n skillReference(skillPaths),\n TASK_BASICS,\n body,\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/** The seed agent's full prompt: injected basics, then the authored intent. */\nexport function assembleSeedPrompt(\n ctx: OrchestratorPromptContext,\n body: string,\n preQueued: readonly { id: string; type: string }[] = [],\n): string {\n return [projectContext(ctx), SEED_BASICS, preQueuedTasks(preQueued), body]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/** Orchestrator tools are MCP tools under the `posthog-wizard` server. Frontmatter\n * names them short (e.g. `enqueue_task`); the SDK gates on the full name. */\nconst ORCHESTRATOR_TOOL_PREFIX = 'mcp__posthog-wizard__';\nconst ORCHESTRATOR_TOOLS = new Set([\n 'enqueue_task',\n 'complete_task',\n 'read_handoffs',\n]);\n\n/** The one tool that stops a task until a person answers. Named short in frontmatter. */\nexport const ASK_TOOL = 'wizard_ask';\n\n/** The skill-menu tools, as agents ask for them in frontmatter. */\nconst SKILL_MENU_TOOL = 'load_skill_menu';\nconst INSTALL_SKILL_TOOL = 'install_skill';\n\n/**\n * The PostHog MCP, as an agent asks for it in frontmatter. Every tool a task\n * gets is granted by its own prompt, this one included: a task that never names\n * it never has the server wired in, and one that does gets it under this name\n * on both harnesses.\n */\nexport const POSTHOG_MCP_TOOL = 'posthog_exec';\n/** The same tool as the anthropic SDK names it, on the hosted PostHog server. */\nconst POSTHOG_MCP_SDK_TOOL = 'mcp__posthog-wizard__exec';\n\n/** Whether a task asked for the PostHog MCP — accepts either spelling. */\nexport function allowsPostHogMcp(\n allowedTools: readonly string[] | undefined,\n): boolean {\n return (allowedTools ?? []).some(\n (name) => name === POSTHOG_MCP_TOOL || name === POSTHOG_MCP_SDK_TOOL,\n );\n}\n\n/** The queue tools a task holds — all of them minus its disallows. Short names.\n * Single source for both the injected inventory and the harness's tool grant. */\nexport function queueTools(disallowedTools: readonly string[]): string[] {\n const disallowed = new Set(\n disallowedTools.map((n) => n.replace(ORCHESTRATOR_TOOL_PREFIX, '')),\n );\n return [...ORCHESTRATOR_TOOLS].filter((t) => !disallowed.has(t));\n}\n\n/** A parsed agent prompt. The frontmatter fields plus the markdown body. */\nexport interface AgentPrompt {\n type: string;\n /** Human-readable title for the TUI; falls back to `type` when absent. */\n label?: string;\n /** The flow this agent belongs to (the program id, e.g. \\`posthog-integration\\`). */\n flow?: string;\n /** Marks the flow's planner: it seeds the queue and is not an enqueueable task. */\n seed: boolean;\n /** Marks a task that runs last: it must depend on every other task in the queue. */\n sink: boolean;\n /**\n * Marks a task only the wizard may queue. The planner never sees the type, so\n * whether it runs is a decision the client makes from what it detected, not\n * one an agent can reach — it can neither invent the task nor forget it.\n */\n runnerSeeded: boolean;\n /** Per-profile model + effort. `pi` = the gpt/pi harness, `sdk` = the anthropic\n * harness. The mapping is not 1:1 across providers, so each agent names both. */\n modelPi?: string;\n effortPi?: ThinkingLevel;\n modelSdk?: string;\n effortSdk?: ThinkingLevel;\n skills: string[];\n allowedTools: string[];\n disallowedTools: string[];\n /**\n * Task types this one runs after. Read differently by the two kinds of task:\n *\n * - **Enqueueable types**: advisory. The planner authors the real graph with\n * `enqueue_task`, passing ids, and its seed prompt describes the shape it\n * should build. Nothing resolves this field for them.\n * - **`runnerSeeded` types**: authoritative. Such a task is queued before the\n * planner runs, so it cannot name ids; the runner resolves these types to\n * the ids the planner produced and applies them (see `seeded-deps.ts`).\n * Empty means \"after everything that is not the sink\".\n */\n dependsOn: string[];\n body: string;\n}\n\n/** The model + effort an agent runs on for a given harness — `pi` picks the gpt\n * column, anything else the sdk (anthropic) column. */\nexport function promptModelFor(\n prompt: AgentPrompt,\n harness: string,\n): { model?: string; effort?: ThinkingLevel } {\n const pi = harness === 'pi';\n return {\n model: pi ? prompt.modelPi : prompt.modelSdk,\n effort: pi ? prompt.effortPi : prompt.effortSdk,\n };\n}\n\nexport interface AgentRegistry {\n /** The flow's task types — every prompt except the seed. */\n readonly types: string[];\n /** The types an agent may enqueue: `types` minus the runner-seeded ones. */\n readonly enqueueableTypes: string[];\n /** The types that run last and must depend on the whole queue. */\n readonly sinkTypes: string[];\n /** The types only the wizard queues, from what it detected before the run. */\n readonly runnerSeededTypes: string[];\n /** The flow's planner, the one prompt marked `seed: true` in its frontmatter. */\n readonly seed?: AgentPrompt;\n get(type: string): AgentPrompt | undefined;\n}\n\n/** The registry for one flow's prompts. Pure; the loader feeds it the fetched set. */\nexport function buildRegistry(\n prompts: readonly AgentPrompt[],\n flow: string,\n opts?: {\n exclude?: readonly string[];\n /** Per-stage pi model/effort overlays, keyed by task type ('seed' for the planner). Applied here — the one place prompts enter the wizard — so every downstream read sees the effective spec. */\n overrides?: Record<\n string,\n { model?: string; effort?: ThinkingLevel } | undefined\n >;\n },\n): AgentRegistry {\n // The harness can exclude task types (CI excludes dashboards). An excluded\n // type does not exist for the run: the seed cannot enqueue it and no agent\n // is ever spun up for it.\n const excluded = new Set(opts?.exclude ?? []);\n const inFlow = prompts\n .filter((p) => p.flow === flow && !excluded.has(p.type))\n .map((p) => {\n const o = opts?.overrides?.[p.seed ? 'seed' : p.type];\n if (!o) return p;\n return {\n ...p,\n modelPi: o.model ?? p.modelPi,\n effortPi: o.effort ?? p.effortPi,\n };\n });\n const byType = new Map(inFlow.map((p) => [p.type, p]));\n const tasks = inFlow.filter((p) => !p.seed);\n return {\n types: tasks.map((p) => p.type),\n enqueueableTypes: tasks.filter((p) => !p.runnerSeeded).map((p) => p.type),\n sinkTypes: tasks.filter((p) => p.sink).map((p) => p.type),\n runnerSeededTypes: tasks.filter((p) => p.runnerSeeded).map((p) => p.type),\n seed: inFlow.find((p) => p.seed),\n get: (type) => byType.get(type),\n };\n}\n\ninterface AgentMenu {\n /** `flow` arrived with context-mill's flow-scoped agents folder; older menus omit it. */\n agents: { id: string; flow?: string; downloadUrl: string }[];\n}\n\n/** A native tool passes through; an MCP tool gets its fully-qualified name. */\nfunction expandToolName(name: string): string {\n if (name === ASK_TOOL) return WIZARD_TOOL_NAMES.wizardAsk;\n if (name === SKILL_MENU_TOOL) return WIZARD_TOOL_NAMES.loadSkillMenu;\n if (name === INSTALL_SKILL_TOOL) return WIZARD_TOOL_NAMES.installSkill;\n if (name === POSTHOG_MCP_TOOL) return POSTHOG_MCP_SDK_TOOL;\n return ORCHESTRATOR_TOOLS.has(name)\n ? `${ORCHESTRATOR_TOOL_PREFIX}${name}`\n : name;\n}\n\n/** A prompt's allow/disallow lists with orchestrator tool names MCP-qualified. */\nexport function agentRunTools(prompt: AgentPrompt): {\n allowedTools: string[];\n disallowedTools: string[];\n} {\n return {\n allowedTools: prompt.allowedTools.map(expandToolName),\n disallowedTools: prompt.disallowedTools.map(expandToolName),\n };\n}\n\nfunction toStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((v): v is string => typeof v === 'string');\n}\n\n/**\n * Parse the leading `---` frontmatter block and the markdown body. The\n * frontmatter is a small, known schema (scalars and inline `[a, b]` arrays), so\n * a tiny parser covers it without a YAML dependency. Inline `# comments` after a\n * value are stripped. `fallbackType` (the menu id) and `fallbackFlow` (the\n * menu entry's flow) apply when the frontmatter omits `type:`/`flow:`.\n */\nexport function parseAgentPrompt(\n text: string,\n fallbackType: string,\n fallbackFlow?: string,\n): AgentPrompt {\n const match = text.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n const frontmatter = match ? match[1] : '';\n const body = (match ? match[2] : text).trim();\n\n const fields: Record<string, unknown> = {};\n for (const rawLine of frontmatter.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\s+#.*$/, '').trim();\n if (!line || line.startsWith('#')) continue;\n const kv = line.match(/^([\\w-]+):\\s*(.*)$/);\n if (!kv) continue;\n const [, key, raw] = kv;\n if (raw.startsWith('[') && raw.endsWith(']')) {\n fields[key] = raw\n .slice(1, -1)\n .split(',')\n .map((s) => s.trim().replace(/^['\"]|['\"]$/g, ''))\n .filter(Boolean);\n } else {\n fields[key] = raw.replace(/^['\"]|['\"]$/g, '');\n }\n }\n\n const str = (v: unknown) => (typeof v === 'string' ? v : undefined);\n // Effort is remote data — reject typos here so downstream carries ThinkingLevel.\n const effort = (v: unknown, key: string): ThinkingLevel | undefined => {\n if (v === undefined) return undefined;\n if (isThinkingLevel(v)) return v;\n logToFile(\n `[agent-prompt] ${fallbackType}: ignoring invalid ${key} \"${String(v)}\"`,\n );\n analytics.wizardCapture('agent prompt invalid effort', {\n task_type: fallbackType,\n key,\n value: String(v),\n });\n return undefined;\n };\n return {\n type: typeof fields.type === 'string' ? fields.type : fallbackType,\n label: typeof fields.label === 'string' ? fields.label : undefined,\n flow: typeof fields.flow === 'string' ? fields.flow : fallbackFlow,\n seed: fields.seed === 'true',\n sink: fields.sink === 'true',\n runnerSeeded: fields.runnerSeeded === 'true',\n modelPi: str(fields.model_pi),\n effortPi: effort(fields.effort_pi, 'effort_pi'),\n modelSdk: str(fields.model_sdk),\n effortSdk: effort(fields.effort_sdk, 'effort_sdk'),\n skills: toStringArray(fields.skills),\n allowedTools: toStringArray(fields.allowedTools),\n disallowedTools: toStringArray(fields.disallowedTools),\n dependsOn: toStringArray(fields.dependsOn),\n body,\n };\n}\n\nasync function fetchText(url: string): Promise<string> {\n const res = await fetchWithRetry(url);\n return res.text();\n}\n\n/**\n * Fetch the agent menu and every agent prompt it lists, parse them, and build\n * the registry for one flow. Throws if the menu cannot be fetched — the\n * orchestrator cannot run without its prompts.\n */\nexport async function loadAgentRegistry(\n skillsBaseUrl: string,\n flow: string,\n opts?: Parameters<typeof buildRegistry>[2],\n): Promise<AgentRegistry> {\n const menuRaw = await fetchText(`${skillsBaseUrl}/agent-menu.json`);\n const menu = JSON.parse(menuRaw) as AgentMenu;\n\n // Menus that carry a flow per entry let us skip other flows' prompts before\n // fetching them; entries without one are fetched and filtered by their\n // frontmatter in buildRegistry, as before.\n const entries = (menu.agents ?? []).filter(\n (entry) => !entry.flow || entry.flow === flow,\n );\n const prompts = await Promise.all(\n entries.map(async (entry) => {\n const text = await fetchText(entry.downloadUrl);\n return parseAgentPrompt(text, entry.id, entry.flow);\n }),\n );\n\n return buildRegistry(prompts, flow, opts);\n}\n\n/**\n * Render a task's own inputs into a section, so a fanned-out task (e.g. one\n * `capture` per event) sees the specific thing it owns. Empty when there are none.\n */\nfunction renderInputs(task: QueuedTask): string {\n const entries = Object.entries(task.inputs ?? {});\n if (entries.length === 0) return '';\n const lines = entries.map(([k, v]) => `- ${k}: ${formatInputValue(v)}`);\n return `## Your task input\\n\\n${lines.join('\\n')}`;\n}\n\nfunction formatInputValue(value: unknown): string {\n if (typeof value === 'string') return value;\n return JSON.stringify(value);\n}\n\n/**\n * The ids of every task `task` transitively depends on — the full upstream\n * chain, not just direct dependencies — ordered roots-first, each once. A `seen`\n * set dedupes diamonds and guards against cycles.\n */\nfunction ancestorIds(task: QueuedTask, store: QueueStore): string[] {\n const seen = new Set<string>();\n const ordered: string[] = [];\n const visit = (id: string): void => {\n if (seen.has(id)) return;\n seen.add(id);\n const t = store.get(id);\n if (!t) return;\n for (const dep of t.dependsOn) visit(dep); // ancestors before dependents\n ordered.push(id);\n };\n for (const dep of task.dependsOn) visit(dep);\n return ordered;\n}\n\n/**\n * Render the handoffs of every step `task` transitively depends on into a context\n * section, so a fresh agent sees the whole upstream chain — not just its direct\n * dependencies. Reliability over token economy: a step must never have to\n * re-discover what any ancestor already established just because an intermediate\n * handoff happened to omit it. Empty when there are no completed ancestors.\n */\nfunction renderHandoffContext(task: QueuedTask, store: QueueStore): string {\n const lines: string[] = [];\n for (const id of ancestorIds(task, store)) {\n const dep = store.get(id);\n const handoff = store.readHandoff(id);\n if (!dep || !handoff) continue;\n lines.push(`### ${dep.type}`);\n lines.push(`- did: ${handoff.did}`);\n lines.push(`- for you: ${handoff.forNextAgent}`);\n if (handoff.filesTouched?.length) {\n lines.push(`- files: ${handoff.filesTouched.join(', ')}`);\n }\n if (handoff.evidence) {\n lines.push(`- evidence: ${handoff.evidence}`);\n }\n if (handoff.assumptions) {\n lines.push(`- assumed: ${handoff.assumptions}`);\n }\n if (handoff.reportSection) {\n lines.push(`- report section:\\n${handoff.reportSection}`);\n }\n lines.push('');\n }\n if (lines.length === 0) return '';\n return `## Context from previous steps\\n\\n${lines.join('\\n')}`.trim();\n}\n\n/**\n * Resolve a queued task to its run config: the prompt body (with upstream\n * handoffs appended), the model, and the tool lists with orchestrator tool names\n * MCP-qualified. The model precedence is enqueue override, then prompt, then\n * default. Throws if no prompt is registered for the task's type.\n */\nexport function resolveTask(\n registry: AgentRegistry,\n task: QueuedTask,\n store: QueueStore,\n): ResolvedTask {\n const prompt = registry.get(task.type);\n if (!prompt) {\n throw new Error(`No agent prompt registered for task type \"${task.type}\"`);\n }\n\n const body = [\n renderInputs(task),\n prompt.body,\n renderHandoffContext(task, store),\n ]\n .filter(Boolean)\n .join('\\n\\n');\n\n return {\n ...agentRunTools(prompt),\n prompt: body,\n skills: prompt.skills,\n };\n}\n\n/** The model + effort a task runs on for a harness: enqueue override, then the\n * prompt's per-profile frontmatter; the caller's switchboard pick is the fallback. */\nexport function taskModelSpec(\n registry: AgentRegistry,\n task: QueuedTask,\n harness: string,\n): { model?: string; effort?: ThinkingLevel } {\n const picked = promptModelFor(\n registry.get(task.type) ?? EMPTY_PROMPT,\n harness,\n );\n return {\n model: task.model ?? picked.model,\n effort: picked.effort,\n };\n}\n\nconst EMPTY_PROMPT = {} as AgentPrompt;\n"],"mappings":";;;;;AAgDA,SAAS,eAAe,KAAwC;AAK9D,QAAO;;;wBAGe,IAAI,UAAU;0BACZ,IAAI,cAAc;kBAC1B,IAAI,KAAK,QAAQ;wEACqC,IAAI,KAAK;;;AAIjF,SAAS,iBAAiB,KAA+C;AACvE,KAAI,CAAC,IAAI,YAAa,QAAO;AAC7B,QAAO,8DAA8D,IAAI,YAAY;;;AAIvF,SAAS,sBAAsB,KAA+C;AAC5E,KAAI,CAAC,IAAI,iBAAkB,QAAO;AAClC,QAAO,iDAAiD,IAAI,iBAAiB;;;;;;;;;;AAW/E,SAAgB,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CAAqC,MAAM,KAAK,KAAK,GAAG,MAAM;;;;;;;;AASvE,SAAgB,YACd,UACA,MACA,OACc;CACd,MAAM,SAAS,SAAS,IAAI,KAAK,KAAK;AACtC,KAAI,CAAC,OACH,OAAM,IAAI,MAAM,6CAA6C,KAAK,KAAK,GAAG;CAG5E,MAAM,OAAO;EACX,aAAa,KAAK;EAClB,OAAO;EACP,qBAAqB,MAAM,MAAM;EAClC,CACE,OAAO,QAAQ,CACf,KAAK,OAAO;AAEf,QAAO;EACL,GAAG,cAAc,OAAO;EACxB,QAAQ;EACR,QAAQ,OAAO;EAChB;;;;AAKH,SAAgB,cACd,UACA,MACA,SAC4C;CAC5C,MAAM,SAAS,eACb,SAAS,IAAI,KAAK,KAAK,IAAI,cAC3B,QACD;AACD,QAAO;EACL,OAAO,KAAK,SAAS,OAAO;EAC5B,QAAQ,OAAO;EAChB;;AAGH,MAAM,eAAe,EAAE"}
@@ -1,17 +1,18 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
2
- import { A as GPT5_6_LUNA_MODEL, D as DEFAULT_AGENT_MODEL, F as Harness, M as GPT5_6_TERRA_MODEL, _ as evaluateWizardReadiness, a as getLogFilePath, c as WIZARD_BENCHMARK_FILE, ct as WIZARD_ORCHESTRATOR_OVERRIDE_FLAG_KEY, et as SONNET_5_MODEL, f as getUI, ft as WIZARD_SELF_DRIVING_USE_PI_HARNESS_FLAG_KEY, g as SIGNUP_WIZARD_READINESS_CONFIG, gt as VERSION, h as SERVICE_LABELS, i as enableDebugLogs, j as GPT5_6_SOL_MODEL, l as WIZARD_LOG_FILE, lt as WIZARD_ORCHESTRATOR_SEEDED_TASKS_FLAG_KEY, mt as getSkillsBaseUrl, o as initLogFile, rt as WIZARD_CONTACT_EMAIL, s as logToFile, st as WIZARD_ORCHESTRATOR_FLAG_KEY, t as configureLogFile, tt as Sequence, v as getBlockingServiceKeys, vt as RUN_SURFACE, xt as runtimeEnv } from "./debug-BKqv-yfT.js";
3
- import { a as ciExcludedTaskTypes, n as analytics, r as groupsFromUser } from "./analytics-D8JNuPAT.js";
4
- import { c as mcpUrlFor, t as getOrAskForProjectData } from "./setup-utils-aWZEdfwh.js";
5
- import "./wizard-session-DTyLMPsX.js";
6
- import { i as wizardAbort, n as registerCleanup, t as WizardError } from "./wizard-abort-D9jiMkZA.js";
7
- import { n as isNonInteractiveEnvironment } from "./environment-Cl-fIQku.js";
8
- import { c as uncoveredBySink, d as SkipReason, f as TaskStatus, g as isValidModel, l as QUEUE_DIR_NAME, s as dependencyClosure, u as QueueStore, v as requireKnownModel } from "./queue-tools-DABh1Ssc.js";
9
- import { G as createTriageLLMProvider, M as installSkillById, c as classifySettingsConflicts, i as runAgent$1, j as fetchSkillMenu, n as buildRunTags, o as backupAndFixClaudeSettings, p as AgentSignals, r as initializeAgent, s as checkAllSettingsConflicts, u as restoreClaudeSettings, z as createWizardAskBridge } from "./agent-interface-D3MNaDp3.js";
10
- import { a as flushScanReport, m as writeScanReport, o as formatScanReport, s as formatYaraAbortMessage } from "./yara-hooks-BXDBIOBq.js";
11
- import { a as piBackend, s as createAioCapture } from "./pi-W-4RUPFY.js";
12
- import { a as detectNodePackageManagers } from "./package-manager-BQDHm7ER.js";
13
- import { t as FRAMEWORK_REGISTRY } from "./registry-CxNpCNAj.js";
14
- import { a as assembleTaskPrompt, d as taskModelSpec, i as assembleSeedPrompt, n as agentRunTools, o as loadAgentRegistry, s as promptModelFor, t as ASK_TOOL, u as resolveTask } from "./agent-prompt-loader-D8Bajo-L.js";
2
+ import { a as AgentSignals, i as AGENT_ERROR_CODE, l as ErrorCodes, n as skillErrorCode } from "./errors-BHervYGs.js";
3
+ import { A as GPT5_6_LUNA_MODEL, D as DEFAULT_AGENT_MODEL, F as Harness, M as GPT5_6_TERRA_MODEL, _ as evaluateWizardReadiness, a as getLogFilePath, c as WIZARD_BENCHMARK_FILE, ct as WIZARD_ORCHESTRATOR_OVERRIDE_FLAG_KEY, et as SONNET_5_MODEL, f as getUI, ft as WIZARD_SELF_DRIVING_USE_PI_HARNESS_FLAG_KEY, g as SIGNUP_WIZARD_READINESS_CONFIG, gt as VERSION, h as SERVICE_LABELS, i as enableDebugLogs, j as GPT5_6_SOL_MODEL, l as WIZARD_LOG_FILE, lt as WIZARD_ORCHESTRATOR_SEEDED_TASKS_FLAG_KEY, mt as getSkillsBaseUrl, o as initLogFile, rt as WIZARD_CONTACT_EMAIL, s as logToFile, st as WIZARD_ORCHESTRATOR_FLAG_KEY, t as configureLogFile, tt as Sequence, v as getBlockingServiceKeys, vt as RUN_SURFACE, xt as runtimeEnv } from "./debug-aA5dm2MR.js";
4
+ import { a as ciExcludedTaskTypes, n as analytics, r as groupsFromUser } from "./analytics-tF06lcmE.js";
5
+ import { c as mcpUrlFor, t as getOrAskForProjectData } from "./setup-utils-BLKhAx6g.js";
6
+ import "./wizard-session-C_7r3-rO.js";
7
+ import { i as wizardAbort, n as registerCleanup, t as WizardError } from "./wizard-abort-Bv87YVSp.js";
8
+ import { n as isNonInteractiveEnvironment } from "./environment-BGUJxuvj.js";
9
+ import { A as installSkillById, R as createWizardAskBridge, W as createTriageLLMProvider, c as classifySettingsConflicts, i as runAgent$1, k as fetchSkillMenu, n as buildRunTags, o as backupAndFixClaudeSettings, q as gatewayAuth, r as initializeAgent, s as checkAllSettingsConflicts, u as restoreClaudeSettings } from "./agent-interface-CaEptZuu.js";
10
+ import { c as uncoveredBySink, d as SkipReason, f as TaskStatus, g as isValidModel, l as QUEUE_DIR_NAME, s as dependencyClosure, u as QueueStore, v as requireKnownModel } from "./queue-tools-i_TmeI02.js";
11
+ import { a as flushScanReport, m as writeScanReport, o as formatScanReport, s as formatYaraAbortMessage } from "./yara-hooks-DeonKbE_.js";
12
+ import { a as piBackend, s as createAioCapture } from "./pi-CKyt4bcu.js";
13
+ import { a as detectNodePackageManagers } from "./package-manager-BPoVLj7W.js";
14
+ import { t as FRAMEWORK_REGISTRY } from "./registry-CbXqxcX0.js";
15
+ import { a as assembleTaskPrompt, d as taskModelSpec, i as assembleSeedPrompt, n as agentRunTools, o as loadAgentRegistry, s as promptModelFor, t as ASK_TOOL, u as resolveTask } from "./agent-prompt-loader-DZHc9tIG.js";
15
16
  import fs, { cpSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "fs";
16
17
  import * as path$1 from "path";
17
18
  import path from "path";
@@ -86,6 +87,7 @@ const anthropicBackend = {
86
87
  skillsBaseUrl,
87
88
  wizardFlags,
88
89
  wizardMetadata,
90
+ programId: boot.programId,
89
91
  integrationLabel: config.integrationLabel,
90
92
  askBridge,
91
93
  askMaxQuestions: config.maxQuestions,
@@ -127,6 +129,7 @@ const anthropicBackend = {
127
129
  host: boot.credentials.host,
128
130
  detectPackageManager: detectNodePackageManagers,
129
131
  skillsBaseUrl: boot.skillsBaseUrl,
132
+ programId: boot.programId,
130
133
  wizardFlags: boot.wizardFlags,
131
134
  wizardMetadata: boot.wizardMetadata,
132
135
  integrationLabel: programConfig.id,
@@ -1357,6 +1360,7 @@ function assemblePrompt(runDef, ctx) {
1357
1360
  //#region src/lib/agent/runner/shared/errors.ts
1358
1361
  async function abortOnInstallFailure(integrationLabel, result) {
1359
1362
  if (result.kind === "ok") return;
1363
+ const code = skillErrorCode(result) ?? void 0;
1360
1364
  await wizardAbort({
1361
1365
  message: (() => {
1362
1366
  switch (result.kind) {
@@ -1365,12 +1369,13 @@ async function abortOnInstallFailure(integrationLabel, result) {
1365
1369
  case "download-failed": return `Failed to install skill: ${result.message}\nPlease try again.`;
1366
1370
  }
1367
1371
  })(),
1372
+ code,
1368
1373
  error: new WizardError(`Skill install failed: ${result.kind}`, {
1369
1374
  integration: integrationLabel,
1370
1375
  error_type: result.kind,
1371
1376
  platform: process.platform,
1372
1377
  ...result.kind === "download-failed" ? { error_detail: result.message.slice(0, 500) } : {}
1373
- })
1378
+ }, code)
1374
1379
  });
1375
1380
  }
1376
1381
  //#endregion
@@ -1444,16 +1449,21 @@ async function runLinearProgram(session, config, programConfig, boot, composed =
1444
1449
  if (agentResult.error === "WIZARD_ABORT") {
1445
1450
  const reason = agentResult.message ?? "";
1446
1451
  const matched = config.abortCases?.find((c) => c.match.test(reason));
1452
+ const abortCode = matched?.errorCode ?? ErrorCodes.AgentAbort;
1447
1453
  const outroData = matched ? {
1448
1454
  kind: "error",
1449
1455
  message: matched.message,
1450
1456
  body: matched.body,
1451
- docsUrl: matched.docsUrl
1457
+ docsUrl: matched.docsUrl,
1458
+ errorCode: abortCode,
1459
+ errorDetail: { reason }
1452
1460
  } : {
1453
1461
  kind: "error",
1454
1462
  message: `${config.integrationLabel} aborted`,
1455
1463
  body: reason || "The agent aborted the program.",
1456
- docsUrl: config.docsUrl
1464
+ docsUrl: config.docsUrl,
1465
+ errorCode: abortCode,
1466
+ errorDetail: { reason }
1457
1467
  };
1458
1468
  analytics.wizardCapture("agent aborted", {
1459
1469
  integration: config.integrationLabel,
@@ -1462,14 +1472,16 @@ async function runLinearProgram(session, config, programConfig, boot, composed =
1462
1472
  });
1463
1473
  await wizardAbort({
1464
1474
  outroData,
1475
+ code: abortCode,
1465
1476
  error: new WizardError(`Agent aborted: ${reason}`, {
1466
1477
  integration: config.integrationLabel,
1467
1478
  error_type: "WIZARD_ABORT",
1468
1479
  reason
1469
- })
1480
+ }, abortCode)
1470
1481
  });
1471
1482
  }
1472
1483
  if (agentResult.error === "WIZARD_MCP_MISSING") await wizardAbort({
1484
+ code: AGENT_ERROR_CODE["WIZARD_MCP_MISSING"],
1473
1485
  message: `Could not access the PostHog MCP server
1474
1486
 
1475
1487
  The wizard was unable to connect to the PostHog MCP server.
@@ -1480,9 +1492,10 @@ Please try again, or check the documentation:\n${config.docsUrl}`,
1480
1492
  integration: config.integrationLabel,
1481
1493
  error_type: "WIZARD_MCP_MISSING",
1482
1494
  signal: AgentSignals.ERROR_MCP_MISSING
1483
- })
1495
+ }, AGENT_ERROR_CODE["WIZARD_MCP_MISSING"])
1484
1496
  });
1485
1497
  if (agentResult.error === "WIZARD_RESOURCE_MISSING") await wizardAbort({
1498
+ code: AGENT_ERROR_CODE["WIZARD_RESOURCE_MISSING"],
1486
1499
  message: `Could not access the setup resource
1487
1500
 
1488
1501
  This may indicate a version mismatch or a temporary service issue.
@@ -1492,14 +1505,15 @@ Please try again, or check the documentation:\n${config.docsUrl}`,
1492
1505
  integration: config.integrationLabel,
1493
1506
  error_type: "WIZARD_RESOURCE_MISSING",
1494
1507
  signal: AgentSignals.ERROR_RESOURCE_MISSING
1495
- })
1508
+ }, AGENT_ERROR_CODE["WIZARD_RESOURCE_MISSING"])
1496
1509
  });
1497
1510
  if (agentResult.error === "WIZARD_YARA_VIOLATION") await wizardAbort({
1511
+ code: AGENT_ERROR_CODE["WIZARD_YARA_VIOLATION"],
1498
1512
  message: formatYaraAbortMessage(),
1499
1513
  error: new WizardError("YARA scanner terminated session", {
1500
1514
  integration: config.integrationLabel,
1501
1515
  error_type: "WIZARD_YARA_VIOLATION"
1502
- })
1516
+ }, AGENT_ERROR_CODE["WIZARD_YARA_VIOLATION"])
1503
1517
  });
1504
1518
  if (agentResult.error === "WIZARD_NO_PROGRESS") {
1505
1519
  analytics.wizardCapture("agent no progress", {
@@ -1507,11 +1521,12 @@ Please try again, or check the documentation:\n${config.docsUrl}`,
1507
1521
  error_type: "WIZARD_NO_PROGRESS"
1508
1522
  });
1509
1523
  await wizardAbort({
1524
+ code: AGENT_ERROR_CODE["WIZARD_NO_PROGRESS"],
1510
1525
  message: "The Wizard exited without changing your project. Please contact the PostHog team with wizard@posthog.com about this error.",
1511
1526
  error: new WizardError("Agent made no progress", {
1512
1527
  integration: config.integrationLabel,
1513
1528
  error_type: "WIZARD_NO_PROGRESS"
1514
- })
1529
+ }, AGENT_ERROR_CODE["WIZARD_NO_PROGRESS"])
1515
1530
  });
1516
1531
  }
1517
1532
  if (agentResult.error === "WIZARD_INCOMPLETE_TASKS") {
@@ -1520,11 +1535,12 @@ Please try again, or check the documentation:\n${config.docsUrl}`,
1520
1535
  error_type: "WIZARD_INCOMPLETE_TASKS"
1521
1536
  });
1522
1537
  await wizardAbort({
1538
+ code: AGENT_ERROR_CODE["WIZARD_INCOMPLETE_TASKS"],
1523
1539
  message: "The Wizard exited without completing its planned tasks. Please contact the PostHog team with wizard@posthog.com about this error.",
1524
1540
  error: new WizardError("Agent left planned tasks incomplete", {
1525
1541
  integration: config.integrationLabel,
1526
1542
  error_type: "WIZARD_INCOMPLETE_TASKS"
1527
- })
1543
+ }, AGENT_ERROR_CODE["WIZARD_INCOMPLETE_TASKS"])
1528
1544
  });
1529
1545
  }
1530
1546
  if (agentResult.error === "WIZARD_RATE_LIMIT" || agentResult.error === "WIZARD_API_ERROR") {
@@ -1534,11 +1550,12 @@ Please try again, or check the documentation:\n${config.docsUrl}`,
1534
1550
  error_message: agentResult.message
1535
1551
  });
1536
1552
  await wizardAbort({
1553
+ code: AGENT_ERROR_CODE[agentResult.error],
1537
1554
  message: `API Error\n\n${agentResult.message || "Unknown error"}\n\nPlease report this to: wizard@posthog.com`,
1538
1555
  error: new WizardError(`API error: ${agentResult.message}`, {
1539
1556
  integration: config.integrationLabel,
1540
1557
  error_type: agentResult.error
1541
- })
1558
+ }, AGENT_ERROR_CODE[agentResult.error])
1542
1559
  });
1543
1560
  }
1544
1561
  if (config.postRun) await config.postRun(session, credentials);
@@ -2077,19 +2094,23 @@ async function runOrchestrator(session, config, programConfig, boot) {
2077
2094
  framework
2078
2095
  });
2079
2096
  }
2080
- if (missingVariants.length > 0) await wizardAbort({
2081
- message: `Setup instructions for this project failed to download.
2097
+ if (missingVariants.length > 0) {
2098
+ const docsUrl = framework ? FRAMEWORK_REGISTRY[framework]?.metadata.docsUrl : void 0;
2099
+ await wizardAbort({
2100
+ code: ErrorCodes.AgentOrchestratorSkillVariantMissing,
2101
+ message: `Setup instructions for this project failed to download.
2082
2102
  Please try again, or contact wizard@posthog.com.
2083
2103
 
2084
2104
  You can also set up with your agent by downloading the skills here:
2085
2105
  https://github.com/PostHog/context-mill/releases
2086
2106
  or integrate manually here:
2087
- ${(framework ? FRAMEWORK_REGISTRY[framework]?.docsUrl : void 0) ?? "https://posthog.com/docs"}`,
2088
- error: new WizardError("Orchestrator preflight: skill variant missing", {
2089
- missing: missingVariants.join(", "),
2090
- framework
2091
- })
2092
- });
2107
+ ${docsUrl ?? "https://posthog.com/docs"}`,
2108
+ error: new WizardError("Orchestrator preflight: skill variant missing", {
2109
+ missing: missingVariants.join(", "),
2110
+ framework
2111
+ }, ErrorCodes.AgentOrchestratorSkillVariantMissing)
2112
+ });
2113
+ }
2093
2114
  const promptContext = {
2094
2115
  projectId: boot.credentials.projectId,
2095
2116
  projectApiKey: boot.credentials.projectApiKey,
@@ -2169,6 +2190,7 @@ or integrate manually here:
2169
2190
  spinnerMessage: "Planning the integration...",
2170
2191
  successMessage: "Planned the integration",
2171
2192
  additionalFeatureQueue: [],
2193
+ requestRemark: false,
2172
2194
  analyticsProperties: {
2173
2195
  task_type: "seed",
2174
2196
  harness: seedPick.harness
@@ -2213,11 +2235,12 @@ or integrate manually here:
2213
2235
  if (unwaited.length > 0) {
2214
2236
  analytics.wizardCapture("orchestrator sink invariant violated", { uncovered_types: unwaited.map((t) => t.type) });
2215
2237
  await wizardAbort({
2238
+ code: ErrorCodes.AgentOrchestratorSinkInvariant,
2216
2239
  message: `The wizard could not plan this setup: the final step would have skipped ${unwaited.map((t) => t.type).join(", ")}.\n\nPlease report this to: ${WIZARD_CONTACT_EMAIL}`,
2217
2240
  error: new WizardError("orchestrator sink does not cover the queue", {
2218
2241
  uncovered: unwaited.map((t) => `${t.type} (${t.id})`).join(", "),
2219
2242
  queue_state: JSON.stringify(store.list())
2220
- })
2243
+ }, ErrorCodes.AgentOrchestratorSinkInvariant)
2221
2244
  });
2222
2245
  }
2223
2246
  const taskSkillsRoot = path$1.join(QUEUE_DIR_NAME, "skills");
@@ -2275,6 +2298,7 @@ or integrate manually here:
2275
2298
  spinnerMessage: "",
2276
2299
  successMessage: "",
2277
2300
  additionalFeatureQueue: [],
2301
+ requestRemark: false,
2278
2302
  analyticsProperties: {
2279
2303
  task_type: task.type,
2280
2304
  task_id: task.id,
@@ -2334,15 +2358,17 @@ or integrate manually here:
2334
2358
  const failedTypes = verdict.requiredFailedTypes.join(", ");
2335
2359
  const whatFailed = failedTypes ? `the ${failedTypes} step failed` : `${blocked} steps never ran`;
2336
2360
  const missingScopes = boot.credentials.missingScopes ?? [];
2361
+ const message = missingScopes.length > 0 ? `The wizard could not finish setup: ${whatFailed}, and this run was authorized without the following permission${missingScopes.length === 1 ? "" : "s"}: ${missingScopes.join(", ")}.\n\nPlease try again, approving all permissions on the PostHog authorization screen. If it still fails, report it to: ${WIZARD_CONTACT_EMAIL}` : `The wizard was unable to set up PostHog: ${whatFailed}.\n\nPlease report this to: ${WIZARD_CONTACT_EMAIL}`;
2337
2362
  await wizardAbort({
2338
- message: missingScopes.length > 0 ? `The wizard could not finish setup: ${whatFailed}, and this run was authorized without the following permission${missingScopes.length === 1 ? "" : "s"}: ${missingScopes.join(", ")}.\n\nPlease try again, approving all permissions on the PostHog authorization screen. If it still fails, report it to: ${WIZARD_CONTACT_EMAIL}` : `The wizard was unable to set up PostHog: ${whatFailed}.\n\nPlease report this to: ${WIZARD_CONTACT_EMAIL}`,
2363
+ code: ErrorCodes.AgentOrchestratorTasksFailed,
2364
+ message,
2339
2365
  error: new WizardError("orchestrator drain ended with failed tasks", {
2340
2366
  tasks_failed: summary.failed,
2341
2367
  tasks_blocked: blocked,
2342
2368
  failed_types: failedTypes,
2343
2369
  missing_oauth_scopes: missingScopes.join(" "),
2344
2370
  queue_state: JSON.stringify(store.list())
2345
- })
2371
+ }, ErrorCodes.AgentOrchestratorTasksFailed)
2346
2372
  });
2347
2373
  }
2348
2374
  const optionalFailedCount = verdict.optionalFailedTypes.length;
@@ -2528,9 +2554,18 @@ function resolveBinding(ctx, role = "default") {
2528
2554
  * answer. Per-program disabling is done by adding WIZARD_ASK_TOOL_NAME to
2529
2555
  * the program's `disallowedTools` so the SDK rejects calls outright.
2530
2556
  * Extracted so the policy can be unit-tested directly.
2557
+ *
2558
+ * `session.e2eAsk` is the one escape hatch. The e2e harness runs a `ci`
2559
+ * session, but it does have an answerer — the driver loop answers each
2560
+ * `wizard_ask` batch from the program's e2e profile. Without the flag the
2561
+ * agent-in-the-loop layer (the ask bridge in both sequence arms, and the
2562
+ * orchestrator's seeded warehouse task) stays unreachable from a test.
2563
+ *
2564
+ * Only the e2e TUI host sets the flag, from the `E2E_ASK` env var. No CLI flag
2565
+ * populates it, so plain `--ci` and `--signup` runs behave exactly as before.
2531
2566
  */
2532
2567
  function shouldDisableAsk(session) {
2533
- return session.ci || session.signup;
2568
+ return (session.ci || session.signup) && !session.e2eAsk;
2534
2569
  }
2535
2570
  function sessionToOptions(session) {
2536
2571
  return {
@@ -2568,7 +2603,10 @@ async function bootstrapProgram(session, config, programConfig) {
2568
2603
  const blockingLabels = getBlockingServiceKeys(readiness.health, readinessConfig).map((k) => `${SERVICE_LABELS[k]} (${readiness.health[k].status})`);
2569
2604
  logToFile(`[agent-runner] blocked by: ${blockingLabels.join(", ")}`);
2570
2605
  await getUI().showBlockingOutage(readiness);
2571
- if (!isNonInteractiveEnvironment()) await wizardAbort({ message: "Cannot start — external services are down:\n" + blockingLabels.map((l) => ` - ${l}`).join("\n") + "\n\nPlease try again later." });
2606
+ if (!isNonInteractiveEnvironment()) await wizardAbort({
2607
+ code: ErrorCodes.EnvServiceOutage,
2608
+ message: "Cannot start — external services are down:\n" + blockingLabels.map((l) => ` - ${l}`).join("\n") + "\n\nPlease try again later."
2609
+ });
2572
2610
  } else if (readiness.decision === "yes_with_warnings") getUI().setReadinessWarnings(readiness);
2573
2611
  }
2574
2612
  const settingsConflicts = checkAllSettingsConflicts(session.installDir);
@@ -2598,6 +2636,10 @@ async function bootstrapProgram(session, config, programConfig) {
2598
2636
  unfixable = [...failClosed, ...autoFix];
2599
2637
  }
2600
2638
  if (unfixable.length > 0) {
2639
+ if (isNonInteractiveEnvironment()) await wizardAbort({
2640
+ code: ErrorCodes.SettingsUnfixableConflict,
2641
+ message: "Cannot start — a Claude settings file redirects the agent away from the PostHog gateway and cannot be neutralized automatically:\n" + unfixable.map((c) => ` - ${c.source} (${c.path}): ${c.keys.join(", ")}`).join("\n") + "\n\nRemove the conflicting keys and re-run the wizard."
2642
+ });
2601
2643
  await getUI().showSettingsOverride(unfixable, () => backupAndFixClaudeSettings(session.installDir));
2602
2644
  logToFile("[agent-runner] settings override resolved");
2603
2645
  }
@@ -2631,16 +2673,20 @@ async function bootstrapProgram(session, config, programConfig) {
2631
2673
  skillId: config.skillId
2632
2674
  });
2633
2675
  const credentials = session.credentials;
2676
+ const auth = await gatewayAuth(credentials.host, credentials.accessToken, programConfig.id);
2634
2677
  return {
2635
2678
  skillsBaseUrl,
2636
2679
  credentials,
2680
+ programId: programConfig.id,
2637
2681
  wizardFlags,
2638
2682
  wizardFlagPayloads,
2639
2683
  wizardMetadata,
2640
2684
  project,
2641
2685
  triageProvider: createTriageLLMProvider({
2642
- baseURL: credentials.host.gatewayUrl,
2643
- authToken: credentials.accessToken,
2686
+ baseURL: auth.gatewayUrl,
2687
+ authToken: auth.token,
2688
+ edition: auth.edition,
2689
+ teamId: auth.teamId,
2644
2690
  wizardMetadata: {
2645
2691
  ...wizardMetadata,
2646
2692
  call_type: "yara-triage"
@@ -2752,4 +2798,4 @@ var agent_runner_exports = /* @__PURE__ */ __exportAll({ runAgent: () => runAgen
2752
2798
  //#endregion
2753
2799
  export { formatCostUsd as a, computeTokenCostUsd as i, runAgent as n, formatTokenCount as o, shouldDisableAsk as r, authenticate as s, agent_runner_exports as t };
2754
2800
 
2755
- //# sourceMappingURL=agent-runner-DEeMqJxy.js.map
2801
+ //# sourceMappingURL=agent-runner-Do5kyhPo.js.map