@posthog/wizard 2.76.1 → 2.78.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 (176) hide show
  1. package/README.md +30 -15
  2. package/dist/README.md +16 -15
  3. package/dist/{add-mcp-server-to-clients-4yHaRvOo.js → add-mcp-server-to-clients-JMv8LP-O.js} +429 -114
  4. package/dist/add-mcp-server-to-clients-JMv8LP-O.js.map +1 -0
  5. package/dist/agent-bCZ3i3fh.js +3085 -0
  6. package/dist/agent-bCZ3i3fh.js.map +1 -0
  7. package/dist/{agent-interface-DPaPdIjS.js → agent-interface-BAOIHuXS.js} +452 -377
  8. package/dist/agent-interface-BAOIHuXS.js.map +1 -0
  9. package/dist/{agent-prompt-loader-BlhabNM2.js → agent-prompt-loader-7Pd4CfZO.js} +24 -8
  10. package/dist/agent-prompt-loader-7Pd4CfZO.js.map +1 -0
  11. package/dist/analytics-BcV-WCM4.js +2 -0
  12. package/dist/{analytics-DSVyjIVF.js → analytics-CHCZ_qUR.js} +10 -6
  13. package/dist/analytics-CHCZ_qUR.js.map +1 -0
  14. package/dist/{api-Ci0dZWLR.js → api-Diy_2fp8.js} +4 -17
  15. package/dist/api-Diy_2fp8.js.map +1 -0
  16. package/dist/bin.js +410 -68
  17. package/dist/bin.js.map +1 -1
  18. package/dist/{bounded-fs-FbZJ_vJ_.js → bounded-fs-Bx9zTe6m.js} +4 -4
  19. package/dist/bounded-fs-Bx9zTe6m.js.map +1 -0
  20. package/dist/check-screens.tsx +1 -1
  21. package/dist/{ci-install-CEVCqahf.js → ci-install-CDdQYsPe.js} +6 -5
  22. package/dist/ci-install-CDdQYsPe.js.map +1 -0
  23. package/dist/constants-jFI2SaE1.js +260 -0
  24. package/dist/constants-jFI2SaE1.js.map +1 -0
  25. package/dist/debug-Ch4BDOtD.js +171 -0
  26. package/dist/debug-Ch4BDOtD.js.map +1 -0
  27. package/dist/{debug-C6KWXbQi.js → debug-M2gV2iDq.js} +1 -1
  28. package/dist/{defaults-DulzMJpN.js → defaults-C6J7yL4O.js} +26 -3
  29. package/dist/defaults-C6J7yL4O.js.map +1 -0
  30. package/dist/endpoints-DCVbM06L.js +108 -0
  31. package/dist/endpoints-DCVbM06L.js.map +1 -0
  32. package/dist/{env-api-key-DwmkB3fm.js → env-api-key-Qx8NnYHm.js} +3 -3
  33. package/dist/env-api-key-Qx8NnYHm.js.map +1 -0
  34. package/dist/{environment-1wA7uwAS.js → environment-B07Bmxae.js} +6 -6
  35. package/dist/environment-B07Bmxae.js.map +1 -0
  36. package/dist/{errors--OqLxmWR.js → errors-CQ9kttJD.js} +30 -35
  37. package/dist/errors-CQ9kttJD.js.map +1 -0
  38. package/dist/{file-C3HGL1IM.js → file-BcLTjU16.js} +2 -2
  39. package/dist/{file-C3HGL1IM.js.map → file-BcLTjU16.js.map} +1 -1
  40. package/dist/{file-watcher-D8s0b-VT.js → file-watcher-DWc_bTs6.js} +2 -2
  41. package/dist/{file-watcher-D8s0b-VT.js.map → file-watcher-DWc_bTs6.js.map} +1 -1
  42. package/dist/{gateway-session-OqzCMpZ9.js → gateway-CjoShdLa.js} +175 -20
  43. package/dist/gateway-CjoShdLa.js.map +1 -0
  44. package/dist/generate-version.cjs +1 -1
  45. package/dist/{headless-ui-DRGWDg9Z.js → headless-ui-BFFmYC4v.js} +13 -2
  46. package/dist/headless-ui-BFFmYC4v.js.map +1 -0
  47. package/dist/{interactive-B6OlvhSf.js → interactive-D6zV7brJ.js} +2 -2
  48. package/dist/{interactive-B6OlvhSf.js.map → interactive-D6zV7brJ.js.map} +1 -1
  49. package/dist/{local-dev-DPZiIPCK.js → local-dev-McsurOC-.js} +2 -2
  50. package/dist/local-dev-McsurOC-.js.map +1 -0
  51. package/dist/logging-ui-_TwoMNbG.js +226 -0
  52. package/dist/logging-ui-_TwoMNbG.js.map +1 -0
  53. package/dist/mcp-DAgaoGk5.js +97 -0
  54. package/dist/mcp-DAgaoGk5.js.map +1 -0
  55. package/dist/{mcp-prompt-streaming-E1d8DJcX.js → mcp-prompt-streaming-I2U_X7BC.js} +7 -6
  56. package/dist/mcp-prompt-streaming-I2U_X7BC.js.map +1 -0
  57. package/dist/{mint-failure-C82j0RMC.js → mint-failure-D4nd2XmZ.js} +134 -48
  58. package/dist/mint-failure-D4nd2XmZ.js.map +1 -0
  59. package/dist/models-DDdBJKwT.js +83 -0
  60. package/dist/models-DDdBJKwT.js.map +1 -0
  61. package/dist/{non-interactive-DGT2H_n4.js → non-interactive-Dzow7YKY.js} +3 -3
  62. package/dist/non-interactive-Dzow7YKY.js.map +1 -0
  63. package/dist/oauth-session-DJ8h6GFa.js +74 -0
  64. package/dist/oauth-session-DJ8h6GFa.js.map +1 -0
  65. package/dist/{orchestrator-tools-BBBNV1z5.js → orchestrator-tools-szcdscwn.js} +5 -5
  66. package/dist/orchestrator-tools-szcdscwn.js.map +1 -0
  67. package/dist/{package-json-xt3eeyBI.js → package-json-DY70kkNp.js} +2 -2
  68. package/dist/package-json-DY70kkNp.js.map +1 -0
  69. package/dist/{pi-fG5fT50Y.js → pi-D3h5Ok0i.js} +329 -65
  70. package/dist/pi-D3h5Ok0i.js.map +1 -0
  71. package/dist/{playground-UFSHP-Yn.js → playground-5AB4WgNF.js} +18 -10
  72. package/dist/playground-5AB4WgNF.js.map +1 -0
  73. package/dist/{posthog-O9kKcnda.js → posthog-DNn574nW.js} +8 -3
  74. package/dist/posthog-DNn574nW.js.map +1 -0
  75. package/dist/{provisioning-B-tzjG4r.js → provisioning-B8uSqRZk.js} +6 -5
  76. package/dist/provisioning-B8uSqRZk.js.map +1 -0
  77. package/dist/{queue-tools-7Oso-fpt.js → queue-tools-9OOVx5TE.js} +11 -86
  78. package/dist/queue-tools-9OOVx5TE.js.map +1 -0
  79. package/dist/{registry-D1L5e-WQ.js → registry-8YG-kuXk.js} +265 -6
  80. package/dist/registry-8YG-kuXk.js.map +1 -0
  81. package/dist/run-agent-legacy-d7rWlzQR.js +3739 -0
  82. package/dist/run-agent-legacy-d7rWlzQR.js.map +1 -0
  83. package/dist/{security-n3-xdINN.js → security-Cg_4a7vB.js} +6 -6
  84. package/dist/security-Cg_4a7vB.js.map +1 -0
  85. package/dist/{setup-utils-Bj0gejEf.js → setup-utils-CmTCTPkX.js} +46 -18
  86. package/dist/setup-utils-CmTCTPkX.js.map +1 -0
  87. package/dist/smoke-test.sh +1 -1
  88. package/dist/{start-tui-BowrTPXm.js → start-tui-CB2PZs1x.js} +42 -48
  89. package/dist/start-tui-CB2PZs1x.js.map +1 -0
  90. package/dist/{steps-CpNTGu9N.js → steps-BZcXRJNY.js} +7 -7
  91. package/dist/{steps-CpNTGu9N.js.map → steps-BZcXRJNY.js.map} +1 -1
  92. package/dist/{store-CVkJKlny.js → store-UN7c-ASf.js} +18 -55
  93. package/dist/store-UN7c-ASf.js.map +1 -0
  94. package/dist/{subagent-SxmvfDfp.js → subagent-BofIDK-O.js} +8 -3
  95. package/dist/subagent-BofIDK-O.js.map +1 -0
  96. package/dist/{task-nF7Ry8ff.js → task-r9t1UhQP.js} +124 -36
  97. package/dist/task-r9t1UhQP.js.map +1 -0
  98. package/dist/{task-stream-C9BLiAhz.js → task-stream-CMUilu54.js} +45 -15
  99. package/dist/task-stream-CMUilu54.js.map +1 -0
  100. package/dist/{tasks-BEEVIBcT.js → tasks-Bbv_lOBG.js} +17 -13
  101. package/dist/tasks-Bbv_lOBG.js.map +1 -0
  102. package/dist/{telemetry-PD7bhcda.js → telemetry-D6ruCtnv.js} +5 -5
  103. package/dist/telemetry-D6ruCtnv.js.map +1 -0
  104. package/dist/{terminal-NhNl-BIA.js → terminal-DrGyci_a.js} +63 -94
  105. package/dist/terminal-DrGyci_a.js.map +1 -0
  106. package/dist/{tools-BBdpgcIf.js → tools-Dyfh9aCD.js} +11 -11
  107. package/dist/tools-Dyfh9aCD.js.map +1 -0
  108. package/dist/ui-BBVuTM1v.js +15 -0
  109. package/dist/ui-BBVuTM1v.js.map +1 -0
  110. package/dist/version-aXxpgRKx.js +6 -0
  111. package/dist/version-aXxpgRKx.js.map +1 -0
  112. package/dist/warlock-smoke-test.ts +2 -2
  113. package/dist/{wizard-abort-hqHF-9xD.js → wizard-abort-BBkiUxfS.js} +23 -20
  114. package/dist/wizard-abort-BBkiUxfS.js.map +1 -0
  115. package/dist/wizard-abort-BU4aLyvh.js +3 -0
  116. package/dist/{wizard-session-FSJCkTcP.js → wizard-session-2w4Ru-Wz.js} +12 -16
  117. package/dist/wizard-session-2w4Ru-Wz.js.map +1 -0
  118. package/dist/wizard-session-DGaUHOF3.js +2 -0
  119. package/dist/wizard-ui-DoyOZxK8.js +16 -0
  120. package/dist/wizard-ui-DoyOZxK8.js.map +1 -0
  121. package/dist/{yara-hooks-BaPKsm-B.js → yara-hooks-DCeMDd1o.js} +19 -68
  122. package/dist/yara-hooks-DCeMDd1o.js.map +1 -0
  123. package/dist/yara-hooks-DSGuCU9A.js +2 -0
  124. package/package.json +8 -1
  125. package/dist/add-mcp-server-to-clients-4yHaRvOo.js.map +0 -1
  126. package/dist/agent-interface-DPaPdIjS.js.map +0 -1
  127. package/dist/agent-prompt-loader-BlhabNM2.js.map +0 -1
  128. package/dist/agent-runner-JFwQQj2k.js +0 -6100
  129. package/dist/agent-runner-JFwQQj2k.js.map +0 -1
  130. package/dist/analytics-CcHoyhE_.js +0 -2
  131. package/dist/analytics-DSVyjIVF.js.map +0 -1
  132. package/dist/api-Ci0dZWLR.js.map +0 -1
  133. package/dist/bounded-fs-FbZJ_vJ_.js.map +0 -1
  134. package/dist/ci-install-CEVCqahf.js.map +0 -1
  135. package/dist/debug-DWYDVp0B.js +0 -750
  136. package/dist/debug-DWYDVp0B.js.map +0 -1
  137. package/dist/defaults-DulzMJpN.js.map +0 -1
  138. package/dist/env-api-key-DwmkB3fm.js.map +0 -1
  139. package/dist/environment-1wA7uwAS.js.map +0 -1
  140. package/dist/errors--OqLxmWR.js.map +0 -1
  141. package/dist/gateway-session-OqzCMpZ9.js.map +0 -1
  142. package/dist/gateway-session-s1xr8b48.js +0 -2
  143. package/dist/headless-ui-DRGWDg9Z.js.map +0 -1
  144. package/dist/local-dev-DPZiIPCK.js.map +0 -1
  145. package/dist/mcp-BprhJJ2c.js +0 -64
  146. package/dist/mcp-BprhJJ2c.js.map +0 -1
  147. package/dist/mcp-prompt-streaming-E1d8DJcX.js.map +0 -1
  148. package/dist/mint-failure-C82j0RMC.js.map +0 -1
  149. package/dist/non-interactive-DGT2H_n4.js.map +0 -1
  150. package/dist/orchestrator-tools-BBBNV1z5.js.map +0 -1
  151. package/dist/package-json-xt3eeyBI.js.map +0 -1
  152. package/dist/package-manager-DU3aVif4.js +0 -290
  153. package/dist/package-manager-DU3aVif4.js.map +0 -1
  154. package/dist/pi-fG5fT50Y.js.map +0 -1
  155. package/dist/playground-UFSHP-Yn.js.map +0 -1
  156. package/dist/posthog-O9kKcnda.js.map +0 -1
  157. package/dist/provisioning-B-tzjG4r.js.map +0 -1
  158. package/dist/queue-tools-7Oso-fpt.js.map +0 -1
  159. package/dist/registry-D1L5e-WQ.js.map +0 -1
  160. package/dist/security-n3-xdINN.js.map +0 -1
  161. package/dist/setup-utils-Bj0gejEf.js.map +0 -1
  162. package/dist/start-tui-BowrTPXm.js.map +0 -1
  163. package/dist/store-CVkJKlny.js.map +0 -1
  164. package/dist/subagent-SxmvfDfp.js.map +0 -1
  165. package/dist/task-nF7Ry8ff.js.map +0 -1
  166. package/dist/task-stream-C9BLiAhz.js.map +0 -1
  167. package/dist/tasks-BEEVIBcT.js.map +0 -1
  168. package/dist/telemetry-PD7bhcda.js.map +0 -1
  169. package/dist/terminal-NhNl-BIA.js.map +0 -1
  170. package/dist/tools-BBdpgcIf.js.map +0 -1
  171. package/dist/wizard-abort-D3YA1hXX.js +0 -2
  172. package/dist/wizard-abort-hqHF-9xD.js.map +0 -1
  173. package/dist/wizard-session-CYvyYnti.js +0 -2
  174. package/dist/wizard-session-FSJCkTcP.js.map +0 -1
  175. package/dist/yara-hooks-BaPKsm-B.js.map +0 -1
  176. package/dist/yara-hooks-CwfQuEl3.js +0 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-bCZ3i3fh.js","names":["executeAgent","path"],"sources":["../src/agent/runner/shared/bootstrap.ts","../src/agent/runner/harness/anthropic/index.ts","../src/agent/runner/switchboard/flags/orchestrator.ts","../src/agent/runner/switchboard/flags/self-driving.ts","../src/agent/runner/switchboard/flags/schemes.ts","../src/agent/runner/switchboard/flags/index.ts","../src/agent/runner/switchboard/harness.ts","../src/agent/middleware/phase-detector.ts","../src/agent/middleware/pipeline.ts","../src/agent/middleware/config.ts","../src/agent/middleware/benchmarks/turn-counter.ts","../src/agent/middleware/benchmarks/token-tracker.ts","../src/agent/middleware/benchmarks/cache-tracker.ts","../src/agent/middleware/benchmarks/compaction-tracker.ts","../src/agent/middleware/benchmarks/context-size-tracker.ts","../src/shared/token-pricing.ts","../src/agent/middleware/benchmarks/cost-tracker.ts","../src/agent/middleware/benchmarks/duration-tracker.ts","../src/agent/middleware/benchmarks/summary.ts","../src/agent/middleware/benchmarks/json-writer.ts","../src/agent/middleware/benchmarks/index.ts","../src/agent/middleware/benchmark.ts","../src/agent/agent-prompt.ts","../src/agent/runner/shared/errors.ts","../src/agent/runner/shared/ask.ts","../src/agent/runner/sequence/linear.ts","../src/shared/utils/terminal-bell.ts","../src/agent/runner/sequence/orchestrator/executor.ts","../src/agent/runner/sequence/orchestrator/run-metrics.ts","../src/agent/runner/sequence/orchestrator/seeded-deps.ts","../src/agent/runner/sequence/orchestrator/orchestrator-runner.ts","../src/agent/runner/switchboard/sequence.ts","../src/agent/runner/switchboard/index.ts","../src/agent/runner/index.ts","../src/agent/index.ts"],"sourcesContent":["/**\n * Shared preparation for the runner pipeline.\n *\n * Runs before the fork into the linear or orchestrator arm: logging targets,\n * the gateway mint and the scan-triage classifier built on it. Everything the\n * caller must decide first — health gates, settings conflicts, authentication,\n * the AI opt-in gate, post-auth gates, feature flags, run tags, token refresh —\n * arrives already resolved in `RunConfig` and `RunInput`.\n */\n\nimport { createTriageLLMProvider } from '@agent/triage-provider';\nimport { gatewayAuth } from '@agent/gateway-session';\nimport { currentAccessToken } from '@shared/oauth-session';\nimport { logToFile } from '@utils/debug';\nimport { CallType, IS_DEV } from '@shared/constants';\nimport { VERSION } from '@shared/version';\nimport { mcpUrlFor } from '@shared/host-resolution';\nimport type { WizardRunOptions } from '@utils/types';\nimport type { BootstrapResult, RunConfig, RunFlags, RunInput } from './types';\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * Decide whether the `wizard_ask` overlay should be wired for this run.\n * Disabled in non-interactive modes (CI, signup) — there's no human to\n * answer. Per-program disabling is done by adding WIZARD_ASK_TOOL_NAME to\n * the program's `disallowedTools` so the SDK rejects calls outright.\n * Extracted so the policy can be unit-tested directly.\n *\n * `e2eAsk` is the one escape hatch. The e2e harness runs a `ci`\n * session, but it does have an answerer — the driver loop answers each\n * `wizard_ask` batch from the program's e2e profile. Without the flag the\n * agent-in-the-loop layer (the ask bridge in both sequence arms, and the\n * orchestrator's seeded warehouse task) stays unreachable from a test.\n *\n * Only the e2e TUI host sets the flag, from the `E2E_ASK` env var. No CLI flag\n * populates it, so plain `--ci` and `--signup` runs behave exactly as before.\n */\nexport function shouldDisableAsk(\n flags: Pick<RunFlags, 'ci' | 'signup' | 'e2eAsk'>,\n): boolean {\n return (flags.ci || flags.signup) && !flags.e2eAsk;\n}\n\n/** The option bag the agent interface and the middleware read. */\nexport function runOptions(input: RunInput): WizardRunOptions {\n return {\n installDir: input.installDir,\n debug: input.flags.debug,\n signup: input.flags.signup,\n ci: input.flags.ci,\n benchmark: input.flags.benchmark,\n projectId: input.host.projectId,\n apiKey: input.host.apiKey,\n yaraReport: input.flags.yaraReport,\n };\n}\n\n// ── Prepare ───────────────────────────────────────────────────────────\n\n/**\n * Shared setup for both arms: logging targets, then the gateway mint and the\n * triage classifier. Throws when the mint is refused, so the run fails before\n * any agent starts — the caller maps that the way it maps any unexpected error.\n */\nexport async function prepareRun(\n config: RunConfig,\n input: RunInput,\n): Promise<BootstrapResult> {\n const { skillsBaseUrl } = config;\n\n // Where this run actually points. The three services switch independently,\n // so otherwise \"why did it use prod skills?\" means reading three call sites.\n logToFile(\n `[agent-runner] targets build=${VERSION}${IS_DEV ? '/dev' : ''} ` +\n `skills=${skillsBaseUrl} ` +\n `mcp=${mcpUrlFor(input.flags.localMcp)} ` +\n `posthog=${input.host.baseUrl ?? 'region-resolved'}`,\n );\n\n const { credentials } = input;\n const { wizardFlags, wizardFlagPayloads, wizardMetadata, programId } = config;\n\n // Mint now so a refusal fails the boot before any agent starts. Later\n // readers re-resolve through the cache, which re-mints past the refresh\n // point.\n const currentGatewayAuth = () =>\n // TODO(B2): the agent must not mint inference auth. It receives the\n // PostHog token here and derives a gateway token from it, re-minting near\n // expiry. Programs own credentials (stack plan 4.5): pass a resolved\n // inference-auth provider on RunInput.credentials and move\n // gateway-session.ts out of src/agent with it.\n currentAccessToken(credentials).then((token) =>\n gatewayAuth(credentials.host, token, programId),\n );\n await currentGatewayAuth();\n\n return {\n skillsBaseUrl,\n credentials,\n // Carried so per-task sessions re-resolve against the same program the boot\n // minted for, rather than digging it back out of the metadata bag.\n programId,\n wizardFlags,\n wizardFlagPayloads,\n wizardMetadata,\n project: input.project,\n // Resolved once, here: the only place holding both the run-level harness\n // and the gateway auth. Every skill install downstream reads it off boot.\n triageProvider: createTriageLLMProvider(async () => {\n const auth = await currentGatewayAuth();\n return {\n baseURL: auth.gatewayUrl,\n authToken: auth.token,\n teamId: auth.teamId,\n // `call_type` splits scan spend out of the program's agent cost,\n // the same tag the in-run triage provider carries.\n wizardMetadata: { ...wizardMetadata, call_type: CallType.yaraTriage },\n wizardFlags,\n };\n }, config.binding.harness),\n };\n}\n","// Supported legacy SDK fallback; both this adapter and Pi implement run and runTask.\n\nimport { Harness } from '@shared/constants';\nimport {\n initializeAgent,\n runAgent as executeAgent,\n} from '@agent/agent-interface';\nimport { createAioCapture } from '@agent/aio-capture';\nimport { getLogFilePath, logToFile } from '@utils/debug';\nimport { detectNodePackageManagers } from '@utils/package-manager';\nimport { runOptions } from '@agent/runner/shared/bootstrap';\nimport { currentAccessToken } from '@shared/oauth-session';\nimport { createEmitLog } from '@agent/runner/shared/progress-collector';\nimport type {\n AgentResult,\n AgentHarness,\n BackendRunInputs,\n TaskRunInputs,\n} from '../types';\n\nexport const anthropicBackend: AgentHarness = {\n name: Harness.anthropic,\n\n async run(inputs: BackendRunInputs): Promise<AgentResult> {\n const {\n config: runConfig,\n input,\n boot,\n emit,\n prompt,\n spinner,\n askBridge,\n middleware,\n model,\n } = inputs;\n const config = runConfig.run;\n const { skillsBaseUrl, credentials, wizardFlags, wizardMetadata } = boot;\n const { accessToken, host, projectApiKey } = credentials;\n const log = createEmitLog(emit);\n\n const capture = createAioCapture({\n enabled: input.flags.captureAio,\n projectApiKey,\n apiHost: host.apiHost,\n runTags: wizardMetadata,\n });\n\n log.step('Initializing Claude agent...');\n const agent = await initializeAgent(\n {\n workingDirectory: input.installDir,\n posthogMcpUrl: host.mcpUrl,\n posthogApiKey: accessToken,\n currentPosthogApiKey: () => currentAccessToken(credentials),\n host,\n additionalMcpServers: config.additionalMcpServers,\n detectPackageManager:\n config.detectPackageManager ?? detectNodePackageManagers,\n skillsBaseUrl,\n wizardFlags,\n wizardMetadata,\n programId: boot.programId,\n integrationLabel: config.integrationLabel,\n askBridge,\n getPendingQuestion: askBridge?.getPendingQuestion,\n askMaxQuestions: config.maxQuestions,\n allowedTools: runConfig.allowedTools,\n disallowedTools: runConfig.disallowedTools,\n modelOverride: model,\n capture,\n emit,\n },\n runOptions(input),\n );\n log.step(`Verbose logs: ${getLogFilePath()}`);\n log.success(\"Agent initialized. Let's get cooking!\");\n logToFile('[agent-runner] agent initialized');\n\n return executeAgent(\n { ...agent, signal: inputs.signal },\n prompt,\n runOptions(input),\n spinner,\n {\n estimatedDurationMinutes: config.estimatedDurationMinutes,\n spinnerMessage: config.spinnerMessage,\n successMessage: config.successMessage,\n errorMessage:\n config.errorMessage ?? `${config.integrationLabel} failed`,\n abortCases: config.abortCases,\n emitStepEvents: config.trackStepProgress ?? false,\n resolveStepKey: config.resolveStepKey,\n triageProvider: boot.triageProvider,\n },\n middleware,\n );\n },\n\n async runTask(inputs: TaskRunInputs): Promise<AgentResult> {\n const {\n config,\n input,\n boot,\n emit,\n prompt,\n spinner,\n model,\n allowedTools,\n disallowedTools,\n askBridge,\n orchestrator,\n spinnerMessage,\n successMessage,\n errorMessage,\n requestRemark,\n analyticsProperties,\n } = inputs;\n const options = runOptions(input);\n\n const capture = createAioCapture({\n enabled: input.flags.captureAio,\n projectApiKey: boot.credentials.projectApiKey,\n apiHost: boot.credentials.host.apiHost,\n runTags: boot.wizardMetadata,\n });\n\n // Per-task agent config — the wizard-tools MCP server is bound to the\n // orchestrator context (queue store + current task id) so complete_task /\n // enqueue_task attribute to the right agent when tasks run in parallel.\n const agent = await initializeAgent(\n {\n workingDirectory: input.installDir,\n posthogMcpUrl: boot.credentials.host.mcpUrl,\n posthogApiKey: boot.credentials.accessToken,\n currentPosthogApiKey: () => currentAccessToken(boot.credentials),\n host: boot.credentials.host,\n detectPackageManager: detectNodePackageManagers,\n skillsBaseUrl: boot.skillsBaseUrl,\n programId: boot.programId,\n wizardFlags: boot.wizardFlags,\n wizardMetadata: boot.wizardMetadata,\n integrationLabel: config.programId,\n // Only a task allowed to ask carries a bridge, so the Write/Edit pause\n // that rides on a pending question stays inside that task's agent.\n askBridge,\n getPendingQuestion: askBridge?.getPendingQuestion,\n orchestrator,\n capture,\n emit,\n },\n options,\n );\n\n return executeAgent(\n { ...agent, model, allowedTools, disallowedTools, signal: inputs.signal },\n prompt,\n options,\n spinner,\n {\n spinnerMessage,\n successMessage,\n errorMessage,\n requestRemark,\n analyticsProperties,\n },\n );\n },\n};\n","/** Orchestrator gate: wizard-orchestrator on/off. On routes the declared programs to the orchestrator on pi; every model/effort comes from prompt frontmatter. */\nimport {\n Harness,\n Sequence,\n WIZARD_ORCHESTRATOR_FLAG_KEY,\n WIZARD_ORCHESTRATOR_OVERRIDE_FLAG_KEY,\n WIZARD_ORCHESTRATOR_SEEDED_TASKS_FLAG_KEY,\n} from '@shared/constants';\nimport type { HarnessExperiment, SequenceExperiment } from './schemes';\n\nexport const ORCHESTRATOR_SEQUENCE_ROUTE: SequenceExperiment = {\n programs: ['posthog-integration'],\n flag: WIZARD_ORCHESTRATOR_FLAG_KEY,\n sequence: Sequence.orchestrator,\n};\n\n/** Same flag, harness axis: the orchestrator drives tasks through pi. */\nexport const ORCHESTRATOR_HARNESS_ROUTE: HarnessExperiment = {\n program: 'posthog-integration',\n flags: { useFlag: WIZARD_ORCHESTRATOR_FLAG_KEY, harness: Harness.pi },\n};\n\n/** Same programs, per-stage overrides: the variant payload (`{stage: {model?, effort?}}`) outranks prompt frontmatter for the stages it names. */\nexport const ORCHESTRATOR_STAGE_OVERRIDES = {\n programs: ORCHESTRATOR_SEQUENCE_ROUTE.programs,\n flag: WIZARD_ORCHESTRATOR_OVERRIDE_FLAG_KEY,\n} as const;\n\n/**\n * Kill switch for the runner-seeded task mechanism (the optional warehouse\n * step). Off or unset, the orchestrator queues nothing itself and the run is\n * identical to a project with no detected sources.\n */\nexport function areSeededTasksEnabled(\n flags: Record<string, string> = {},\n): boolean {\n return flags[WIZARD_ORCHESTRATOR_SEEDED_TASKS_FLAG_KEY] === 'true';\n}\n\n/** Raw flag read — for telemetry/log lines only, never for routing. */\nexport function isOrchestratorEnabled(\n flags: Record<string, string> = {},\n): boolean {\n return flags[ORCHESTRATOR_SEQUENCE_ROUTE.flag] === 'true';\n}\n","/**\n * Self-driving pi experiment.\n *\n * Flag: wizard-self-driving-use-pi-harness (bool; payload `{model, effort?,\n * harness?, sequence?}`)\n * Routes: ONLY `self-driving` — any axis the payload pins. A missing or\n * invalid payload keeps the non-flagged binding default.\n */\nimport { WIZARD_SELF_DRIVING_USE_PI_HARNESS_FLAG_KEY } from '@shared/constants';\nimport type { HarnessExperiment } from './schemes';\n\nexport const SELF_DRIVING_EXPERIMENT: HarnessExperiment = {\n program: 'self-driving',\n flags: {\n useFlag: WIZARD_SELF_DRIVING_USE_PI_HARNESS_FLAG_KEY,\n },\n};\n","/**\n * Flag config schemes — the shapes a PostHog flag set can take to route a\n * program to the pi harness, plus the shared vocabulary and the per-config\n * resolution. Experiment modules in this folder declare *which* flags they\n * use; this module owns *how* a config resolves to a route.\n */\nimport { z } from 'zod';\nimport {\n GPT5_6_LUNA_MODEL,\n GPT5_6_SOL_MODEL,\n GPT5_6_TERRA_MODEL,\n Harness,\n Sequence,\n SONNET_5_MODEL,\n} from '@shared/constants';\nimport type { ProgramId } from '@lib/programs/program-registry';\nimport { logToFile } from '@utils/debug';\nimport type { EffortLevel } from '../models';\n\n// ── Shared vocabulary ─────────────────────────────────────────────────────\n\n/** Model variant key → gateway id. A key the gateway no longer mints is dropped\n * rather than re-aimed: the payload then fails validation and the binding\n * default stands, which is visible in the log instead of silently rerouting. */\nconst MODEL_FLAG_VARIANTS: Record<string, string> = {\n 'gpt-5-6-luna': GPT5_6_LUNA_MODEL,\n 'gpt-5-6-terra': GPT5_6_TERRA_MODEL,\n 'gpt-5-6-sol': GPT5_6_SOL_MODEL,\n 'sonnet-5': SONNET_5_MODEL,\n};\n\n/** Valid effort variants; anything else leaves the model's table default. */\nconst EFFORT_FLAG_VARIANTS = [\n 'minimal',\n 'low',\n 'medium',\n 'high',\n 'xhigh',\n] as const satisfies readonly EffortLevel[];\n\n/** A resolved flag route. Absent fields keep the axis's default (pi harness, sequence resolved by its own chain, table effort). */\nexport interface FlagRoute {\n model?: string;\n thinkingLevel?: EffortLevel;\n harness?: Harness;\n sequence?: Sequence;\n}\n\n// ── Config schemes ────────────────────────────────────────────────────────\n\n/** Harness-only scheme: the useFlag routes the harness; model/effort stay at the binding default so prompt frontmatter governs. */\nexport interface HarnessConfigFlag {\n useFlag: string;\n harness: Harness;\n}\n\n/** Boolean-flag scheme: the useFlag's zod-validated `{model, effort?, harness?, sequence?}` payload picks the route; anything invalid keeps the non-flagged binding default. */\nexport interface PayloadConfigFlag {\n useFlag: string;\n harness?: never;\n}\n\nexport type ConfigFlag = HarnessConfigFlag | PayloadConfigFlag;\n\n/**\n * A harness-axis experiment: ONE program and the flags that route it. The\n * scope is part of the declaration — the flags are inert for every other\n * program.\n */\nexport interface HarnessExperiment {\n program: ProgramId;\n flags: ConfigFlag;\n}\n\n/** A sequence-axis experiment: one boolean flag, inert outside its listed programs. */\nexport interface SequenceExperiment {\n programs: readonly ProgramId[];\n flag: string;\n /** Sequence the flag routes covered programs to. */\n sequence: Sequence;\n}\n\n/** Variant key validated against the shared vocabulary, transformed to its gateway id. */\nconst modelVariantSchema = z\n .string()\n .refine((key) => key in MODEL_FLAG_VARIANTS)\n .transform((key) => MODEL_FLAG_VARIANTS[key]);\n\n/** `{model, effort?, harness?, sequence?}` payload shape; extra keys tolerated for forward compat. */\nconst payloadConfigFlagSchema = z.object({\n model: modelVariantSchema,\n effort: z.enum(EFFORT_FLAG_VARIANTS).optional(),\n harness: z.nativeEnum(Harness).optional(),\n sequence: z.nativeEnum(Sequence).optional(),\n});\n\n/**\n * PostHog serves a variant's payload as a JSON string, e.g. the\n * wizard-orchestrator-override `terra-review` variant arrives as\n * `'{\"review\":{\"model\":\"gpt-5-6-terra\",\"effort\":\"medium\"}}'`; local CI\n * overrides inject the same payloads as already-parsed objects. Coerce both\n * to the value; anything unparseable is undefined.\n */\nfunction coerceJson(raw: unknown): unknown {\n if (typeof raw !== 'string') return raw;\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return undefined;\n }\n}\n\n// ── Resolution ────────────────────────────────────────────────────────────\n\n/** Per-stage overrides keyed by stage; a whole-payload parse failure fails closed to frontmatter everywhere. */\nconst stageOverridesSchema = z.record(\n z.object({\n model: modelVariantSchema.optional(),\n effort: z.enum(EFFORT_FLAG_VARIANTS).optional(),\n }),\n);\n\nexport type StageOverride = { model?: string; effort?: EffortLevel };\n\n/** Validate a stage-override payload (object or JSON string); undefined on any unexpected shape. */\nexport function stageOverridesFromPayload(\n raw: unknown,\n): Record<string, StageOverride> | undefined {\n const parsed = stageOverridesSchema.safeParse(coerceJson(raw));\n return parsed.success ? parsed.data : undefined;\n}\n\n/** Validate a payload (object or JSON string) into a route; undefined on any unexpected shape. */\nfunction parseFlagPayload(raw: unknown): FlagRoute | undefined {\n const parsed = payloadConfigFlagSchema.safeParse(coerceJson(raw));\n if (!parsed.success) return undefined;\n return {\n model: parsed.data.model,\n thinkingLevel: parsed.data.effort,\n harness: parsed.data.harness,\n sequence: parsed.data.sequence,\n };\n}\n\n/**\n * Resolve one config against the flag snapshot, or undefined when it doesn't\n * validly route: use flag off, or a payload that fails validation — the\n * caller then keeps the non-flagged binding default.\n */\nexport function routeFromConfigFlag(\n cfg: ConfigFlag,\n flags: Record<string, string>,\n flagPayloads?: Record<string, unknown>,\n): FlagRoute | undefined {\n if (flags[cfg.useFlag] !== 'true') return undefined;\n if (cfg.harness) return { harness: cfg.harness };\n const route = parseFlagPayload(flagPayloads?.[cfg.useFlag]);\n if (!route) {\n logToFile(\n `[switchboard] ${cfg.useFlag} on but payload missing/invalid — keeping the non-flagged default`,\n );\n }\n return route;\n}\n","/**\n * Switchboard flags, one module per experiment. Every experiment declares its\n * own scope — which program(s) its flags route — so the flag→program mapping\n * is readable per file, never implied. `schemes.ts` owns the shared config\n * shapes and resolution.\n */\nimport { RUN_SURFACE } from '@env';\nimport { logToFile } from '@utils/debug';\nimport type { Sequence } from '@shared/constants';\nimport type { ProgramId } from '@lib/programs/program-registry';\nimport {\n ORCHESTRATOR_HARNESS_ROUTE,\n ORCHESTRATOR_SEQUENCE_ROUTE,\n ORCHESTRATOR_STAGE_OVERRIDES,\n} from './orchestrator';\nimport { SELF_DRIVING_EXPERIMENT } from './self-driving';\nimport {\n routeFromConfigFlag,\n stageOverridesFromPayload,\n type FlagRoute,\n type HarnessExperiment,\n type SequenceExperiment,\n type StageOverride,\n} from './schemes';\n\n/** Every experiment on each axis. An experiment routes ONLY by being listed here, and only for the programs it declares. */\nexport const HARNESS_EXPERIMENTS: readonly HarnessExperiment[] = [\n ORCHESTRATOR_HARNESS_ROUTE,\n SELF_DRIVING_EXPERIMENT,\n];\nexport const SEQUENCE_EXPERIMENTS: readonly SequenceExperiment[] = [\n ORCHESTRATOR_SEQUENCE_ROUTE,\n];\n\n/** The flag-driven route for a program, or undefined when no experiment covers it or its flags don't validly route. */\nexport function resolveFlagRoute(\n program: ProgramId,\n flags: Record<string, string>,\n flagPayloads?: Record<string, unknown>,\n): FlagRoute | undefined {\n const experiment = HARNESS_EXPERIMENTS.find((e) => e.program === program);\n return (\n experiment && routeFromConfigFlag(experiment.flags, flags, flagPayloads)\n );\n}\n\n/** The flag-driven sequence for a program, or undefined when no sequence experiment covers it with its flag on. Surface/build scoping is the flag's own job (see `flagPersonProperties`). */\nexport function resolveFlagSequence(\n program: ProgramId,\n flags: Record<string, string>,\n): Sequence | undefined {\n return SEQUENCE_EXPERIMENTS.find(\n (e) => e.programs.includes(program) && flags[e.flag] === 'true',\n )?.sequence;\n}\n\n/** The per-stage overrides for a program's run, or undefined (prompt frontmatter stays). Applied once, where the agent prompts are loaded. */\nexport function resolveStageOverrides(\n program: ProgramId,\n flags: Record<string, string>,\n flagPayloads?: Record<string, unknown>,\n): Record<string, StageOverride> | undefined {\n if (RUN_SURFACE === 'cloud') return undefined;\n const exp = ORCHESTRATOR_STAGE_OVERRIDES;\n if (!exp.programs.includes(program)) return undefined;\n const variant = flags[exp.flag];\n if (!variant || variant === 'false') return undefined;\n const overrides = stageOverridesFromPayload(flagPayloads?.[exp.flag]);\n if (!overrides) {\n logToFile(\n `[switchboard] ${exp.flag}=${variant} but payload missing/invalid — keeping frontmatter`,\n );\n }\n return overrides;\n}\n\nexport { isOrchestratorEnabled, areSeededTasksEnabled } from './orchestrator';\nexport type {\n ConfigFlag,\n FlagRoute,\n HarnessExperiment,\n SequenceExperiment,\n StageOverride,\n} from './schemes';\n","/**\n * Harness axis: registry, middleware, resolver. Mirrors `sequence.ts`.\n */\n\nimport { IS_PRODUCTION_BUILD } from '@env';\nimport { Harness } from '@shared/constants';\nimport { logToFile } from '@utils/debug';\nimport { anthropicBackend } from '../harness/anthropic';\nimport { piBackend } from '../harness/pi';\nimport type { AgentHarness } from '../harness/types';\nimport { resolveFlagRoute } from './flags';\nimport {\n DEFAULT_BINDING,\n PROGRAM_BINDINGS,\n runChain,\n type HarnessPick,\n type Middleware,\n type SwitchboardCtx,\n} from '.';\n\nexport const HARNESS_OPTIONS: Partial<Record<Harness, AgentHarness>> = {\n [Harness.anthropic]: anthropicBackend,\n [Harness.pi]: piBackend,\n};\n\nexport function getHarness(name: Harness): AgentHarness {\n const harness = HARNESS_OPTIONS[name];\n if (!harness) {\n throw new Error(`No harness registered for '${name}'.`);\n }\n return harness;\n}\n\n/**\n * PostHog-flag routing to pi (see `./flags`). No valid route — flag off, no\n * config, or an invalid payload — keeps the non-flagged binding default.\n */\nconst flagRunnerOverride: Middleware<HarnessPick> = (ctx, next) => {\n const pick = next();\n const route = resolveFlagRoute(ctx.program, ctx.flags, ctx.flagPayloads);\n if (!route) return pick;\n if (ctx.trace) {\n ctx.trace.harness = 'flag';\n // Harness-only routes keep the binding's model — trace it truthfully so\n // analytics never attributes the fallback model to the flag.\n if (route.model) ctx.trace.model = 'flag';\n }\n return {\n harness: route.harness ?? Harness.pi,\n model: route.model ?? pick.model,\n thinkingLevel: route.thinkingLevel ?? pick.thinkingLevel,\n };\n};\n\n/** `--harness` override. Dev/test only — the option is gated out of published builds. */\nconst cliHarnessOverride: Middleware<HarnessPick> = (ctx, next) => {\n const pick = next();\n if (!ctx.cliHarness) return pick;\n if (ctx.trace) ctx.trace.harness = 'cli';\n return { ...pick, harness: ctx.cliHarness };\n};\n\n/** `--model` override. Dev/test only — the option is gated out of published builds. */\nconst cliModelOverride: Middleware<HarnessPick> = (ctx, next) => {\n const pick = next();\n if (!ctx.cliModel) return pick;\n if (ctx.trace) ctx.trace.model = 'cli';\n return { ...pick, model: ctx.cliModel };\n};\n\n// Order = precedence: CLI > flag > binding default. The prod spread collapses\n// to [], dropping the CLI overrides from the chain.\nconst HARNESS_MIDDLEWARE: Middleware<HarnessPick>[] = [\n ...(IS_PRODUCTION_BUILD ? [] : [cliHarnessOverride, cliModelOverride]),\n flagRunnerOverride,\n];\n\n/**\n * Resolve the harness for a role. Linear callers omit `role`; orchestrator\n * callers pass `'seed'` or `task.type`. `contextMillOverride[role]` overlays.\n */\nexport function resolveHarness(\n ctx: SwitchboardCtx,\n role = 'default',\n): HarnessPick {\n const pick = runChain(HARNESS_MIDDLEWARE, ctx, () => {\n if (ctx.trace)\n Object.assign(ctx.trace, { harness: 'binding', model: 'binding' });\n const binding = PROGRAM_BINDINGS[ctx.program] ?? DEFAULT_BINDING;\n return {\n harness: binding.harness,\n model: binding.model,\n thinkingLevel: binding.thinkingLevel,\n ...binding.contextMillOverride?.[role],\n };\n });\n logToFile(\n `[switchboard] resolved: program=${ctx.program} harness=${pick.harness}` +\n `${ctx.trace?.harness ? ` (${ctx.trace.harness})` : ''} model=${\n pick.model\n }` +\n `${ctx.trace?.model ? ` (${ctx.trace.model})` : ''}`,\n );\n return pick;\n}\n","/** Phase transitions from [STATUS] in assistant text. Keep in sync with program \"Status to report\" bullets. */\n\nconst PHASES_ORDER = [\n '1.0-begin',\n '1.1-edit',\n '1.2-revise',\n '1.3-conclude',\n] as const;\n\nconst STATUS_PHRASES_BY_PHASE: Record<(typeof PHASES_ORDER)[number], string[]> =\n {\n '1.0-begin': [\n 'Checking project structure',\n 'Verifying PostHog dependencies',\n 'Generating events based on project',\n ],\n '1.1-edit': ['Inserting PostHog capture code'],\n '1.2-revise': [\n 'Finding and correcting errors',\n 'Report details of any errors you fix',\n 'Linting, building and prettying',\n ],\n '1.3-conclude': ['Configured dashboard', 'Created setup report'],\n };\n\nexport class PhaseDetector {\n private currentPhase: 'setup' | (typeof PHASES_ORDER)[number] = 'setup';\n\n detect(message: any): string | null {\n if (message.type !== 'assistant') return null;\n\n const nextPhase = this.getNextPhase();\n if (nextPhase === null) return null;\n\n const content = message.message?.content;\n if (!Array.isArray(content)) return null;\n\n for (const block of content) {\n if (block.type !== 'text' || typeof block.text !== 'string') continue;\n if (!block.text.includes('[STATUS]')) continue;\n\n const phrases = STATUS_PHRASES_BY_PHASE[nextPhase];\n for (const phrase of phrases) {\n if (block.text.includes(phrase)) {\n this.currentPhase = nextPhase;\n return nextPhase;\n }\n }\n }\n\n return null;\n }\n\n private getNextPhase(): (typeof PHASES_ORDER)[number] | null {\n if (this.currentPhase === 'setup') return '1.0-begin';\n const i = PHASES_ORDER.indexOf(this.currentPhase);\n if (i < 0 || i >= PHASES_ORDER.length - 1) return null;\n return PHASES_ORDER[i + 1];\n }\n\n reset(): void {\n this.currentPhase = 'setup';\n }\n}\n","/**\n * Middleware pipeline orchestrator.\n *\n * Implements the same { onMessage, finalize } interface that runAgent() expects,\n * while internally dispatching to an ordered list of middleware plugins.\n */\n\nimport { PhaseDetector } from './phase-detector';\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n SDKMessage,\n} from './types';\n\nexport class MiddlewarePipeline {\n private middlewares: Middleware[];\n private store = new Map<string, unknown>();\n private phaseDetector: PhaseDetector;\n private autoDetectPhases: boolean;\n private _currentPhase = 'setup';\n private _currentPhaseFreshContext = true;\n\n constructor(\n middlewares: Middleware[],\n opts?: { phaseDetector?: PhaseDetector; autoDetectPhases?: boolean },\n ) {\n this.middlewares = middlewares;\n this.phaseDetector = opts?.phaseDetector ?? new PhaseDetector();\n this.autoDetectPhases = opts?.autoDetectPhases ?? true;\n\n const ctx = this.createContext();\n for (const mw of this.middlewares) {\n mw.onInit?.(ctx);\n }\n }\n\n /** Feed an SDK message through all middleware (satisfies tracker.onMessage) */\n onMessage(message: SDKMessage): void {\n // Phase detection first — updates context before middleware sees it\n if (this.autoDetectPhases) {\n const newPhase = this.phaseDetector.detect(message);\n if (newPhase && newPhase !== this._currentPhase) {\n this.transitionPhase(newPhase, false);\n }\n }\n\n const ctx = this.createContext();\n const storeHandle = this.createStore();\n for (const mw of this.middlewares) {\n mw.onMessage?.(message, ctx, storeHandle);\n }\n }\n\n /** Finalize the run (satisfies tracker.finalize) */\n finalize(resultMessage: any, totalDurationMs: number): any {\n const ctx = this.createContext();\n const storeHandle = this.createStore();\n let result: any;\n for (const mw of this.middlewares) {\n const r = mw.onFinalize?.(\n resultMessage,\n totalDurationMs,\n ctx,\n storeHandle,\n );\n if (r !== undefined) result = r;\n }\n return result;\n }\n\n /** Explicit phase start (for phased runner support) */\n startPhase(name: string, freshContext: boolean): void {\n this.transitionPhase(name, freshContext);\n }\n\n private transitionPhase(newPhase: string, freshContext: boolean): void {\n const oldPhase = this._currentPhase;\n this._currentPhase = newPhase;\n this._currentPhaseFreshContext = freshContext;\n const ctx = this.createContext();\n const storeHandle = this.createStore();\n for (const mw of this.middlewares) {\n mw.onPhaseTransition?.(oldPhase, newPhase, ctx, storeHandle);\n }\n }\n\n private createContext(): MiddlewareContext {\n return {\n currentPhase: this._currentPhase,\n currentPhaseFreshContext: this._currentPhaseFreshContext,\n get: <T>(key: string) => this.store.get(key) as T | undefined,\n };\n }\n\n private createStore(): MiddlewareStore {\n return {\n set: (key: string, value: unknown) => this.store.set(key, value),\n };\n }\n}\n","/**\n * Benchmark configuration loader.\n *\n * Loads .benchmark-config.json from the working directory with sensible defaults.\n * All fields are optional — missing fields fall back to defaults.\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport { logToFile } from '@utils/debug';\nimport { AgentSignals } from '@agent/agent-interface';\nimport { runtimeEnv } from '@env';\nimport { WIZARD_BENCHMARK_FILE, WIZARD_LOG_FILE } from '@utils/paths';\n\nexport interface BenchmarkConfig {\n /** Enable/disable individual metric plugins */\n plugins: Record<string, boolean>;\n output: {\n /** Path for the benchmark JSON output file */\n benchmarkPath: string;\n /** Whether to write the benchmark JSON file */\n benchmarkEnabled: boolean;\n /** Path for the main wizard debug log file */\n logPath: string;\n /** Whether to write the main wizard debug log */\n logEnabled: boolean;\n /** Suppress benchmark console output (disables the summary plugin) */\n suppressWizardLogs: boolean;\n };\n}\n\nconst DEFAULT_CONFIG: BenchmarkConfig = {\n plugins: {\n tokens: true,\n cache: true,\n turns: true,\n compactions: true,\n contextSize: true,\n cost: true,\n duration: true,\n summary: true,\n jsonWriter: true,\n },\n output: {\n benchmarkPath: WIZARD_BENCHMARK_FILE,\n benchmarkEnabled: true,\n logPath: WIZARD_LOG_FILE,\n logEnabled: true,\n suppressWizardLogs: false,\n },\n};\n\nexport function loadBenchmarkConfig(installDir: string): BenchmarkConfig {\n const configPath =\n runtimeEnv('POSTHOG_WIZARD_BENCHMARK_CONFIG') ??\n path.join(installDir, '.benchmark-config.json');\n try {\n const raw = fs.readFileSync(configPath, 'utf-8');\n const parsed = JSON.parse(raw);\n const config: BenchmarkConfig = {\n plugins: { ...DEFAULT_CONFIG.plugins, ...parsed.plugins },\n output: { ...DEFAULT_CONFIG.output, ...parsed.output },\n };\n\n // Env var overrides for parallel runs\n const benchFile = runtimeEnv('POSTHOG_WIZARD_BENCHMARK_FILE');\n if (benchFile) {\n config.output.benchmarkPath = benchFile;\n }\n const logDir = runtimeEnv('POSTHOG_WIZARD_LOG_DIR');\n if (logDir) {\n config.output.logPath = path.join(logDir, 'posthog-wizard.log');\n }\n\n // If benchmark output is disabled, disable the jsonWriter plugin\n if (!config.output.benchmarkEnabled) {\n config.plugins.jsonWriter = false;\n }\n\n logToFile(`${AgentSignals.BENCHMARK} Loaded config from ${configPath}`);\n return config;\n } catch {\n // No config file or invalid JSON — use defaults\n const config = structuredClone(DEFAULT_CONFIG);\n\n // Env var overrides\n const benchFile2 = runtimeEnv('POSTHOG_WIZARD_BENCHMARK_FILE');\n if (benchFile2) {\n config.output.benchmarkPath = benchFile2;\n }\n const logDir2 = runtimeEnv('POSTHOG_WIZARD_LOG_DIR');\n if (logDir2) {\n config.output.logPath = path.join(logDir2, 'posthog-wizard.log');\n }\n\n return config;\n }\n}\n\nexport function getDefaultConfig(): BenchmarkConfig {\n return structuredClone(DEFAULT_CONFIG);\n}\n","/**\n * Turn counting plugin with message deduplication.\n *\n * The SDK emits multiple assistant events per turn (one per content block)\n * with the same message ID. This plugin deduplicates and publishes turn\n * counts + a duplicate flag for downstream plugins.\n */\n\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\n\nexport interface TurnData {\n /** Whether the current message is a duplicate of the last processed turn */\n isDuplicate: boolean;\n /** Turns in the current phase */\n phaseTurns: number;\n /** Total turns across all phases */\n totalTurns: number;\n /** Per-phase turn snapshots: [{ phase, turns }] */\n phaseSnapshots: Array<{ phase: string; turns: number }>;\n}\n\nexport class TurnCounterPlugin implements Middleware {\n readonly name = 'turns';\n\n private lastMessageId: string | null = null;\n private phaseTurns = 0;\n private totalTurns = 0;\n private isDuplicate = false;\n private phaseSnapshots: Array<{ phase: string; turns: number }> = [];\n private currentPhase = 'setup';\n\n onMessage(\n message: any,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n if (message.type !== 'assistant') {\n this.isDuplicate = false;\n store.set('turns', this.getData());\n return;\n }\n\n const msgId: string | undefined = message.message?.id;\n this.isDuplicate = msgId != null && msgId === this.lastMessageId;\n if (msgId) this.lastMessageId = msgId;\n\n if (!this.isDuplicate) {\n this.phaseTurns++;\n this.totalTurns++;\n }\n\n store.set('turns', this.getData());\n }\n\n onPhaseTransition(\n fromPhase: string,\n _toPhase: string,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({ phase: fromPhase, turns: this.phaseTurns });\n this.currentPhase = _toPhase;\n this.phaseTurns = 0;\n this.lastMessageId = null;\n store.set('turns', this.getData());\n }\n\n onFinalize(\n _resultMessage: any,\n _totalDurationMs: number,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: this.currentPhase,\n turns: this.phaseTurns,\n });\n store.set('turns', this.getData());\n }\n\n private getData(): TurnData {\n return {\n isDuplicate: this.isDuplicate,\n phaseTurns: this.phaseTurns,\n totalTurns: this.totalTurns,\n phaseSnapshots: [...this.phaseSnapshots],\n };\n }\n}\n","/**\n * Token tracking plugin for input/output tokens.\n *\n * Accumulates per-turn token usage (input_tokens + cache_read_input_tokens\n * + cache_creation_input_tokens = total input; output_tokens = output).\n * Respects the dedup flag from TurnCounterPlugin. Cache breakdown (r/5m/1h)\n * is tracked by CacheTrackerPlugin for reporting and pricing.\n */\n\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport type { TurnData } from './turn-counter';\n\nexport interface TokenData {\n phaseInput: number;\n phaseOutput: number;\n totalInput: number;\n totalOutput: number;\n /** The raw usage object from the last non-duplicate assistant message */\n lastUsage: any;\n /** Per-phase token snapshots */\n phaseSnapshots: Array<{\n phase: string;\n inputTokens: number;\n outputTokens: number;\n /** Number of turns in this phase that had usage (SDK may not report all) */\n messagesWithUsage: number;\n }>;\n}\n\nexport class TokenTrackerPlugin implements Middleware {\n readonly name = 'tokens';\n\n private phaseInput = 0;\n private phaseOutput = 0;\n private totalInput = 0;\n private totalOutput = 0;\n private lastUsage: any = null;\n private phaseSnapshots: Array<{\n phase: string;\n inputTokens: number;\n outputTokens: number;\n messagesWithUsage: number;\n }> = [];\n private currentPhase = 'setup';\n private phaseMessagesWithUsage = 0;\n\n onMessage(\n message: any,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n if (message.type !== 'assistant') return;\n\n const turns = ctx.get<TurnData>('turns');\n if (turns?.isDuplicate) return;\n\n const usage = message.message?.usage;\n if (usage) {\n const input =\n Number(usage.input_tokens ?? 0) +\n Number(usage.cache_read_input_tokens ?? 0) +\n Number(usage.cache_creation_input_tokens ?? 0);\n const output = Number(usage.output_tokens ?? 0);\n this.phaseInput += input;\n this.phaseOutput += output;\n this.totalInput += input;\n this.totalOutput += output;\n this.lastUsage = usage;\n this.phaseMessagesWithUsage += 1;\n }\n\n store.set('tokens', this.getData());\n }\n\n onPhaseTransition(\n fromPhase: string,\n toPhase: string,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: fromPhase,\n inputTokens: this.phaseInput,\n outputTokens: this.phaseOutput,\n messagesWithUsage: this.phaseMessagesWithUsage,\n });\n this.currentPhase = toPhase;\n this.phaseInput = 0;\n this.phaseOutput = 0;\n this.phaseMessagesWithUsage = 0;\n store.set('tokens', this.getData());\n }\n\n onFinalize(\n _resultMessage: any,\n _totalDurationMs: number,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: this.currentPhase,\n inputTokens: this.phaseInput,\n outputTokens: this.phaseOutput,\n messagesWithUsage: this.phaseMessagesWithUsage,\n });\n store.set('tokens', this.getData());\n }\n\n private getData(): TokenData {\n return {\n phaseInput: this.phaseInput,\n phaseOutput: this.phaseOutput,\n totalInput: this.totalInput,\n totalOutput: this.totalOutput,\n lastUsage: this.lastUsage,\n phaseSnapshots: [...this.phaseSnapshots],\n };\n }\n}\n","/**\n * Cache token tracking plugin (cache_read and cache_creation).\n *\n * Respects the dedup flag from TurnCounterPlugin.\n */\n\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport type { TurnData } from './turn-counter';\n\n/** Matches SDK usage.cache_creation (ephemeral 5m vs 1h for pricing). */\nexport interface CacheCreationBreakdown {\n ephemeral_5m_input_tokens: number;\n ephemeral_1h_input_tokens: number;\n}\n\nexport interface CacheData {\n phaseRead: number;\n phaseCreation: number;\n totalRead: number;\n totalCreation: number;\n totalCreation5m: number;\n totalCreation1h: number;\n phaseSnapshots: Array<{\n phase: string;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n /** When present, use for pricing (5m vs 1h rates). */\n cacheCreation5m: number;\n cacheCreation1h: number;\n }>;\n}\n\nexport class CacheTrackerPlugin implements Middleware {\n readonly name = 'cache';\n\n private phaseRead = 0;\n private phaseCreation = 0;\n private phaseCreation5m = 0;\n private phaseCreation1h = 0;\n private totalRead = 0;\n private totalCreation = 0;\n private totalCreation5m = 0;\n private totalCreation1h = 0;\n private phaseSnapshots: Array<{\n phase: string;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n cacheCreation5m: number;\n cacheCreation1h: number;\n }> = [];\n private currentPhase = 'setup';\n\n onMessage(\n message: any,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n if (message.type !== 'assistant') return;\n\n const turns = ctx.get<TurnData>('turns');\n if (turns?.isDuplicate) return;\n\n const usage = message.message?.usage;\n if (usage) {\n const read = Number(usage.cache_read_input_tokens ?? 0);\n const creation = Number(usage.cache_creation_input_tokens ?? 0);\n const cc = usage.cache_creation;\n const creation5m = Number(cc?.ephemeral_5m_input_tokens ?? 0);\n const creation1h = Number(cc?.ephemeral_1h_input_tokens ?? 0);\n this.phaseRead += read;\n this.phaseCreation += creation;\n this.phaseCreation5m += creation5m;\n this.phaseCreation1h += creation1h;\n this.totalRead += read;\n this.totalCreation += creation;\n }\n\n store.set('cache', this.getData());\n }\n\n onPhaseTransition(\n fromPhase: string,\n toPhase: string,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: fromPhase,\n cacheReadTokens: this.phaseRead,\n cacheCreationTokens: this.phaseCreation,\n cacheCreation5m: this.phaseCreation5m,\n cacheCreation1h: this.phaseCreation1h,\n });\n this.currentPhase = toPhase;\n this.phaseRead = 0;\n this.phaseCreation = 0;\n this.phaseCreation5m = 0;\n this.phaseCreation1h = 0;\n store.set('cache', this.getData());\n }\n\n onFinalize(\n _resultMessage: any,\n _totalDurationMs: number,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: this.currentPhase,\n cacheReadTokens: this.phaseRead,\n cacheCreationTokens: this.phaseCreation,\n cacheCreation5m: this.phaseCreation5m,\n cacheCreation1h: this.phaseCreation1h,\n });\n store.set('cache', this.getData());\n }\n\n private getData(): CacheData {\n return {\n phaseRead: this.phaseRead,\n phaseCreation: this.phaseCreation,\n totalRead: this.totalRead,\n totalCreation: this.totalCreation,\n totalCreation5m: this.totalCreation5m,\n totalCreation1h: this.totalCreation1h,\n phaseSnapshots: [...this.phaseSnapshots],\n };\n }\n}\n","/**\n * Compaction event tracking plugin.\n *\n * Tracks context compaction events (compact_boundary system messages)\n * including pre-compaction token counts per phase.\n */\n\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport { logToFile } from '@utils/debug';\nimport { AgentSignals } from '@agent/agent-interface';\n\nexport interface CompactionData {\n phaseCompactions: number;\n phasePreTokens: number[];\n totalCompactions: number;\n phaseSnapshots: Array<{\n phase: string;\n compactions: number;\n preTokens: number[];\n }>;\n}\n\nexport class CompactionTrackerPlugin implements Middleware {\n readonly name = 'compactions';\n\n private phaseCompactions = 0;\n private phasePreTokens: number[] = [];\n private totalCompactions = 0;\n private phaseSnapshots: Array<{\n phase: string;\n compactions: number;\n preTokens: number[];\n }> = [];\n private currentPhase = 'setup';\n\n onMessage(\n message: any,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n if (message.type !== 'system' || message.subtype !== 'compact_boundary') {\n return;\n }\n\n const preTokens = message.compact_metadata?.pre_tokens ?? 0;\n const trigger = message.compact_metadata?.trigger ?? 'unknown';\n this.phaseCompactions++;\n this.totalCompactions++;\n this.phasePreTokens.push(preTokens);\n\n logToFile(\n `${AgentSignals.BENCHMARK} [COMPACTION] Context compacted during \"${ctx.currentPhase}\" (trigger: ${trigger}, pre_tokens: ${preTokens})`,\n );\n\n store.set('compactions', this.getData());\n }\n\n onPhaseTransition(\n fromPhase: string,\n toPhase: string,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: fromPhase,\n compactions: this.phaseCompactions,\n preTokens: [...this.phasePreTokens],\n });\n this.currentPhase = toPhase;\n this.phaseCompactions = 0;\n this.phasePreTokens = [];\n store.set('compactions', this.getData());\n }\n\n onFinalize(\n _resultMessage: any,\n _totalDurationMs: number,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n this.phaseSnapshots.push({\n phase: this.currentPhase,\n compactions: this.phaseCompactions,\n preTokens: [...this.phasePreTokens],\n });\n store.set('compactions', this.getData());\n }\n\n private getData(): CompactionData {\n return {\n phaseCompactions: this.phaseCompactions,\n phasePreTokens: [...this.phasePreTokens],\n totalCompactions: this.totalCompactions,\n phaseSnapshots: [...this.phaseSnapshots],\n };\n }\n}\n","/**\n * Context size tracking plugin (context tokens in/out per phase).\n *\n * Context tokens out = sum of input + cache_read + cache_creation from the\n * last assistant message's usage (per-turn, NOT aggregate).\n * Context tokens in = previous phase's context tokens out.\n */\n\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport type { TokenData } from './token-tracker';\n\nexport interface ContextSizeData {\n /** Per-phase context size snapshots */\n phaseSnapshots: Array<{\n phase: string;\n contextTokensIn?: number;\n contextTokensOut?: number;\n freshContext: boolean;\n }>;\n}\n\nexport class ContextSizeTrackerPlugin implements Middleware {\n readonly name = 'contextSize';\n\n private phaseSnapshots: Array<{\n phase: string;\n contextTokensIn?: number;\n contextTokensOut?: number;\n freshContext: boolean;\n }> = [];\n private lastContextTokensOut?: number;\n\n onPhaseTransition(\n fromPhase: string,\n _toPhase: string,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n const tokens = ctx.get<TokenData>('tokens');\n const contextTokensOut = this.computeContextTokensOut(tokens?.lastUsage);\n\n this.phaseSnapshots.push({\n phase: fromPhase,\n contextTokensIn: ctx.currentPhaseFreshContext\n ? undefined\n : this.lastContextTokensOut,\n contextTokensOut,\n freshContext: ctx.currentPhaseFreshContext,\n });\n\n this.lastContextTokensOut = contextTokensOut;\n store.set('contextSize', this.getData());\n }\n\n onFinalize(\n _resultMessage: any,\n _totalDurationMs: number,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n const tokens = ctx.get<TokenData>('tokens');\n const contextTokensOut = this.computeContextTokensOut(tokens?.lastUsage);\n\n this.phaseSnapshots.push({\n phase: ctx.currentPhase,\n contextTokensIn: ctx.currentPhaseFreshContext\n ? undefined\n : this.lastContextTokensOut,\n contextTokensOut,\n freshContext: ctx.currentPhaseFreshContext,\n });\n\n store.set('contextSize', this.getData());\n }\n\n private computeContextTokensOut(usage: any): number | undefined {\n if (!usage) return undefined;\n return (\n Number(usage.input_tokens ?? 0) +\n Number(usage.cache_read_input_tokens ?? 0) +\n Number(usage.cache_creation_input_tokens ?? 0)\n );\n }\n\n private getData(): ContextSizeData {\n return {\n phaseSnapshots: [...this.phaseSnapshots],\n };\n }\n}\n","/**\n * Shared exact-match USD-per-token pricing by model id, and the cost formula\n * applied to a token usage delta.\n *\n * Single source of truth for both the benchmark's `CostTrackerPlugin`\n * (`@lib/middleware/benchmarks/cost-tracker`) and the live token/cost HUD\n * (`agent-interface.ts`'s per-turn usage accumulation), so the two estimates\n * never drift apart. Both reconcile against the SDK's own authoritative\n * `total_cost_usd` once the run finishes — this table only prices the\n * *live-updating* estimate shown while the agent is still running.\n *\n * Model-aware because a run's model isn't fixed: `AgentConfig.modelOverride`\n * switches specific programs to Haiku (e.g. source-map detection), and the\n * SDK reports a `model` string on every individual assistant turn (subagents\n * dispatched via the Agent tool can run on a different model than the main\n * session).\n *\n * Deliberately matched by *exact* model id, not family name (no\n * `model.includes('opus')`-style fallback): different versions of the same\n * family are priced differently — e.g. Claude Opus 4.5 ($5/$25 per Mtok) is\n * half of Opus 4.1's rate ($15/$75) — so matching on \"opus\" or \"sonnet\"\n * alone silently mis-prices a newer/older sibling at the wrong rate. The\n * only normalization applied is stripping a trailing release-date suffix\n * (`stripDateSuffix`), since Anthropic's dated and undated ids for the\n * *same* version always carry the same price (verified for every entry\n * below). Claude Sonnet 5 is the one exception with a *time-dependent*\n * price — see `sonnet5Price` — rather than a fixed table entry.\n *\n * Prices verified against https://models.dev/api.json (Anthropic section)\n * on 2026-07-01 — re-verify there when adding an entry or bumping\n * DEFAULT_AGENT_MODEL/HAIKU_MODEL, since this table isn't fetched live.\n */\n\nimport {\n DEFAULT_AGENT_MODEL,\n HAIKU_MODEL,\n SONNET_5_MODEL,\n} from '@shared/constants';\n\nexport interface PricePerMtok {\n input: number;\n output: number;\n cacheRead: number;\n cacheCreation5m: number;\n cacheCreation1h: number;\n}\n\n/**\n * `cacheCreation1h` isn't published by models.dev (it only has one\n * cache-write rate); extrapolated at `input × 2`, the ratio that holds for\n * every model below (mirrors `cacheCreation5m` = `input × 1.25`, `cacheRead`\n * = `input × 0.1` — Anthropic's standard prompt-caching multipliers).\n * Rounded to 6 decimal places to clean up binary float noise from the\n * multiplication (e.g. `3 * 0.1` is `0.30000000000000004`, not `0.3`) — well\n * past cent-level precision at the 1M-token scale these prices are quoted at.\n */\nfunction pricingFromInput(input: number, output: number): PricePerMtok {\n const round = (n: number): number => Math.round(n * 1e6) / 1e6;\n return {\n input,\n output,\n cacheRead: round(input * 0.1),\n cacheCreation5m: round(input * 1.25),\n cacheCreation1h: round(input * 2),\n };\n}\n\n/**\n * Exact-match price table, keyed by the *undated* model id prefix —\n * `pricePerMtokForModel` strips a dated suffix before falling back to this\n * table, so a dated Anthropic id resolves via its undated entry without\n * needing a duplicate key. Ids the wizard no longer dispatches on stay\n * priced, since a subagent turn or the SDK can still report one (a turn on\n * an id NOT in this table contributes $0 to the live estimate rather than\n * guessing, see `pricePerMtokForModel`).\n *\n * `SONNET_5_MODEL` is intentionally absent: its price is time-dependent\n * (promotional launch discount), so `pricePerMtokForModel` resolves it via\n * `sonnet5Price`. It is also `DEFAULT_AGENT_MODEL`, so the no-model fallback\n * goes through that branch.\n */\nconst PRICE_TABLE: Record<string, PricePerMtok> = {\n 'claude-sonnet-4-6': pricingFromInput(3, 15),\n [HAIKU_MODEL]: pricingFromInput(1, 5),\n 'claude-opus-4-5': pricingFromInput(5, 25),\n};\n\n/**\n * Claude Sonnet 5 launched at a promotional discount through 2026-08-31\n * UTC; from 2026-09-01 it reverts to the same rate as Sonnet 4.6 ($3/$15)\n * — not a coincidence, Anthropic prices it identically to 4.6 once the\n * promo ends. Re-verify against https://models.dev/api.json if this ever\n * looks off, and fold this special case into a flat `PRICE_TABLE` entry at\n * the post-promo rate once the window is well past.\n */\nconst SONNET_5_PROMO_ENDS_UTC = new Date('2026-09-01T00:00:00Z');\n\nfunction sonnet5Price(now: Date): PricePerMtok {\n return now < SONNET_5_PROMO_ENDS_UTC\n ? pricingFromInput(2, 10)\n : pricingFromInput(3, 15);\n}\n\n/** Strips a trailing 8-digit release-date suffix (e.g. `-20251001`) — never\n * the version segment, so differently-versioned models are never conflated.\n * `claude-haiku-4-5-20251001` → `claude-haiku-4-5`; `claude-sonnet-4-6` (no\n * date suffix) is returned unchanged. */\nfunction stripDateSuffix(model: string): string {\n return model.replace(/-\\d{8}$/, '');\n}\n\n/**\n * Exact-match pricing lookup. `undefined` model (a caller with no model\n * context, e.g. the benchmark's `CostTrackerPlugin`) falls back to\n * `DEFAULT_AGENT_MODEL`'s price, the default for interactive runs. A\n * *given* but unrecognized model id returns `undefined` rather than\n * guessing from its family name — seeing `undefined` and skipping that\n * delta is strictly more accurate than the family-fallback this replaced,\n * which silently priced e.g. every Opus turn at Opus 4.1's rate.\n *\n * `now` is injectable (defaults to the real clock) only so\n * `sonnet5Price`'s promo-window check is deterministic in tests — no\n * other entry in this table is time-dependent.\n */\nexport function pricePerMtokForModel(\n model?: string,\n now: Date = new Date(),\n): PricePerMtok | undefined {\n const id = model ?? DEFAULT_AGENT_MODEL;\n const undated = stripDateSuffix(id);\n if (undated === SONNET_5_MODEL) return sonnet5Price(now);\n return PRICE_TABLE[id] ?? PRICE_TABLE[undated];\n}\n\n/**\n * Cost in USD for one usage delta, priced at `usage.model`'s exact rates\n * (see `pricePerMtokForModel`) — 0 when `model` is given but not in the\n * table, rather than guessing. `cacheCreation5m`/`cacheCreation1h` come from\n * the SDK's `usage.cache_creation` breakdown, which is only reported on\n * some turns — when both are 0, `cacheCreationTokens` (the plain\n * `cache_creation_input_tokens` total) is priced at the 5m rate instead, so\n * a turn without the breakdown still gets a reasonable estimate rather than\n * being priced at $0.\n *\n * Takes the same shape as `TokenUsageDelta` (`@ui/wizard-ui`) so a caller\n * that already has one — `WizardStore.addTokenUsage` — can pass it straight\n * through instead of re-listing its fields in a fixed positional order.\n */\nexport function computeTokenCostUsd(usage: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreation5m: number;\n cacheCreation1h: number;\n cacheCreationTokens: number;\n model?: string;\n}): number {\n const price = pricePerMtokForModel(usage.model);\n if (!price) return 0;\n const hasBreakdown = usage.cacheCreation5m > 0 || usage.cacheCreation1h > 0;\n return (\n usage.inputTokens * (price.input / 1e6) +\n usage.outputTokens * (price.output / 1e6) +\n usage.cacheReadTokens * (price.cacheRead / 1e6) +\n (hasBreakdown\n ? usage.cacheCreation5m * (price.cacheCreation5m / 1e6) +\n usage.cacheCreation1h * (price.cacheCreation1h / 1e6)\n : usage.cacheCreationTokens * (price.cacheCreation5m / 1e6))\n );\n}\n\n/**\n * Shared display formatters for the hidden Ctrl+T HUD (`TokenCostHud`) and\n * the post-exit scrollback line (`exit-line.ts`) — kept here, not in either\n * of those files, since `exit-line.ts` is deliberately free of `ink`/React\n * imports (it must stay a pure, unit-testable function), and importing a\n * named export from a `.tsx` file would pull `ink` into its module graph\n * anyway. This module has no such dependency.\n */\nexport function formatTokenCount(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;\n if (n >= 1_000) return `${(n / 1000).toFixed(1)}K`;\n return n.toLocaleString();\n}\n\nexport function formatCostUsd(usd: number): string {\n if (usd > 0 && usd < 0.01) return `$${usd.toFixed(4)}`;\n return `$${usd.toFixed(2)}`;\n}\n","import type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport { computeTokenCostUsd } from '@shared/token-pricing';\nimport type { TokenData } from './token-tracker';\nimport type { CacheData } from './cache-tracker';\n\nexport interface CostData {\n totalCost: number;\n phaseCosts: Array<{ phase: string; cost: number }>;\n}\n\n// Pricing table + formula moved to `@lib/agent/token-pricing` so the live\n// token/cost HUD's per-turn estimate can't drift from this benchmark's.\n// No model is passed to computeTokenCostUsd below (falls back to Sonnet\n// pricing) -- MiddlewareContext has no model field to thread through, and\n// `--benchmark` always measures the default flow, never a Haiku-overridden\n// program. Still reconciles to the SDK's authoritative total_cost_usd in\n// onFinalize below, same as the live HUD, so this only risks the\n// unreconciled per-phase breakdown.\n\nexport class CostTrackerPlugin implements Middleware {\n readonly name = 'cost';\n\n private phaseCosts: Array<{ phase: string; cost: number }> = [];\n private totalCost = 0;\n\n onPhaseTransition(\n fromPhase: string,\n _toPhase: string,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n const tokens = ctx.get<TokenData>('tokens');\n const cache = ctx.get<CacheData>('cache');\n const tokenSnap = tokens?.phaseSnapshots.at(-1);\n const cacheSnap = cache?.phaseSnapshots.at(-1);\n\n const totalIn = tokenSnap?.inputTokens ?? 0;\n const read = cacheSnap?.cacheReadTokens ?? 0;\n const creation = cacheSnap?.cacheCreationTokens ?? 0;\n const c5m = cacheSnap?.cacheCreation5m ?? 0;\n const c1h = cacheSnap?.cacheCreation1h ?? 0;\n const baseIn = Math.max(0, totalIn - read - creation);\n\n const phaseCost = computeTokenCostUsd({\n inputTokens: baseIn,\n outputTokens: tokenSnap?.outputTokens ?? 0,\n cacheReadTokens: read,\n cacheCreation5m: c5m,\n cacheCreation1h: c1h,\n cacheCreationTokens: creation,\n });\n\n this.phaseCosts.push({ phase: fromPhase, cost: phaseCost });\n this.totalCost += phaseCost;\n store.set('cost', this.getData());\n }\n\n onFinalize(\n resultMessage: any,\n _totalDurationMs: number,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n const tokens = ctx.get<TokenData>('tokens');\n const cache = ctx.get<CacheData>('cache');\n const tokenSnap = tokens?.phaseSnapshots.at(-1);\n const cacheSnap = cache?.phaseSnapshots.at(-1);\n\n const totalIn = tokenSnap?.inputTokens ?? 0;\n const read = cacheSnap?.cacheReadTokens ?? 0;\n const creation = cacheSnap?.cacheCreationTokens ?? 0;\n const c5m = cacheSnap?.cacheCreation5m ?? 0;\n const c1h = cacheSnap?.cacheCreation1h ?? 0;\n const baseIn = Math.max(0, totalIn - read - creation);\n\n const lastPhaseCost = computeTokenCostUsd({\n inputTokens: baseIn,\n outputTokens: tokenSnap?.outputTokens ?? 0,\n cacheReadTokens: read,\n cacheCreation5m: c5m,\n cacheCreation1h: c1h,\n cacheCreationTokens: creation,\n });\n\n this.phaseCosts.push({ phase: ctx.currentPhase, cost: lastPhaseCost });\n this.totalCost += lastPhaseCost;\n\n const sdkTotal =\n Number(resultMessage?.usage?.total_cost_usd ?? 0) ||\n Number(resultMessage?.total_cost_usd ?? 0);\n\n if (sdkTotal > 0 && this.totalCost > 0) {\n const scale = sdkTotal / this.totalCost;\n this.phaseCosts = this.phaseCosts.map((p) => ({\n phase: p.phase,\n cost: p.cost * scale,\n }));\n this.totalCost = sdkTotal;\n }\n\n store.set('cost', this.getData());\n }\n\n private getData(): CostData {\n return {\n totalCost: this.totalCost,\n phaseCosts: [...this.phaseCosts],\n };\n }\n}\n","/**\n * Duration tracking plugin (per-phase and total).\n */\n\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\n\nexport interface DurationData {\n phaseSnapshots: Array<{\n phase: string;\n startTime: number;\n endTime: number;\n durationMs: number;\n }>;\n totalDurationMs: number;\n}\n\nexport class DurationTrackerPlugin implements Middleware {\n readonly name = 'duration';\n\n private phaseStartTime = Date.now();\n private phaseSnapshots: Array<{\n phase: string;\n startTime: number;\n endTime: number;\n durationMs: number;\n }> = [];\n\n onPhaseTransition(\n fromPhase: string,\n _toPhase: string,\n _ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n const now = Date.now();\n this.phaseSnapshots.push({\n phase: fromPhase,\n startTime: this.phaseStartTime,\n endTime: now,\n durationMs: now - this.phaseStartTime,\n });\n this.phaseStartTime = now;\n store.set('duration', {\n phaseSnapshots: [...this.phaseSnapshots],\n totalDurationMs: 0,\n } satisfies DurationData);\n }\n\n onFinalize(\n _resultMessage: any,\n totalDurationMs: number,\n ctx: MiddlewareContext,\n store: MiddlewareStore,\n ): void {\n const now = Date.now();\n this.phaseSnapshots.push({\n phase: ctx.currentPhase,\n startTime: this.phaseStartTime,\n endTime: now,\n durationMs: now - this.phaseStartTime,\n });\n\n store.set('duration', {\n phaseSnapshots: [...this.phaseSnapshots],\n totalDurationMs,\n } satisfies DurationData);\n }\n}\n","import type { ProgressEmitter, SpinnerHandle } from '@agent/progress';\nimport { AgentSignals } from '@agent/agent-interface';\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport type { TokenData } from './token-tracker';\nimport type { TurnData } from './turn-counter';\nimport type { CostData } from './cost-tracker';\nimport type { DurationData } from './duration-tracker';\nimport type { CompactionData } from './compaction-tracker';\nimport type { ContextSizeData } from './context-size-tracker';\nimport type { CacheData } from './cache-tracker';\n\nfunction fmtDuration(ms: number): string {\n const s = Math.round(ms / 1000);\n const m = Math.floor(s / 60);\n return m > 0 ? `${m}m ${s % 60}s` : `${s}s`;\n}\n\nfunction fmtTok(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;\n if (n >= 1_000) return `${(n / 1000).toFixed(1)}K`;\n return n.toLocaleString();\n}\n\nfunction fmtCost(usd: number): string {\n if (usd > 0 && usd < 0.01) return `$${usd.toFixed(4)}`;\n return `$${usd.toFixed(2)}`;\n}\n\ninterface PhaseStats {\n phase: string;\n durationMs: number;\n turns: number;\n inputTokens: number;\n outputTokens: number;\n cacheRead: number;\n cacheCreation5m: number;\n cacheCreation1h: number;\n cost: number;\n compactions: number;\n contextOut: number | undefined;\n}\n\nfunction printPhase(s: PhaseStats): string {\n const baseIn = Math.max(\n 0,\n s.inputTokens - s.cacheRead - s.cacheCreation5m - s.cacheCreation1h,\n );\n return [\n `${s.phase}: ${fmtDuration(s.durationMs)}, ${\n s.turns\n } turns, cost: ${fmtCost(s.cost)}`,\n ` in: ${fmtTok(baseIn)}, out: ${fmtTok(\n s.outputTokens,\n )}, cache_read: ${fmtTok(s.cacheRead)}, cache_5m: ${fmtTok(\n s.cacheCreation5m,\n )}, cache_1h: ${fmtTok(s.cacheCreation1h)}`,\n s.compactions > 0 ? ` ${s.compactions} compaction(s)` : null,\n s.contextOut !== undefined ? ` ctx_out: ${fmtTok(s.contextOut)}` : null,\n ]\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getPhaseStats(i: number, ctx: MiddlewareContext): PhaseStats | null {\n const duration = ctx.get<DurationData>('duration');\n const dur = duration?.phaseSnapshots[i];\n if (!dur) return null;\n\n const tokens = ctx.get<TokenData>('tokens');\n const turns = ctx.get<TurnData>('turns');\n const cost = ctx.get<CostData>('cost');\n const compactions = ctx.get<CompactionData>('compactions');\n const contextSize = ctx.get<ContextSizeData>('contextSize');\n const cache = ctx.get<CacheData>('cache');\n\n return {\n phase: dur.phase,\n durationMs: dur.durationMs,\n turns: turns?.phaseSnapshots[i]?.turns ?? 0,\n inputTokens: tokens?.phaseSnapshots[i]?.inputTokens ?? 0,\n outputTokens: tokens?.phaseSnapshots[i]?.outputTokens ?? 0,\n cacheRead: cache?.phaseSnapshots[i]?.cacheReadTokens ?? 0,\n cacheCreation5m: cache?.phaseSnapshots[i]?.cacheCreation5m ?? 0,\n cacheCreation1h: cache?.phaseSnapshots[i]?.cacheCreation1h ?? 0,\n cost: cost?.phaseCosts[i]?.cost ?? 0,\n compactions: compactions?.phaseSnapshots[i]?.compactions ?? 0,\n contextOut: contextSize?.phaseSnapshots[i]?.contextTokensOut,\n };\n}\n\nexport class SummaryPlugin implements Middleware {\n readonly name = 'summary';\n\n private spinner: SpinnerHandle;\n\n private readonly info: (message: string) => void;\n\n constructor(spinner: SpinnerHandle, emit: ProgressEmitter) {\n this.spinner = spinner;\n this.info = (message) => emit({ kind: 'log', level: 'info', message });\n }\n\n onPhaseTransition(\n fromPhase: string,\n toPhase: string,\n ctx: MiddlewareContext,\n _store: MiddlewareStore,\n ): void {\n const duration = ctx.get<DurationData>('duration');\n const idx = (duration?.phaseSnapshots.length ?? 1) - 1;\n const stats = getPhaseStats(idx, ctx);\n\n if (stats) {\n this.spinner.stop(`${AgentSignals.BENCHMARK} ${printPhase(stats)}`);\n } else {\n this.spinner.stop(`${AgentSignals.BENCHMARK} ${fromPhase}`);\n }\n\n this.info(`${AgentSignals.BENCHMARK} Starting phase: ${toPhase}`);\n this.spinner.start(`Integrating PostHog (${toPhase})...`);\n }\n\n onFinalize(\n _resultMessage: any,\n totalDurationMs: number,\n ctx: MiddlewareContext,\n _store: MiddlewareStore,\n ): void {\n const duration = ctx.get<DurationData>('duration');\n const cost = ctx.get<CostData>('cost');\n const tokens = ctx.get<TokenData>('tokens');\n const cache = ctx.get<CacheData>('cache');\n\n const phaseCount = duration?.phaseSnapshots.length ?? 0;\n const totalCost = cost?.totalCost ?? 0;\n\n this.info('');\n this.info(\n `◇ ${AgentSignals.BENCHMARK} ${phaseCount} phases in ${fmtDuration(\n totalDurationMs,\n )}, cost: ${fmtCost(totalCost)}`,\n );\n this.info(\n ` total in: ${fmtTok(tokens?.totalInput ?? 0)}, out: ${fmtTok(\n tokens?.totalOutput ?? 0,\n )}, cache_read: ${fmtTok(cache?.totalRead ?? 0)}, cache_5m: ${fmtTok(\n cache?.totalCreation5m ?? 0,\n )}, cache_1h: ${fmtTok(cache?.totalCreation1h ?? 0)}`,\n );\n this.info('');\n this.info(`● ${AgentSignals.BENCHMARK} Summary by phase:`);\n\n if (duration?.phaseSnapshots) {\n for (let i = 0; i < duration.phaseSnapshots.length; i++) {\n const stats = getPhaseStats(i, ctx);\n if (stats) {\n this.info(printPhase(stats));\n }\n }\n }\n\n this.info('');\n }\n}\n","/**\n * JSON file output plugin.\n *\n * Assembles the BenchmarkData structure from all upstream plugin data\n * and writes it to a JSON file. Returns the BenchmarkData for backward compat.\n */\n\nimport fs from 'fs';\nimport type { ProgressEmitter } from '@agent/progress';\nimport { logToFile } from '@utils/debug';\nimport { AgentSignals } from '@agent/agent-interface';\nimport type {\n Middleware,\n MiddlewareContext,\n MiddlewareStore,\n} from '@agent/middleware/types';\nimport type { TokenData } from './token-tracker';\nimport type { CacheData } from './cache-tracker';\nimport type { TurnData } from './turn-counter';\nimport type { CostData } from './cost-tracker';\nimport type { DurationData } from './duration-tracker';\nimport type { CompactionData } from './compaction-tracker';\nimport type { ContextSizeData } from './context-size-tracker';\nimport type { BenchmarkData, StepUsage } from '@agent/middleware/benchmark';\n\n/**\n * Sum token usage across all models from the SDK's modelUsage field.\n */\nfunction sumModelUsage(modelUsage: Record<string, any>): {\n input_tokens: number;\n output_tokens: number;\n cache_creation_input_tokens: number;\n cache_read_input_tokens: number;\n} {\n let input_tokens = 0;\n let output_tokens = 0;\n let cache_creation_input_tokens = 0;\n let cache_read_input_tokens = 0;\n\n for (const model of Object.values(modelUsage)) {\n input_tokens += model.inputTokens ?? 0;\n output_tokens += model.outputTokens ?? 0;\n cache_creation_input_tokens += model.cacheCreationInputTokens ?? 0;\n cache_read_input_tokens += model.cacheReadInputTokens ?? 0;\n }\n\n return {\n input_tokens,\n output_tokens,\n cache_creation_input_tokens,\n cache_read_input_tokens,\n };\n}\n\nexport class JsonWriterPlugin implements Middleware {\n readonly name = 'jsonWriter';\n\n private outputPath: string;\n private readonly info: (message: string) => void;\n\n constructor(outputPath: string, emit: ProgressEmitter) {\n this.outputPath = outputPath;\n this.info = (message) => emit({ kind: 'log', level: 'info', message });\n }\n\n onFinalize(\n resultMessage: any,\n totalDurationMs: number,\n ctx: MiddlewareContext,\n _store: MiddlewareStore,\n ): BenchmarkData {\n const tokens = ctx.get<TokenData>('tokens');\n const cache = ctx.get<CacheData>('cache');\n const turns = ctx.get<TurnData>('turns');\n const cost = ctx.get<CostData>('cost');\n const duration = ctx.get<DurationData>('duration');\n const compactions = ctx.get<CompactionData>('compactions');\n const contextSize = ctx.get<ContextSizeData>('contextSize');\n\n const modelUsage = resultMessage?.modelUsage ?? {};\n const aggregateUsage = sumModelUsage(modelUsage);\n\n const phaseCount = duration?.phaseSnapshots.length ?? 0;\n const steps: StepUsage[] = [];\n\n for (let i = 0; i < phaseCount; i++) {\n const dur = duration!.phaseSnapshots[i];\n const tokenSnap = tokens?.phaseSnapshots[i];\n const cacheSnap = cache?.phaseSnapshots[i];\n const turnSnap = turns?.phaseSnapshots[i];\n const costSnap = cost?.phaseCosts[i];\n const compSnap = compactions?.phaseSnapshots[i];\n const ctxSnap = contextSize?.phaseSnapshots[i];\n\n const step: StepUsage = {\n name: dur.phase,\n usage: {\n input_tokens: tokenSnap?.inputTokens ?? 0,\n output_tokens: tokenSnap?.outputTokens ?? 0,\n cache_creation_input_tokens: cacheSnap?.cacheCreationTokens ?? 0,\n cache_read_input_tokens: cacheSnap?.cacheReadTokens ?? 0,\n ...((cacheSnap?.cacheCreation5m ?? 0) +\n (cacheSnap?.cacheCreation1h ?? 0) >\n 0 && {\n cache_creation: {\n ephemeral_5m_input_tokens: cacheSnap?.cacheCreation5m ?? 0,\n ephemeral_1h_input_tokens: cacheSnap?.cacheCreation1h ?? 0,\n },\n }),\n },\n modelUsage: {},\n totalCostUsd: costSnap?.cost ?? 0,\n durationMs: dur.durationMs,\n durationApiMs: 0,\n numTurns: turnSnap?.turns ?? 0,\n ...(ctxSnap?.contextTokensIn !== undefined && {\n contextTokensIn: ctxSnap.contextTokensIn,\n }),\n ...(ctxSnap?.contextTokensOut !== undefined && {\n contextTokensOut: ctxSnap.contextTokensOut,\n }),\n ...(compSnap && compSnap.compactions > 0\n ? {\n compactions: compSnap.compactions,\n compactionPreTokens: compSnap.preTokens,\n }\n : {}),\n };\n\n steps.push(step);\n }\n\n const totalTurns = turns?.totalTurns ?? 0;\n const totalCost = cost?.totalCost ?? 0;\n const totalCompactions = compactions?.totalCompactions ?? 0;\n const fromModelUsage =\n aggregateUsage.input_tokens +\n aggregateUsage.cache_read_input_tokens +\n aggregateUsage.cache_creation_input_tokens;\n const inputTokens =\n fromModelUsage > 0\n ? fromModelUsage\n : (tokens?.totalInput ?? 0) +\n (cache?.totalRead ?? 0) +\n (cache?.totalCreation ?? 0);\n const outputTokens =\n aggregateUsage.output_tokens > 0\n ? aggregateUsage.output_tokens\n : tokens?.totalOutput ?? 0;\n\n const benchmark: BenchmarkData = {\n timestamp: new Date().toISOString(),\n steps,\n totals: {\n totalCostUsd: totalCost,\n durationMs: totalDurationMs,\n inputTokens,\n outputTokens,\n numTurns: resultMessage?.num_turns ?? totalTurns,\n totalCompactions,\n totalCacheReadTokens: cache?.totalRead ?? 0,\n totalCacheCreation5mTokens: cache?.totalCreation5m ?? 0,\n totalCacheCreation1hTokens: cache?.totalCreation1h ?? 0,\n },\n };\n\n this.writeBenchmarkData(benchmark);\n return benchmark;\n }\n\n private writeBenchmarkData(data: BenchmarkData): void {\n try {\n fs.writeFileSync(this.outputPath, JSON.stringify(data, null, 2));\n logToFile(`Benchmark data written to ${this.outputPath}`);\n this.info(\n `● ${AgentSignals.BENCHMARK} Results written to ${this.outputPath}`,\n );\n } catch (error) {\n logToFile('Failed to write benchmark data:', error);\n }\n }\n}\n","/**\n * Plugin registry and factory.\n *\n * Maps plugin names to constructors and creates the ordered plugin list\n * from a BenchmarkConfig.\n */\n\nimport type {\n Middleware,\n MiddlewareFactoryOptions,\n} from '@agent/middleware/types';\nimport type { BenchmarkConfig } from '@agent/middleware/config';\nimport { TurnCounterPlugin } from './turn-counter';\nimport { TokenTrackerPlugin } from './token-tracker';\nimport { CacheTrackerPlugin } from './cache-tracker';\nimport { CompactionTrackerPlugin } from './compaction-tracker';\nimport { ContextSizeTrackerPlugin } from './context-size-tracker';\nimport { CostTrackerPlugin } from './cost-tracker';\nimport { DurationTrackerPlugin } from './duration-tracker';\nimport { SummaryPlugin } from './summary';\nimport { JsonWriterPlugin } from './json-writer';\n\ntype PluginFactory = (opts: MiddlewareFactoryOptions) => Middleware;\n\nconst PLUGIN_REGISTRY: Record<string, PluginFactory> = {\n turns: () => new TurnCounterPlugin(),\n tokens: () => new TokenTrackerPlugin(),\n cache: () => new CacheTrackerPlugin(),\n compactions: () => new CompactionTrackerPlugin(),\n contextSize: () => new ContextSizeTrackerPlugin(),\n cost: () => new CostTrackerPlugin(),\n duration: () => new DurationTrackerPlugin(),\n summary: (opts) => new SummaryPlugin(opts.spinner!, opts.emit),\n jsonWriter: (opts) => new JsonWriterPlugin(opts.outputPath!, opts.emit),\n};\n\n/**\n * Execution order — data producers before consumers:\n * turns (dedup) -> tokens -> cache -> compactions -> contextSize -> cost -> duration -> summary -> jsonWriter\n */\nconst PLUGIN_ORDER = [\n 'turns',\n 'tokens',\n 'cache',\n 'compactions',\n 'contextSize',\n 'cost',\n 'duration',\n 'summary',\n 'jsonWriter',\n];\n\nexport function createPluginsFromConfig(\n config: BenchmarkConfig,\n opts: MiddlewareFactoryOptions,\n): Middleware[] {\n const resolvedOpts: MiddlewareFactoryOptions = {\n ...opts,\n outputPath: opts.outputPath ?? config.output.benchmarkPath,\n };\n\n // If suppressWizardLogs is set, disable the summary plugin\n const effectivePlugins = { ...config.plugins };\n if (config.output.suppressWizardLogs) {\n effectivePlugins.summary = false;\n }\n\n return PLUGIN_ORDER.filter((name) => effectivePlugins[name] !== false)\n .map((name) => PLUGIN_REGISTRY[name])\n .filter(Boolean)\n .map((factory) => factory(resolvedOpts));\n}\n","/**\n * Benchmark tracking for wizard runs.\n *\n * Usage:\n * const pipeline = createBenchmarkPipeline(emit, spinner, options);\n * pipeline.onMessage(message);\n * pipeline.finalize(resultMessage, durationMs);\n */\n\nimport type { ProgressEmitter, SpinnerHandle } from '@agent/progress';\nimport { logToFile, getLogFilePath, configureLogFile } from '@utils/debug';\nimport { MiddlewarePipeline } from './pipeline';\nimport { PhaseDetector } from './phase-detector';\nimport { loadBenchmarkConfig } from './config';\nimport { createPluginsFromConfig } from './benchmarks';\nimport type { BenchmarkConfig } from './config';\nimport type { WizardRunOptions } from '@utils/types';\nimport { AgentSignals } from '@agent/agent-interface';\n\n// ── Types ──────────────────────────────────────────────────────────────\n\nexport interface StepUsage {\n name: string;\n usage: {\n input_tokens: number;\n output_tokens: number;\n cache_creation_input_tokens: number;\n cache_read_input_tokens: number;\n cache_creation?: {\n ephemeral_5m_input_tokens: number;\n ephemeral_1h_input_tokens: number;\n };\n };\n modelUsage: Record<string, unknown>;\n totalCostUsd: number;\n durationMs: number;\n durationApiMs: number;\n numTurns: number;\n contextTokensIn?: number;\n contextTokensOut?: number;\n compactions?: number;\n compactionPreTokens?: number[];\n}\n\nexport interface BenchmarkData {\n timestamp: string;\n steps: StepUsage[];\n totals: {\n totalCostUsd: number;\n durationMs: number;\n inputTokens: number;\n outputTokens: number;\n numTurns: number;\n totalCompactions: number;\n totalCacheReadTokens: number;\n totalCacheCreation5mTokens: number;\n totalCacheCreation1hTokens: number;\n };\n}\n\n// ── Factory ────────────────────────────────────────────────────────────\n\n/**\n * Create a middleware pipeline configured for benchmarking.\n * Loads .benchmark-config.json from the install dir, falls back to defaults.\n */\nexport function createBenchmarkPipeline(\n emit: ProgressEmitter,\n spinner: SpinnerHandle,\n options: WizardRunOptions,\n configOverride?: BenchmarkConfig,\n): MiddlewarePipeline {\n const config = configOverride ?? loadBenchmarkConfig(options.installDir);\n const info = (message: string) =>\n emit({ kind: 'log', level: 'info', message });\n\n configureLogFile({\n path: config.output.logPath,\n enabled: config.output.logEnabled,\n });\n\n const plugins = createPluginsFromConfig(config, {\n emit,\n spinner,\n phased: false,\n outputPath: config.output.benchmarkPath,\n });\n\n if (!config.output.suppressWizardLogs) {\n info(`${AgentSignals.BENCHMARK} Verbose logs: ${getLogFilePath()}`);\n info(\n `${AgentSignals.BENCHMARK} Benchmark data will be written to: ${config.output.benchmarkPath}`,\n );\n }\n\n logToFile(\n `${AgentSignals.BENCHMARK} Tracking enabled, starting with setup phase`,\n );\n\n return new MiddlewarePipeline(plugins, {\n phaseDetector: new PhaseDetector(),\n autoDetectPhases: true,\n });\n}\n","/**\n * Agent prompt assembly.\n *\n * Three sections, always in this order:\n * 1. Default project prompt — credentials and base context (always included)\n * 2. Custom prompt — additional program-specific instructions (if set)\n * 3. Skill prompt — \"follow SKILL.md\" instructions (if a skill was installed)\n */\n\nimport type { AgentRunDefinition } from './runner/shared/types';\nimport type { HostResolution } from '@shared/host-resolution';\n\n/**\n * Values available to prompt builders after OAuth completes.\n */\nexport interface PromptContext {\n projectId: number;\n projectApiKey: string;\n host: HostResolution;\n /** Set when skillId was provided and the skill was installed successfully. */\n skillPath?: string;\n /**\n * Org-level AI consent (`is_ai_data_processing_approved`) read from the\n * `/api/users/@me/` payload at auth time. `null` = unknown (older orgs,\n * or the user fetch failed). Lets prompts pre-resolve consent state so\n * agents only ask the user when it is actually off or unknown.\n */\n orgAiDataProcessingApproved?: boolean | null;\n /**\n * Team product opt-ins from the `/api/projects/:id/` payload at auth\n * time. Project-level truth for \"is this product enabled\" — products\n * can be instrumented from other repos or the snippet, so repo-local\n * evidence must never rule them out. `null` field = unknown.\n */\n teamProductOptIns?: {\n sessionReplay?: boolean | null;\n exceptionAutocapture?: boolean | null;\n surveys?: boolean | null;\n } | null;\n}\n\nfunction defaultProjectPrompt(ctx: PromptContext): string {\n return `You have access to the PostHog MCP server.\n\nProject context:\n- PostHog Project ID: ${ctx.projectId}\n- PostHog public token: ${ctx.projectApiKey}\n- PostHog Host: ${ctx.host.apiHost}`;\n}\n\nfunction skillPrompt(skillPath: string, reportFile: string): string {\n return `A PostHog skill has been installed at ${skillPath}/. Read ${skillPath}/SKILL.md and follow its instructions completely.\n\nAfter completing the skill workflow, write a brief markdown report to ./${reportFile} summarizing:\n- What changes were made to the project\n- Which files were modified or created\n- Any manual steps the user should take next\n\nImportant: You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.`;\n}\n\n/**\n * Assemble the final agent prompt from the program's run config.\n */\nexport function assemblePrompt(\n runDef: AgentRunDefinition,\n ctx: PromptContext,\n): string {\n const parts: string[] = [];\n\n // Always include the default project prompt\n parts.push(defaultProjectPrompt(ctx));\n\n // Additional program-specific instructions\n if (runDef.customPrompt) {\n parts.push(runDef.customPrompt(ctx));\n }\n\n // Skill prompt (appended when a skill was pre-installed)\n if (ctx.skillPath) {\n parts.push(skillPrompt(ctx.skillPath, runDef.reportFile));\n }\n\n return parts.join('\\n\\n');\n}\n","/**\n * Shared error helpers for the runner pipeline.\n */\n\nimport type { InstallSkillResult } from '@agent/tools';\nimport { ErrorCodes, skillErrorCode } from '@shared/errors';\nimport { RunOutcome, type AgentFailure, type SequenceResult } from './types';\n\nexport const failed = (failure: AgentFailure): SequenceResult => ({\n outcome: RunOutcome.Failed,\n failure,\n});\n\n/** The failure a skill install error decides. The caller reports and exits. */\nexport function installFailure(\n integrationLabel: string,\n result: Exclude<InstallSkillResult, { kind: 'ok' }>,\n): AgentFailure {\n const code = skillErrorCode(result) ?? ErrorCodes.InternalUnhandled;\n\n const message = (() => {\n switch (result.kind) {\n case 'menu-fetch-failed':\n return 'Could not fetch the skill menu from context-mill.\\nCheck your network connection and try again.';\n case 'skill-not-found':\n return `Could not find the \"${result.skillId}\" skill in the context-mill menu.\\nPlease try again later.`;\n case 'download-failed':\n return `Failed to install skill: ${result.message}\\nPlease try again.`;\n }\n })();\n\n return {\n message,\n code,\n detail: {\n integration: integrationLabel,\n error_type: result.kind,\n platform: process.platform,\n ...(result.kind === 'download-failed'\n ? { error_detail: result.message.slice(0, 500) }\n : {}),\n },\n };\n}\n","/**\n * The ask bridge over an injected answerer.\n *\n * `createWizardAskBridge` already owns request ids, the timeout race, the\n * `__cancelled__` sentinel and the analytics; it only ever needed a\n * `showQuestion` that honours each question's own signal. Here that comes from\n * `AgentInteraction` instead of `getUI()`. With no answerer there is no bridge,\n * so `wizard_ask` reports its existing \"not available\" error rather than\n * hanging on a question nobody can see.\n */\n\nimport {\n createWizardAskBridge,\n type WizardAskBridge,\n} from '@agent/wizard-ask-bridge';\nimport type { AgentInteraction } from '@agent/progress';\n\nexport function createAskBridge(\n interaction: AgentInteraction | undefined,\n options: {\n getSource: () => string;\n richLinks: boolean;\n timeoutMs?: number;\n signal?: AbortSignal;\n /** Runs before each question is shown (the orchestrator's bell and metric). */\n beforeShow?: () => void;\n },\n): WizardAskBridge | undefined {\n const ask = interaction?.ask;\n if (!ask) return undefined;\n\n return createWizardAskBridge({\n getSource: options.getSource,\n showQuestion: (question, context) => {\n options.beforeShow?.();\n return ask(question, context);\n },\n richLinks: options.richLinks,\n timeoutMs: options.timeoutMs,\n signal: options.signal,\n });\n}\n","/**\n * The linear pipeline. Single execution path for all non-orchestrator programs,\n * both skill-based (revenue analytics) and framework-based (core integration).\n * The `AgentRunDefinition` controls what varies between them; `RunConfig`\n * carries the program-level static metadata (tool allow/disallow lists, etc.).\n *\n * Reports through `emit`, asks through `interaction`, and returns a decided\n * `RunResult`. Every former `getUI()` call is one progress event in the same\n * place; every former `wizardAbort` is a returned failure with the same\n * arguments, so the caller's exit sequence is unchanged.\n */\n\nimport { OutroKind, type OutroData } from '@agent/progress';\nimport { AgentErrorType } from '../../agent-interface';\nimport { logToFile } from '@utils/debug';\nimport { createBenchmarkPipeline } from '@agent/middleware/benchmark';\nimport { AGENT_ERROR_CODE, ErrorCodes } from '@shared/errors';\nimport { analytics } from '@utils/analytics';\nimport { formatYaraAbortMessage } from '@agent/yara-hooks';\nimport { installSkillById } from '@agent/tools';\nimport { assemblePrompt } from '../../agent-prompt';\nimport type { SequenceResult, SequenceContext } from '../shared/types';\nimport { failed, installFailure } from '../shared/errors';\nimport { RunOutcome } from '../shared/types';\nimport { shouldDisableAsk, runOptions } from '../shared/bootstrap';\nimport { createEmitSpinner } from '../shared/progress-collector';\nimport { createAskBridge } from '../shared/ask';\nimport { getHarness } from '../switchboard';\n\nexport async function runLinearProgram(\n context: SequenceContext,\n): Promise<SequenceResult> {\n // Aborts on the host's signal or when the run ends, so no ask outlives it.\n const controller = new AbortController();\n const abortFromHost = () => controller.abort();\n context.signal?.addEventListener('abort', abortFromHost, { once: true });\n if (context.signal?.aborted) abortFromHost();\n try {\n return await executeLinear(context, controller.signal);\n } finally {\n context.signal?.removeEventListener('abort', abortFromHost);\n controller.abort();\n }\n}\n\n/** The host's `signal` decides the outcome; `runSignal` also ends with the run. */\nasync function executeLinear(\n { config, input, boot, emit, interaction, signal }: SequenceContext,\n runSignal: AbortSignal,\n): Promise<SequenceResult> {\n const { run, composed } = config;\n const { skillsBaseUrl, credentials, project } = boot;\n const { projectApiKey, host, projectId } = credentials;\n const aborted = (): SequenceResult => ({\n outcome: RunOutcome.Aborted,\n failure: { code: ErrorCodes.AgentAbort, message: 'Agent run cancelled' },\n });\n if (signal?.aborted) return aborted();\n\n // 5. Skill install (if skillId provided)\n let skillPath: string | undefined;\n if (run.skillId) {\n logToFile(`[agent-runner] installing skill ${run.skillId}`);\n const installResult = await installSkillById(\n run.skillId,\n input.installDir,\n skillsBaseUrl,\n { triage: boot.triageProvider },\n );\n if (signal?.aborted) return aborted();\n if (installResult.kind !== 'ok') {\n return failed(installFailure(run.integrationLabel, installResult));\n }\n skillPath = installResult.path;\n logToFile(`[agent-runner] skill installed at ${skillPath}`);\n }\n\n // 6. Initialize agent\n const spinner = createEmitSpinner(emit);\n\n emit({ kind: 'lifecycle', phase: 'started' });\n\n // wizard_ask needs an answerer. A human answers at the keyboard; the e2e\n // snapshot/MCP host answers via its driver and sets WIZARD_ASK_AUTODRIVE.\n // CI/signup with neither has no answerer, so we omit the bridge and the tool\n // returns an actionable error rather than hanging on a never-resolving prompt.\n const askDisabled =\n shouldDisableAsk(input.flags) && process.env.WIZARD_ASK_AUTODRIVE !== '1';\n const ask = askDisabled\n ? undefined\n : createAskBridge(interaction, {\n getSource: () => input.skillId ?? run.integrationLabel,\n richLinks: run.richLinks ?? false,\n timeoutMs: run.askTimeoutMs,\n signal: runSignal,\n });\n\n const middleware = input.flags.benchmark\n ? createBenchmarkPipeline(emit, spinner, runOptions(input))\n : undefined;\n\n // 7. Build prompt\n const prompt = assemblePrompt(run, {\n projectId,\n projectApiKey,\n host,\n skillPath,\n orgAiDataProcessingApproved:\n input.apiUser?.organization?.is_ai_data_processing_approved ?? null,\n teamProductOptIns: project\n ? {\n sessionReplay: project.session_recording_opt_in ?? null,\n exceptionAutocapture: project.autocapture_exceptions_opt_in ?? null,\n surveys: project.surveys_opt_in ?? null,\n }\n : null,\n });\n logToFile(`[agent-runner] prompt assembled (${prompt.length} chars)`);\n if (signal?.aborted) return aborted();\n\n // 8. Run the agent through the run-level harness. The harness owns the agent\n // loop + model transport; everything around it (skill install, prompt, ask\n // bridge, error routing, outro) stays here so every harness shares it.\n const { harness, model, thinkingLevel } = config.binding;\n const agentResult = await getHarness(harness).run({\n config,\n input,\n boot,\n emit,\n prompt,\n skillPath,\n spinner,\n askBridge: ask,\n middleware,\n model,\n thinkingLevel,\n signal: runSignal,\n });\n if (signal?.aborted && agentResult.kind === 'success') return aborted();\n\n // 9. Error handling (full set from both harnesses)\n if (agentResult.kind === 'decided_failure') {\n return failed(agentResult.failure);\n }\n\n if (agentResult.kind === 'success') {\n // Success continues through the post-run hooks and outro below.\n } else if (agentResult.kind !== 'abort' && agentResult.kind !== 'failure') {\n const _exhaustive: never = agentResult;\n return _exhaustive;\n }\n\n if (agentResult.kind === 'abort') {\n const reason = agentResult.message ?? '';\n const matched = run.abortCases?.find((c) => c.match.test(reason));\n const abortCode = matched?.errorCode ?? ErrorCodes.AgentAbort;\n const outroData: OutroData = matched\n ? {\n kind: OutroKind.Error,\n message: matched.message,\n body: matched.body,\n docsUrl: matched.docsUrl,\n errorCode: abortCode,\n errorDetail: { reason },\n }\n : {\n kind: OutroKind.Error,\n message: `${run.integrationLabel} aborted`,\n body: reason || 'The agent aborted the program.',\n docsUrl: run.docsUrl,\n errorCode: abortCode,\n errorDetail: { reason },\n };\n analytics.wizardCapture('agent aborted', {\n integration: run.integrationLabel,\n reason,\n matched: matched?.message ?? null,\n });\n return {\n // An agent that stops itself failed the run; only the host's signal cancels it.\n outcome: signal?.aborted ? RunOutcome.Aborted : RunOutcome.Failed,\n failure: {\n message: matched?.message ?? `${run.integrationLabel} aborted`,\n outroData,\n code: abortCode,\n error: agentResult.error,\n },\n };\n }\n\n const classification =\n agentResult.kind === 'failure' ? agentResult.classification : undefined;\n const failureMessage =\n agentResult.kind === 'failure' ? agentResult.message : undefined;\n\n if (classification === AgentErrorType.MCP_MISSING) {\n return failed({\n code: AGENT_ERROR_CODE[AgentErrorType.MCP_MISSING],\n message:\n 'Could not access the PostHog MCP server\\n\\n' +\n 'The wizard was unable to connect to the PostHog MCP server.\\n' +\n 'This could be due to a network issue or a configuration problem.\\n\\n' +\n `Please try again, or check the documentation:\\n${run.docsUrl}`,\n error: agentResult.kind === 'failure' ? agentResult.error : undefined,\n });\n }\n\n if (classification === AgentErrorType.RESOURCE_MISSING) {\n return failed({\n code: AGENT_ERROR_CODE[AgentErrorType.RESOURCE_MISSING],\n message:\n 'Could not access the setup resource\\n\\n' +\n 'This may indicate a version mismatch or a temporary service issue.\\n\\n' +\n `Please try again, or check the documentation:\\n${run.docsUrl}`,\n error: agentResult.kind === 'failure' ? agentResult.error : undefined,\n });\n }\n\n if (classification === AgentErrorType.YARA_VIOLATION) {\n return failed({\n code: AGENT_ERROR_CODE[AgentErrorType.YARA_VIOLATION],\n message: formatYaraAbortMessage(),\n error: agentResult.kind === 'failure' ? agentResult.error : undefined,\n });\n }\n\n if (classification === AgentErrorType.NO_PROGRESS) {\n analytics.wizardCapture('agent no progress', {\n integration: run.integrationLabel,\n error_type: AgentErrorType.NO_PROGRESS,\n });\n return failed({\n code: AGENT_ERROR_CODE[AgentErrorType.NO_PROGRESS],\n message:\n 'The Wizard exited without changing your project. Please contact the ' +\n 'PostHog team with wizard@posthog.com about this error.',\n error: agentResult.kind === 'failure' ? agentResult.error : undefined,\n });\n }\n\n if (classification === AgentErrorType.INCOMPLETE_TASKS) {\n analytics.wizardCapture('agent incomplete tasks', {\n integration: run.integrationLabel,\n error_type: AgentErrorType.INCOMPLETE_TASKS,\n });\n return failed({\n code: AGENT_ERROR_CODE[AgentErrorType.INCOMPLETE_TASKS],\n message:\n 'The Wizard exited without completing its planned tasks. Please contact ' +\n 'the PostHog team with wizard@posthog.com about this error.',\n error: agentResult.kind === 'failure' ? agentResult.error : undefined,\n });\n }\n\n if (\n classification === AgentErrorType.RATE_LIMIT ||\n classification === AgentErrorType.API_ERROR\n ) {\n analytics.wizardCapture('agent api error', {\n integration: run.integrationLabel,\n error_type: classification,\n error_message: failureMessage,\n });\n\n return failed({\n code: AGENT_ERROR_CODE[classification],\n message: `API Error\\n\\n${\n failureMessage || 'Unknown error'\n }\\n\\nPlease report this to: wizard@posthog.com`,\n error: agentResult.kind === 'failure' ? agentResult.error : undefined,\n });\n }\n\n if (agentResult.kind === 'failure') {\n return failed({\n code: AGENT_ERROR_CODE[agentResult.classification],\n message: agentResult.message ?? 'Agent failed',\n error: agentResult.error,\n });\n }\n\n // 10. Post-run hooks\n if (config.hooks?.postRun) {\n await config.hooks.postRun(credentials);\n if (signal?.aborted) return aborted();\n }\n\n // A composed sub-run leaves the terminal outro to its host.\n if (composed) {\n return { outcome: RunOutcome.Success };\n }\n\n // 11. Outro\n const outroData: OutroData | undefined = config.hooks?.buildOutroData\n ? config.hooks.buildOutroData(credentials)\n : {\n kind: OutroKind.Success,\n message: run.successMessage,\n reportFile: run.reportFile,\n docsUrl: run.docsUrl,\n continueUrl: input.flags.signup\n ? `${host.appHost}/products?source=wizard`\n : undefined,\n };\n if (outroData) {\n emit({ kind: 'completion', outro: outroData });\n }\n\n emit({ kind: 'lifecycle', phase: 'completed', message: run.successMessage });\n\n return { outcome: RunOutcome.Success, outro: outroData };\n}\n","/**\n * Ring the terminal bell (BEL, U+0007).\n *\n * The orchestrator takes consent for the warehouse step at the top of the run\n * and asks for the credentials at the end of it, several autonomous minutes\n * later. The person who agreed is often looking at something else by then. A\n * bell is the one attention signal a terminal in a background tab can still\n * deliver, and it costs a user who is watching nothing.\n *\n * Written to stderr, not stdout: Ink owns stdout and repaints whole frames, so\n * a byte written there can land inside one. Silent when stderr is not a TTY —\n * a pipe or a CI log cannot ring, and the byte would only pollute the capture.\n */\nexport function ringTerminalBell(): void {\n if (!process.stderr.isTTY) return;\n try {\n process.stderr.write('\\u0007');\n } catch {\n // A bell is a nicety. It must never be the thing that ends a run.\n }\n}\n","/**\n * The executor drains the queue. It starts every runnable task (dependencies\n * satisfied) as soon as it becomes runnable — parallelism is decided by the\n * task graph, not by an executor knob. Each task runs through an injected\n * `runTask` function and reports its outcome via `complete_task`; a task that\n * ends without reporting is retried while attempts remain, then failed. A\n * `maxStarts` backstop guarantees termination.\n *\n * The drain loop is independent of how a task actually runs. `runTask` is\n * injected: the real one spins up a fresh agent, the tests use a fake.\n */\nimport { analytics } from '@utils/analytics';\nimport { RunOutcome, type AgentFailure } from '../../shared/types';\nimport { logToFile } from '@utils/debug';\nimport { TaskStatus, type QueueStore, type QueuedTask } from './queue';\n\n/** Per-task agent configuration the resolver produces from a task's type.\n * The model is resolved separately (per-harness profile), not here. */\nexport interface ResolvedTask {\n allowedTools: readonly string[];\n disallowedTools: readonly string[];\n /** Mini-skills to install before the task runs (the HOW). */\n skills: readonly string[];\n prompt: string;\n}\n\n/** Resolves a queued task to what the agent needs. The real one is markdown-backed. */\nexport type TaskResolver = (\n task: QueuedTask,\n store: QueueStore,\n) => ResolvedTask;\n\n/** Runs one task's agent. It is expected to drive the task to a terminal state\n * (via the task agent calling complete_task). */\nexport type RunTask = (task: QueuedTask) => Promise<void>;\n\n/**\n * Thrown by a `RunTask` when its harness returned a decided failure that ends\n * the whole run (a 401 the auth screen already reported), not just the task.\n * `drainQueue` lets it through so the sequence can return the failure where\n * the harness used to exit the process.\n */\nexport class RunTaskFatal extends Error {\n constructor(\n public readonly failure: AgentFailure,\n public readonly outcome:\n | RunOutcome.Aborted\n | RunOutcome.Failed = RunOutcome.Failed,\n /** The type of the task that ended the run, for the steps it stopped. */\n public readonly taskType?: string,\n ) {\n super(failure.message ?? 'agent run failed');\n this.name = 'RunTaskFatal';\n }\n}\n\nexport interface DrainOptions {\n /** Backstop against a pathological always-one-more-pending loop. */\n maxStarts: number;\n signal?: AbortSignal;\n onFatal?: () => void;\n}\n\nexport const DEFAULT_DRAIN_OPTIONS: DrainOptions = {\n maxStarts: 200,\n};\n\nasync function runOne(\n store: QueueStore,\n runTask: RunTask,\n task: QueuedTask,\n signal?: AbortSignal,\n): Promise<void> {\n if (signal?.aborted) return;\n store.start(task.id);\n try {\n await runTask(task);\n } catch (error) {\n if (signal?.aborted) return;\n if (error instanceof RunTaskFatal) throw error;\n // The task threw rather than reporting. The outcome check below handles\n // the queue; the exception itself should never be silent.\n logToFile(`[executor] runTask threw for ${task.type}:`, error);\n analytics.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'orchestrator_run_task', task_type: task.type },\n );\n }\n\n if (signal?.aborted) return;\n\n const after = store.get(task.id);\n if (!after) return;\n\n if (after.status === TaskStatus.Running) {\n // The agent ended without calling complete_task. Retry or fail.\n if (after.attempts < after.maxAttempts) {\n store.requeue(task.id);\n } else {\n store.fail(task.id, {\n type: 'no-report',\n message: 'Task ended without calling complete_task.',\n });\n }\n return;\n }\n\n if (\n after.status === TaskStatus.Failed &&\n after.attempts < after.maxAttempts\n ) {\n store.requeue(task.id);\n }\n}\n\n/**\n * Drain the queue to a terminal state. Every runnable task starts the moment\n * its dependencies finish; independent branches run concurrently. Returns when\n * every task is done, failed, or blocked by a failed dependency, or when the\n * start backstop trips.\n */\nexport async function drainQueue(\n store: QueueStore,\n runTask: RunTask,\n opts: DrainOptions = DEFAULT_DRAIN_OPTIONS,\n): Promise<void> {\n const running = new Map<string, Promise<void>>();\n let starts = 0;\n let failure: { error: unknown } | undefined;\n\n try {\n for (;;) {\n if (opts.signal?.aborted) break;\n if (failure) throw failure.error;\n for (const task of store.nextRunnable()) {\n if (opts.signal?.aborted) break;\n if (++starts > opts.maxStarts) break;\n const p = runOne(store, runTask, task, opts.signal)\n .catch((error: unknown) => {\n if (!failure) {\n failure = { error };\n try {\n opts.onFatal?.();\n } catch (abortError) {\n try {\n logToFile(\n '[executor] fatal cancellation failed:',\n abortError,\n );\n } catch {\n // Reporting cancellation failure cannot replace the fatal.\n }\n }\n }\n })\n .finally(() => running.delete(task.id));\n running.set(task.id, p);\n }\n if (running.size === 0) break;\n await Promise.race(running.values());\n }\n } finally {\n // No queue or skill cleanup may run while a sibling still uses them.\n await Promise.allSettled(running.values());\n }\n if (failure) throw failure.error;\n}\n","/**\n * Responsiveness metrics for an orchestrator run.\n *\n * Responsiveness is the experiment's headline: how quickly the user sees the\n * first progress, and whether progress stays steady (no long silences). The math\n * is accumulated from queue transitions but kept here, pure and time-injected, so\n * it is unit-testable away from the runner. Wall-clock times are passed in as\n * milliseconds; the caller owns the clock.\n */\n\nexport interface RunMetricsSummary {\n /** Run start → first task started. */\n time_to_first_task_ms?: number;\n /** Run start → first task completed (the first visible \"done\"). */\n time_to_first_completion_ms?: number;\n /** Longest silence between two consecutive user-visible transitions. */\n max_gap_ms?: number;\n /**\n * Run start → the first question put to the user. The number that says whether\n * a task which waits on a person actually runs late: small means it interrupted\n * the autonomous work, large means it waited for it. `undefined` on a run that\n * asked nothing, which is most of them.\n */\n time_to_first_ask_ms?: number;\n}\n\n/** The per-event timing the `orchestrator task started` event reports. */\nexport interface StartTiming {\n ms_since_run_start: number;\n gap_since_prev_start_ms?: number;\n}\n\nexport class RunMetrics {\n private firstStartMs?: number;\n private lastStartMs?: number;\n private firstCompleteMs?: number;\n private firstAskMs?: number;\n private lastVisibleMs?: number;\n private maxGapMs = 0;\n\n constructor(private readonly runStartMs: number) {}\n\n /** A task started. Returns the per-start-event timing for the start event. */\n recordStart(nowMs: number): StartTiming {\n const timing: StartTiming = {\n ms_since_run_start: nowMs - this.runStartMs,\n gap_since_prev_start_ms:\n this.lastStartMs === undefined ? undefined : nowMs - this.lastStartMs,\n };\n this.firstStartMs ??= nowMs;\n this.lastStartMs = nowMs;\n this.markVisible(nowMs);\n return timing;\n }\n\n /** A task completed. */\n recordComplete(nowMs: number): void {\n this.firstCompleteMs ??= nowMs;\n this.markVisible(nowMs);\n }\n\n /** A task reached a terminal non-complete state the user sees (skip/fail). */\n recordTerminal(nowMs: number): void {\n this.markVisible(nowMs);\n }\n\n /**\n * A question was put to the user. Only the first matters here, and it is not a\n * queue transition — waiting on a person is not the silence `max_gap_ms`\n * measures, so this deliberately does not mark visible progress.\n */\n recordAsk(nowMs: number): void {\n this.firstAskMs ??= nowMs;\n }\n\n /**\n * The run-level responsiveness summary. Timings are `undefined` when the\n * relevant transition never happened (e.g. a run that started no task), so a\n * no-task run stays distinguishable from a genuine zero.\n */\n summary(): RunMetricsSummary {\n return {\n time_to_first_task_ms:\n this.firstStartMs === undefined\n ? undefined\n : this.firstStartMs - this.runStartMs,\n time_to_first_completion_ms:\n this.firstCompleteMs === undefined\n ? undefined\n : this.firstCompleteMs - this.runStartMs,\n max_gap_ms: this.lastVisibleMs === undefined ? undefined : this.maxGapMs,\n time_to_first_ask_ms:\n this.firstAskMs === undefined\n ? undefined\n : this.firstAskMs - this.runStartMs,\n };\n }\n\n /** requeue is not user-visible, so a retry stall counts as silence here. */\n private markVisible(nowMs: number): void {\n if (this.lastVisibleMs !== undefined) {\n this.maxGapMs = Math.max(this.maxGapMs, nowMs - this.lastVisibleMs);\n }\n this.lastVisibleMs = nowMs;\n }\n}\n","/**\n * Where a runner-seeded task sits in the planner's graph.\n *\n * A runner-seeded task is queued from what the wizard detected, before the\n * planner runs (see `ProgramConfig.seedTasks`). At that moment the tasks it\n * should wait for do not exist, so it cannot name them: it is enqueued with no\n * dependencies and is therefore runnable in the first drain tier, alongside the\n * first coding tasks. For a task that stops to ask the user for credentials that\n * is the wrong place — the questions land while the coding agents are still\n * mid-flight.\n *\n * This module answers \"what should it wait for?\" once the planner has seeded the\n * queue. The task's agent prompt names the types it follows (`dependsOn` in\n * frontmatter); a prompt that names none waits for everything that is not the\n * sink, which puts it last but still ahead of the reporting step.\n *\n * Pure and store-reading only — the runner applies what this returns, and the\n * queue enforces the DAG.\n */\nimport type { QueuedTask, QueueStore } from './queue';\nimport { dependencyClosure } from './queue-tools';\n\nexport interface SeededDepsResult {\n /** Ids the seeded task should be made to wait for. */\n depIds: string[];\n /**\n * Declared types with no task of that type in the queue — the planner chose\n * not to queue one. Not an error: the edge is simply dropped, and the task\n * still runs after whatever else was declared.\n */\n unresolvedTypes: string[];\n /** Whether the ids came from the prompt's declared types or from the default. */\n declared: boolean;\n}\n\n/**\n * Resolve a runner-seeded task's dependencies against the planned queue.\n *\n * Two exclusions apply to both the declared and the default path:\n *\n * - **Sinks are never dependencies.** A sink runs last and must depend on the\n * whole queue, this task included. Depending on it back would invert the edge\n * and cost the report this task's `reportSection`. Leaving sinks out means a\n * planner that forgot the sink→seeded edge is still caught by the sink\n * invariant check rather than silently papered over here.\n * - **Anything already downstream of this task is never a dependency**, which is\n * what makes the result cycle-free by construction rather than by the queue's\n * per-edge refusal.\n */\nexport function seededDependencies(\n store: QueueStore,\n seededTaskId: string,\n declaredTypes: readonly string[],\n sinkTypes: readonly string[],\n): SeededDepsResult {\n const eligible = store.list().filter((task) => {\n if (task.id === seededTaskId) return false;\n if (sinkTypes.includes(task.type)) return false;\n // Downstream of us already (the planner hung it off this task): depending on\n // it would close a loop.\n return !dependencyClosure(store, [task.id]).has(seededTaskId);\n });\n\n if (declaredTypes.length === 0) {\n return {\n depIds: eligible.map((t) => t.id),\n unresolvedTypes: [],\n declared: false,\n };\n }\n\n const depIds: string[] = [];\n const unresolvedTypes: string[] = [];\n for (const type of declaredTypes) {\n // Against the whole queue, not just `eligible` — a declared type that was\n // queued but is downstream of us was resolved, just not usable as an edge.\n // Only a type the planner never queued at all is unresolved.\n if (!store.list().some((t) => t.type === type)) {\n unresolvedTypes.push(type);\n continue;\n }\n for (const task of eligible) {\n // Every task of the type, so a fanned-out step (one `capture` per event)\n // is waited for in full rather than by its first task alone.\n if (task.type === type && !depIds.includes(task.id)) depIds.push(task.id);\n }\n }\n\n return { depIds, unresolvedTypes, declared: true };\n}\n\n/** What deferring one seeded task did, for the runner to log and report. */\nexport interface DeferredSeededTask {\n type: string;\n /** Types the prompt declared; empty when it fell back to the default. */\n declaredTypes: string[];\n declared: boolean;\n /** Edges actually added to the queue. */\n added: string[];\n /**\n * Edges the queue refused — a cycle or an unknown id. Always empty in a\n * healthy run: this resolver already excludes both, so anything here means the\n * two disagree and is worth a telemetry look.\n */\n refused: string[];\n unresolvedTypes: string[];\n}\n\n/**\n * Give every runner-seeded task the dependencies it could not name at enqueue,\n * and report what happened per task.\n *\n * The runner calls this once, after the planner has seeded the queue and before\n * the sink invariant is checked. Kept here rather than inline in the runner so\n * the wiring — which prompt's types feed which task — is testable without\n * standing up a whole run.\n */\nexport function deferSeededTasks(\n store: QueueStore,\n seededTasks: readonly QueuedTask[],\n declaredTypesFor: (type: string) => readonly string[],\n sinkTypes: readonly string[],\n): DeferredSeededTask[] {\n return seededTasks.map((seeded) => {\n const declaredTypes = [...declaredTypesFor(seeded.type)];\n const resolved = seededDependencies(\n store,\n seeded.id,\n declaredTypes,\n sinkTypes,\n );\n const { added, refused } = store.addDependencies(\n seeded.id,\n resolved.depIds,\n );\n return {\n type: seeded.type,\n declaredTypes,\n declared: resolved.declared,\n added,\n refused,\n unresolvedTypes: resolved.unresolvedTypes,\n };\n });\n}\n","/**\n * Experimental task-queue orchestrator runner.\n *\n * Branches from the linear runner when the `wizard-orchestrator` flag is on. An\n * orchestrator agent inspects the repo and seeds an in-memory task queue; an\n * executor drains it, running one fresh agent per task.\n *\n * Both the WHAT (agent prompts: model, goal, success criteria, tools) and the\n * HOW (mini-skills) are markdown served from context-mill — the seed and every\n * task resolve to a prompt fetched at startup into the registry. The wizard side\n * stays product-ignorant: it is the queue, the executor, and the loader.\n */\nimport { failed } from '../../shared/errors';\nimport { RunOutcome } from '../../shared/types';\nimport { randomUUID } from 'crypto';\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n readdirSync,\n rmSync,\n writeFileSync,\n} from 'fs';\nimport * as path from 'path';\nimport { OutroKind, type TaskNotice } from '@agent/progress';\nimport {\n POSTHOG_DOCS_URL,\n WIZARD_CONTACT_EMAIL,\n WIZARD_OAUTH_SCOPES,\n WIZARD_PROVISIONING_SCOPES,\n} from '@shared/constants';\nimport { installSkillById } from '@agent/tools';\nimport { fetchSkillMenu, type SkillEntry } from '@shared/skill-menu';\nimport { analytics } from '@utils/analytics';\nimport { ciExcludedTaskTypes } from '@utils/ci-flag-overrides';\nimport { logToFile } from '@utils/debug';\nimport { ringTerminalBell } from '@utils/terminal-bell';\nimport {\n AGENT_ERROR_CODE,\n classifyRunFailure,\n ErrorCodes,\n WizardError,\n} from '@shared/errors';\nimport type { AgentResult } from '../../harness/types';\nimport type { AgentInteraction } from '@agent/progress';\nimport type {\n AgentFailure,\n RunConfig,\n SequenceResult,\n SequenceContext,\n} from '../../shared/types';\nimport { createEmitSpinner } from '../../shared/progress-collector';\nimport { createAskBridge } from '../../shared/ask';\nimport {\n areSeededTasksEnabled,\n getHarness,\n resolveHarness,\n resolveStageOverrides,\n type HarnessPick,\n} from '../../switchboard';\nimport { isValidModel, requireKnownModel } from '../../switchboard/models';\nimport type { AgentHarness } from '../../harness/types';\nimport {\n QueueStore,\n QUEUE_DIR_NAME,\n SkipReason,\n TaskStatus,\n type QueuedTask,\n type TaskOutcome,\n} from './queue';\nimport {\n DEFAULT_DRAIN_OPTIONS,\n drainQueue,\n RunTaskFatal,\n type RunTask,\n} from './executor';\nimport { RunMetrics } from './run-metrics';\nimport { dependencyClosure, uncoveredBySink } from './queue-tools';\nimport { deferSeededTasks } from './seeded-deps';\nimport { LONGER_ASK_TIMEOUT_MS } from '@agent/wizard-ask-bridge';\nimport { shouldDisableAsk } from '../../shared/bootstrap';\nimport {\n agentRunTools,\n assembleSeedPrompt,\n assembleTaskPrompt,\n loadAgentRegistry,\n promptModelFor,\n resolveTask,\n taskModelSpec,\n ASK_TOOL,\n type AgentPrompt,\n type OrchestratorPromptContext,\n} from '@agent/agent-prompt-loader';\n\n/** Docs page (`django.md`, `nuxt-js-3-6.md`) — steps start with a digit, agent artifacts (`SKILL.md`, `EXAMPLE*`, `COMMANDMENTS.md`) have uppercase. */\nconst isDocPage = (name: string): boolean =>\n name.endsWith('.md') && name === name.toLowerCase() && !/^\\d/.test(name);\n\n/** Copy only the framework docs pages out of the run cache into .claude/skills — the one durable artifact an orchestrator run leaves. Never clobbers an existing install. */\nexport function promoteReferenceSkill(\n referenceDir: string,\n claudeSkillsDir: string,\n referenceSkillId: string,\n): void {\n const target = path.join(claudeSkillsDir, referenceSkillId);\n const refs = path.join(referenceDir, 'references');\n if (!existsSync(refs) || existsSync(target)) return;\n const docs = readdirSync(refs).filter(isDocPage);\n if (docs.length === 0) return;\n mkdirSync(path.join(target, 'references'), { recursive: true });\n for (const f of docs) {\n cpSync(path.join(refs, f), path.join(target, 'references', f));\n }\n writeFileSync(path.join(target, '.posthog-wizard'), '');\n}\n\n/**\n * Remove skills that task agents installed durably mid-run (load_skill):\n * wizard-marked, new this run, and not the framework reference docs.\n * User-authored and pre-existing skills stay.\n */\nexport function sweepRunInstalledSkills(\n claudeSkillsDir: string,\n preexistingSkills: ReadonlySet<string>,\n referenceSkillId: string | undefined,\n): void {\n if (!existsSync(claudeSkillsDir)) return;\n for (const id of readdirSync(claudeSkillsDir)) {\n if (preexistingSkills.has(id) || id === referenceSkillId) continue;\n if (!existsSync(path.join(claudeSkillsDir, id, '.posthog-wizard'))) {\n continue;\n }\n rmSync(path.join(claudeSkillsDir, id), { recursive: true, force: true });\n logToFile(`[orchestrator] removed run-installed skill ${id}`);\n }\n}\n\nfunction toTodoStatus(status: TaskStatus): string {\n switch (status) {\n case TaskStatus.Running:\n return 'in_progress';\n case TaskStatus.Done:\n return 'completed';\n case TaskStatus.Failed:\n return 'failed';\n case TaskStatus.Skipped:\n return 'skipped';\n default:\n return 'pending';\n }\n}\n\n/**\n * Look up the harness impl for a resolved pick and enforce the `runTask`\n * capability. Pi trips this today with the honest impl-gap error instead of\n * silently downgrading to anthropic.\n */\nfunction requireTaskHarness(pick: HarnessPick): AgentHarness & {\n runTask: NonNullable<AgentHarness['runTask']>;\n} {\n const harness = getHarness(pick.harness);\n if (!harness.runTask) {\n throw new Error(\n `Harness \"${pick.harness}\" does not implement runTask; orchestrator mode requires it.`,\n );\n }\n return harness as AgentHarness & {\n runTask: NonNullable<AgentHarness['runTask']>;\n };\n}\n\nfunction terminalResult(\n result: AgentResult,\n): { outcome: RunOutcome.Failed; failure: AgentFailure } | undefined {\n switch (result.kind) {\n case 'success':\n return undefined;\n case 'decided_failure':\n return { outcome: RunOutcome.Failed, failure: result.failure };\n case 'abort':\n // Callers return first on the run's signal, so this abort is the agent's own.\n return {\n outcome: RunOutcome.Failed,\n failure: {\n code: AGENT_ERROR_CODE[result.classification],\n message: result.message ?? 'Agent aborted',\n error: result.error,\n },\n };\n case 'failure':\n return {\n outcome: RunOutcome.Failed,\n failure: {\n code: AGENT_ERROR_CODE[result.classification],\n message: result.message ?? 'Agent failed',\n error: result.error,\n },\n };\n }\n}\n\nfunction cancelledRun(): SequenceResult {\n return {\n outcome: RunOutcome.Aborted,\n failure: { code: ErrorCodes.AgentAbort, message: 'Agent run cancelled' },\n };\n}\n\n/** Every skill entry the menu knows, across categories. */\nasync function fetchSkillMenuEntries(\n skillsBaseUrl: string,\n): Promise<SkillEntry[]> {\n const menu = await fetchSkillMenu(skillsBaseUrl);\n if (!menu) return [];\n return Object.values(menu.categories).flat();\n}\n\n/** Menu id for a bare skill id + framework via the menu's declared group/framework/default fields; undefined when nothing matches. */\nexport function resolveSkillVariantId(\n entries: readonly SkillEntry[],\n skillId: string,\n framework: string | undefined,\n): string | undefined {\n if (entries.some((e) => e.id === skillId)) return skillId;\n if (!framework) return undefined;\n const family = entries.filter(\n (e) => e.group === skillId && e.framework === framework,\n );\n return (family.find((e) => e.default) ?? family[0])?.id;\n}\n\n/**\n * The framework reference is the full `integration` skill. `input.skillId` is\n * the bare framework (e.g. `django`), but the skill menu ids it as\n * `integration-<variant>`.\n */\nfunction resolveReferenceSkillId(\n entries: readonly SkillEntry[],\n framework: string,\n): string | undefined {\n return resolveSkillVariantId(entries, 'integration', framework);\n}\n\n/**\n * How long an optional step's notice waits for an answer.\n *\n * Much shorter than LONGER_ASK_TIMEOUT_MS, because it is asking for something\n * much smaller: one keypress to accept or decline, not \"go mint a restricted\n * Stripe key\". It cannot be unbounded either — the notice is a modal, and a run\n * that stops forever behind one nobody is looking at is worse than one that\n * takes the safe answer and carries on.\n *\n * The offer is made at seed time, seconds into the run, so five minutes is a\n * generous allowance for a person who is by then still watching the wizard\n * start. It was not: from 2.63.0 to 2.65.0 the offer was made at the moment the\n * step became runnable — a median seven minutes in, after every coding task —\n * and this timeout became the answer for about a quarter of all runs.\n */\nexport const TASK_NOTICE_TIMEOUT_MS = 5 * 60 * 1000;\n\ninterface SeededTaskOptions {\n timeoutMs?: number;\n interaction?: AgentInteraction;\n signal?: AbortSignal;\n}\n\n/**\n * Offer an optional step, defaulting to declining it if nobody answers.\n *\n * Skip is the right default on a timeout: continuing would send the step on to\n * ask for credentials that the same absent user cannot supply either, burning\n * {@link LONGER_ASK_TIMEOUT_MS} per question before falling back to the same\n * links declining gives immediately.\n */\nexport async function offerSeededTask(\n notice: TaskNotice,\n {\n timeoutMs = TASK_NOTICE_TIMEOUT_MS,\n interaction,\n signal,\n }: SeededTaskOptions = {},\n): Promise<{ keep: boolean; timedOut: boolean }> {\n if (signal?.aborted) return { keep: false, timedOut: false };\n // No one to show the notice to: a step nobody can answer for must not run.\n // The same answer a non-interactive host gives today.\n if (!interaction?.taskNotice) return { keep: false, timedOut: false };\n const { taskNotice } = interaction;\n\n // This notice's own signal: its timeout or the run's cancellation aborts it.\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n let cancelForAbort: (() => void) | undefined;\n const timeout = new Promise<boolean>((resolve) => {\n timer = setTimeout(() => {\n timedOut = true;\n // Settle first: a host that rejects once dismissed must not win.\n resolve(false);\n // The host dismisses this notice's overlay and settles its promise too,\n // so the losing side of the race cannot leave a modal on screen.\n controller.abort();\n }, timeoutMs);\n });\n const aborted = new Promise<boolean>((resolve) => {\n cancelForAbort = () => {\n resolve(false);\n controller.abort();\n };\n signal?.addEventListener('abort', cancelForAbort, { once: true });\n });\n try {\n const keep = await Promise.race([\n taskNotice(notice, { signal: controller.signal }),\n timeout,\n aborted,\n ]);\n return { keep, timedOut };\n } finally {\n if (timer) clearTimeout(timer);\n if (cancelForAbort) signal?.removeEventListener('abort', cancelForAbort);\n }\n}\n\n/**\n * Which runner-seeded task types finished successfully.\n *\n * Handed to the program's `buildOutroNextSteps` so it can drop a next step its\n * own seeded task already carried out. Only `Done` counts: a skipped, declined\n * or failed step left the work undone, and that is exactly when the outro\n * bullet pointing at the app is the one thing the user still needs.\n */\nexport function completedSeededTypes(\n store: QueueStore,\n seededTasks: readonly QueuedTask[],\n): string[] {\n return seededTasks\n .filter((task) => store.get(task.id)?.status === TaskStatus.Done)\n .map((task) => task.type);\n}\n\n/** One seeded task's answer to its notice, taken once, at seed time. */\nexport interface SeededConsent {\n keep: boolean;\n timedOut: boolean;\n /** The notice could not be shown at all. Read as a decline, never as a yes. */\n errored: boolean;\n}\n\n/** Which skip reason a negative {@link SeededConsent} carries onto the event. */\nexport function consentSkipReason(consent: SeededConsent): SkipReason {\n if (consent.errored) return SkipReason.NoticeError;\n return consent.timedOut ? SkipReason.NoticeTimeout : SkipReason.UserDeclined;\n}\n\n/**\n * Apply the seed-time answers to the queue, before the drain starts.\n *\n * A declined task is skipped rather than dropped, so the graph the planner saw\n * is the graph that ran — the sink already depends on this task, and\n * `nextRunnable` treats a skipped dependency as satisfied, so the report still\n * runs and can say the step was declined. The decline also stays in the funnel,\n * arriving as a `skipped` event carrying the reason that caused it rather than\n * as a task that silently never existed.\n *\n * It happens here rather than inside `runTask` because the executor marks a\n * task running — and fires `orchestrator task started` — before it hands the\n * task over. A decline applied on the far side of that emitted a start for a\n * task no agent ever ran, so every rate measured against starts counted the\n * declines twice: once in the denominator as a task that began, and again in\n * the numerator as a task that was skipped. Nothing upstream of the drain reads\n * task status, so applying the answers here changes only what the drain sees.\n *\n * Returns how many tasks were skipped, so the caller can redraw once.\n */\nexport function skipDeclinedSeededTasks(\n store: Pick<QueueStore, 'get' | 'skip'>,\n consentByTaskId: ReadonlyMap<string, SeededConsent>,\n labelFor: (task: { type: string; label?: string }) => string,\n): number {\n let skipped = 0;\n for (const [taskId, consent] of consentByTaskId) {\n if (consent.keep) continue;\n const task = store.get(taskId);\n if (!task) continue;\n const reason = consentSkipReason(consent);\n logToFile(`[orchestrator] runner-seeded ${task.type} skipped: ${reason}`);\n const declinedByUser = reason === SkipReason.UserDeclined;\n store.skip(taskId, reason, {\n goals: labelFor(task),\n did: declinedByUser\n ? 'Nothing — the user chose to skip this step when offered it.'\n : 'Nothing — the step was offered at the start of the run and never accepted.',\n forNextAgent: declinedByUser\n ? 'This step was offered and declined, so it did no work. Report it as skipped at the user’s request, not as failed.'\n : 'This step was offered and never accepted, so it did no work. Report it as not set up, and point the user at how to do it later.',\n });\n skipped += 1;\n }\n return skipped;\n}\n\n/**\n * Ask for one seeded task's consent, and record how the answer came about.\n *\n * Consent and execution are separate concerns, and this is the consent half.\n * It runs at seed time — seconds into the run, with the user still watching —\n * while `seeded-deps.ts` keeps the work itself at the end of the queue. Asking\n * at the moment of execution instead, as 2.63.0 did, put the question in front\n * of a user who had long since tabbed away.\n *\n * Fails closed. The step this gates goes on to ask for live database and API\n * credentials, so a question that could not be put to the user is never read as\n * a yes.\n */\nexport async function askSeededConsent(\n type: string,\n notice: TaskNotice,\n options: SeededTaskOptions = {},\n): Promise<SeededConsent> {\n const consent = await offerSeededTask(notice, options).then(\n (answer): SeededConsent => ({ ...answer, errored: false }),\n (err: unknown): SeededConsent => {\n logToFile(\n `[orchestrator] notice failed for ${type}, declining: ${String(err)}`,\n );\n analytics.captureException(\n err instanceof Error ? err : new Error(String(err)),\n { step: 'orchestrator_task_notice' },\n );\n return { keep: false, timedOut: false, errored: true };\n },\n );\n analytics.wizardCapture('orchestrator task notice answered', {\n type,\n kept: consent.keep,\n timed_out: consent.timedOut,\n errored: consent.errored,\n });\n return consent;\n}\n\n/** Whether a task's prompt lets it ask the user, and so needs the ask bridge. */\nfunction canAsk(prompt: AgentPrompt | undefined): boolean {\n return (prompt?.allowedTools ?? []).includes(ASK_TOOL);\n}\n\n/** Splits terminal failures into run-failing (required) and reported-only (optional). */\nexport function drainVerdict(tasks: readonly QueuedTask[]): {\n requiredFailedTypes: string[];\n optionalFailedTypes: string[];\n blocked: number;\n blockedTypes: string[];\n} {\n const failed = tasks.filter((t) => t.status === TaskStatus.Failed);\n const pending = tasks.filter((t) => t.status === TaskStatus.Pending);\n return {\n requiredFailedTypes: failed\n .filter((t) => t.optional !== true)\n .map((t) => t.type),\n optionalFailedTypes: failed\n .filter((t) => t.optional === true)\n .map((t) => t.type),\n blocked: pending.length,\n blockedTypes: pending.map((t) => t.type),\n };\n}\n\n/**\n * The one-line \"what went wrong\" the abort message leads with.\n *\n * Both halves are named. A drain that ends with work still pending used to\n * report only how many steps never ran, which is the least useful fact about\n * them: a user who agreed to connect their data sources and then read that\n * \"2 steps never ran\" had no way to tell whether that step was one of them.\n */\nexport function describeDrainFailure(verdict: {\n requiredFailedTypes: string[];\n blockedTypes: string[];\n}): string {\n const parts: string[] = [];\n if (verdict.requiredFailedTypes.length > 0) {\n parts.push(`the ${verdict.requiredFailedTypes.join(', ')} step failed`);\n }\n if (verdict.blockedTypes.length > 0) {\n parts.push(\n `the ${verdict.blockedTypes.join(', ')} step${\n verdict.blockedTypes.length === 1 ? '' : 's'\n } never ran`,\n );\n }\n return parts.join(', so ');\n}\n\n/** One `orchestrator task blocked` event per pending task, best effort once the outcome is decided. */\nfunction reportBlockedTasks(\n tasks: readonly QueuedTask[],\n failedTypes: readonly string[],\n): void {\n for (const task of tasks) {\n if (task.status !== TaskStatus.Pending) continue;\n try {\n analytics.wizardCapture('orchestrator task blocked', {\n type: task.type,\n optional: task.optional === true,\n failed_types: failedTypes.join(',') || 'none',\n });\n } catch {\n // Reporting must not replace the run result.\n }\n }\n}\n\n/** How many tasks deep in the graph a task sits — 0 when it depends on nothing. */\nfunction graphDepth(\n task: QueuedTask,\n byId: ReadonlyMap<string, QueuedTask>,\n memo: Map<string, number>,\n): number {\n const cached = memo.get(task.id);\n if (cached !== undefined) return cached;\n memo.set(task.id, 0); // breaks a cycle rather than recursing forever\n const depth = task.dependsOn.reduce((deepest, id) => {\n const dep = byId.get(id);\n return dep ? Math.max(deepest, graphDepth(dep, byId, memo) + 1) : deepest;\n }, 0);\n memo.set(task.id, depth);\n return depth;\n}\n\n/**\n * The queue in the order the user should read it, which is not the order tasks\n * were queued. Tasks the wizard seeded before the planner ran are queued first\n * but are optional side quests, so they sit at the end of the tier they run in\n * — the list reads as the run unfolds, and the first line is work that actually\n * started. Ordering only; nothing here changes what runs when.\n */\nexport function displayOrder(\n tasks: readonly QueuedTask[],\n isOptional: (task: QueuedTask) => boolean,\n): QueuedTask[] {\n const byId = new Map(tasks.map((t) => [t.id, t]));\n const memo = new Map<string, number>();\n const rank = tasks.map((task, index) => ({\n task,\n depth: graphDepth(task, byId, memo),\n optional: isOptional(task) ? 1 : 0,\n index,\n }));\n return rank\n .sort(\n (a, b) =>\n a.depth - b.depth || a.optional - b.optional || a.index - b.index,\n )\n .map((entry) => entry.task);\n}\n\n/**\n * The run's excluded task types: CI gates plus the program's flag mapping.\n * Exported so a test can pin the flag→exclusion hookup against the real\n * program config — the registry and seed note both read this one list.\n */\nexport function effectiveExcludedTaskTypes(\n source: Pick<RunConfig, 'excludedTaskTypes'>,\n flags: Record<string, string>,\n): string[] {\n return [\n ...ciExcludedTaskTypes(),\n ...(source.excludedTaskTypes?.(flags) ?? []),\n ];\n}\n\nexport async function runOrchestrator(\n context: SequenceContext,\n): Promise<SequenceResult> {\n const controller = new AbortController();\n const abortFromHost = () => controller.abort();\n context.signal?.addEventListener('abort', abortFromHost, { once: true });\n if (context.signal?.aborted) abortFromHost();\n let cleaned = false;\n const cleanupQueue = (): void => {\n if (cleaned) return;\n cleaned = true;\n try {\n rmSync(path.join(context.input.installDir, QUEUE_DIR_NAME), {\n recursive: true,\n force: true,\n });\n } catch (error) {\n try {\n analytics.captureException(\n error instanceof Error ? error : new Error(String(error)),\n { step: 'orchestrator_cache_cleanup' },\n );\n } catch {\n // Cleanup reporting must not replace the run result.\n }\n }\n };\n try {\n return await executeOrchestrator(\n { ...context, signal: controller.signal },\n cleanupQueue,\n controller,\n );\n } finally {\n context.signal?.removeEventListener('abort', abortFromHost);\n cleanupQueue();\n }\n}\n\nasync function executeOrchestrator(\n { config, input, boot, emit, interaction, signal }: SequenceContext,\n cleanupQueue: () => void,\n controller: AbortController,\n): Promise<SequenceResult> {\n if (signal?.aborted) return cancelledRun();\n const runId = randomUUID();\n const { run } = config;\n const programId = config.programId;\n\n // Switchboard context — reused for every per-role harness resolution below.\n // The caller resolved the run-level binding from it; per-task roles overlay\n // `binding.contextMillOverride[role]` on the same inputs.\n const switchboardCtx = { ...config.switchboard, trace: undefined };\n\n // The WHAT (agent prompts) is served from context-mill. Fetch the registry\n // once up front: its types drive enqueue validation, and resolving a task to\n // its run config is then synchronous, with no mid-drain network latency.\n const flow = config.agentFlow ?? programId;\n const registry = await loadAgentRegistry(boot.skillsBaseUrl, flow, {\n exclude: effectiveExcludedTaskTypes(config, boot.wizardFlags),\n // Baked into the prompts at load, so enqueue, dispatch, and telemetry all read one effective spec.\n overrides: resolveStageOverrides(\n programId,\n boot.wizardFlags,\n boot.wizardFlagPayloads,\n ),\n });\n if (signal?.aborted) return cancelledRun();\n const seedPrompt = registry.seed;\n if (!seedPrompt) {\n throw new Error(\n `No seed agent prompt (frontmatter \\`seed: true\\`) for flow \"${flow}\" is available from ${boot.skillsBaseUrl}.`,\n );\n }\n\n // The end decision the switchboard event defers to: the model each task will actually run on.\n const taskModels = Object.fromEntries(\n ['seed', ...registry.types].map((type) => {\n const prompt = type === 'seed' ? seedPrompt : registry.get(type);\n const pick = resolveHarness(switchboardCtx, type);\n const specModel = prompt && promptModelFor(prompt, pick.harness).model;\n return [type, isValidModel(specModel) ? specModel : pick.model];\n }),\n );\n logToFile(\n `[orchestrator] task models: ${Object.entries(taskModels)\n .map(([t, m]) => `${t}=${m}`)\n .join(' ')}`,\n );\n analytics.wizardCapture('orchestrator task models', taskModels);\n\n // Responsiveness is the headline metric of the dark launch: time to first\n // visible progress, and no single step dominating wall-clock. Track it from\n // queue transitions, with the resolved model so cheap work is attributable\n // to cheap models.\n const runStartMs = Date.now();\n const metrics = new RunMetrics(runStartMs);\n const durationMs = (t: QueuedTask) =>\n t.startedAt && t.finishedAt\n ? Date.parse(t.finishedAt) - Date.parse(t.startedAt)\n : undefined;\n\n const store = new QueueStore(input.installDir, runId, {\n onTransition: (event, task) => {\n const pick = resolveHarness(switchboardCtx, task.type);\n // Mirror dispatch's allow-list fallback so attribution names the model that runs.\n const specModel = taskModelSpec(registry, task, pick.harness).model;\n const base = {\n type: task.type,\n model: isValidModel(specModel) ? specModel : pick.model,\n attempts: task.attempts,\n // A failed optional task aborts nothing (see drainVerdict).\n optional: task.optional === true,\n };\n switch (event) {\n case 'enqueue':\n analytics.wizardCapture('orchestrator task enqueued', {\n type: task.type,\n enqueued_by: task.enqueuedBy,\n dynamic: task.enqueuedBy !== 'orchestrator',\n });\n break;\n case 'start':\n analytics.wizardCapture('orchestrator task started', {\n ...base,\n ...metrics.recordStart(Date.now()),\n });\n break;\n case 'complete':\n metrics.recordComplete(Date.now());\n analytics.wizardCapture('orchestrator task completed', {\n ...base,\n duration_ms: durationMs(task),\n });\n break;\n case 'skip':\n metrics.recordTerminal(Date.now());\n analytics.wizardCapture('orchestrator task skipped', {\n ...base,\n duration_ms: durationMs(task),\n // Additive: the event's name and every other property are unchanged,\n // so existing dashboards keep reading. Without this a step the user\n // declined, a step nobody answered for, and a step the agent found\n // did not apply were one number — which is how a regression that\n // halved the warehouse completion rate stayed invisible for a week.\n reason: task.skipReason,\n // Also additive, and only ever set alongside `agent-not-needed`:\n // that reason names the agent as the decider without saying what it\n // decided, so a step the user withheld a credential for counted as\n // a step that did not apply to the project.\n not_needed_reason: task.notNeededReason,\n });\n break;\n case 'fail':\n metrics.recordTerminal(Date.now());\n analytics.wizardCapture('orchestrator task failed', {\n ...base,\n duration_ms: durationMs(task),\n error: task.error?.type,\n });\n break;\n case 'requeue':\n break;\n }\n },\n });\n\n // Give task agents the framework's finished reference integration to match,\n // the same EXAMPLE.md the linear flow uses. Install it under the run dir rather\n // than .claude/skills so its \"do everything\" workflow is not auto-loaded as a\n // skill — only the example file is read, when the agent's prompt points at it.\n let examplePath: string | undefined;\n let commandmentsPath: string | undefined;\n let referenceInstallPath: string | undefined;\n const menuSkillEntries = await fetchSkillMenuEntries(boot.skillsBaseUrl);\n if (signal?.aborted) return cancelledRun();\n // The framework key for reference + variant resolution. `input.integration`\n // is the detected framework and always wins; `input.skillId` is the\n // fallback for the basic-integration path, where the caller sets it to the\n // framework label. Programs whose run config carries their own skill id\n // (agent-skill commands like replay-vision) would otherwise leak that id in\n // here as a bogus framework after the caller overwrites the detect result.\n const framework = input.integration ?? input.skillId ?? undefined;\n const referenceSkillId = framework\n ? resolveReferenceSkillId(menuSkillEntries, framework)\n : undefined;\n if (referenceSkillId) {\n const ref = await installSkillById(\n referenceSkillId,\n input.installDir,\n boot.skillsBaseUrl,\n {\n skillsRoot: path.join(QUEUE_DIR_NAME, 'reference'),\n triage: boot.triageProvider,\n },\n );\n if (signal?.aborted) return cancelledRun();\n if (ref.kind === 'ok') {\n referenceInstallPath = ref.path;\n const example = path.join(ref.path, 'references', 'EXAMPLE.md');\n if (existsSync(path.join(input.installDir, example))) {\n examplePath = example;\n }\n const commandments = path.join(ref.path, 'references', 'COMMANDMENTS.md');\n if (existsSync(path.join(input.installDir, commandments))) {\n commandmentsPath = commandments;\n }\n } else {\n logToFile(\n `[orchestrator] reference unavailable: ${ref.kind} (${referenceSkillId})`,\n );\n }\n } else if (framework) {\n logToFile(\n `[orchestrator] no integration skill for framework \"${framework}\"`,\n );\n }\n\n // Preflight every task's mini-skills: a miss would run tasks skill-less, so fail properly instead.\n const missingVariants: string[] = [];\n for (const type of registry.types) {\n for (const skillId of registry.get(type)?.skills ?? []) {\n if (resolveSkillVariantId(menuSkillEntries, skillId, framework)) {\n continue;\n }\n missingVariants.push(`${type}/${skillId}`);\n logToFile(\n `[orchestrator] no skill variant type=${type} skill=${skillId} framework=${\n framework ?? 'none'\n }`,\n );\n analytics.wizardCapture('orchestrator skill variant missing', {\n task_type: type,\n skill: skillId,\n framework,\n });\n }\n }\n if (missingVariants.length > 0) {\n // The framework's own docs page, resolved by the caller; generic docs when detection found none.\n const docsUrl = framework ? input.frameworkDocsUrl : undefined;\n return failed({\n code: ErrorCodes.AgentOrchestratorSkillVariantMissing,\n message:\n 'Setup instructions for this project failed to download.\\n' +\n 'Please try again, or contact wizard@posthog.com.\\n\\n' +\n 'You can also set up with your agent by downloading the skills here:\\n' +\n ' https://github.com/PostHog/context-mill/releases\\n' +\n 'or integrate manually here:\\n' +\n ` ${docsUrl ?? POSTHOG_DOCS_URL}`,\n error: new WizardError(\n 'Orchestrator preflight: skill variant missing',\n {\n missing: missingVariants.join(', '),\n framework,\n },\n ErrorCodes.AgentOrchestratorSkillVariantMissing,\n ),\n });\n }\n\n // The client injects the basics (project context + the I/O contract) around\n // every authored agent-prompt body.\n const promptContext: OrchestratorPromptContext = {\n projectId: boot.credentials.projectId,\n projectApiKey: boot.credentials.projectApiKey,\n host: boot.credentials.host,\n examplePath,\n commandmentsPath,\n };\n\n logToFile(\n `[orchestrator] START program=${programId} dir=${input.installDir} run=${runId}`,\n );\n analytics.wizardCapture('orchestrator started', {\n program_id: programId,\n });\n emit({ kind: 'lifecycle', phase: 'started' });\n\n // Label precedence: what the orchestrator set at enqueue, then the agent\n // prompt's default, then the bare type.\n const labelFor = (t: { type: string; label?: string }) =>\n t.label ?? registry.get(t.type)?.label ?? t.type;\n const renderQueue = () =>\n emit({\n kind: 'tasks',\n tasks: displayOrder(store.list(), (t) =>\n registry.runnerSeededTypes.includes(t.type),\n ).map((t) => ({\n id: `${runId}:${t.id}`,\n source: runId,\n content: labelFor(t),\n status: toTodoStatus(t.status),\n activeForm: labelFor(t),\n })),\n });\n\n // Each task's run binds the wizard-tools MCP server to a per-task\n // orchestrator context so complete_task / enqueue_task attribute correctly\n // when independent tasks run in parallel. The seed is not a task, so its\n // context has no task id.\n const orchestratorCtx = (currentTaskId?: string) => ({\n store,\n // The planner is offered only the types an agent may queue. A runner-seeded\n // type is not among them, so an attempt to queue one trips the unknown-type\n // guard instead of duplicating work the wizard already placed.\n validTypes: registry.enqueueableTypes,\n sinkTypes: registry.sinkTypes,\n // The edge to a runner-seeded task is one-way: the sink may wait for it,\n // nothing else may. Enforced at enqueue, because prose alone cannot hold it\n // — a single planner edge is enough to pull the task back to the front of\n // the drain and put its prompt in front of the code work again.\n runnerSeededTypes: registry.runnerSeededTypes,\n // Optionality comes from the task's frontmatter, never from the enqueue call.\n optionalTypes: registry.optionalTypes,\n currentTaskId,\n });\n\n // Tasks the wizard queues itself, from what detection found. They exist\n // before the planner runs, so the sink guard forces the reporting task to\n // depend on them, and no prompt has to remember they are there.\n // Kill switch: off (or unset), the wizard queues nothing itself and the run\n // is byte-identical to a project with no detected sources.\n const seedEntries = areSeededTasksEnabled(boot.wizardFlags)\n ? config.seedTasks?.() ?? []\n : [];\n const seededTypes: string[] = [];\n // Kept so their dependencies can be resolved once the planner has run — they\n // are queued before it, so they cannot name what they wait for yet.\n const seededTasks: QueuedTask[] = [];\n // Each seeded task's answer to its notice, taken here and applied later.\n //\n // Consent belongs at seed time: the user is at the keyboard, watching the run\n // start, and one keypress is all the question needs. The work does not — the\n // warehouse step asks for credentials, and those questions belong after the\n // autonomous coding, which is what `seeded-deps.ts` arranges. 2.63.0 collapsed\n // the two onto one modal at the moment of execution, a median seven minutes\n // in, by which time the user had gone; the five-minute timeout then answered\n // for them, and it answers \"skip\".\n //\n // The answer is recorded rather than acted on, so a declined task still enters\n // the queue as an ordinary pending task. The planner plans around it,\n // `deferSeededTasks` can still add its edges, and the sink invariant still\n // covers it — none of which is true of a task that was enqueued and skipped\n // before the planner ever ran. `runTask` applies the answer when the drain\n // reaches the task.\n const seededConsent = new Map<string, SeededConsent>();\n for (const seeded of seedEntries) {\n if (!registry.runnerSeededTypes.includes(seeded.type)) {\n logToFile(\n `[orchestrator] skipping runner-seeded task \"${seeded.type}\": not a runner-seeded type in this flow`,\n );\n continue;\n }\n const task = store.enqueue({\n type: seeded.type,\n label: seeded.label,\n inputs: seeded.inputs,\n enqueuedBy: 'orchestrator',\n // Terminal failure is reported per-task and never aborts the run.\n optional: true,\n });\n seededTypes.push(seeded.type);\n seededTasks.push(task);\n if (seeded.notice) {\n // Awaited inside the loop, so at most one notice is ever on screen. The\n // store holds a single pending-notice slot: a second `showTaskNotice`\n // overwrites the first's resolver, the first promise never settles, and\n // its task hangs for the rest of the run. A serial loop makes that\n // unreachable; the drain, which starts every runnable task at once, does\n // not, which is why the offer lives here and not there.\n seededConsent.set(\n task.id,\n await askSeededConsent(seeded.type, seeded.notice, {\n interaction,\n signal,\n }),\n );\n if (signal?.aborted) return cancelledRun();\n }\n logToFile(`[orchestrator] runner-seeded task ${seeded.type}`);\n }\n\n // A run that stops to ask a person is not comparable with one that does not\n // — its wall-clock is the user's, not the model's. Tag every event of the run\n // from here on, so those runs filter out cleanly.\n //\n // A declined step asks nothing, and the answer is known by now, so it leaves\n // the tag alone. While the offer was made mid-drain this was unknowable here,\n // and roughly a quarter of runs were tagged as waiting on a user who had in\n // fact already been auto-declined out of the only step that asks.\n const askingTypes = seededTasks\n .filter((task) => seededConsent.get(task.id)?.keep !== false)\n .map((task) => task.type)\n .filter((type) => canAsk(registry.get(type)));\n analytics.setTag('orchestrator_awaits_user', askingTypes.length > 0);\n analytics.setTag(\n 'orchestrator_runner_seeded_types',\n seededTypes.join(',') || 'none',\n );\n if (askingTypes.length > 0) {\n analytics.wizardCapture('orchestrator awaits user', {\n task_types: askingTypes,\n ask_timeout_ms: LONGER_ASK_TIMEOUT_MS,\n });\n }\n\n // One bridge for the run, handed only to a task whose prompt allows asking.\n // Absent in CI and signup, where nobody can answer.\n const askBridge = shouldDisableAsk(input.flags)\n ? undefined\n : createAskBridge(interaction, {\n signal,\n getSource: () => input.skillId ?? programId,\n beforeShow: () => {\n // How late the first ask lands is the measure of this run shape: it\n // should follow the autonomous work, not interrupt it.\n metrics.recordAsk(Date.now());\n // Consent is taken in the first seconds of the run and these questions\n // arrive at the end of it, so the user who agreed may well be looking\n // at another window by now. Nothing here waits on the bell — an\n // unanswered ask still times out into the deep-link fallback — it just\n // gives a person who stepped away a chance to come back first.\n ringTerminalBell();\n },\n richLinks: run.richLinks ?? false,\n // A task ask waits on a person, and the drain waits it out — the\n // executor holds the task's promise — so this is the only real limit.\n timeoutMs: LONGER_ASK_TIMEOUT_MS,\n });\n\n const spinner = createEmitSpinner(emit);\n\n // 1. Seed the queue with the orchestrator agent. It is itself an agent prompt\n // (the WHAT), so its model and tools come from its frontmatter. The seed\n // plans the graph, it is not a task.\n //\n // Prompt-frontmatter model wins over the switchboard pick (§3.6 of the\n // switchboard plan) — the switchboard's model is the fallback when the\n // prompt is silent.\n const seedPick = resolveHarness(switchboardCtx, 'seed');\n const seedHarness = requireTaskHarness(seedPick);\n const seedModel = promptModelFor(seedPrompt, seedPick.harness);\n const seedResult = await seedHarness.runTask({\n signal,\n config,\n input,\n boot,\n emit,\n // The exclusion note names `registry.excludedTypes` — the excluded types\n // this flow actually had — so the planner never hears about work that was\n // never available, and overlapping exclusion sources cannot double-list.\n prompt: assembleSeedPrompt(\n promptContext,\n seedPrompt.body,\n store.list(),\n registry.excludedTypes,\n ),\n spinner,\n model: requireKnownModel(seedModel.model, seedPick.model),\n effort: seedModel.effort,\n ...agentRunTools(seedPrompt),\n orchestrator: orchestratorCtx(),\n spinnerMessage: 'Planning the integration...',\n successMessage: 'Planned the integration',\n requestRemark: false,\n analyticsProperties: { task_type: 'seed', harness: seedPick.harness },\n });\n if (signal?.aborted) return cancelledRun();\n const seedTerminal = terminalResult(seedResult);\n if (seedTerminal) return seedTerminal;\n analytics.wizardCapture('orchestrator seeded', {\n task_count: store.list().length,\n types: store.list().map((t) => t.type),\n });\n renderQueue();\n\n // Now that the graph exists, give each runner-seeded task the dependencies it\n // could not name when it was queued. Without this it sits at depth 0 and runs\n // in the first tier — which for the warehouse step means its credential\n // prompts arrive while the coding tasks are still writing files. Deferred, the\n // one step that waits on a person waits until the autonomous work is done.\n //\n // Before the sink check below on purpose: sinks are never added as\n // dependencies, so a planner that forgot to make its sink wait for a seeded\n // task is still caught there rather than masked here.\n const deferred = deferSeededTasks(\n store,\n seededTasks,\n (type) => registry.get(type)?.dependsOn ?? [],\n registry.sinkTypes,\n );\n for (const entry of deferred) {\n logToFile(\n `[orchestrator] deferred runner-seeded ${entry.type}: ` +\n `${entry.added.length} deps (${\n entry.declared\n ? `declared: ${entry.declaredTypes.join(', ')}`\n : 'default'\n })${\n entry.refused.length > 0 ? `, ${entry.refused.length} refused` : ''\n }${\n entry.unresolvedTypes.length > 0\n ? `, unresolved: ${entry.unresolvedTypes.join(', ')}`\n : ''\n }`,\n );\n analytics.wizardCapture('orchestrator seeded task deferred', {\n type: entry.type,\n dep_count: entry.added.length,\n declared: entry.declared,\n declared_types: entry.declaredTypes,\n unresolved_types: entry.unresolvedTypes,\n // Non-empty means a cycle or an unknown id was rejected — the resolver and\n // the queue disagreeing, never expected in a good run.\n refused_count: entry.refused.length,\n });\n }\n if (deferred.length > 0) renderQueue();\n\n // Canary for the one-way rule. The enqueue guard rejects the edge outright, so\n // this should never fire — but if it ever does, the seeded task has been\n // pulled back toward the front of the drain and its prompt lands mid-run\n // again, which is precisely the failure this whole step exists to prevent.\n // Silent regressions here would look like \"the ordering just stopped\n // working\", so make it visible rather than abort a run that is otherwise fine.\n for (const seeded of seededTasks) {\n const dependants = store\n .list()\n .filter(\n (t) =>\n !registry.sinkTypes.includes(t.type) &&\n t.id !== seeded.id &&\n dependencyClosure(store, [t.id]).has(seeded.id),\n );\n if (dependants.length === 0) continue;\n logToFile(\n `[orchestrator] one-way rule broken: ${dependants\n .map((t) => t.type)\n .join(', ')} depend on runner-seeded ${seeded.type}`,\n );\n analytics.wizardCapture('orchestrator seeded task depended on', {\n type: seeded.type,\n dependant_types: dependants.map((t) => t.type),\n });\n }\n\n // The enqueue guard rejects a sink that misses part of the queue, so a\n // planner that respected its errors cannot get here with a broken graph.\n // Check it again anyway: a run whose report never sees a task's handoff is\n // worse than a run that stops and says so.\n const unwaited = store\n .list()\n .filter((t) => registry.sinkTypes.includes(t.type))\n .flatMap((sink) =>\n uncoveredBySink(\n { store, validTypes: registry.types, sinkTypes: registry.sinkTypes },\n { type: sink.type, dependsOn: sink.dependsOn },\n ).filter((t) => t.id !== sink.id),\n );\n if (unwaited.length > 0) {\n analytics.wizardCapture('orchestrator sink invariant violated', {\n uncovered_types: unwaited.map((t) => t.type),\n });\n return failed({\n code: ErrorCodes.AgentOrchestratorSinkInvariant,\n message: `The wizard could not plan this setup: the final step would have skipped ${unwaited\n .map((t) => t.type)\n .join(', ')}.\\n\\nPlease report this to: ${WIZARD_CONTACT_EMAIL}`,\n error: new WizardError(\n 'orchestrator sink does not cover the queue',\n {\n uncovered: unwaited.map((t) => `${t.type} (${t.id})`).join(', '),\n queue_state: JSON.stringify(store.list()),\n },\n ErrorCodes.AgentOrchestratorSinkInvariant,\n ),\n });\n }\n\n // 2. Drain the queue, one fresh agent per task; independent tasks run in\n // parallel, the seed's graph being the only schedule. Each task resolves to\n // its agent prompt (the WHAT) and the mini-skills it needs (the HOW), then\n // runs on its own model and tools.\n const taskSkillsRoot = path.join(QUEUE_DIR_NAME, 'skills');\n // Task agents can install durable skills mid-run (load_skill), and only the\n // framework reference docs earn a place — snapshot what was already there so\n // the sweeps remove exactly what this run added.\n const claudeSkillsDir = path.join(input.installDir, '.claude', 'skills');\n const preexistingSkills = new Set(\n existsSync(claudeSkillsDir) ? readdirSync(claudeSkillsDir) : [],\n );\n const runTask: RunTask = async (task) => {\n if (signal?.aborted) return;\n renderQueue();\n\n try {\n const resolved = resolveTask(registry, task, store);\n // Task instructions are one-run scaffolding, not durable skills, so they\n // install under the run dir rather than .claude/skills — the SDK must not\n // auto-load them and they must never land in the project (or a CI PR).\n // The prompt points the agent at them instead.\n const skillPaths: string[] = [];\n for (const skillId of resolved.skills) {\n if (signal?.aborted) return;\n // Agent prompts name the bare step-skill (`integration-v2-install`);\n // SDK-divergent steps ship per-framework variants, so resolve against\n // the menu with the session's framework before installing.\n const variantId = resolveSkillVariantId(\n menuSkillEntries,\n skillId,\n framework,\n );\n if (!variantId) {\n logToFile(\n `[orchestrator] no skill variant type=${\n task.type\n } skill=${skillId} framework=${framework ?? 'none'}`,\n );\n continue;\n }\n const result = await installSkillById(\n variantId,\n input.installDir,\n boot.skillsBaseUrl,\n { skillsRoot: taskSkillsRoot, triage: boot.triageProvider },\n );\n if (signal?.aborted) return;\n if (result.kind === 'ok') {\n skillPaths.push(path.join(result.path, 'SKILL.md'));\n } else {\n logToFile(\n `[orchestrator] skill install failed type=${task.type} skill=${variantId} ${result.kind}`,\n );\n // A task without its instructions must fail here, not run blind:\n // run 91cf40eb's report task started after two EACCES install\n // failures (unwritable external-volume cache) and died silently.\n // The executor catches this, captures the exception, and fails the\n // task through the normal outcome check.\n throw new Error(\n `Skill \"${variantId}\" for task \"${task.type}\" could not be installed (${result.kind}). ` +\n 'If this is a permissions error, check that the project directory is writable.',\n );\n }\n }\n // Empty spinner messages suppress the per-task spinner line (the queue\n // panel shows progress); errors still surface — the harness stops the\n // spinner with its own error text.\n //\n // Per-task role = task.type — the switchboard consults\n // PROGRAM_BINDINGS[id].contextMillOverride?.[task.type] for wizard-side\n // per-agent overrides. Prompt-frontmatter model still wins (§3.6).\n const taskPick = resolveHarness(switchboardCtx, task.type);\n const taskHarness = requireTaskHarness(taskPick);\n const taskModel = taskModelSpec(registry, task, taskPick.harness);\n let taskResult: AgentResult;\n try {\n taskResult = await taskHarness.runTask({\n signal,\n config,\n input,\n boot,\n emit,\n prompt: assembleTaskPrompt(\n promptContext,\n resolved.prompt,\n skillPaths,\n ),\n spinner,\n model: requireKnownModel(taskModel.model, taskPick.model),\n effort: taskModel.effort,\n allowedTools: resolved.allowedTools,\n disallowedTools: resolved.disallowedTools,\n askBridge: canAsk(registry.get(task.type)) ? askBridge : undefined,\n orchestrator: orchestratorCtx(task.id),\n spinnerMessage: '',\n successMessage: '',\n requestRemark: false,\n analyticsProperties: {\n task_type: task.type,\n task_id: task.id,\n harness: taskPick.harness,\n },\n });\n } catch (error) {\n if (signal?.aborted) return;\n if (error instanceof RunTaskFatal) throw error;\n const failure = classifyRunFailure(error);\n throw new RunTaskFatal(\n {\n code: failure.code,\n message: failure.message,\n error: error instanceof Error ? error : undefined,\n },\n RunOutcome.Failed,\n task.type,\n );\n }\n if (signal?.aborted) return;\n const terminal = terminalResult(taskResult);\n if (terminal)\n throw new RunTaskFatal(terminal.failure, terminal.outcome, task.type);\n } finally {\n // Durable skills a task installed are irrelevant to later tasks — and\n // the sdk harness auto-loads .claude/skills into every agent — so sweep\n // as each task ends, not only at run end.\n try {\n sweepRunInstalledSkills(\n claudeSkillsDir,\n preexistingSkills,\n referenceSkillId,\n );\n } catch (err) {\n try {\n logToFile('[orchestrator] per-task skill sweep failed:', err);\n } catch {\n // Cleanup logging must not replace the task result.\n }\n }\n try {\n renderQueue();\n } catch (err) {\n try {\n logToFile('[orchestrator] per-task queue render failed:', err);\n } catch {\n // Cleanup logging must not replace the task result.\n }\n }\n }\n };\n // A task that stops for the user is offered, not imposed, and the answer was\n // taken at seed time. Apply it before the drain begins, so the drain only\n // ever starts tasks that are going to run.\n if (skipDeclinedSeededTasks(store, seededConsent, labelFor) > 0) {\n renderQueue();\n }\n\n let fatal: RunTaskFatal | undefined;\n try {\n await drainQueue(store, runTask, {\n ...DEFAULT_DRAIN_OPTIONS,\n signal,\n onFatal: () => controller.abort(),\n });\n } catch (error) {\n if (!(error instanceof RunTaskFatal)) throw error;\n fatal = error;\n } finally {\n // The queue file is wiped below; the e2e harness reads outcomes from here.\n config.hooks?.recordTaskOutcomes?.(\n store.list().map((t) => ({\n type: t.type,\n status: t.status,\n optional: t.optional === true,\n })) satisfies TaskOutcome[],\n );\n try {\n if (!signal?.aborted && referenceSkillId && referenceInstallPath) {\n promoteReferenceSkill(\n path.join(input.installDir, referenceInstallPath),\n claudeSkillsDir,\n referenceSkillId,\n );\n }\n } catch (err) {\n try {\n analytics.captureException(\n err instanceof Error ? err : new Error(String(err)),\n { step: 'orchestrator_reference_promote' },\n );\n } catch {\n // Cleanup reporting must not replace the run result.\n }\n }\n cleanupQueue();\n try {\n sweepRunInstalledSkills(\n claudeSkillsDir,\n preexistingSkills,\n referenceSkillId,\n );\n } catch (err) {\n try {\n analytics.captureException(\n err instanceof Error ? err : new Error(String(err)),\n { step: 'orchestrator_skill_sweep' },\n );\n } catch {\n // Cleanup reporting must not replace the run result.\n }\n }\n }\n\n if (fatal) {\n // The steps the fatal task stopped still get their terminal event.\n const stoppedBy = drainVerdict(store.list()).requiredFailedTypes;\n if (fatal.taskType && !stoppedBy.includes(fatal.taskType)) {\n stoppedBy.push(fatal.taskType);\n }\n reportBlockedTasks(store.list(), stoppedBy);\n return { outcome: fatal.outcome, failure: fatal.failure };\n }\n if (signal?.aborted) return cancelledRun();\n\n renderQueue();\n\n const summary = store.summary();\n logToFile(\n `[orchestrator] DONE done=${summary.done} failed=${summary.failed} total=${summary.total}`,\n );\n\n analytics.wizardCapture('orchestrator run finished', {\n tasks_total: summary.total,\n tasks_done: summary.done,\n tasks_failed: summary.failed,\n tasks_skipped: summary[TaskStatus.Skipped],\n total_duration_ms: Date.now() - runStartMs,\n ...metrics.summary(),\n dynamic_enqueue_count: store\n .list()\n .filter((t) => t.enqueuedBy !== 'orchestrator').length,\n retried_task_count: store.list().filter((t) => t.attempts > 1).length,\n });\n\n // The review step flags any unresolved conflict in its handoff; surface the\n // one-liner here and point the user at the report for the detail.\n const reviewTask = store.list().find((t) => t.type === 'review');\n const conflict = reviewTask\n ? store.readHandoff(reviewTask.id)?.conflict\n : undefined;\n\n // Not-needed tasks were never work, so they leave the denominator too.\n const notRequired = summary[TaskStatus.Skipped];\n\n // A drain that ends with failed tasks (retries exhausted) or tasks still\n // pending (blocked behind a failed dependency) did NOT set PostHog up —\n // abort like a linear agent failure instead of claiming success.\n // A failed optional task is exempt: reported per-task, never run-failing.\n const verdict = drainVerdict(store.list());\n const blocked = verdict.blocked;\n // A pending task at this point never ran and never will — its dependency\n // failed. No transition fires for it, so without this the step leaves no\n // terminal event at all: a step the user was offered and accepted simply\n // drops out of the funnel. The queue itself is left alone, because the run\n // cache is already wiped by here and writing to it would recreate the folder\n // the cleanup just removed.\n reportBlockedTasks(store.list(), verdict.requiredFailedTypes);\n if (verdict.requiredFailedTypes.length > 0 || blocked > 0) {\n const failedTypes = verdict.requiredFailedTypes.join(', ');\n const whatFailed = describeDrainFailure(verdict);\n // A grant narrowed at login is the one failure cause the user can fix\n // alone — lead with the fix, and only fall back to the report-a-bug line\n // when trying again doesn't work.\n const missingScopes = (boot.credentials.missingScopes ?? []).filter(\n (scope) =>\n WIZARD_PROVISIONING_SCOPES.some((required) => required === scope) ||\n !WIZARD_OAUTH_SCOPES.some((requested) => requested === scope),\n );\n const message =\n missingScopes.length > 0\n ? `The wizard could not finish setup: ${whatFailed}, and this run was authorized without the following permission${\n missingScopes.length === 1 ? '' : 's'\n }: ${missingScopes.join(\n ', ',\n )}.\\n\\nPlease try again, approving all permissions on the PostHog authorization screen. If it still fails, report it to: ${WIZARD_CONTACT_EMAIL}`\n : `The wizard was unable to set up PostHog: ${whatFailed}.\\n\\nPlease report this to: ${WIZARD_CONTACT_EMAIL}`;\n return failed({\n code: ErrorCodes.AgentOrchestratorTasksFailed,\n message,\n error: new WizardError(\n 'orchestrator drain ended with failed tasks',\n {\n tasks_failed: summary.failed,\n tasks_blocked: blocked,\n failed_types: failedTypes,\n missing_oauth_scopes: missingScopes.join(' '),\n queue_state: JSON.stringify(store.list()),\n },\n ErrorCodes.AgentOrchestratorTasksFailed,\n ),\n });\n }\n\n // A drain that produced no tasks at all means the seed step never got a\n // usable model response (e.g. the gateway returned empty completions).\n // \"0/0 completed\" is a dead run, not a success with an empty denominator.\n if (summary.total === 0) {\n return failed({\n code: ErrorCodes.AgentOrchestratorHollowRun,\n message: `The wizard was unable to set up PostHog: the planning step produced no work, so nothing ran.\\n\\nPlease try again — and if it happens again, report it to: ${WIZARD_CONTACT_EMAIL}`,\n error: new WizardError(\n 'orchestrator drain produced zero tasks',\n { queue_state: JSON.stringify(store.list()) },\n ErrorCodes.AgentOrchestratorHollowRun,\n ),\n });\n }\n\n // A failed optional step leaves the denominator and is named instead.\n const optionalFailedCount = verdict.optionalFailedTypes.length;\n const stepNotes = [\n notRequired > 0 ? `${notRequired} skipped as not required` : '',\n optionalFailedCount > 0\n ? `${optionalFailedCount} optional step failed`\n : '',\n ].filter(Boolean);\n const message = conflict\n ? 'PostHog set up, with one conflict to review.'\n : `PostHog set up: ${summary.done}/${\n summary.total - notRequired - optionalFailedCount\n } steps completed${\n stepNotes.length > 0 ? ` (${stepNotes.join(', ')})` : ''\n }.`;\n const outro = {\n kind: OutroKind.Success,\n message,\n body: conflict\n ? `⚠ Build conflict: ${conflict}\\nFull details are in the setup report.`\n : undefined,\n docsUrl: 'https://posthog.com/docs/ai-engineering/ai-wizard',\n nextSteps: config.hooks?.buildOutroNextSteps?.(\n boot.credentials,\n completedSeededTypes(store, seededTasks),\n ),\n };\n emit({ kind: 'completion', outro });\n emit({ kind: 'lifecycle', phase: 'completed', message });\n return { outcome: RunOutcome.Success, outro };\n}\n","/**\n * Sequence axis: gate helpers, registry, middleware, resolver.\n * Percentage rollouts are PostHog-side — the gate just reads the resolved bool.\n */\n\nimport { IS_PRODUCTION_BUILD } from '@env';\nimport { Sequence } from '@shared/constants';\nimport { logToFile } from '@utils/debug';\nimport {\n isOrchestratorEnabled,\n resolveFlagRoute,\n resolveFlagSequence,\n} from './flags';\nimport { getHarness, resolveHarness } from './harness';\nimport type { SequenceResult, SequenceContext } from '../shared/types';\nimport { runLinearProgram } from '../sequence/linear';\nimport { runOrchestrator } from '../sequence/orchestrator/orchestrator-runner';\nimport {\n DEFAULT_BINDING,\n PROGRAM_BINDINGS,\n runChain,\n type Middleware,\n type SwitchboardCtx,\n} from '.';\n\n// ── Registry ────────────────────────────────────────────────────────────\n\nexport interface SequenceRunner {\n readonly name: Sequence;\n /** Run one program to a decided result. Unexpected errors propagate. */\n run(ctx: SequenceContext): Promise<SequenceResult>;\n}\n\nexport const SEQUENCE_OPTIONS: Partial<Record<Sequence, SequenceRunner>> = {\n [Sequence.linear]: {\n name: Sequence.linear,\n run: (ctx) => runLinearProgram(ctx),\n },\n [Sequence.orchestrator]: {\n name: Sequence.orchestrator,\n run: (ctx) => runOrchestrator(ctx),\n },\n};\n\nexport function getSequence(name: Sequence): SequenceRunner {\n const sequence = SEQUENCE_OPTIONS[name];\n if (!sequence) {\n throw new Error(`No sequence registered for '${name}'.`);\n }\n return sequence;\n}\n\n// ── Middleware + resolver ───────────────────────────────────────────────\n\n/**\n * A composed sub-run (integration inside self-driving) is structurally\n * linear: the orchestrator owns the full run lifecycle (queue, outro) and\n * cannot nest. Sits above every override, including CLI.\n */\nconst composedClampMw: Middleware<Sequence> = (ctx, next) => {\n if (!ctx.composed) return next();\n if (ctx.trace) ctx.trace.sequence = 'composed';\n return Sequence.linear;\n};\n\n/** `--sequence` override. Dev/test only — the option is gated out of published builds. */\nconst cliSequenceMw: Middleware<Sequence> = (ctx, next) => {\n if (!ctx.cliSequence) return next();\n if (ctx.trace) ctx.trace.sequence = 'cli';\n return ctx.cliSequence;\n};\n\n/** A program's own flag route may pin the sequence; wins over the global orchestrator flag. Traced as 'payload' to stay distinguishable from sequence experiments ('flag'). */\nconst flagRouteSequenceMw: Middleware<Sequence> = (ctx, next) => {\n const route = resolveFlagRoute(ctx.program, ctx.flags, ctx.flagPayloads);\n if (!route?.sequence) return next();\n if (ctx.trace) ctx.trace.sequence = 'payload';\n return route.sequence;\n};\n\n/** Sequence experiments (e.g. wizard-orchestrator), each inert outside its declared programs. */\nconst sequenceExperimentMw: Middleware<Sequence> = (ctx, next) => {\n const sequence = resolveFlagSequence(ctx.program, ctx.flags);\n if (!sequence) return next();\n if (ctx.trace) ctx.trace.sequence = 'flag';\n return sequence;\n};\n\n/**\n * The orchestrator drives harnesses through `runTask`; a harness that has not\n * implemented it clamps the run to linear. A capability check, not a harness\n * identity check — a harness gains orchestrator support by implementing the\n * method, with no switchboard change. Sits below the CLI override so\n * `--sequence orchestrator` still reproduces the hard error in dev builds.\n */\nconst runTaskCapabilityClampMw: Middleware<Sequence> = (ctx, next) => {\n const pick = resolveHarness(ctx);\n if (getHarness(pick.harness).runTask) return next();\n if (isOrchestratorEnabled(ctx.flags)) {\n logToFile(\n `[switchboard] wizard-orchestrator ignored: ${pick.harness} has no runTask, clamping to linear`,\n );\n }\n if (ctx.trace) ctx.trace.sequence = 'runtask-clamp';\n return Sequence.linear;\n};\n\n// Order = precedence: CLI > capability clamp > flag > binding default. The\n// prod spread collapses to [], dropping cliSequenceMw from the chain.\nconst SEQUENCE_MIDDLEWARE: Middleware<Sequence>[] = [\n composedClampMw,\n ...(IS_PRODUCTION_BUILD ? [] : [cliSequenceMw]),\n runTaskCapabilityClampMw,\n flagRouteSequenceMw,\n sequenceExperimentMw,\n];\n\n/** CLI wins over `wizard-orchestrator` flag wins over binding default. */\nexport function resolveSequence(ctx: SwitchboardCtx): Sequence {\n const sequence = runChain(SEQUENCE_MIDDLEWARE, ctx, () => {\n if (ctx.trace) ctx.trace.sequence = 'binding';\n const binding = PROGRAM_BINDINGS[ctx.program] ?? DEFAULT_BINDING;\n return binding.sequence;\n });\n logToFile(\n `[switchboard] resolved: program=${ctx.program} sequence=${sequence}` +\n `${ctx.trace?.sequence ? ` (${ctx.trace.sequence})` : ''}`,\n );\n return sequence;\n}\n","// Resolves routing; model additions also require mint allowlists and gateway prompt/transport support.\n\nimport {\n DEFAULT_AGENT_MODEL,\n GPT5_6_SOL_MODEL,\n GPT5_6_TERRA_MODEL,\n Harness,\n Sequence,\n} from '@shared/constants';\nimport type { ProgramId } from '@lib/programs/program-registry';\nimport { resolveHarness } from './harness';\nimport type { EffortLevel } from './models';\nimport { resolveSequence } from './sequence';\n\n// ── Shared machinery ────────────────────────────────────────────────────\n\n/** Which precedence rung decided each axis. Stamped by middlewares as they assert. */\nexport interface SwitchboardTrace {\n harness?: 'cli' | 'flag' | 'binding';\n model?: 'cli' | 'flag' | 'binding';\n sequence?:\n | 'cli'\n | 'composed'\n | 'runtask-clamp'\n | 'payload'\n | 'flag'\n | 'binding';\n}\n\n/** Everything a resolver middleware may branch on. Built once per run. */\nexport interface SwitchboardCtx {\n program: ProgramId;\n /** Composed sub-run (a dependency inside a parent program). Structurally linear — no override can orchestrate it. */\n composed?: boolean;\n flags: Record<string, string>;\n /** Flag payloads from the same snapshot (payload-carrying flags, e.g. self-driving pi). */\n flagPayloads?: Record<string, unknown>;\n /** CLI override (`--harness`). Wins over `flags`. */\n cliHarness?: Harness;\n /** CLI override (`--sequence`). Wins over `flags`. */\n cliSequence?: Sequence;\n /** CLI override (`--model`, gateway id). Wins over the binding's model. */\n cliModel?: string;\n /** Filled during resolution; read by the caller for telemetry. */\n trace?: SwitchboardTrace;\n}\n\n/** A resolver middleware: defer via `next()`, or assert by returning a value. */\nexport type Middleware<D> = (ctx: SwitchboardCtx, next: () => D) => D;\n\n/**\n * Run a middleware chain over `ctx`. Each middleware receives `next` (which\n * runs the rest of the chain) and can either:\n * - defer: call `next()` and optionally modify its result (overlay pattern)\n * - short-circuit: return a value without calling `next()` (skip the rest)\n *\n * **Earlier in the array = higher precedence.** Index 0 runs first and can\n * short-circuit the rest; index 1 only runs if index 0 deferred. So\n * `[cliSequenceMw, orchestratorFeatureFlagMw]` means CLI takes precedence over the\n * flag, not the other way around.\n *\n * `fallback` runs at the end — reached only when every middleware deferred.\n * Typically the map read for the base value.\n */\nexport function runChain<D>(\n chain: Middleware<D>[],\n ctx: SwitchboardCtx,\n fallback: () => D,\n): D {\n function step(index: number): D {\n if (index >= chain.length) return fallback();\n const middleware = chain[index];\n const next = () => step(index + 1);\n return middleware(ctx, next);\n }\n return step(0);\n}\n\n// ── Data model ──────────────────────────────────────────────────────────\n\n/** Harness + model for one leaf of agent work. */\nexport interface HarnessPick {\n harness: Harness;\n /** Gateway model id (string). */\n model: string;\n /** Reasoning-effort override. Absent → the model's table default. */\n thinkingLevel?: EffortLevel;\n}\n\nexport interface ProgramBinding {\n sequence: Sequence;\n harness: Harness;\n model: string;\n /** Reasoning-effort override for the model. Absent → the model's table default. */\n thinkingLevel?: EffortLevel;\n /**\n * Per-role overrides applied only in orchestrator mode — keys are\n * agent-prompt `type` values published by context-mill (`'seed'`,\n * `'install'`, `'capture'`, etc.). Linear runs use role `'default'` and\n * skip this map.\n */\n contextMillOverride?: Record<string, Partial<HarnessPick>>;\n}\n\n// Legacy fallback; new programs should explicitly choose Pi and prefer orchestration.\nexport const DEFAULT_BINDING: ProgramBinding = {\n sequence: Sequence.linear,\n harness: Harness.pi,\n model: GPT5_6_SOL_MODEL,\n thinkingLevel: 'medium',\n};\n\n/**\n * Per-program routing. Kept in lockstep with `PROGRAM_REGISTRY` by the\n * switchboard test. Anything absent falls back to `DEFAULT_BINDING`.\n */\nexport const PROGRAM_BINDINGS: Partial<Record<ProgramId, ProgramBinding>> = {\n 'posthog-integration': DEFAULT_BINDING,\n 'revenue-analytics-setup': DEFAULT_BINDING,\n 'warehouse-source': DEFAULT_BINDING,\n 'error-tracking-upload-source-maps': {\n sequence: Sequence.linear,\n harness: Harness.pi,\n model: GPT5_6_SOL_MODEL,\n thinkingLevel: 'medium',\n },\n audit: DEFAULT_BINDING,\n 'events-audit': DEFAULT_BINDING,\n 'posthog-doctor': DEFAULT_BINDING,\n 'web-analytics-doctor': DEFAULT_BINDING,\n migration: DEFAULT_BINDING,\n 'self-driving': DEFAULT_BINDING,\n 'agent-skill': DEFAULT_BINDING,\n 'mcp-add': DEFAULT_BINDING,\n 'mcp-remove': DEFAULT_BINDING,\n 'mcp-tutorial': DEFAULT_BINDING,\n 'mcp-analytics': DEFAULT_BINDING,\n // Orchestrator on pi. The binding routes only; every stage's model and\n // effort are pinned context-mill side in the flow's frontmatter\n // (`model_pi`/`effort_pi`: terra seed, sol tasks, luna report).\n metrics: {\n sequence: Sequence.orchestrator,\n harness: Harness.pi,\n model: DEFAULT_AGENT_MODEL,\n },\n 'replay-vision': {\n sequence: Sequence.orchestrator,\n harness: Harness.anthropic,\n model: DEFAULT_AGENT_MODEL,\n },\n // Orchestrator on pi, like metrics. The binding routes only; every stage's\n // model and effort are pinned context-mill side in the flow's frontmatter\n // (`model_pi`/`effort_pi`: terra seed, install and init, sol tasks, luna report).\n 'error-tracking': {\n sequence: Sequence.orchestrator,\n harness: Harness.pi,\n model: DEFAULT_AGENT_MODEL,\n },\n 'ai-observability': {\n sequence: Sequence.linear,\n harness: Harness.pi,\n model: GPT5_6_TERRA_MODEL,\n thinkingLevel: 'high',\n },\n slack: DEFAULT_BINDING,\n};\n\n// ── Unified resolver ────────────────────────────────────────────────────\n\n/** Compose both axes. Callers needing only one axis use the per-axis resolver. */\nexport function resolveBinding(\n ctx: SwitchboardCtx,\n role = 'default',\n): ProgramBinding {\n ctx.trace ??= {};\n const sequence = resolveSequence(ctx);\n const { harness, model, thinkingLevel } = resolveHarness(ctx, role);\n return { sequence, harness, model, thinkingLevel };\n}\n\n// ── Unified re-export surface ───────────────────────────────────────────\nexport { HARNESS_OPTIONS, getHarness, resolveHarness } from './harness';\nexport {\n SEQUENCE_OPTIONS,\n getSequence,\n resolveSequence,\n type SequenceRunner,\n} from './sequence';\nexport {\n isOrchestratorEnabled,\n areSeededTasksEnabled,\n resolveStageOverrides,\n} from './flags';\n","/**\n * Unified program runner — dispatcher.\n *\n * One callable, `runAgent(config, input, options)`, runs a program's agent\n * pipeline to a decided result. `config` is resolved execution data (which\n * program, how it is routed, which flags apply); `input` is the invocation\n * snapshot (directory, credentials, project); `options` carries an optional\n * progress observer, an optional answerer.\n *\n * The pipeline prepares the run (logging targets, gateway mint, scan triage),\n * then forks. The `orchestrator` variant routes to the task-queue runner.\n * Every other variant runs the fixed linear pipeline:\n * [skill install] → agent init → prompt → run → errors → [postRun] → outro\n *\n * The agent reports and asks, it never renders, never reads a session, never\n * exits the process, never sends the process's terminal analytics and never\n * rejects. A decided failure comes back in\n * `RunResult.failure` with the same fields `wizardAbort` takes; an error the\n * agent did not decide (a refused mint, an SDK crash) comes back as\n * `outcome: RunOutcome.Crashed` with the original error attached, so a caller can keep\n * handling it the way it always did. The legacy adapter in\n * `src/lib/programs/run-agent-legacy.ts` rebuilds today's session-driven\n * behavior on top of this call for every existing caller.\n */\n\nimport { Sequence } from '@shared/constants';\nimport { RunOutcome } from './shared/types';\nexport { RunOutcome } from './shared/types';\nimport { classifyRunFailure, ErrorCodes } from '@shared/errors';\nimport { logToFile } from '@utils/debug';\nimport type {\n RunAgentOptions,\n RunConfig,\n RunInput,\n RunResult,\n} from './shared/types';\nimport { prepareRun } from './shared/bootstrap';\nimport { createProgressCollector } from './shared/progress-collector';\nimport { getSequence } from './switchboard';\nimport { flushScanReport } from '@agent/yara-hooks';\n\nexport type {\n AbortCase,\n AgentFailure,\n BootstrapResult,\n Credentials,\n AgentRunDefinition,\n PromptContext,\n ResolvedBinding,\n RunAgentOptions,\n RunConfig,\n RunFlags,\n RunHooks,\n RunInput,\n RunResult,\n RunSnapshot,\n SeedTaskEntry,\n} from './shared/types';\nexport type {\n AgentInteraction,\n AgentProgress,\n ProgressEmitter,\n} from '@agent/progress';\nexport { shouldDisableAsk } from './shared/bootstrap';\nexport { resolveBinding } from './switchboard';\nexport type { ProgramBinding, SwitchboardCtx } from './switchboard';\nexport { TASK_OUTCOMES_KEY } from './sequence/orchestrator/queue';\nexport type { TaskOutcome } from './sequence/orchestrator/queue';\n\n/**\n * Run a program's agent pipeline.\n *\n * Prepare → dispatch to the sequence the binding names → return its result\n * with the agent's own snapshot of what it reported. Missing observers change\n * nothing; a throwing observer is logged and the run continues.\n */\nexport async function runAgent(\n config: RunConfig,\n input: RunInput,\n options: RunAgentOptions = {},\n): Promise<RunResult> {\n let collector: ReturnType<typeof createProgressCollector> | undefined;\n const snapshot = (): RunResult['snapshot'] => {\n try {\n if (collector) return collector.snapshot();\n } catch {\n // A partial snapshot must not replace the run's primary failure.\n }\n return {\n tasks: [],\n statusMessages: [],\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheCreationTokens: 0,\n },\n };\n };\n const flushReport = (): void => {\n try {\n const report = flushScanReport({ yaraReport: input.flags.yaraReport });\n if (report)\n collector?.emit({ kind: 'log', level: 'info', message: report });\n } catch {\n // Scan reporting is best effort after the run outcome is decided.\n }\n };\n let result: RunResult;\n try {\n collector = createProgressCollector(options.onProgress);\n const { emit } = collector;\n const log = (message: string) =>\n emit({ kind: 'log', level: 'info', message });\n if (options.signal?.aborted) {\n flushReport();\n return {\n outcome: RunOutcome.Aborted,\n skillId: input.skillId,\n failure: {\n code: ErrorCodes.AgentAbort,\n message: 'Agent run cancelled',\n },\n snapshot: snapshot(),\n };\n }\n const boot = await prepareRun(config, input);\n if (config.binding.sequence === Sequence.orchestrator) {\n log('Task-queue orchestrator enabled.');\n }\n try {\n logToFile(\n `[agent-runner] run program=${config.programId} sequence=${config.binding.sequence}` +\n ` harness=${config.binding.harness} composed=${config.composed}`,\n );\n } catch {\n // Logging is best effort.\n }\n const sequenceResult = await getSequence(config.binding.sequence).run({\n config,\n input,\n boot,\n emit,\n interaction: options.interaction,\n signal: options.signal,\n });\n result = {\n ...(options.signal?.aborted &&\n sequenceResult.outcome === RunOutcome.Success\n ? {\n outcome: RunOutcome.Aborted as const,\n failure: {\n code: ErrorCodes.AgentAbort,\n message: 'Agent run cancelled',\n },\n }\n : sequenceResult),\n skillId: input.skillId,\n snapshot: snapshot(),\n };\n } catch (error) {\n const original =\n error instanceof Error ? error : new Error(safeErrorMessage(error));\n let failure: ReturnType<typeof classifyRunFailure>;\n try {\n failure = classifyRunFailure(original);\n } catch {\n failure = {\n code: ErrorCodes.InternalUnhandled,\n message: 'Unexpected agent error',\n coded: false,\n };\n }\n try {\n logToFile('[agent-runner] run failed:', original);\n } catch {\n // Logging is best effort.\n }\n let abortError = false;\n try {\n abortError = original.name === 'AbortError';\n } catch {\n /* Hostile Error getter. */\n }\n if (failure.coded) {\n result = {\n outcome: RunOutcome.Failed,\n skillId: input?.skillId,\n failure: {\n code: failure.code,\n message: failure.message,\n error: original,\n },\n snapshot: snapshot(),\n };\n } else if (options.signal?.aborted && abortError) {\n result = {\n outcome: RunOutcome.Aborted,\n skillId: input?.skillId,\n failure: {\n code: ErrorCodes.AgentAbort,\n message: 'Agent run cancelled',\n },\n snapshot: snapshot(),\n };\n } else {\n result = {\n outcome: RunOutcome.Crashed,\n skillId: input?.skillId,\n failure: {\n code: failure.code,\n message: failure.message,\n error: original,\n },\n snapshot: snapshot(),\n };\n }\n }\n flushReport();\n return result;\n}\n\nfunction safeErrorMessage(error: unknown): string {\n try {\n return String(error);\n } catch {\n return 'Unknown thrown value';\n }\n}\n","/**\n * Public entry of the agent. Code outside `src/agent` imports runtime values\n * from here and types from `./types`; deeper imports fail lint and the\n * architecture test. Keep this list to what callers use, and keep it cheap:\n * the startup chunk imports this module, so anything re-exported here loads\n * before the wizard does any work. Heavy paths stay behind a lazy import.\n *\n * Grouped by fate, per the stack plan (sections 4.1 to 4.5 and 7).\n */\n\n/**\n * Stays. The agent's contract: the one way to run it, the marker strings\n * program prompts embed, and the tool ids programs put in allowedTools and\n * disallowedTools.\n */\nexport type * from './types';\nexport { runAgent, RunOutcome } from './runner';\nexport { AgentSignals } from './agent-interface';\nexport { WIZARD_TOOL_NAMES } from './tools';\n\n/**\n * Leaves in B1. Bindings and program data move to programs: resolveBinding\n * is keyed by PROGRAM_BINDINGS and the agent keeps only \"run from an\n * already-resolved binding\"; shouldDisableAsk is a flags policy programs\n * decide and pass in; LONGER_ASK_TIMEOUT_MS is a tuning number programs own\n * as askTimeoutMs.\n */\nexport { resolveBinding, shouldDisableAsk } from './runner';\nexport { LONGER_ASK_TIMEOUT_MS } from './wizard-ask-bridge';\n\n/**\n * Leaves in B2. Programs own credentials and the legacy adapter dies.\n * initializeAgent, executeAgent and buildRunTags are the pre-runAgent surface\n * that detection/agentic.ts and run-agent-legacy.ts still call; they go\n * through runAgent or leave with detection, and AgentErrorType, which\n * classifies executeAgent's failures, goes with them.\n * configureGatewayFromCIEnvironment is CI inference auth the headless provider\n * owns. flushScanReport becomes a progress event rather than a call.\n * downloadSkill leaves once the skill scan runs at load and skill install\n * becomes shared.\n */\nexport {\n AgentErrorType,\n buildRunTags,\n initializeAgent,\n runAgent as executeAgent,\n} from './agent-interface';\nexport { configureGatewayFromCIEnvironment } from './gateway-session';\nexport { flushScanReport } from './yara-hooks';\nexport { downloadSkill } from './tools';\n/** The frameworkContext slot the legacy adapter fills for the e2e harness. */\nexport { TASK_OUTCOMES_KEY } from './runner';\n\n/**\n * Leaves in C2. The TUI receives agent data through program state. Until\n * then the suggested-prompts screen streams through this wrapper, which loads\n * the streaming module on first call so the startup chunk does not grow.\n */\nexport async function* runMcpPromptViaSdk(\n args: Parameters<\n typeof import('./mcp-prompt-streaming').runMcpPromptViaSdk\n >[0],\n): AsyncIterable<import('./types').AgentChunk> {\n const streaming = await import('./mcp-prompt-streaming');\n y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