github-router 0.3.350 → 0.3.352

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 (146) hide show
  1. package/NOTICE +72 -0
  2. package/README.md +19 -0
  3. package/dist/ado-tools-xbuVU7YN.js +1 -0
  4. package/dist/{aic-ledger-D4oMcg7c.js → aic-ledger-BdvCgRmx.js} +3 -3
  5. package/dist/{aic-ledger-D4oMcg7c.js.map → aic-ledger-BdvCgRmx.js.map} +1 -1
  6. package/dist/{aic-statusline-settings-DCFywz3N.js → aic-statusline-settings-LnoxjBPe.js} +2 -2
  7. package/dist/{aic-statusline-settings-DCFywz3N.js.map → aic-statusline-settings-LnoxjBPe.js.map} +1 -1
  8. package/dist/{attribution-settings-B9T-EsEs.js → attribution-settings-ul6VU6iP.js} +11 -650
  9. package/dist/attribution-settings-ul6VU6iP.js.map +1 -0
  10. package/dist/{auth-Cgsy2T0s.js → auth-a_1lXYZ1.js} +4 -4
  11. package/dist/{auth-Cgsy2T0s.js.map → auth-a_1lXYZ1.js.map} +1 -1
  12. package/dist/{bluebird-client-DpYl1YmJ.js → bluebird-client-ltPIiyJU.js} +1103 -499
  13. package/dist/bluebird-client-ltPIiyJU.js.map +1 -0
  14. package/dist/bluebird-client-mr3M67k-.js +1 -0
  15. package/dist/browser-bridge/index.js +116 -98
  16. package/dist/browser-ext/manifest.json +1 -1
  17. package/dist/{check-usage-26G2hw_F.js → check-usage-Bsbc-Sn6.js} +4 -4
  18. package/dist/{check-usage-26G2hw_F.js.map → check-usage-Bsbc-Sn6.js.map} +1 -1
  19. package/dist/claude-md-injection-BoXOsg7h.js +669 -0
  20. package/dist/claude-md-injection-BoXOsg7h.js.map +1 -0
  21. package/dist/{claude-BY4e9ueE.js → claude-xO1XW-Nn.js} +79 -51
  22. package/dist/claude-xO1XW-Nn.js.map +1 -0
  23. package/dist/{codex-BOugL-uX.js → codex-DzUR40JA.js} +10 -8
  24. package/dist/{codex-BOugL-uX.js.map → codex-DzUR40JA.js.map} +1 -1
  25. package/dist/{copilot-discount-CilBhKQW.js → copilot-discount-C3jfysK-.js} +2 -2
  26. package/dist/{copilot-discount-CilBhKQW.js.map → copilot-discount-C3jfysK-.js.map} +1 -1
  27. package/dist/{debug-CigFsS-h.js → debug-BtqbflcL.js} +2 -2
  28. package/dist/{debug-CigFsS-h.js.map → debug-BtqbflcL.js.map} +1 -1
  29. package/dist/engine-DwLIk1Zn.js +1 -0
  30. package/dist/{exec-MCU1H-KZ.js → exec-Bf8g_bIR.js} +27 -2
  31. package/dist/exec-Bf8g_bIR.js.map +1 -0
  32. package/dist/{gate-discovery-BFqulsWz.js → gate-discovery-Cvdko01z.js} +6 -6
  33. package/dist/{gate-discovery-BFqulsWz.js.map → gate-discovery-Cvdko01z.js.map} +1 -1
  34. package/dist/{get-copilot-usage-C_6ast5h.js → get-copilot-usage-0_S8pRWJ.js} +3 -3
  35. package/dist/{get-copilot-usage-C_6ast5h.js.map → get-copilot-usage-0_S8pRWJ.js.map} +1 -1
  36. package/dist/{hook-mcp-client-BRL_y-bz.js → hook-mcp-client-DERIkeR7.js} +5 -3
  37. package/dist/{hook-mcp-client-BRL_y-bz.js.map → hook-mcp-client-DERIkeR7.js.map} +1 -1
  38. package/dist/hooks.mjs +10998 -6840
  39. package/dist/hooks.sha256 +1 -1
  40. package/dist/{index-cmd-DXYWgKS6.js → index-cmd-CJXUOH4q.js} +5 -5
  41. package/dist/{index-cmd-DXYWgKS6.js.map → index-cmd-CJXUOH4q.js.map} +1 -1
  42. package/dist/{internal-aic-status-lM0YNDaH.js → internal-aic-status-Dmi2bCsR.js} +4 -4
  43. package/dist/{internal-aic-status-lM0YNDaH.js.map → internal-aic-status-Dmi2bCsR.js.map} +1 -1
  44. package/dist/{internal-artifact-open-DErO3WpR.js → internal-artifact-open-C67gDjKo.js} +2 -2
  45. package/dist/{internal-artifact-open-DErO3WpR.js.map → internal-artifact-open-C67gDjKo.js.map} +1 -1
  46. package/dist/{internal-fast-dispatch-guard-DRsZJ-Rg.js → internal-fast-dispatch-guard-BQm1MI9d.js} +2 -2
  47. package/dist/{internal-fast-dispatch-guard-DRsZJ-Rg.js.map → internal-fast-dispatch-guard-BQm1MI9d.js.map} +1 -1
  48. package/dist/internal-fast-dispatch-guard-Cv7zf0ZI.js +1 -0
  49. package/dist/{internal-first-mate-guard-BEwDjHfX.js → internal-first-mate-guard-BJvCsVlU.js} +3 -3
  50. package/dist/{internal-first-mate-guard-BEwDjHfX.js.map → internal-first-mate-guard-BJvCsVlU.js.map} +1 -1
  51. package/dist/internal-first-mate-guard-D-IQGiTs.js +1 -0
  52. package/dist/{internal-max-dispatch-guard-DSjJwVH2.js → internal-max-dispatch-guard-DkJixDmG.js} +7 -5
  53. package/dist/{internal-max-dispatch-guard-DSjJwVH2.js.map → internal-max-dispatch-guard-DkJixDmG.js.map} +1 -1
  54. package/dist/internal-max-dispatch-guard-T-M7DRIW.js +1 -0
  55. package/dist/{internal-plan-review-DbX-mr9i.js → internal-plan-review-DIvaBBUd.js} +4 -4
  56. package/dist/{internal-plan-review-DbX-mr9i.js.map → internal-plan-review-DIvaBBUd.js.map} +1 -1
  57. package/dist/internal-prompt-submit-6OXEdQCK.js +2 -0
  58. package/dist/internal-prompt-submit-B9MJxc3K.js +194 -0
  59. package/dist/internal-prompt-submit-B9MJxc3K.js.map +1 -0
  60. package/dist/{internal-rebrief-BH9PMJhF.js → internal-rebrief-zIdunX3R.js} +6 -6
  61. package/dist/{internal-rebrief-BH9PMJhF.js.map → internal-rebrief-zIdunX3R.js.map} +1 -1
  62. package/dist/{internal-session-bind-DxdVbJ7x.js → internal-session-bind-CQLDPuTx.js} +2 -2
  63. package/dist/{internal-session-bind-DxdVbJ7x.js.map → internal-session-bind-CQLDPuTx.js.map} +1 -1
  64. package/dist/{internal-stop-hook-DlGc9WwJ.js → internal-stop-hook-DGcRVh_2.js} +7 -7
  65. package/dist/{internal-stop-hook-DlGc9WwJ.js.map → internal-stop-hook-DGcRVh_2.js.map} +1 -1
  66. package/dist/{internal-stop-review-CORT3UGr.js → internal-stop-review-X7zRRhyc.js} +3 -3
  67. package/dist/{internal-stop-review-CORT3UGr.js.map → internal-stop-review-X7zRRhyc.js.map} +1 -1
  68. package/dist/{internal-worker-guard-C0FJ4b29.js → internal-worker-guard-wP3UN-3D.js} +2 -2
  69. package/dist/{internal-worker-guard-C0FJ4b29.js.map → internal-worker-guard-wP3UN-3D.js.map} +1 -1
  70. package/dist/{internal-workspace-header-tvJVAXpv.js → internal-workspace-header-DiUnkUeU.js} +2 -2
  71. package/dist/{internal-workspace-header-tvJVAXpv.js.map → internal-workspace-header-DiUnkUeU.js.map} +1 -1
  72. package/dist/lib/tree-sitter-pool/worker.js +1 -2
  73. package/dist/{lifecycle-BqWTXaeC.js → lifecycle-BJ83L0tz.js} +3 -3
  74. package/dist/{lifecycle-BqWTXaeC.js.map → lifecycle-BJ83L0tz.js.map} +1 -1
  75. package/dist/lifecycle-CVg2-zQ3.js +1 -0
  76. package/dist/lifecycle-Dk_BHtfz.js +1 -0
  77. package/dist/{lifecycle-kpLzHUgD.js → lifecycle-aApO0hZW.js} +2 -2
  78. package/dist/{lifecycle-kpLzHUgD.js.map → lifecycle-aApO0hZW.js.map} +1 -1
  79. package/dist/main.js +23 -23
  80. package/dist/{max-profile-contract--dAYkEG1.js → max-profile-contract-DQDEDCsR.js} +2 -2
  81. package/dist/{max-profile-contract--dAYkEG1.js.map → max-profile-contract-DQDEDCsR.js.map} +1 -1
  82. package/dist/{mcp-workspace-header-B77WqVFw.js → mcp-workspace-header-DBQugQlQ.js} +2 -2
  83. package/dist/{mcp-workspace-header-B77WqVFw.js.map → mcp-workspace-header-DBQugQlQ.js.map} +1 -1
  84. package/dist/{models-BGCeGVXl.js → models-JIvKAGn0.js} +3 -3
  85. package/dist/{models-BGCeGVXl.js.map → models-JIvKAGn0.js.map} +1 -1
  86. package/dist/{orchestration-Dkqv-iv0.js → orchestration-D-S_0GVt.js} +3 -3
  87. package/dist/{orchestration-Dkqv-iv0.js.map → orchestration-D-S_0GVt.js.map} +1 -1
  88. package/dist/paths-C9x5U3dO.js +1 -0
  89. package/dist/{paths-CpbTHKeP.js → paths-xTSEAWfN.js} +115 -22
  90. package/dist/paths-xTSEAWfN.js.map +1 -0
  91. package/dist/{peer-mcp-personas-BwwSNnBC.js → peer-mcp-personas-DDMKRFFG.js} +2350 -836
  92. package/dist/peer-mcp-personas-DDMKRFFG.js.map +1 -0
  93. package/dist/{pi-Dpw8Otxw.js → pi-jVNeQXWf.js} +362 -37
  94. package/dist/pi-jVNeQXWf.js.map +1 -0
  95. package/dist/{plan-review-hook-LfG01VMp.js → plan-review-hook-BQ29WGv7.js} +5 -5
  96. package/dist/{plan-review-hook-LfG01VMp.js.map → plan-review-hook-BQ29WGv7.js.map} +1 -1
  97. package/dist/{provision-9TAIgyL7.js → provision-BtYRtvrj.js} +26 -18
  98. package/dist/provision-BtYRtvrj.js.map +1 -0
  99. package/dist/{self-invocation-DIUyoRgL.js → self-invocation-Dr5zlbpM.js} +2 -2
  100. package/dist/{self-invocation-DIUyoRgL.js.map → self-invocation-Dr5zlbpM.js.map} +1 -1
  101. package/dist/{serve-BRKRWkd1.js → serve-CmgmxigM.js} +35 -17
  102. package/dist/serve-CmgmxigM.js.map +1 -0
  103. package/dist/{server-setup-DXVFE7bf.js → server-setup-DinOFWiC.js} +393 -42
  104. package/dist/server-setup-DinOFWiC.js.map +1 -0
  105. package/dist/{service-backend-7SPDLUB9.js → service-backend-DV1u5x0Q.js} +51 -23
  106. package/dist/service-backend-DV1u5x0Q.js.map +1 -0
  107. package/dist/{start-CoR3jqUR.js → start-Dgsaz0HM.js} +4 -4
  108. package/dist/{start-CoR3jqUR.js.map → start-Dgsaz0HM.js.map} +1 -1
  109. package/dist/{state-CVp30CBF.js → state-CfEVoqBM.js} +8 -1
  110. package/dist/{state-CVp30CBF.js.map → state-CfEVoqBM.js.map} +1 -1
  111. package/dist/{prompt-submit-hook-DzhmQRs_.js → static-context-pack-CyucviRD.js} +402 -4
  112. package/dist/static-context-pack-CyucviRD.js.map +1 -0
  113. package/dist/{stop-gate-hook-C9VNxmt1.js → stop-gate-hook-BYd0NruJ.js} +4 -4
  114. package/dist/{stop-gate-hook-C9VNxmt1.js.map → stop-gate-hook-BYd0NruJ.js.map} +1 -1
  115. package/dist/{stop-gate-policy-DQsfjnsx.js → stop-gate-policy-FGAfpfc-.js} +3 -3
  116. package/dist/{stop-gate-policy-DQsfjnsx.js.map → stop-gate-policy-FGAfpfc-.js.map} +1 -1
  117. package/dist/{token-s5Wd-Kwr.js → token-CTf5jCmP.js} +7 -5
  118. package/dist/{token-s5Wd-Kwr.js.map → token-CTf5jCmP.js.map} +1 -1
  119. package/dist/{worker-dispatch-lRhno09M.js → worker-dispatch-BjfROaic.js} +2 -2
  120. package/dist/{worker-dispatch-lRhno09M.js.map → worker-dispatch-BjfROaic.js.map} +1 -1
  121. package/docs/azure-mcp.md +453 -0
  122. package/docs/bluebird-search.md +96 -7
  123. package/package.json +22 -22
  124. package/dist/attribution-settings-B9T-EsEs.js.map +0 -1
  125. package/dist/bluebird-client-DpYl1YmJ.js.map +0 -1
  126. package/dist/bluebird-client-bn9Yv6Cb.js +0 -2
  127. package/dist/claude-BY4e9ueE.js.map +0 -1
  128. package/dist/engine-DZfLaVcf.js +0 -2
  129. package/dist/exec-MCU1H-KZ.js.map +0 -1
  130. package/dist/internal-fast-dispatch-guard-DeZ6KilC.js +0 -2
  131. package/dist/internal-first-mate-guard-CAefr6Ce.js +0 -2
  132. package/dist/internal-max-dispatch-guard-KmbYwh7h.js +0 -2
  133. package/dist/internal-prompt-submit-CA5Y4DWM.js +0 -2
  134. package/dist/internal-prompt-submit-UhfnM_qG.js +0 -573
  135. package/dist/internal-prompt-submit-UhfnM_qG.js.map +0 -1
  136. package/dist/lifecycle-DMRZswwc.js +0 -2
  137. package/dist/lifecycle-FT75ohVw.js +0 -2
  138. package/dist/paths-CpbTHKeP.js.map +0 -1
  139. package/dist/paths-Dfivvq21.js +0 -2
  140. package/dist/peer-mcp-personas-BwwSNnBC.js.map +0 -1
  141. package/dist/pi-Dpw8Otxw.js.map +0 -1
  142. package/dist/prompt-submit-hook-DzhmQRs_.js.map +0 -1
  143. package/dist/provision-9TAIgyL7.js.map +0 -1
  144. package/dist/serve-BRKRWkd1.js.map +0 -1
  145. package/dist/server-setup-DXVFE7bf.js.map +0 -1
  146. package/dist/service-backend-7SPDLUB9.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"worker-dispatch-lRhno09M.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n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AgB,OAA2B,YAAmC;CAC5F,OAAO,CAAC,QAAQ,WAAW,IAAI;AACjC;;;;;;;;;;;AAYA,SAAgB,4BACd,YACA,YACA,OACQ;CACR,MAAM,KAAK,MAAsB,IAAI,EAAE;CACvC,MAAM,OAAO,uCAAuC,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,KAAK,GAAG,CAAC;CAC9F,OAAO,iBAAiB,YAAY,IAAI;AAC1C;;AAGA,SAAgB,cAAc,KAAoD;CAChF,IAAI,CAAC,KAAK,OAAO,CAAC,GAAG,iBAAiB;CACtC,MAAM,QAAQ,IAAI,IAAY,yBAAyB;CACvD,MAAM,MAAM,IACT,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,QAAQ,MAAM,MAAM,IAAI,CAAC,CAAC;CAC7B,OAAO,IAAI,SAAS,IAAI,MAAM,CAAC,GAAG,iBAAiB;AACrD;AAuC0F,OAAO,OAAO;CACtG,0BAA0B,OAAO,OAAO;EACtC,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,kBAAkB,OAAO,OAAO;EAC9B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"worker-dispatch-BjfROaic.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI;AAChC;;;AAIA,SAAgB,oBAAoB,MAAsD;CACxF,OAAO,KAAK,SAAS,CAAC,GAAG,mBAAmB,kBAAkB,IAAI,CAAC,GAAG,iBAAiB;AACzF;AAEA,SAAS,YAAY,GAAmB;CACtC,OAAO,EAAE,QAAQ,uBAAuB,MAAM;AAChD;;;;;;;;AASA,SAAgB,iBAAiB,YAAoB,OAAk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AAO;CACtG,0BAA0B,OAAO,OAAO;EACtC,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,kBAAkB,OAAO,OAAO;EAC9B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;CACD,gBAAgB,OAAO,OAAO;EAC5B,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,UAAU;CACZ,CAAC;AACH,CAAC"}
@@ -0,0 +1,453 @@
1
+ # Azure MCP groups: `ado` and `kusto`
2
+
3
+ Two scoped MCP groups expose Microsoft's Azure surfaces to the model, in the same
4
+ shape as the Bluebird integration ([`docs/bluebird-search.md`](bluebird-search.md)):
5
+
6
+ | Group | Server name | Endpoint | Tools |
7
+ | --- | --- | --- | --- |
8
+ | `ado` | `github-router-ado` | `https://mcp.dev.azure.com/{organization}` | whatever the remote advertises under the selected toolsets |
9
+ | `kusto` | `github-router-kusto` | `{cluster}/v1/rest/{query,mgmt}` | five static tools over an in-repo client |
10
+
11
+ Both are **off unless something turns them on** (a flag, or repository
12
+ discovery in an Azure DevOps checkout, see below), and both mint their own Azure
13
+ access token through the already-authenticated `az` CLI. Neither token ever reaches a child
14
+ process: `ADO_MCP_TOKEN` and `KUSTO_TOKEN` are in the stripped-env key list
15
+ beside `BLUEBIRD_TOKEN`, so a value the operator exports for a manual run is
16
+ consumed by the router and removed from the environment Claude, Codex, and every
17
+ tool under them inherits.
18
+
19
+ ## Enabling
20
+
21
+ ```sh
22
+ github-router claude --ado --ado-org contoso
23
+ github-router claude --kusto-cluster https://example.kusto.windows.net --kusto-database Telemetry
24
+ github-router claude --kusto # no default cluster: every call names the one it queries
25
+ ```
26
+
27
+ | Flag | Effect |
28
+ | --- | --- |
29
+ | `--ado` / `--no-ado` | Expose / refuse the Azure DevOps group |
30
+ | `--ado-org <org>` | Organization. Overrides the git remote; naming one is itself an opt-in |
31
+ | `--ado-toolsets <csv>` | Toolsets to request. Default `repos,wit,pipelines,wiki` |
32
+ | `--ado-all-toolsets` | Request every toolset (sends no `X-MCP-Toolsets` header) |
33
+ | `--ado-write` | Omit `X-MCP-Readonly`, making mutating tools reachable |
34
+ | `--kusto` / `--no-kusto` | Expose / refuse the Kusto group. The flag alone is a complete opt-in; an Azure DevOps remote enables it too |
35
+ | `--kusto-cluster <uri>` | Default cluster origin for the calls that do not name one |
36
+ | `--kusto-database <name>` | Default database for the calls that do not name one, on whichever cluster a call resolves |
37
+
38
+ Environment equivalents: `GH_ROUTER_ENABLE_ADO`, `GH_ROUTER_ADO_ORG`,
39
+ `GH_ROUTER_ADO_TOOLSETS`, `GH_ROUTER_ADO_ALL_TOOLSETS`, `GH_ROUTER_ENABLE_KUSTO`,
40
+ `GH_ROUTER_KUSTO_CLUSTER`, `GH_ROUTER_KUSTO_DATABASE`. `GH_ROUTER_AZURE_MCPS=off`
41
+ (or `0` / `no` / `false`) suppresses every Azure surface including explicit
42
+ positives.
43
+
44
+ ## Auto-enable on Azure DevOps repository discovery
45
+
46
+ Launching inside a checkout whose git remotes resolve to an Azure DevOps
47
+ repository turns **Bluebird, `ado` and `kusto`** on without a flag.
48
+
49
+ Kusto joined that rule when the cluster became a per-call argument. What kept it
50
+ out before was that a git remote carries no cluster identity, so a
51
+ discovery-enabled group would have advertised five tools that could not answer
52
+ anything. With the cluster named per call, the remote says only "this is an
53
+ Azure workspace" and the model picks the cluster; the operator still owns the
54
+ only thing that bounds what a call can read, which is their own identity in each
55
+ cluster. Discovery never supplies a cluster, and the launch says so when the
56
+ group came on without one.
57
+
58
+ Resolution order per capability:
59
+
60
+ 1. explicit negative (`--no-*`, or the kill switch),
61
+ 2. explicit positive (`--*`, `GH_ROUTER_ENABLE_*`),
62
+ 3. Azure DevOps remote discovery,
63
+ 4. off.
64
+
65
+ **The trust question, answered rather than ignored.** A cloned repository's
66
+ `origin` is attacker-controllable, so this rule does derive authority from a URL
67
+ the user did not type. Four properties bound it:
68
+
69
+ - It can never enable writes. `--ado-write` is an explicit flag that discovery
70
+ does not touch.
71
+ - It is suppressible per capability (`--no-bluebird`, `--no-ado`, `--no-kusto`)
72
+ and wholesale (`GH_ROUTER_AZURE_MCPS=off`).
73
+ - The banner names both what turned on and the remote that caused it, so a
74
+ session that suddenly has three more servers is explainable rather than
75
+ mysterious; a surface a flag enabled is never miscredited to the remote.
76
+ - Kusto is the one surface whose reach extends past the repository, and
77
+ discovery does not extend it: discovery may turn the *group* on, never the
78
+ cluster, and the cluster a call names is held to a Kusto-shaped https origin.
79
+ What a call can actually read is bounded by the operator's own identity: the
80
+ router grants no cluster access the `az` session behind it did not already
81
+ have.
82
+
83
+ The probe is one memoized, bounded (`5 s`) `git` read per process, and any
84
+ failure resolves to "not an Azure DevOps workspace" rather than failing the
85
+ launch. Tests inject a synthetic probe; see "Testing" below.
86
+
87
+ ## Azure DevOps (`ado`)
88
+
89
+ ### Authentication
90
+
91
+ `az account get-access-token --resource 2a72489c-aab2-4b65-b93a-a91edccf33b8`
92
+ (app-id / audience for the remote server, scope `Ado.Mcp.Tools`). `az` is a
93
+ `.cmd` shim on Windows, so every invocation goes through `resolveExecutable` /
94
+ `buildExecInvocation` in `src/lib/exec.ts` like the rest of the tree.
95
+
96
+ Microsoft documents the remote server as Entra-OAuth for clients that support the
97
+ interactive flow with a custom app registration. This proxy is not such a client:
98
+ it mints a bearer with the already-authenticated `az` session, which was verified
99
+ to work. A tenant without the `Ado.Mcp.Tools` enterprise application, without
100
+ admin consent, or without a matching `az login` fails at the launch probe with an
101
+ actionable warning, and the group is switched off rather than advertised empty.
102
+
103
+ ### Read-only by default
104
+
105
+ `X-MCP-Readonly: true` is sent on every request. The header is the control: the
106
+ server removes the mutating tools from `tools/list` and refuses a mutation at
107
+ call time. Measured live (2026-10-15, read-only, `tools/list` only): with
108
+ `X-MCP-Toolsets: repos,wit,pipelines,wiki` the server advertises **20 tools**
109
+ under `X-MCP-Readonly: true` and **31** without it; across every toolset the
110
+ counts are **26** and **43**. The read-only set is a strict subset whose
111
+ difference is exactly the 11 tools named
112
+ `*_write` / `*_upload` / `*_create_*` / `upsert`.
113
+
114
+ `--ado-write` omits the header for an operator who explicitly wants mutations,
115
+ and prints a banner line so an elevated session is never silent. The two knobs
116
+ are **independent**: the toolset filter applies identically in both modes, so
117
+ `--ado-all-toolsets` alone can never produce a write tool (pinned by a test).
118
+
119
+ ### Toolset selection
120
+
121
+ `X-MCP-Toolsets` accepts `all`, `repos`, `advsec`, `wit`, `pipelines`, `wiki`,
122
+ `work`, `testplan`, `elm`. **`core` and `repositories` are not valid values**
123
+ (they were a wrong guess in an earlier draft of this work and are rejected
124
+ client-side so the mistake cannot reach the wire). The curated default is
125
+ `repos,wit,pipelines,wiki`: pull requests and files, work items, builds, and
126
+ wiki, excluding the toolsets whose tools are off the main repository loop. The
127
+ four `core_*` tools are always present regardless of toolset.
128
+
129
+ ### Why the tool list is dynamic
130
+
131
+ Every other group in `NON_PERSONA_MCP_TOOLS` is a frozen array of hand-written
132
+ entries, pinned at boot by `assertMcpToolSurfaceConsistent()`. This group cannot
133
+ be: the remote server owns the tool set, it is large, and its names and
134
+ descriptions change on Microsoft's schedule. Freezing twenty entries would mean a
135
+ transcription that drifts silently and a proxy release for every upstream rename.
136
+
137
+ So `tools/list` is forwarded from the upstream `tools/list`, and the two headers
138
+ above ARE the filter. What the static contract still guarantees:
139
+
140
+ - **Name uniqueness.** The dynamic entries are checked against the static
141
+ registry at snapshot time, and a collision drops the upstream tool with a
142
+ warning rather than shadowing a proxy tool. A duplicate would be worse than a
143
+ missing tool: the model would call one name and reach the other's code.
144
+ - **Scope and capability symmetry.** Each entry carries `group: "ado"` and
145
+ `capability: "ado"`, so the same list-time filter and the same call-time gate
146
+ apply as to any static tool.
147
+ - **Read-only default.** The subset is whatever the server returned after being
148
+ told `X-MCP-Readonly: true`, not a classification computed here.
149
+
150
+ The snapshot is taken **once at launch**, awaited (20 s bound) before the child
151
+ process starts, because `toolEntries()` is synchronous and cannot fetch. A
152
+ failure disables the group: an `ado` server that advertises no tools is worse
153
+ than an absent one, because the model would see the group, find nothing usable,
154
+ and have no way to tell whether the group or its own query was wrong.
155
+
156
+ The `action` argument on the dispatcher tools is advertised as a plain `string`
157
+ with no `enum`; the accepted values live only inside the description text. No
158
+ client-side classification is therefore possible, which is the second reason the
159
+ headers are the filter.
160
+
161
+ ## Kusto (`kusto`)
162
+
163
+ ### Why an in-repo client
164
+
165
+ There is no public Microsoft-hosted remote MCP endpoint for Azure Data Explorer.
166
+ The official route is the `kusto` namespace inside `@azure/mcp` 3.0.0: seven
167
+ tools, stdio transport, shipped as a **122 MB** platform binary needing a managed
168
+ .NET child process, for tools whose entire value is one authenticated POST to
169
+ `/v1/rest/query`. A wrong-shaped request here is a JSON body; a wrong-shaped
170
+ request there is a failed native spawn on the canonical Windows environment. The
171
+ router therefore owns a thin client.
172
+
173
+ ### Read-only is enforced by the service
174
+
175
+ Every request carries **both**:
176
+
177
+ - the `x-ms-readonly: true` header, and
178
+ - `properties.Options.request_readonly_hardline: true` in the body.
179
+
180
+ Kusto documents both as unavailable to a `set` statement, so a hostile query
181
+ string cannot lift them. That is the property a leading-dot or text allowlist in
182
+ the client could not provide: Kusto composes multiple `;`-separated statements
183
+ per request, so "does this text contain a mutating command" is not a question a
184
+ prefix check answers. **The client performs no KQL inspection** and relies on the
185
+ service to refuse a mutation.
186
+
187
+ ### Wire shape
188
+
189
+ | | |
190
+ | --- | --- |
191
+ | Query | `POST {cluster}/v1/rest/query` |
192
+ | Management (leading `.`) | `POST {cluster}/v1/rest/mgmt` |
193
+ | Body | `{db, csl, properties: {Options: {...}}}` |
194
+ | Audience | the cluster URI |
195
+
196
+ The query field is **`csl`**, not `query` — a `query` field is silently ignored
197
+ by the service. `truncationmaxrecords` (200) and `truncationmaxsize` (64 MiB)
198
+ bound the response; an 8 MiB client-side cap and a rendered-size cap bound it
199
+ again; a response over either is a stated truncation, never a silent short read.
200
+ The 8 MiB cap is counted in **bytes**, not UTF-16 code units, and a
201
+ `content-length` that already declares an oversize body is refused before the
202
+ body is buffered at all: a character count lets a multi-byte body past a budget
203
+ named in bytes.
204
+
205
+ Cluster references are normalized to a bare https origin. Anything else is
206
+ refused, because the value becomes both a request URL and an `az --resource`
207
+ argument: `http` would send a bearer in cleartext, a path would silently address
208
+ a different endpoint than the audience, and embedded credentials would be echoed
209
+ into a command line. Table and column identifiers interpolated into generated
210
+ commands (`| getschema`, `| take N`) are restricted to
211
+ `[A-Za-z_][A-Za-z0-9_]*` rather than escaped, because a smaller reviewable
212
+ surface beats an escaper.
213
+
214
+ ### Choosing a cluster
215
+
216
+ `cluster` is optional on all five tools. A call that omits it runs against the
217
+ launch's `--kusto-cluster`; a launch with no cluster leaves every call to name
218
+ its own, and one that does not is refused with both ways out (name a cluster, or
219
+ set a default at launch). Different tables live in different clusters, so a
220
+ question spanning two of them is two calls with two `cluster` values.
221
+
222
+ A call-named cluster goes through a **stricter** normalizer than the launch one:
223
+ the same https / no-credentials / no-path rules, plus a requirement that the
224
+ hostname carry a `kusto` label (`<name>.<region>.kusto.windows.net`,
225
+ `*.kusto.usgovcloudapi.net`, `*.kusto.chinacloudapi.cn`,
226
+ `*.kusto.azuresynapse.net`, `*.kusto.fabric.microsoft.com`). Three properties of
227
+ that split are deliberate:
228
+
229
+ - **The label rule is a shape guard, not an allowlist.** Anything
230
+ Kusto-shaped is accepted; no list of pre-approved clusters exists, matching the
231
+ code-search model where a workspace is any path the process can read. What the
232
+ label buys is the audience namespace. AAD mints a token per cluster URI and
233
+ does not check that the cluster exists or that the identity can reach it:
234
+ measured on 2026-10-16, an invented host
235
+ (`https://gh-router-probe-xyz123.kusto.windows.net`) returned a token whose
236
+ audience is that exact URI, while `https://example.com` was refused with
237
+ AADSTS500011. So the shape rule is what keeps the audience inside the Kusto
238
+ family, and the data boundary is the cluster's own authorization of that token,
239
+ which is the identity's RBAC inside the cluster (a 403, see "Token refresh").
240
+ A host that does not resolve surfaces as the client's own transport error.
241
+ - **A launch cluster stays permissive.** An operator may legitimately point
242
+ `--kusto-cluster` at a reverse proxy or a private-DNS front end that carries no
243
+ `kusto` label, so that path keeps the other rules only. A call cannot name such
244
+ a host, and the refusal says to omit `cluster`.
245
+ - **Clusters cannot be enumerated.** `clusters_list` is absent (see below), so
246
+ when the cluster is not already known the `databases` description tells the
247
+ model to ask the user rather than guess at a name.
248
+
249
+ Every tool takes `cluster` before `database`, because the database is scoped by
250
+ the cluster: the same database name can exist in two clusters with different
251
+ contents.
252
+
253
+ ### Tools
254
+
255
+ Five, all read-only, all in the `kusto` group:
256
+
257
+ | Tool | Arguments | Purpose |
258
+ | --- | --- | --- |
259
+ | `databases` | optional `cluster` | The databases this identity can see in one cluster |
260
+ | `tables` | optional `cluster`, `database` | Tables and stored functions in one database |
261
+ | `schema` | required `table`, optional `cluster`, `database` | Column names and types |
262
+ | `sample` | required `table`, optional `rows` (1-100), `cluster`, `database` | First N rows, as a grid |
263
+ | `query` | required `csl`, optional `cluster`, `database` | Arbitrary KQL |
264
+
265
+ `cluster` is conditionally required in prose rather than in the schema: nothing
266
+ here validates arguments against `inputSchema`, and the refusal names what to
267
+ pass, which is more useful to a model than a schema error. `--kusto` with no
268
+ cluster is therefore a working group whose calls must each name a cluster, not a
269
+ degraded one.
270
+
271
+ `clusters_list` is deliberately absent: enumerating clusters is an ARM
272
+ (`management.azure.com`) operation on a different audience and token, so it had
273
+ no implementation path under the cluster-scoped token this client mints.
274
+
275
+ Results are rendered as a compact aligned grid, never raw wire JSON —
276
+ `{"Tables":[{"Columns":[{"ColumnName":…` is both unreadable to the model and
277
+ several times the tokens of the same content as columns and rows.
278
+
279
+ ### Results at the relay boundary
280
+
281
+ Both groups' tool results pass through `relaySafeText` as the last transform
282
+ before they leave `/mcp`. A result over the relay cap spills **in full** to a
283
+ file and the model receives a bounded preview plus that path, instead of a
284
+ string truncated where the model cannot see it (the ADO client had its own 60k
285
+ character clip for exactly that, and it is deleted: clipping there made the
286
+ relay's "full result saved to" trailer untrue). Kusto's rendered-size cap
287
+ stays, because it bounds RENDERING work rather than relay size, and the spill
288
+ file carries that client's own truncation trailer so "full" is never read as
289
+ "everything the service had".
290
+
291
+ ### Token refresh
292
+
293
+ One process-lifetime cache keyed by cluster URI (which is also the audience),
294
+ with one entry per distinct origin, so a session that queries two clusters holds
295
+ two live tokens and mints each on first use. An `az` mint against a cold or
296
+ expired MSAL entry measured 7-20 s on the machine this was written on, against
297
+ the client's 20 s `AZ_TIMEOUT_MS`, so the first call of a session can fail with
298
+ the retriable "Azure CLI did not answer" timeout before the cache is warm; the
299
+ retry succeeds. A 5-minute refresh margin ahead of
300
+ the reported expiry and a **single-flighted** refresh: concurrent callers that
301
+ see the same expired entry await ONE `az` invocation. A token whose expiry `az` does not report is used but **not cached**,
302
+ because a cache entry with no deadline can only be either immortal (serving a
303
+ dead token) or arbitrary (minting in a loop). A **401 alone** invalidates the
304
+ cached entry, so the retry (and every later call) mints a fresh token rather
305
+ than replaying the dead value. A **403 does not**, and is not reported as a
306
+ credential problem: ADX answers 403 for a valid identity that has no access to
307
+ the cluster or database, so invalidating would send the operator to
308
+ re-authenticate against a token that is fine while spawning an `az` call per
309
+ attempt that still 403s. The service's own text names the missing grant, so it
310
+ is read (under the same byte cap) and surfaced rather than replaced by a guess.
311
+ This is the same distinction `src/lib/token.ts` makes for GitHub: only a 401 is
312
+ a rejected credential, a bare 403 is not.
313
+
314
+ ### Retries
315
+
316
+ 429 and 5xx, plus transport failures, retry three times at 1/2/4 seconds, with
317
+ `Retry-After` winning when the service sends one (both the delta-seconds and
318
+ the HTTP-date forms, clamped to 300 s). Every request here is read-only, which
319
+ is what makes resending it safe:
320
+ no tool in this client mutates anything, by construction rather than by
321
+ convention, since read-only is enforced by the service. A 401 retries at most
322
+ once, and only after the cache invalidation above, so a second 401 from a
323
+ freshly minted token is a real auth verdict instead of something another `az`
324
+ call would fix. The ladder is injectable through the client's `retryDelaysMs`
325
+ seam; an empty array makes every retriable verdict final, which is how the
326
+ suites assert a verdict without paying the production backoff.
327
+
328
+ ## Token acquisition
329
+
330
+ All three Azure clients share `src/lib/azure-cli-token.ts`, which resolves a
331
+ bearer in three layers: an environment override (`BLUEBIRD_TOKEN`,
332
+ `ADO_MCP_TOKEN`, `KUSTO_TOKEN`), then a **silent** `az account get-access-token
333
+ --resource <r>`, then a single interactive login when, and only when, the silent
334
+ mint fails for a credential-shaped reason.
335
+
336
+ `KUSTO_TOKEN` is a single value with no audience of its own, and it is used
337
+ verbatim for whichever cluster a call names. It is therefore correct only when
338
+ every call in the session targets one cluster; a session that queries two needs
339
+ the `az` path, which mints per cluster.
340
+
341
+ The classification is the point, because the remedies differ:
342
+
343
+ | `az` stderr | Class | What the router does |
344
+ | --- | --- | --- |
345
+ | `Please run 'az login' to setup account.` | `login-required` | one interactive login, then one re-mint |
346
+ | `V2Error: invalid_resource AADSTS500011` | `tenant` | never a login: names the resource and tenant, points at `AZURE_TENANT_ID` |
347
+ | binary not resolvable | `az-missing` | never a login: names the install |
348
+ | timeout | `timeout` | surfaces the timeout |
349
+ | anything else | `unknown` | surfaces the text |
350
+
351
+ `AZURE_TENANT_ID` (or `--tenant` semantics) is applied to both the mint and the
352
+ interactive login, so a multi-tenant operator does not have to re-point `az`
353
+ globally.
354
+
355
+ The interactive login is `az login` first (the browser carries the session), then
356
+ `az login --use-device-code` when the browser cannot complete it; the code and URL
357
+ are printed to the operator's own terminal, which is why the child inherits stdio.
358
+ It is bounded (120 s browser, 300 s device code), single-flighted so concurrent
359
+ callers share one login, and counted **only when an attempt completes**: an
360
+ aborted attempt does not permanently consume the session's one try, and a
361
+ genuinely failed attempt backs off (5 min) rather than retrying per request. A
362
+ caller that goes away does not kill a login other callers are waiting on: the
363
+ login runs under its own controller, not the caller's signal.
364
+
365
+ Two paths deliberately **never** reach it. The launch probe (`provisionAdoTools`)
366
+ runs under `PROVISION_TIMEOUT_MS = 20_000`, and its abort tree-kills the child, so
367
+ a 120 s browser login underneath it would be killed at 20 s and reported as a
368
+ failure; the probe stays silent-mint only and keeps its existing behavior of
369
+ switching the group off with a visible reason. And an environment override
370
+ short-circuits the whole ladder, so an operator-supplied token is never
371
+ second-guessed by a browser popup.
372
+
373
+ Every client invalidates its cache entry on a 401 before re-minting, so the retry
374
+ sends a genuinely fresh token instead of replaying the rejected one. A 401 is the
375
+ only invalidation trigger, matching the Kusto rationale above: a 403 is an
376
+ authorization verdict, not a credential verdict.
377
+
378
+ ## Clients that receive these groups
379
+
380
+ | Client | `ado` / `kusto` |
381
+ | --- | --- |
382
+ | `github-router claude` | yes: scoped `mcpServers` entries injected into the mirrored `.claude.json` |
383
+ | `github-router serve` | yes: same injection through `src/lib/serve/enhancements.ts` |
384
+ | `github-router pi` | yes: entries written to `<mirror>/mcp.json`, read by `pi-mcp-adapter` |
385
+ | `github-router codex` | no: nothing registers MCP servers for Codex today |
386
+ | worker subagents (`explore` / `review` / `implement`) | no: the worker toolset is its own fixed list |
387
+
388
+ The Pi route differs from the Claude one. Pi reaches `peers`, `search`, and
389
+ `browser` through a generated extension that calls `/mcp/<group>` directly; the
390
+ two Azure groups have no extension seam, so they ride **Pi's own `mcp.json`** in
391
+ the per-launch mirror (`<Pi agent dir>/mcp.json`, which the adapter reads on Pi
392
+ 0.99+). Three consequences worth knowing:
393
+
394
+ - Every key is prefixed `gh-router-<group>`. In the adapter's precedence order
395
+ the mirror file is a user-global source, and `.mcp.json` / `.pi/mcp.json` /
396
+ `.pi/mcp-adapter.json` all outrank it and replace a same-named server
397
+ **wholesale**. A bare `ado` key would therefore hand the model the workspace's
398
+ own `ado` server under a name meant for ours. A project file that declares one
399
+ of our prefixed keys is reported at launch, never edited.
400
+ - The bearer is written as `Bearer ${GH_ROUTER_HOOK_NONCE}`, which the adapter
401
+ interpolates from the child environment at connect time. The file never
402
+ contains a token.
403
+ - The write is gated on `--helpers` **and** `--peers` (the adapter's own gates)
404
+ plus the group being enabled. `--no-helpers` and `--no-peers` therefore leave
405
+ Pi with no Azure MCP surface at all, and so does a failed offline install of
406
+ the adapter package. The gate is deliberately conservative in the other
407
+ direction too: the same file is Pi's *built-in* MCP config, so writing it
408
+ without the adapter would expose the groups through a backend this path has
409
+ never validated.
410
+
411
+ Observed on a real launch (Pi 1.3.0 on Windows, adapter installed into the
412
+ mirror): the adapter's own `mcp-cache.json` lists `gh-router-ado` with exactly
413
+ 20 tools (`repo_repository`, `repo_pull_request`, `wit_work_item`,
414
+ `pipelines_build`, `wiki`, `repo_search_commits`, ...) - the read-only set, so
415
+ `X-MCP-Readonly` holds through this route as well - and the session transcript
416
+ shows a completed model turn, which is the end-to-end proof that the nonce
417
+ interpolation and the scoped URL work from Pi. That cache file is the check to
418
+ reach for, because it can only exist after the adapter has connected.
419
+
420
+ The same launch surfaced a non-network way for the install to fail: npm >= 11.19
421
+ rejects a CLI- or env-sourced `allow-scripts` for a project-scoped install, and
422
+ Pi's per-boot `npm install --prefix <mirror>/npm` is exactly that shape, so a
423
+ shell export of `npm_config_allow_scripts` killed the whole launch before any
424
+ package landed. `getPiLaunchEnvVars` now emits `npm_config_allow_scripts=""` for
425
+ the Pi child, which hands the decision back to the `.npmrc` cascade (rationale
426
+ and measurements in [`pi-launch.md`](pi-launch.md)).
427
+
428
+ ## Testing policy
429
+
430
+ The `docs/bluebird-search.md` policy extends verbatim to both clients: **unit and
431
+ end-to-end tests must not call the real Azure DevOps endpoint, a real Kusto
432
+ cluster, or a real repository.** Tests inject a fictional base URL, mock `fetch`,
433
+ and use synthetic paths, queries, organization names, and tokens. Live checks are
434
+ manual, read-only, and must never print or inspect an access token.
435
+
436
+ `tests/bluebird-test-isolation.test.ts` enforces this for the whole family. It
437
+ reads the live endpoint constants **out of the client sources** rather than
438
+ transcribing them, so a guard that would stop guarding when a constant moves
439
+ follows it instead, and it asserts that the protocol suites address only
440
+ IANA-reserved hosts (`example.*`, `.test`, `.invalid`) — a host that could
441
+ resolve to a real service is unrepresentable rather than merely discouraged.
442
+
443
+ `AdoMcpClient` takes an optional `baseUrl` for exactly this reason, so no test
444
+ ever names the production host.
445
+
446
+ ## Related
447
+
448
+ - [`docs/peer-mcp-design.md`](peer-mcp-design.md) — the group system, the scoped
449
+ `/mcp/<group>` endpoints, and the tool-surface minimality rule.
450
+ - [`docs/bluebird-search.md`](bluebird-search.md) — the sibling integration this
451
+ one follows, including the shared Azure CLI token plumbing.
452
+ - [`docs/unsupported-features.md`](unsupported-features.md) — Anthropic surfaces
453
+ with no Copilot equivalent.