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,26 +1,27 @@
1
- import { A as confineToWorkspaceResult, C as provisionColbert, D as resolveRipgrep, M as recommendedRgThreads, O as searchCode, P as outlineFile, S as colbertSmokeOk, _ as gitState, d as runSemanticSearch, f as startupKickAllowed, j as isSensitivePath, k as validateWorkspace, o as serviceBackendEnabled, r as runServiceSearch, u as kickBackgroundInit, x as colbertArtifactsPresent, y as readColbertMeta } from "./service-backend-7SPDLUB9.js";
1
+ import { A as validateWorkspace, C as provisionColbert, D as colbertPlatformSupported, F as outlineFile, M as isSensitivePath, N as recommendedRgThreads, O as resolveRipgrep, S as colbertSmokeOk, _ as gitState, d as runSemanticSearch, f as startupKickAllowed, j as confineToWorkspaceResult, k as searchCode, o as serviceBackendEnabled, r as runServiceSearch, u as kickBackgroundInit, x as colbertArtifactsPresent, y as readColbertMeta } from "./service-backend-DV1u5x0Q.js";
2
2
  import { n as explicitPackageRoot } from "./package-root-B-osctCk.js";
3
3
  import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
4
- import { t as PATHS } from "./paths-CpbTHKeP.js";
5
- import { t as state } from "./state-CVp30CBF.js";
6
- import { C as githubAgentGraphQLHeaders, S as copilotVersion, b as copilotBaseUrl, d as resolveModel, f as sleep$2, g as HTTPError, h as isAllowedCopilotHost, i as tryRefreshAndRetry, v as GITHUB_API_BASE_URL, w as githubAgentHeaders, x as copilotHeaders, y as GITHUB_GRAPHQL_URL } from "./token-s5Wd-Kwr.js";
4
+ import { t as PATHS } from "./paths-xTSEAWfN.js";
5
+ import { t as state } from "./state-CfEVoqBM.js";
6
+ import { C as githubAgentGraphQLHeaders, S as copilotVersion, b as copilotBaseUrl, d as resolveModel, f as sleep$2, g as HTTPError, h as isAllowedCopilotHost, i as tryRefreshAndRetry, v as GITHUB_API_BASE_URL, w as githubAgentHeaders, x as copilotHeaders, y as GITHUB_GRAPHQL_URL } from "./token-CTf5jCmP.js";
7
7
  import { a as withTransientRetry, i as sanitizeTransportText, n as classifyTransportError, r as fetchWithTransientRetry } from "./upstream-retry-i1k1Xai2.js";
8
- import { a as parseIntEnv, i as parseBoolEnv, l as runManagedExeCapture, o as resolveExecutable } from "./exec-MCU1H-KZ.js";
8
+ import { a as parseBoolEnv, d as runManagedExeCapture, o as parseIntEnv, s as resolveExecutable } from "./exec-Bf8g_bIR.js";
9
9
  import { S as FAST_PROFILE_ORACLE_MODEL, _ as FAST_PROFILE_MODELS, a as BALANCED_PROFILE_NATIVE_EFFORTS, b as FAST_PROFILE_NATIVE_MODELS, c as BALANCED_PROFILE_ORACLE_MODEL, d as FAST_PROFILE_ADVISOR_EFFORT, f as FAST_PROFILE_ADVISOR_MODEL, m as FAST_PROFILE_ASTRA_MODEL, r as BALANCED_PROFILE_MODELS, x as FAST_PROFILE_ORACLE_EFFORT, y as FAST_PROFILE_NATIVE_EFFORTS } from "./balanced-profile-contract-XiIj4O1U.js";
10
- import { A as normalizeTrailingOneMSuffix, D as maxPeerInstructions, E as maxPeerDescription, O as fastEndpointForCatalogId, b as MAX_ADVISOR_SYSTEM_PROMPT, f as maxCodexReviewerModel, g as maxProReplacementModel, h as maxOpusModel, i as MAX_PROFILE_MODELS, k as fastEndpointForModel, m as maxGrokModel, p as maxGeminiModel, r as MAX_PROFILE_LEAD_MODEL, v as maxSonnetModel } from "./max-profile-contract--dAYkEG1.js";
11
- import { i as registerExitHandlers$1, n as getInstanceUuid, r as recordWorkerRepo, t as WorktreeRegistry } from "./lifecycle-kpLzHUgD.js";
12
- import { t as MCP_WORKSPACE_HEADER } from "./mcp-workspace-header-B77WqVFw.js";
10
+ import { A as normalizeTrailingOneMSuffix, D as maxPeerInstructions, E as maxPeerDescription, O as fastEndpointForCatalogId, b as MAX_ADVISOR_SYSTEM_PROMPT, f as maxCodexReviewerModel, g as maxProReplacementModel, h as maxOpusModel, i as MAX_PROFILE_MODELS, k as fastEndpointForModel, m as maxGrokModel, p as maxGeminiModel, r as MAX_PROFILE_LEAD_MODEL, v as maxSonnetModel } from "./max-profile-contract-DQDEDCsR.js";
11
+ import { i as registerExitHandlers$1, n as getInstanceUuid, r as recordWorkerRepo, t as WorktreeRegistry } from "./lifecycle-aApO0hZW.js";
12
+ import { t as MCP_WORKSPACE_HEADER } from "./mcp-workspace-header-DBQugQlQ.js";
13
13
  import { n as ArtifactError, r as applyInsecureTls, t as ArtifactClient } from "./client-CQMfroGV.js";
14
- import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, p as extractCopilotUsage } from "./aic-ledger-D4oMcg7c.js";
15
- import { a as BluebirdError, c as ensureBluebirdClient } from "./bluebird-client-DpYl1YmJ.js";
16
- import { r as registerColbertExitHandlers } from "./lifecycle-BqWTXaeC.js";
17
- import { h as runGateChecks, m as sealedGateIds, p as resolveSealedGate } from "./stop-gate-hook-C9VNxmt1.js";
18
- import { t as liveExec } from "./orchestration-Dkqv-iv0.js";
14
+ import { d as isCheapestRewriteDisabledEnv, f as isCheapestRewriteEligible, p as runCheapestRewrite, s as isNonTrivialPrompt, t as buildStaticPack } from "./static-context-pack-CyucviRD.js";
15
+ import { f as stopReviewStateDir, o as fileRewriteFlagStore } from "./stop-gate-policy-FGAfpfc-.js";
16
+ import { _ as isRecord$3, b as sleep$3, g as RemoteMcpError, h as RemoteMcpClient, l as ensureBluebirdClient, m as describeAzFailure, o as BluebirdError, p as AzCliAccessTokenCache, v as parseRetryAfter, y as sanitizeRemoteDetail } from "./bluebird-client-ltPIiyJU.js";
17
+ import { r as registerColbertExitHandlers } from "./lifecycle-BJ83L0tz.js";
18
+ import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, p as extractCopilotUsage } from "./aic-ledger-BdvCgRmx.js";
19
+ import { h as runGateChecks, m as sealedGateIds, p as resolveSealedGate } from "./stop-gate-hook-BYd0NruJ.js";
20
+ import { t as liveExec } from "./orchestration-D-S_0GVt.js";
19
21
  import { createRequire } from "node:module";
20
22
  import consola from "consola";
21
23
  import { chmodSync, closeSync, constants, cpSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
22
- import * as path$1 from "node:path";
23
- import path from "node:path";
24
+ import path, * as path$1 from "node:path";
24
25
  import { fileURLToPath } from "node:url";
25
26
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
26
27
  import fs$1, { open, readFile, stat } from "node:fs/promises";
@@ -32,13 +33,10 @@ import { z } from "zod";
32
33
  import { AsyncLocalStorage } from "node:async_hooks";
33
34
  import WebSocket from "ws";
34
35
  import { events } from "fetch-event-stream";
35
- import { Type, Type as Type$1 } from "typebox";
36
+ import { Type } from "typebox";
36
37
  import "partial-json";
37
38
  import { Compile } from "typebox/compile";
38
39
  import { Value } from "typebox/value";
39
- import "yaml";
40
- import "ignore";
41
- import "diff";
42
40
  //#region src/lib/cheap-profile-contract.ts
43
41
  /**
44
42
  * Fixed identities for the literal `github-router claude -m cheap` and
@@ -47,8 +45,10 @@ import "diff";
47
45
  * A cost-lean sibling of `-m fast`: identical fixed four-agent surface, but
48
46
  * every SUBAGENT runs at Claude Code's 200K DEFAULT context window (bare
49
47
  * slug, no `[1m]` accounting bracket). `-m cheap` also drives the Gemini
50
- * LEAD at the same 200K default (bare slug, no `[1m]`) with medium effort,
51
- * so its only peer is the `grok-4.6`/medium Oracle. `-m cheap1m` is the named successor of the
48
+ * LEAD at the same 200K default (bare slug, no `[1m]`) with high effort —
49
+ * the de-facto lead effort is `high` (the request preprocessor maps bare
50
+ * Gemini to `high` and the client stamps its `high` default, so the wire
51
+ * runs high), and `CHEAP_PROFILE_LEAD_EFFORT` records exactly that. `-m cheap1m` is the named successor of the
52
52
  * original cheap launch: the leader keeps its full 1M window (`[1m]`) and
53
53
  * the `astra` peer (`gpt-6-astra`) remains available next to Oracle — still
54
54
  * at the 200K default window and medium effort.
@@ -133,6 +133,16 @@ Object.freeze({
133
133
  * plans directly and reviews the final plan with the Advisor (advisory)
134
134
  * before presenting it.
135
135
  *
136
+ * "max" on the lead is enforced at two layers: the launcher seeds
137
+ * `CLAUDE_CODE_EFFORT_LEVEL=max` (so the client stamps max instead of its
138
+ * `high` default on lead requests) and the request preprocessor defaults
139
+ * bare-Luna lead traffic to max when no explicit effort is present.
140
+ *
141
+ * The "200K window" here is enforced client-side by the launcher-seeded
142
+ * `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` (see `getClaudeCodeEnvVars`), not by
143
+ * the bare slugs alone: every row maps via `behavesAs` onto a known Claude
144
+ * model whose client-side profile is native-1M.
145
+ *
136
146
  * This module is deliberately dependency-free, including its own delegation
137
147
  * graph literal: each pinned profile owns its graph so tuning one roster
138
148
  * cannot silently retune another.
@@ -1140,6 +1150,537 @@ function enumProp$1(values, description) {
1140
1150
  };
1141
1151
  }
1142
1152
  //#endregion
1153
+ //#region src/lib/colbert/index.ts
1154
+ /**
1155
+ * ColBERT semantic-search sidecar — public entry points.
1156
+ *
1157
+ * `provisionAndIndexColbert()` is the fire-and-forget call site the
1158
+ * `start` / `claude` / `codex` launchers invoke after `setupAndServe`
1159
+ * (mirroring `provisionToolbelt()` / `runSelfUpdate()`):
1160
+ * 1. Bail unless opted in (`--search` / `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1`);
1161
+ * `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` hard-disables.
1162
+ * 2. Register the exit handlers (tree-kill tracked colgrep children).
1163
+ * 3. Provision the binary/model/ORT under a lock + smoke test
1164
+ * (best-effort, never throws to the launcher).
1165
+ * 4. If the launch cwd is a git repo and its index is absent/stale,
1166
+ * kick a background `colgrep init` (non-blocking).
1167
+ *
1168
+ * On-demand indexing for non-cwd workspaces is handled inside the MCP
1169
+ * tool handler (`runSemanticSearch` kicks a debounced background init
1170
+ * for an unindexed workspace and reports `unavailable` meanwhile).
1171
+ */
1172
+ /**
1173
+ * True only when the operator opted in via `--search`
1174
+ * (`state.searchEnabled`, set by `setupAndServe`) or
1175
+ * `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1`. Semantic search is OFF BY
1176
+ * DEFAULT (no auto-provision, no background-index); the capability gate
1177
+ * additionally requires the artifacts to be present on disk +
1178
+ * smoke-passed, so the `code` tool stays lexical until both the opt-in
1179
+ * and provisioning have completed.
1180
+ *
1181
+ * `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` hard-disables and wins over every
1182
+ * opt-in signal (escape hatch for tests and managed environments).
1183
+ */
1184
+ function semanticSearchOptedIn() {
1185
+ if (parseBoolEnv(process$1.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) return false;
1186
+ return state.searchEnabled === true || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
1187
+ }
1188
+ /**
1189
+ * Availability predicate for ColBERT semantic search — the single
1190
+ * source of truth, living in this leaf module so callers that must not
1191
+ * import `mcp-capabilities` (notably the unified code-search helper)
1192
+ * can read it without closing an import cycle through `worker-agent`.
1193
+ *
1194
+ * True iff the operator hasn't opted out AND the colgrep binary + model
1195
+ * + ORT are provisioned on disk AND the post-provision smoke test
1196
+ * passed. `mcp-capabilities.semanticSearchEnabled()` delegates here.
1197
+ */
1198
+ function colbertSearchEnabled() {
1199
+ return semanticSearchOptedIn() && colbertArtifactsPresent() && colbertSmokeOk();
1200
+ }
1201
+ let _started = false;
1202
+ /**
1203
+ * Fire-and-forget provision + background-index. Never throws; safe to
1204
+ * `void`-call from a launcher right after the server is listening.
1205
+ * Idempotent within a proxy run (subsequent calls no-op).
1206
+ */
1207
+ async function provisionAndIndexColbert(opts = {}) {
1208
+ if (!semanticSearchOptedIn()) return;
1209
+ if (_started) return;
1210
+ _started = true;
1211
+ registerColbertExitHandlers();
1212
+ let provisioned;
1213
+ try {
1214
+ const result = await provisionColbert();
1215
+ provisioned = result.status === "ready";
1216
+ if (result.status === "unsupported") consola.debug("colbert: semantic search unsupported on this platform");
1217
+ else if (result.status !== "ready") consola.debug(`colbert: provision not ready (${result.status}: ${result.reason ?? ""})`);
1218
+ } catch (err) {
1219
+ consola.debug("colbert: provision threw (swallowed):", err);
1220
+ return;
1221
+ }
1222
+ if (!provisioned) return;
1223
+ if (opts.skipCwdIndex) return;
1224
+ const cwd = opts.cwd ?? process$1.cwd();
1225
+ try {
1226
+ if ((await gitState(cwd)).isRepo && await startupKickAllowed(cwd)) kickBackgroundInit(cwd);
1227
+ } catch (err) {
1228
+ consola.debug("colbert: cwd git-detect skipped:", err);
1229
+ }
1230
+ }
1231
+ /**
1232
+ * One-line operator warning when this workspace's semantic index is sitting in
1233
+ * a terminal `failed` state, or `null` when there is nothing to say.
1234
+ *
1235
+ * This exists because the failure mode that motivated it was SILENCE: semantic
1236
+ * search degraded to lexical on a real repo for an unknown period — possibly
1237
+ * weeks — and nobody noticed, because the only signals were a `notice` string
1238
+ * the model reads and a `consola.debug` the file logger drops. Neither reaches
1239
+ * a human. The launcher writes this to stderr next to the readiness line so a
1240
+ * degraded capability is visible at the moment the user starts a session.
1241
+ *
1242
+ * `logsToFile` says where the failure detail actually went. `claude` and
1243
+ * `codex` call `enableFileLogging()`, which redirects warnings to
1244
+ * ERROR_LOG_PATH; `start` does not, so its warnings stay on the terminal and
1245
+ * pointing at the file would send the operator to a stale or absent one.
1246
+ *
1247
+ * Deliberately advisory and best-effort: lexical search still works, so this
1248
+ * must never block or fail a launch.
1249
+ */
1250
+ async function colbertDegradedWarning(cwd, opts = {}) {
1251
+ if (!semanticSearchOptedIn()) return null;
1252
+ try {
1253
+ const target = cwd ?? process$1.cwd();
1254
+ const meta = await readColbertMeta(target);
1255
+ if (!meta || meta.status !== "failed") return null;
1256
+ const cls = meta.failureClass ?? "error";
1257
+ return `Semantic search DEGRADED for this workspace (colbert: ${cls}) — lexical code search still works. ${opts.logsToFile ? `See ${PATHS.ERROR_LOG_PATH}` : "See the proxy log output"}.${cls === "stuck" ? " For a very large repo, raise GH_ROUTER_COLBERT_INIT_STALL_MS / GH_ROUTER_COLBERT_INIT_TIMEOUT_MS." : ""}`;
1258
+ } catch {
1259
+ return null;
1260
+ }
1261
+ }
1262
+ //#endregion
1263
+ //#region src/lib/unified-code-search.ts
1264
+ /**
1265
+ * Unified, semantic-first code search; the single source of truth behind
1266
+ * BOTH the MCP `code` tool (`src/lib/peer-mcp-personas.ts`) and the worker
1267
+ * subagent's internal `code_search` tool (`src/lib/worker-agent/tools.ts`).
1268
+ *
1269
+ * Default behaviour (omitted mode or `mode:"semantic"`) ranks by MEANING
1270
+ * via ColBERT (colgrep) and TRANSPARENTLY falls back to lexical BM25F when
1271
+ * the per-workspace index isn't ready (building / stale / unavailable /
1272
+ * failed) or colgrep isn't provisioned on this host. The forced lexical
1273
+ * family (`lexical|exact|regex|ast`) never touches colgrep.
1274
+ *
1275
+ * Under `--bluebird` (`state.bluebirdEnabled`), the `semantic` and
1276
+ * `lexical` modes route through
1277
+ * the Bluebird Azure DevOps MCP server instead (the unified `code_search`
1278
+ * tool, with legacy tool-name compatibility); `exact|regex|ast` stay local, and
1279
+ * Bluebird errors surface as `source:"error"` with NO silent local
1280
+ * fallback.
1281
+ *
1282
+ * Provenance is carried in a FOUR-valued `source` field, independent of
1283
+ * `notice`:
1284
+ * - "semantic" colgrep/Bluebird ran and the index was fresh
1285
+ * - "lexical" the caller explicitly forced a lexical mode
1286
+ * - "lexical-fallback" a semantic/default query degraded to lexical
1287
+ * because the index wasn't ready
1288
+ * - "error" the Bluebird backend failed after retries; the
1289
+ * response carries `notice` with the cause
1290
+ * `notice` keeps the lexical backend's size-cap > structural priority, so
1291
+ * on a hit-heavy fallback the urgent size notice can win; `source` still
1292
+ * conveys "this was a fallback" unambiguously, and never conflates a
1293
+ * degraded result with a deliberately-forced lexical search.
1294
+ *
1295
+ * Contract split vs. `runSemanticSearch`: the runner itself stays
1296
+ * NO-FALLBACK (it returns honest status, never another engine). The
1297
+ * fallback lives only here, at the merged-tool layer.
1298
+ *
1299
+ * Import-cycle note: this module imports ONLY from `./code-search`,
1300
+ * `./colbert`, `./bluebird-client`, and `./state`. It must NOT import
1301
+ * `./mcp-capabilities`; that would close a cycle through `worker-agent`.
1302
+ * The colbert-availability decision is read from the leaf
1303
+ * `colbertSearchEnabled()`. (`./state` reaches `./bluebird-client` by
1304
+ * type-only import, and `./bluebird-client` reaches this module by
1305
+ * type-only import, so neither edge exists at runtime.)
1306
+ */
1307
+ /** Map the unified mode onto `searchCode`'s internal `mode` enum. */
1308
+ function lexicalSearchCodeMode(mode) {
1309
+ switch (mode) {
1310
+ case "exact": return "literal";
1311
+ case "regex": return "regex";
1312
+ default: return "ranked";
1313
+ }
1314
+ }
1315
+ /**
1316
+ * Status-specific, actionable fallback hint. The semantic index isn't ready,
1317
+ * so the model got LEXICAL results (great for exact symbols, sparse for a
1318
+ * natural-language phrase since the lexical backend matches literally). Tell
1319
+ * it both levers: retry `mode:"semantic"` (the index is self-healing in the
1320
+ * background) OR re-query now with specific symbol/keyword terms.
1321
+ *
1322
+ * "shortly" was too vague and cost a real recovery. A build takes MINUTES on a
1323
+ * large repo, and after a failed build the FIRST query is consumed triggering
1324
+ * the re-kick and still returns a fallback. So a caller who retried once,
1325
+ * seconds later, saw a second fallback and concluded the tool was broken
1326
+ * rather than mid-repair. Observed end to end on this repo: query, then
1327
+ * ~5 minutes of `building`, then `ready`. Naming the timescale and the
1328
+ * one-query-to-trigger behaviour is what turns "it's still broken" into
1329
+ * "it's coming back".
1330
+ *
1331
+ * The wording stays a range rather than a number: build time scales with
1332
+ * repository size, so a hard figure would be wrong for most callers.
1333
+ */
1334
+ const FALLBACK_GUIDANCE_MARKER = "retry mode:\"semantic\"";
1335
+ const FALLBACK_GUIDANCE = `${FALLBACK_GUIDANCE_MARKER} in minutes or use exact symbols`;
1336
+ function fallbackNoticeFor(status) {
1337
+ const tail = FALLBACK_GUIDANCE;
1338
+ switch (status) {
1339
+ case "building": return `semantic index building — returned lexical matches; ${tail}`;
1340
+ case "stale": return `semantic index stale (HEAD moved) — re-index started, returned lexical matches; ${tail}`;
1341
+ case "unavailable": return `no semantic index yet — build started, returned lexical matches; ${tail}`;
1342
+ case "failed": return `semantic index failed — this query started a background rebuild, returned lexical matches; ${tail}`;
1343
+ default: return "returned lexical results";
1344
+ }
1345
+ }
1346
+ /**
1347
+ * Combine the lexical backend's own notice (size-cap / structural, the
1348
+ * urgent "you're missing results" signal) with a fallback hint, keeping a
1349
+ * single string. The lexical notice stays primary; the hint is appended so
1350
+ * neither is lost.
1351
+ */
1352
+ function joinNotice(primary, secondary) {
1353
+ if (primary && secondary) return `${primary} (${secondary})`;
1354
+ return primary || secondary || void 0;
1355
+ }
1356
+ /** Preserve runner-specific context while guaranteeing actionable guidance once. */
1357
+ function semanticFallbackNotice(sem) {
1358
+ if (!sem.notice) return fallbackNoticeFor(sem.status);
1359
+ if (sem.notice.includes(FALLBACK_GUIDANCE_MARKER)) return sem.notice;
1360
+ return `${sem.notice} — ${FALLBACK_GUIDANCE}`;
1361
+ }
1362
+ /**
1363
+ * Why semantic search did not run, in the terms the reader can act on.
1364
+ *
1365
+ * `--search` is the right lever only on a platform-arch that HAS a colgrep
1366
+ * build. Where the manifest has no asset (win32-arm64 today) provisioning has
1367
+ * nothing to fetch and the smoke test can never pass, so `colbertSearchEnabled()`
1368
+ * is false for a reason no flag can change — and the old text told the operator
1369
+ * to pass that flag anyway, which turns a permanent platform limitation into a
1370
+ * mystery that looks like a misconfiguration. The capability gate is shared
1371
+ * with `mcp-capabilities`, so its honesty is what the model and the operator
1372
+ * both read.
1373
+ */
1374
+ function semanticOffNotice() {
1375
+ if (!colbertPlatformSupported()) return `semantic search is unavailable on this platform (${process.platform}-${process.arch} has no prebuilt engine); returned lexical results`;
1376
+ return "semantic search is off (launch with --search to enable); returned lexical results";
1377
+ }
1378
+ async function outlinesForSemanticResults(input, results, signal) {
1379
+ if (input.summary === false) return void 0;
1380
+ const seen = /* @__PURE__ */ new Set();
1381
+ const files = [];
1382
+ for (const result of results) {
1383
+ if (seen.has(result.file)) continue;
1384
+ seen.add(result.file);
1385
+ files.push(result.file);
1386
+ if (files.length >= 10) break;
1387
+ }
1388
+ const outlines = [];
1389
+ const deadline = Date.now() + 2e3;
1390
+ const workspace = path.resolve(input.workspace);
1391
+ for (const file of files) {
1392
+ if (signal?.aborted || Date.now() > deadline) break;
1393
+ const normalized = file.replaceAll("\\", "/").replace(/^\/+/, "");
1394
+ if (!normalized || normalized.includes("\0") || /^[A-Za-z]:/.test(normalized) || normalized.startsWith("//")) continue;
1395
+ if (normalized.split("/").some((part) => part === "..")) continue;
1396
+ const abs = path.resolve(workspace, normalized);
1397
+ const rel = path.relative(workspace, abs);
1398
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) continue;
1399
+ try {
1400
+ const outlined = await outlineFile(abs, signal);
1401
+ outlines.push({
1402
+ file: normalized,
1403
+ outline: outlined.outline.slice(0, 60)
1404
+ });
1405
+ } catch {}
1406
+ }
1407
+ return outlines;
1408
+ }
1409
+ async function runLexical(input, mode, source, signal) {
1410
+ const isAst = mode === "ast";
1411
+ const resp = await searchCode({
1412
+ query: input.query,
1413
+ workspace: input.workspace,
1414
+ mode: lexicalSearchCodeMode(mode),
1415
+ file_glob: input.file_glob,
1416
+ limit: input.limit,
1417
+ context_lines: input.context_lines,
1418
+ structural: input.structural,
1419
+ summary: input.summary,
1420
+ complete: input.complete,
1421
+ multiline: input.multiline,
1422
+ scan: input.scan,
1423
+ ast_pattern: isAst ? input.ast_pattern : void 0,
1424
+ ast_lang: isAst ? input.ast_lang : void 0
1425
+ }, signal);
1426
+ return {
1427
+ source,
1428
+ results: resp.results.map((h) => ({
1429
+ file: h.file,
1430
+ line: h.line,
1431
+ snippet: h.snippet,
1432
+ ...h.role ? { role: h.role } : {}
1433
+ })),
1434
+ notice: joinNotice(resp.notice ?? void 0, emptyPhraseHint(input, resp.results.length)),
1435
+ outlines: resp.outlines,
1436
+ truncated: resp.truncated
1437
+ };
1438
+ }
1439
+ /**
1440
+ * Hint emitted when a multi-word lexical query matches nothing.
1441
+ *
1442
+ * Observed, and only this much is verified: a natural-language multi-word query
1443
+ * can return `results: []` on this backend even when the individual words all
1444
+ * appear in the repository, and the same question answered instantly via a
1445
+ * single identifier or a plain `Grep`. A blind capability audit hit exactly that
1446
+ * on a real lookup and concluded the code did not exist.
1447
+ *
1448
+ * The mechanism is NOT fully characterised. The audit proposed contiguous-phrase
1449
+ * matching; that explanation does not survive testing, because other multi-word
1450
+ * queries whose words are spread across lines do return hits. So this hint
1451
+ * deliberately describes the SYMPTOM and the recovery, and claims nothing about
1452
+ * the cause.
1453
+ *
1454
+ * It is worth emitting regardless of mechanism: a bare empty result reads as
1455
+ * "not in this repository" rather than "that query shape did not work", and this
1456
+ * project's own guidance steers callers here before `Grep`. A silently empty
1457
+ * result is worse than a missing tool, because a missing tool routes you
1458
+ * elsewhere and an empty one convinces you. The advice it gives (retry a single
1459
+ * identifier, or use regex) is correct for a genuine no-match too, so the hint
1460
+ * costs nothing when the repository really lacks the term.
1461
+ */
1462
+ function emptyPhraseHint(input, hitCount) {
1463
+ if (hitCount > 0) return void 0;
1464
+ if (input.mode === "regex" || input.mode === "ast") return void 0;
1465
+ const terms = input.query.trim().split(/\s+/).filter(Boolean);
1466
+ if (terms.length < 2) return void 0;
1467
+ const candidate = terms.map((t) => t.replace(/[^A-Za-z0-9_]/g, "")).filter((t) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)).sort((a, b) => b.length - a.length)[0];
1468
+ return `no hits for a multi-word query. This can happen even when the words all appear in the repository, so do NOT read this as "not present". Retry with a single identifier${candidate ? ` (e.g. \`${candidate}\`)` : ""}, or use \`mode: "regex"\` or grep, before concluding the code is absent.`;
1469
+ }
1470
+ /**
1471
+ * Bluebird backend for the `semantic` and `lexical` modes. `exact|regex|ast`
1472
+ * never reach here (they stay local by contract). Errors surface as
1473
+ * `source:"error"` — the `--bluebird` promise is "Bluebird or a visible
1474
+ * error", never a silent local fallback that would mask an auth/outage
1475
+ * problem as a relevance problem.
1476
+ */
1477
+ async function runBluebird(input, mode, signal) {
1478
+ const limit = input.limit ?? 200;
1479
+ try {
1480
+ const workspace = validateWorkspace(input.workspace);
1481
+ if (!workspace.ok || !workspace.canonical) throw new Error(workspace.error ?? "workspace path is not accessible");
1482
+ const client = await ensureBluebirdClient(workspace.canonical, signal);
1483
+ const results = (mode === "semantic" ? await client.doVectorSearch(input.query, {
1484
+ limit,
1485
+ file_glob: input.file_glob,
1486
+ signal
1487
+ }) : await client.searchFileContent(input.query, {
1488
+ limit,
1489
+ file_glob: input.file_glob,
1490
+ signal
1491
+ })).slice(0, limit).map((r) => ({
1492
+ file: r.file,
1493
+ line: r.line,
1494
+ snippet: r.snippet,
1495
+ ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
1496
+ ...r.name !== void 0 ? { name: r.name } : {},
1497
+ ...r.score !== void 0 ? { score: r.score } : {}
1498
+ }));
1499
+ const outlines = await outlinesForSemanticResults(input, results, signal);
1500
+ return {
1501
+ source: mode,
1502
+ results,
1503
+ ...outlines ? { outlines } : {}
1504
+ };
1505
+ } catch (err) {
1506
+ if (signal?.aborted) throw err;
1507
+ return {
1508
+ source: "error",
1509
+ results: [],
1510
+ notice: `Bluebird ${mode} search failed: ${err instanceof BluebirdError ? err.message : err instanceof Error ? err.message : String(err)} (no local fallback under --bluebird; retry, or use mode:"exact"/"regex"/"ast" for the local engine)`
1511
+ };
1512
+ }
1513
+ }
1514
+ /**
1515
+ * Route a unified code-search request. Throws only on input/workspace
1516
+ * validation failure (propagated from `searchCode`); callers wrap in
1517
+ * try/catch exactly as they do today for `searchCode`.
1518
+ *
1519
+ * Under `--bluebird` (initialized client present), `semantic` (the
1520
+ * default) and `lexical` route through Bluebird; `exact|regex|ast` stay
1521
+ * local. Bluebird failures return `source:"error"` with the cause in
1522
+ * `notice` — never a silent local fallback.
1523
+ */
1524
+ async function runUnifiedCodeSearch(input, signal) {
1525
+ const mode = input.mode ?? "semantic";
1526
+ if (state.bluebirdEnabled === true && (mode === "semantic" || mode === "lexical")) return runBluebird(input, mode, signal);
1527
+ if (mode !== "semantic") return runLexical(input, mode, "lexical", signal);
1528
+ if (!colbertSearchEnabled()) {
1529
+ const r = await runLexical(input, "lexical", "lexical-fallback", signal);
1530
+ return {
1531
+ ...r,
1532
+ notice: joinNotice(r.notice, semanticOffNotice())
1533
+ };
1534
+ }
1535
+ if (serviceBackendEnabled()) try {
1536
+ const svc = await runServiceSearch({
1537
+ query: input.query,
1538
+ workspace: input.workspace,
1539
+ limit: input.limit,
1540
+ signal
1541
+ });
1542
+ if (svc.status === "ready") {
1543
+ const results = (svc.results ?? []).map((r) => ({
1544
+ file: r.file,
1545
+ line: r.line,
1546
+ snippet: r.snippet,
1547
+ ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
1548
+ ...r.name !== void 0 ? { name: r.name } : {},
1549
+ ...r.score !== void 0 ? { score: r.score } : {}
1550
+ }));
1551
+ return {
1552
+ source: "semantic",
1553
+ results,
1554
+ outlines: await outlinesForSemanticResults(input, results, signal),
1555
+ ...svc.freshness ? { freshness: svc.freshness } : {},
1556
+ ...svc.stale_files !== void 0 ? { stale_files: svc.stale_files } : {}
1557
+ };
1558
+ }
1559
+ } catch {}
1560
+ let sem;
1561
+ try {
1562
+ sem = await runSemanticSearch({
1563
+ query: input.query,
1564
+ workspace: input.workspace,
1565
+ limit: input.limit,
1566
+ pattern: input.pattern,
1567
+ signal,
1568
+ serveStale: true
1569
+ });
1570
+ } catch {
1571
+ const r = await runLexical(input, "lexical", "lexical-fallback", signal);
1572
+ return {
1573
+ ...r,
1574
+ notice: joinNotice(r.notice, "semantic search errored; returned lexical results")
1575
+ };
1576
+ }
1577
+ if (sem.status === "ready") {
1578
+ const results = (sem.results ?? []).map((r) => ({
1579
+ file: r.file,
1580
+ line: r.line,
1581
+ snippet: r.snippet,
1582
+ ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
1583
+ ...r.name !== void 0 ? { name: r.name } : {},
1584
+ ...r.score !== void 0 ? { score: r.score } : {}
1585
+ }));
1586
+ return {
1587
+ source: "semantic",
1588
+ results,
1589
+ outlines: await outlinesForSemanticResults(input, results, signal),
1590
+ ...sem.notice ? { notice: sem.notice } : {},
1591
+ ...sem.freshness ? { freshness: sem.freshness } : {},
1592
+ ...sem.stale_files !== void 0 ? { stale_files: sem.stale_files } : {}
1593
+ };
1594
+ }
1595
+ const r = await runLexical(input, "lexical", "lexical-fallback", signal);
1596
+ return {
1597
+ ...r,
1598
+ notice: joinNotice(r.notice, semanticFallbackNotice(sem))
1599
+ };
1600
+ }
1601
+ //#endregion
1602
+ //#region src/lib/hook-prompt-brief.ts
1603
+ /** One grounding search, rendered compactly. "" on any failure. */
1604
+ async function searchText(query, mode, workspace, signal) {
1605
+ try {
1606
+ return (await runUnifiedCodeSearch({
1607
+ query,
1608
+ workspace,
1609
+ mode,
1610
+ limit: 10,
1611
+ summary: false
1612
+ }, signal)).results.slice(0, 10).map((hit) => `${hit.file}:${hit.line}\n${hit.snippet}`).join("\n\n");
1613
+ } catch {
1614
+ return "";
1615
+ }
1616
+ }
1617
+ /**
1618
+ * Produce the cheapest-profile brief for one prompt.
1619
+ *
1620
+ * `profile` is the launch profile id; only `"cheapest"` is eligible, matching
1621
+ * the Claude hook exactly (the launcher exports `GH_ROUTER_PROFILE` into the
1622
+ * hook process there, and the launch registry carries it here). The one-shot
1623
+ * flag is keyed on `sessionId` and marked on ATTEMPT, so a session that spends
1624
+ * the rewrite and misses does not retry on every later prompt.
1625
+ */
1626
+ async function runHookPromptBrief(input) {
1627
+ const steerEnabled = input.steerEnabled ?? true;
1628
+ const rewriteDisabled = input.rewriteDisabled ?? isCheapestRewriteDisabledEnv();
1629
+ if (rewriteDisabled) return {
1630
+ brief: null,
1631
+ reason: "disabled"
1632
+ };
1633
+ if (!isCheapestRewriteEligible({
1634
+ profile: input.profile,
1635
+ promptIsNonTrivial: isNonTrivialPrompt(input.prompt),
1636
+ steerEnabled,
1637
+ rewriteDisabled
1638
+ })) return {
1639
+ brief: null,
1640
+ reason: "not-eligible"
1641
+ };
1642
+ const workspace = input.workspace.trim();
1643
+ if (workspace.length === 0) return {
1644
+ brief: null,
1645
+ reason: "no-workspace"
1646
+ };
1647
+ const sessionId = input.sessionId.trim();
1648
+ if (sessionId.length === 0) return {
1649
+ brief: null,
1650
+ reason: "no-session"
1651
+ };
1652
+ const flags = fileRewriteFlagStore(stopReviewStateDir());
1653
+ try {
1654
+ if (await flags.hasRun(sessionId)) return {
1655
+ brief: null,
1656
+ reason: "already-run"
1657
+ };
1658
+ } catch {}
1659
+ try {
1660
+ await flags.markRun(sessionId);
1661
+ } catch {}
1662
+ const { brief, timedOut } = await runCheapestRewrite({
1663
+ prompt: input.prompt,
1664
+ searchEnabled: input.searchEnabled,
1665
+ bluebirdEnabled: input.bluebirdEnabled,
1666
+ io: {
1667
+ searchCode: (query, mode, signal) => searchText(query, mode, workspace, signal),
1668
+ inferSol: (system, user, signal) => input.infer(system, user, signal),
1669
+ staticPack: async () => buildStaticPack(workspace),
1670
+ hasRewriteRun: () => flags.hasRun(sessionId),
1671
+ markRewriteRun: () => flags.markRun(sessionId)
1672
+ }
1673
+ });
1674
+ if (brief && brief.trim().length > 0) return {
1675
+ brief,
1676
+ reason: "ok"
1677
+ };
1678
+ return {
1679
+ brief: null,
1680
+ reason: timedOut ? "timed-out" : "miss"
1681
+ };
1682
+ }
1683
+ //#endregion
1143
1684
  //#region src/lib/gemini-review-model.ts
1144
1685
  const GEMINI_REVIEW_DEFAULT_MODEL = "gemini-3.1-pro-preview";
1145
1686
  //#endregion
@@ -4069,9 +4610,11 @@ async function getRequiredChecksForSha(repo, sha) {
4069
4610
  const anyPending = runningCount > 0 || legacyPending || checkRunsIncomplete;
4070
4611
  const anySignal = checkRuns.length > 0 || hasLegacyStatuses || checkRunsIncomplete;
4071
4612
  let rollup = "none";
4072
- if (anySignal) if (anyFailing) rollup = "failing";
4073
- else if (anyPending) rollup = "pending";
4074
- else rollup = "passing";
4613
+ if (anySignal) {
4614
+ if (anyFailing) rollup = "failing";
4615
+ else if (anyPending) rollup = "pending";
4616
+ else rollup = "passing";
4617
+ }
4075
4618
  const checks = checkRuns.slice(0, CHECK_SUMMARY_LIMIT).map((check) => ({
4076
4619
  id: check.id ?? 0,
4077
4620
  name: check.name ?? "",
@@ -7744,25 +8287,26 @@ async function observeBlockedUnit(unit, deps, applied) {
7744
8287
  const mergedPr = observed.prs.find((pr) => pr.merged || pr.state === "MERGED");
7745
8288
  const mergedIsPinned = mergedPr != null && unit.pr != null && mergedPr.number === unit.pr;
7746
8289
  const floorHeadMatches = unit.floorSha != null && unit.floorSha.length > 0 && mergedPr != null && mergedPr.headSha.length > 0 && mergedPr.headSha === unit.floorSha;
7747
- if (mutation === "merged") if (decision?.type === "merge_approval" && mergedIsPinned && floorHeadMatches && unit.validation === "floor_passed") {
7748
- unit.terminal = true;
7749
- unit.phase = "done";
7750
- unit.artifact = "pr_merged";
7751
- unit.validation = "floor_passed";
7752
- unit.blockingDecisionId = null;
7753
- await answer("superseded_external_merge");
7754
- applied.push(`reconciled approved external merge for ${repoLabel$1(unit.repo)}#${unit.pr}`);
7755
- } else {
7756
- unit.terminal = true;
7757
- unit.phase = "done";
7758
- unit.artifact = "pr_merged";
7759
- unit.validation = "external_merge_unverified";
7760
- unit.blockingDecisionId = null;
7761
- await answer("superseded_external_merge_unverified");
7762
- consola.warn(`first-mate: ${repoLabel$1(unit.repo)}#${unit.pr ?? "?"} was merged out-of-band WITHOUT a verified floor pass (decision ${decision?.type ?? "unknown"}) — recorded external_merge_unverified`);
7763
- applied.push(`recorded UNVERIFIED external merge for ${repoLabel$1(unit.repo)}#${unit.pr ?? "?"}`);
7764
- }
7765
- else if (mutation === "closed") {
8290
+ if (mutation === "merged") {
8291
+ if (decision?.type === "merge_approval" && mergedIsPinned && floorHeadMatches && unit.validation === "floor_passed") {
8292
+ unit.terminal = true;
8293
+ unit.phase = "done";
8294
+ unit.artifact = "pr_merged";
8295
+ unit.validation = "floor_passed";
8296
+ unit.blockingDecisionId = null;
8297
+ await answer("superseded_external_merge");
8298
+ applied.push(`reconciled approved external merge for ${repoLabel$1(unit.repo)}#${unit.pr}`);
8299
+ } else {
8300
+ unit.terminal = true;
8301
+ unit.phase = "done";
8302
+ unit.artifact = "pr_merged";
8303
+ unit.validation = "external_merge_unverified";
8304
+ unit.blockingDecisionId = null;
8305
+ await answer("superseded_external_merge_unverified");
8306
+ consola.warn(`first-mate: ${repoLabel$1(unit.repo)}#${unit.pr ?? "?"} was merged out-of-band WITHOUT a verified floor pass (decision ${decision?.type ?? "unknown"}) — recorded external_merge_unverified`);
8307
+ applied.push(`recorded UNVERIFIED external merge for ${repoLabel$1(unit.repo)}#${unit.pr ?? "?"}`);
8308
+ }
8309
+ } else if (mutation === "closed") {
7766
8310
  unit.terminal = true;
7767
8311
  unit.phase = "done";
7768
8312
  unit.artifact = "pr_closed";
@@ -12381,438 +12925,782 @@ function anyProp(description) {
12381
12925
  return { description };
12382
12926
  }
12383
12927
  //#endregion
12384
- //#region src/lib/colbert/index.ts
12385
- /**
12386
- * ColBERT semantic-search sidecar — public entry points.
12387
- *
12388
- * `provisionAndIndexColbert()` is the fire-and-forget call site the
12389
- * `start` / `claude` / `codex` launchers invoke after `setupAndServe`
12390
- * (mirroring `provisionToolbelt()` / `runSelfUpdate()`):
12391
- * 1. Bail unless opted in (`--search` / `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1`);
12392
- * `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` hard-disables.
12393
- * 2. Register the exit handlers (tree-kill tracked colgrep children).
12394
- * 3. Provision the binary/model/ORT under a lock + smoke test
12395
- * (best-effort, never throws to the launcher).
12396
- * 4. If the launch cwd is a git repo and its index is absent/stale,
12397
- * kick a background `colgrep init` (non-blocking).
12398
- *
12399
- * On-demand indexing for non-cwd workspaces is handled inside the MCP
12400
- * tool handler (`runSemanticSearch` kicks a debounced background init
12401
- * for an unindexed workspace and reports `unavailable` meanwhile).
12402
- */
12928
+ //#region src/lib/kusto-client.ts
12929
+ /**
12930
+ * Azure Data Explorer (Kusto) REST client.
12931
+ *
12932
+ * The router talks to ADX directly rather than through `@azure/mcp`'s `kusto`
12933
+ * namespace: that package ships a 122 MB platform binary and a managed .NET
12934
+ * child process for seven tools whose entire value is one authenticated POST
12935
+ * to `/v1/rest/query`. A wrong-shaped request here is a JSON body; a
12936
+ * wrong-shaped request there is a failed native spawn on the canonical Windows
12937
+ * environment.
12938
+ *
12939
+ * **Read-only is enforced by the service, not by this file.** Every request
12940
+ * carries the `x-ms-readonly: true` header AND
12941
+ * `properties.Options.request_readonly_hardline: true`. Kusto documents both as
12942
+ * unavailable to a `set` statement, so a query string cannot lift them. That is
12943
+ * the property a leading-dot/text allowlist in the client could not provide:
12944
+ * Kusto composes multiple `;`-separated statements per request, so "does this
12945
+ * text contain a mutating command" is not a question a prefix check answers.
12946
+ * The client therefore performs NO KQL inspection and relies on the service to
12947
+ * refuse a mutation.
12948
+ *
12949
+ * Auth: `az account get-access-token --resource <cluster-uri>` (ADX uses the
12950
+ * cluster URI as its audience). A process-lifetime, single-flighted cache with
12951
+ * a refresh margin is the auto-refresh path; `KUSTO_TOKEN` overrides for tests
12952
+ * and manual runs.
12953
+ */
12954
+ const KUSTO_TOKEN_ENV = "KUSTO_TOKEN";
12955
+ var KustoError = class extends Error {
12956
+ retriable;
12957
+ status;
12958
+ retryAfterMs;
12959
+ constructor(message, opts = {}) {
12960
+ super(sanitizeRemoteDetail(message));
12961
+ this.name = "KustoError";
12962
+ this.retriable = opts.retriable ?? false;
12963
+ if (opts.status !== void 0) this.status = opts.status;
12964
+ if (opts.retryAfterMs !== void 0) this.retryAfterMs = opts.retryAfterMs;
12965
+ }
12966
+ };
12967
+ /** Wire-shape size limits. A tool result is context, not an export format. */
12968
+ const MAX_CSL_CHARS = 1e5;
12969
+ const MAX_RESPONSE_BYTES = 8388608;
12970
+ const DEFAULT_ROW_CAP = 200;
12971
+ const DEFAULT_CELL_CHARS = 300;
12972
+ const DEFAULT_RENDER_CHARS = 6e4;
12973
+ const REQUEST_TIMEOUT_MS = 6e4;
12974
+ /**
12975
+ * Backoff for a retriable verdict (429/5xx/transport), mirroring the shared
12976
+ * remote-MCP transport's `initializeWithRecovery`: three retries at 1/2/4 s,
12977
+ * with `Retry-After` winning when the service sends one. Every request here is
12978
+ * read-only, which is what makes resending it safe.
12979
+ */
12980
+ const KUSTO_RETRY_DELAYS_MS = [
12981
+ 1e3,
12982
+ 2e3,
12983
+ 4e3
12984
+ ];
12403
12985
  /**
12404
- * True only when the operator opted in via `--search`
12405
- * (`state.searchEnabled`, set by `setupAndServe`) or
12406
- * `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1`. Semantic search is OFF BY
12407
- * DEFAULT (no auto-provision, no background-index); the capability gate
12408
- * additionally requires the artifacts to be present on disk +
12409
- * smoke-passed, so the `code` tool stays lexical until both the opt-in
12410
- * and provisioning have completed.
12411
- *
12412
- * `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` hard-disables and wins over every
12413
- * opt-in signal (escape hatch for tests and managed environments).
12414
- */
12415
- function semanticSearchOptedIn() {
12416
- if (parseBoolEnv(process$1.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) return false;
12417
- return state.searchEnabled === true || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
12986
+ * Read a response body under `MAX_RESPONSE_BYTES`, in BYTES.
12987
+ *
12988
+ * The cap is a byte budget, so it has to be measured in bytes: `text.length`
12989
+ * counts UTF-16 code units, so a body of multi-byte characters passes a
12990
+ * char-count check while occupying up to 3x the memory the cap names. A
12991
+ * `content-length` that already declares an oversized body is refused before
12992
+ * it is buffered at all; a chunked or header-less response falls back to the
12993
+ * byte count after the read, which is the only remaining signal.
12994
+ */
12995
+ async function readBoundedBody(res) {
12996
+ const declaredHeader = res.headers.get("content-length");
12997
+ const declared = declaredHeader ? Number(declaredHeader) : NaN;
12998
+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
12999
+ await res.body?.cancel().catch(() => {});
13000
+ throw new KustoError(`Kusto response declared ${declared} bytes, over the 8 MiB client cap. Narrow the query.`, { retriable: false });
13001
+ }
13002
+ const text = await res.text();
13003
+ const bytes = Buffer.byteLength(text, "utf8");
13004
+ if (bytes > MAX_RESPONSE_BYTES) throw new KustoError(`Kusto response exceeded the 8 MiB client cap (${bytes} bytes). Narrow the query.`, { retriable: false });
13005
+ return text;
12418
13006
  }
12419
13007
  /**
12420
- * Availability predicate for ColBERT semantic search — the single
12421
- * source of truth, living in this leaf module so callers that must not
12422
- * import `mcp-capabilities` (notably the unified code-search helper)
12423
- * can read it without closing an import cycle through `worker-agent`.
13008
+ * Normalize an operator-supplied cluster reference into an origin.
12424
13009
  *
12425
- * True iff the operator hasn't opted out AND the colgrep binary + model
12426
- * + ORT are provisioned on disk AND the post-provision smoke test
12427
- * passed. `mcp-capabilities.semanticSearchEnabled()` delegates here.
13010
+ * Accepts `https://name.region.kusto.windows.net`, with or without a trailing
13011
+ * slash, and a bare host. Rejects anything that is not https, anything with a
13012
+ * path/query/credentials, and anything that is not a syntactically valid
13013
+ * hostname — this value becomes both a request URL and an `az --resource`
13014
+ * audience, so a malformed one would otherwise reach the CLI.
12428
13015
  */
12429
- function colbertSearchEnabled() {
12430
- return semanticSearchOptedIn() && colbertArtifactsPresent() && colbertSmokeOk();
12431
- }
12432
- let _started = false;
12433
- /**
12434
- * Fire-and-forget provision + background-index. Never throws; safe to
12435
- * `void`-call from a launcher right after the server is listening.
12436
- * Idempotent within a proxy run (subsequent calls no-op).
12437
- */
12438
- async function provisionAndIndexColbert(opts = {}) {
12439
- if (!semanticSearchOptedIn()) return;
12440
- if (_started) return;
12441
- _started = true;
12442
- registerColbertExitHandlers();
12443
- let provisioned;
13016
+ function normalizeKustoClusterUri(cluster) {
13017
+ const raw = cluster.trim();
13018
+ if (!raw) throw new KustoError("Kusto cluster is empty.", { retriable: false });
13019
+ const withScheme = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
13020
+ let url;
12444
13021
  try {
12445
- const result = await provisionColbert();
12446
- provisioned = result.status === "ready";
12447
- if (result.status === "unsupported") consola.debug("colbert: semantic search unsupported on this platform");
12448
- else if (result.status !== "ready") consola.debug(`colbert: provision not ready (${result.status}: ${result.reason ?? ""})`);
12449
- } catch (err) {
12450
- consola.debug("colbert: provision threw (swallowed):", err);
12451
- return;
13022
+ url = new URL(withScheme);
13023
+ } catch {
13024
+ throw new KustoError("Kusto cluster is not a valid URL.", { retriable: false });
13025
+ }
13026
+ if (url.protocol !== "https:") throw new KustoError("Kusto cluster must use https.", { retriable: false });
13027
+ if (url.username || url.password) throw new KustoError("Kusto cluster must not embed credentials.", { retriable: false });
13028
+ if (!/^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(url.hostname)) throw new KustoError("Kusto cluster host is not a valid domain name.", { retriable: false });
13029
+ if (url.pathname.replace(/\/+$/, "")) throw new KustoError("Kusto cluster must be an origin with no path.", { retriable: false });
13030
+ return `${url.protocol}//${url.host}`;
13031
+ }
13032
+ /**
13033
+ * Normalize a MODEL-SUPPLIED cluster reference, for the per-call `cluster`
13034
+ * argument.
13035
+ *
13036
+ * Stricter than `normalizeKustoClusterUri`, and deliberately a sibling rather
13037
+ * than an option on it. The launch form stays permissive because an operator
13038
+ * may legitimately point `--kusto-cluster` at a reverse proxy in front of ADX,
13039
+ * and an options bag would let a future caller of the launch form omit the
13040
+ * strictness by accident. Here the REQUEST HOST is chosen by a model, so the
13041
+ * host must carry ADX's `.kusto.` service label, the shape every public cloud's
13042
+ * ADX endpoint has and one that nothing else carries.
13043
+ *
13044
+ * **This is a shape guard, not an access boundary.** What a call can reach is
13045
+ * bounded by AAD, which will not mint a token for a resource the identity
13046
+ * cannot use, plus that identity's RBAC at the cluster. The label rule is here
13047
+ * so a typo or a hallucinated host fails before a token mint and an outbound
13048
+ * request, with the expectation named, instead of as an opaque connect error.
13049
+ *
13050
+ * The rule is `.kusto.` ANYWHERE but at the start of the host, which is what
13051
+ * every public cloud's ADX host has: `*.kusto.windows.net`,
13052
+ * `*.kusto.usgovcloudapi.net`, `*.kusto.chinacloudapi.cn`,
13053
+ * `*.kusto.azuresynapse.net`, `*.kusto.fabric.microsoft.com`. A host that
13054
+ * merely BEGINS with the word (`kusto.<domain>`) is not an ADX endpoint shape
13055
+ * and stays rejected; the cost of a false rejection is one actionable message,
13056
+ * while the cost of a widened rule is acceptance of hosts that are not ADX.
13057
+ *
13058
+ * The refusal text avoids a literal `https://` example on purpose: every
13059
+ * `KustoError` message passes through `sanitizeRemoteDetail`, which rewrites a
13060
+ * URL to `[REDACTED URL]` and would leave the model reading a redaction where
13061
+ * the example should be.
13062
+ */
13063
+ function normalizeKustoCallClusterUri(cluster) {
13064
+ const origin = normalizeKustoClusterUri(cluster);
13065
+ if (!/\.kusto\./i.test(new URL(origin).hostname)) throw new KustoError("`cluster` must name a Kusto endpoint, whose host carries a `kusto` label such as <name>.<region>.kusto.windows.net. Omit `cluster` to use the host set at launch with --kusto-cluster.", { retriable: false });
13066
+ return origin;
13067
+ }
13068
+ /**
13069
+ * Table/column identifiers interpolated into a generated command. Kusto's own
13070
+ * `['name']`-quoting is not used because the server accepts a strict
13071
+ * `[A-Za-z_][A-Za-z0-9_]*` name verbatim and rejecting anything else is a
13072
+ * smaller, reviewable surface than building an escaper.
13073
+ */
13074
+ function assertIdentifier(value, what) {
13075
+ const trimmed = value.trim();
13076
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(trimmed)) throw new KustoError(`${what} must be a simple identifier (letters, digits, underscore; not starting with a digit).`, { retriable: false });
13077
+ return trimmed;
13078
+ }
13079
+ /** Process-lifetime token cache shared by every Kusto client in the process. */
13080
+ const kustoTokenCache = new AzCliAccessTokenCache();
13081
+ var KustoClient = class {
13082
+ clusterUri;
13083
+ database;
13084
+ fetchImpl;
13085
+ tokenProvider;
13086
+ retryDelaysMs;
13087
+ constructor(opts) {
13088
+ this.clusterUri = normalizeKustoClusterUri(opts.clusterUri);
13089
+ this.database = opts.database?.trim() || void 0;
13090
+ this.fetchImpl = opts.fetchImpl ?? fetch;
13091
+ this.tokenProvider = opts.tokenProvider ?? ((signal) => getKustoToken(this.clusterUri, signal));
13092
+ this.retryDelaysMs = opts.retryDelaysMs ?? KUSTO_RETRY_DELAYS_MS;
13093
+ }
13094
+ resolveDatabase(database) {
13095
+ const db = database?.trim() || this.database;
13096
+ if (!db) throw new KustoError("No Kusto database selected. Pass `database` explicitly or launch with `--kusto-database <name>`.", { retriable: false });
13097
+ return db;
13098
+ }
13099
+ async post(endpoint, body, signal) {
13100
+ let refreshed = false;
13101
+ for (let attempt = 0;; attempt++) try {
13102
+ return await this.attemptOnce(endpoint, body, signal);
13103
+ } catch (err) {
13104
+ if (signal?.aborted) throw signal.reason ?? err;
13105
+ if (err instanceof KustoError && err.status === 401 && !refreshed) {
13106
+ refreshed = true;
13107
+ continue;
13108
+ }
13109
+ if (!(err instanceof KustoError ? err.retriable : true) || attempt >= this.retryDelaysMs.length) throw err;
13110
+ const hint = err instanceof KustoError ? err.retryAfterMs : void 0;
13111
+ await sleep$3(hint ?? this.retryDelaysMs[attempt], signal);
13112
+ }
12452
13113
  }
12453
- if (!provisioned) return;
12454
- if (opts.skipCwdIndex) return;
12455
- const cwd = opts.cwd ?? process$1.cwd();
13114
+ /**
13115
+ * One attempt: mint/confirm the token, POST, classify the response. Every
13116
+ * thrown `KustoError` carries a verdict the caller in `post` acts on, so the
13117
+ * retry policy lives in exactly one place.
13118
+ */
13119
+ async attemptOnce(endpoint, body, signal) {
13120
+ const token = await this.tokenProvider(signal);
13121
+ const controller = new AbortController();
13122
+ const onAbort = () => controller.abort(signal?.reason ?? /* @__PURE__ */ new Error("aborted"));
13123
+ if (signal?.aborted) onAbort();
13124
+ else signal?.addEventListener("abort", onAbort, { once: true });
13125
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Kusto request timed out")), REQUEST_TIMEOUT_MS);
13126
+ timer.unref?.();
13127
+ let res;
13128
+ try {
13129
+ try {
13130
+ res = await this.fetchImpl(`${this.clusterUri}/v1/rest/${endpoint}`, {
13131
+ method: "POST",
13132
+ headers: {
13133
+ "Content-Type": "application/json; charset=utf-8",
13134
+ Accept: "application/json",
13135
+ Authorization: `Bearer ${token}`,
13136
+ "x-ms-readonly": "true"
13137
+ },
13138
+ body: JSON.stringify(body),
13139
+ signal: controller.signal
13140
+ });
13141
+ } catch (err) {
13142
+ if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
13143
+ throw new KustoError(`Kusto transport failed: ${sanitizeRemoteDetail(err)}`, { retriable: true });
13144
+ }
13145
+ if (res.status === 401) {
13146
+ kustoTokenCache.invalidate(this.clusterUri);
13147
+ throw new KustoError("Kusto rejected the access token (HTTP 401). Verify `az login` targets the tenant that owns this cluster, then retry.", {
13148
+ retriable: false,
13149
+ status: 401
13150
+ });
13151
+ }
13152
+ if (res.status === 403) throw new KustoError(`Kusto refused the request (HTTP 403): ${kustoErrorDetail(await readBoundedBody(res))} The token was accepted; this is an access-permission verdict for the cluster or database.`, {
13153
+ retriable: false,
13154
+ status: 403
13155
+ });
13156
+ const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
13157
+ if ([
13158
+ 429,
13159
+ 500,
13160
+ 502,
13161
+ 503,
13162
+ 504
13163
+ ].includes(res.status)) throw new KustoError(`Kusto responded with HTTP ${res.status}.`, {
13164
+ retriable: true,
13165
+ status: res.status,
13166
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
13167
+ });
13168
+ const text = await readBoundedBody(res);
13169
+ if (!res.ok) throw new KustoError(`Kusto responded with HTTP ${res.status}: ${kustoErrorDetail(text)}`, {
13170
+ retriable: false,
13171
+ status: res.status
13172
+ });
13173
+ return parseKustoResponse(text);
13174
+ } finally {
13175
+ clearTimeout(timer);
13176
+ signal?.removeEventListener("abort", onAbort);
13177
+ }
13178
+ }
13179
+ /**
13180
+ * Run `csl` against `database`. Leading-dot text is a management command and
13181
+ * is routed to `/v1/rest/mgmt`; everything else is a query. Both carry the
13182
+ * same read-only controls, so the routing is about endpoint correctness, not
13183
+ * about safety.
13184
+ */
13185
+ async runCsl(csl, opts = {}) {
13186
+ const text = csl.trim();
13187
+ if (!text) throw new KustoError("`csl` must be a non-empty KQL query.", { retriable: false });
13188
+ if (text.length > MAX_CSL_CHARS) throw new KustoError(`\`csl\` exceeds the ${MAX_CSL_CHARS}-character limit.`, { retriable: false });
13189
+ const database = this.resolveDatabase(opts.database);
13190
+ const isMgmt = text.startsWith(".");
13191
+ return this.post(isMgmt ? "mgmt" : "query", {
13192
+ db: database,
13193
+ csl: text,
13194
+ properties: { Options: {
13195
+ request_readonly_hardline: true,
13196
+ truncationmaxrecords: DEFAULT_ROW_CAP,
13197
+ truncationmaxsize: 67108864
13198
+ } }
13199
+ }, opts.signal);
13200
+ }
13201
+ /** `.show databases` — the databases this identity can see. */
13202
+ async databasesList(signal) {
13203
+ const names = (await this.post("mgmt", {
13204
+ csl: ".show databases",
13205
+ properties: { Options: { request_readonly_hardline: true } }
13206
+ }, signal)).tables.flatMap((table) => table.rows).map((row) => row[0] === void 0 || row[0] === null ? "" : String(row[0])).filter((name) => name.length > 0);
13207
+ if (names.length === 0) return "No databases visible to this identity.";
13208
+ return `${names.length} database(s):\n${names.map((n) => ` ${n}`).join("\n")}`;
13209
+ }
13210
+ /** `.show tables` — entity names in the selected database. */
13211
+ async tablesList(database, signal) {
13212
+ const db = this.resolveDatabase(database);
13213
+ const names = (await this.post("mgmt", {
13214
+ db,
13215
+ csl: ".show tables",
13216
+ properties: { Options: { request_readonly_hardline: true } }
13217
+ }, signal)).tables.flatMap((table) => table.rows).map((row) => row[0] === void 0 || row[0] === null ? "" : String(row[0])).filter((name) => name.length > 0);
13218
+ if (names.length === 0) return `${db}: no tables.`;
13219
+ return `${db}: ${names.length} table(s)/function(s):\n${names.map((n) => ` ${n}`).join("\n")}`;
13220
+ }
13221
+ /** Column names and types for one table or function. */
13222
+ async tableSchema(table, database, signal) {
13223
+ const name = assertIdentifier(table, "`table`");
13224
+ return renderKustoResponse(await this.runCsl(`${name} | getschema`, {
13225
+ ...database ? { database } : {},
13226
+ ...signal ? { signal } : {}
13227
+ }));
13228
+ }
13229
+ /** First `rows` rows of `table`. */
13230
+ async sample(table, rows = 10, database, signal) {
13231
+ const name = assertIdentifier(table, "`table`");
13232
+ const bounded = Number.isFinite(rows) ? Math.max(1, Math.min(100, Math.floor(rows))) : 10;
13233
+ return renderKustoResponse(await this.runCsl(`${name} | take ${bounded}`, {
13234
+ ...database ? { database } : {},
13235
+ ...signal ? { signal } : {}
13236
+ }));
13237
+ }
13238
+ };
13239
+ function kustoErrorDetail(text) {
13240
+ const trimmed = text.trim();
13241
+ if (!trimmed) return "no detail";
12456
13242
  try {
12457
- if ((await gitState(cwd)).isRepo && await startupKickAllowed(cwd)) kickBackgroundInit(cwd);
12458
- } catch (err) {
12459
- consola.debug("colbert: cwd git-detect skipped:", err);
13243
+ const parsed = JSON.parse(trimmed);
13244
+ if (typeof parsed === "object" && parsed !== null) {
13245
+ const record = parsed;
13246
+ const error = record.error;
13247
+ if (typeof error === "object" && error !== null) {
13248
+ const message = error.message;
13249
+ if (typeof message === "string" && message.trim()) return sanitizeRemoteDetail(message).slice(0, 500);
13250
+ }
13251
+ if (typeof record["@message"] === "string") return sanitizeRemoteDetail(record["@message"]).slice(0, 500);
13252
+ }
13253
+ } catch {}
13254
+ return sanitizeRemoteDetail(trimmed).slice(0, 500);
13255
+ }
13256
+ function parseKustoResponse(text) {
13257
+ let parsed;
13258
+ try {
13259
+ parsed = JSON.parse(text);
13260
+ } catch {
13261
+ throw new KustoError("Kusto returned a response that was not JSON.", { retriable: true });
13262
+ }
13263
+ if (typeof parsed !== "object" || parsed === null) throw new KustoError("Kusto returned an unexpected response shape.", { retriable: true });
13264
+ const rawTables = parsed.Tables;
13265
+ if (!Array.isArray(rawTables)) throw new KustoError("Kusto returned an unexpected response shape.", { retriable: true });
13266
+ const tables = [];
13267
+ let truncated = false;
13268
+ for (const raw of rawTables) {
13269
+ if (typeof raw !== "object" || raw === null) continue;
13270
+ const record = raw;
13271
+ const columns = Array.isArray(record.Columns) ? record.Columns.map((column) => typeof column === "object" && column !== null && typeof column.ColumnName === "string" ? String(column.ColumnName) : "?") : [];
13272
+ const rows = Array.isArray(record.Rows) ? record.Rows.filter((row) => Array.isArray(row)) : [];
13273
+ if (rows.length >= DEFAULT_ROW_CAP) truncated = true;
13274
+ tables.push({
13275
+ name: typeof record.TableName === "string" ? record.TableName : "Table",
13276
+ columns,
13277
+ rows
13278
+ });
12460
13279
  }
13280
+ return {
13281
+ tables,
13282
+ truncated
13283
+ };
13284
+ }
13285
+ function cellText(value, maxChars) {
13286
+ if (value === null || value === void 0) return "";
13287
+ const single = (typeof value === "string" ? value : JSON.stringify(value) ?? String(value)).replace(/\s*\r?\n\s*/g, " ⏎ ");
13288
+ return single.length > maxChars ? `${single.slice(0, maxChars)}…` : single;
12461
13289
  }
12462
13290
  /**
12463
- * One-line operator warning when this workspace's semantic index is sitting in
12464
- * a terminal `failed` state, or `null` when there is nothing to say.
12465
- *
12466
- * This exists because the failure mode that motivated it was SILENCE: semantic
12467
- * search degraded to lexical on a real repo for an unknown period — possibly
12468
- * weeks — and nobody noticed, because the only signals were a `notice` string
12469
- * the model reads and a `consola.debug` the file logger drops. Neither reaches
12470
- * a human. The launcher writes this to stderr next to the readiness line so a
12471
- * degraded capability is visible at the moment the user starts a session.
12472
- *
12473
- * `logsToFile` says where the failure detail actually went. `claude` and
12474
- * `codex` call `enableFileLogging()`, which redirects warnings to
12475
- * ERROR_LOG_PATH; `start` does not, so its warnings stay on the terminal and
12476
- * pointing at the file would send the operator to a stale or absent one.
13291
+ * Render a Kusto result as a compact aligned grid. Never the raw wire JSON:
13292
+ * `{"Tables":[{"Columns":[{"ColumnName":…` is both unreadable to the model and
13293
+ * several times the tokens of the same content as columns and rows.
13294
+ */
13295
+ function renderKustoResponse(response, opts = {}) {
13296
+ const maxCellChars = opts.maxCellChars ?? DEFAULT_CELL_CHARS;
13297
+ const maxChars = opts.maxChars ?? DEFAULT_RENDER_CHARS;
13298
+ const blocks = [];
13299
+ let total = 0;
13300
+ let anyTruncated = response.truncated;
13301
+ for (const table of response.tables) {
13302
+ const header = `(${table.rows.length} row(s)) ${table.columns.join(" | ")}`;
13303
+ const body = table.rows.map((row) => row.map((cell) => cellText(cell, maxCellChars)).join(" | "));
13304
+ let block = table.rows.length === 0 && table.columns.length === 0 ? `${table.name}: empty result.` : [header, ...body].join("\n");
13305
+ if (total + block.length > maxChars) {
13306
+ const room = Math.max(0, maxChars - total);
13307
+ if (room > 0) {
13308
+ block = block.slice(0, room);
13309
+ blocks.push(block);
13310
+ }
13311
+ anyTruncated = true;
13312
+ break;
13313
+ }
13314
+ total += block.length;
13315
+ blocks.push(block);
13316
+ }
13317
+ if (blocks.length === 0) return "Kusto returned no result tables.";
13318
+ const trailer = anyTruncated ? `\n… result truncated at the client's row/character cap; narrow the query for the full set.` : "";
13319
+ return `${blocks.join("\n\n")}${trailer}`;
13320
+ }
13321
+ /** Token source: explicit env first (tests/manual), else `az` CLI. */
13322
+ /**
13323
+ * Token source: explicit env first (tests/manual), else the `az` ladder.
12477
13324
  *
12478
- * Deliberately advisory and best-effort: lexical search still works, so this
12479
- * must never block or fail a launch.
13325
+ * `allowInteractiveLogin` is safe here because this module is call-time only:
13326
+ * the Kusto group has no launch probe (its tools are static and a malformed
13327
+ * cluster fails the launch independently), so no caller reaches this under a
13328
+ * short launch deadline.
12480
13329
  */
12481
- async function colbertDegradedWarning(cwd, opts = {}) {
12482
- if (!semanticSearchOptedIn()) return null;
13330
+ async function getKustoToken(clusterUri, signal) {
13331
+ if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
13332
+ const env = process.env[KUSTO_TOKEN_ENV]?.trim();
13333
+ if (env) return env;
12483
13334
  try {
12484
- const target = cwd ?? process$1.cwd();
12485
- const meta = await readColbertMeta(target);
12486
- if (!meta || meta.status !== "failed") return null;
12487
- const cls = meta.failureClass ?? "error";
12488
- return `Semantic search DEGRADED for this workspace (colbert: ${cls}) — lexical code search still works. ${opts.logsToFile ? `See ${PATHS.ERROR_LOG_PATH}` : "See the proxy log output"}.${cls === "stuck" ? " For a very large repo, raise GH_ROUTER_COLBERT_INIT_STALL_MS / GH_ROUTER_COLBERT_INIT_TIMEOUT_MS." : ""}`;
12489
- } catch {
12490
- return null;
13335
+ return await kustoTokenCache.get(clusterUri, {
13336
+ ...signal ? { signal } : {},
13337
+ allowInteractiveLogin: true
13338
+ });
13339
+ } catch (err) {
13340
+ if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
13341
+ throw new KustoError(describeAzFailure("Kusto", err), { retriable: false });
12491
13342
  }
12492
13343
  }
12493
13344
  //#endregion
12494
- //#region src/lib/unified-code-search.ts
13345
+ //#region src/lib/worker-agent/relay-cap.ts
12495
13346
  /**
12496
- * Unified, semantic-first code search; the single source of truth behind
12497
- * BOTH the MCP `code` tool (`src/lib/peer-mcp-personas.ts`) and the worker
12498
- * subagent's internal `code_search` tool (`src/lib/worker-agent/tools.ts`).
12499
- *
12500
- * Default behaviour (omitted mode or `mode:"semantic"`) ranks by MEANING
12501
- * via ColBERT (colgrep) and TRANSPARENTLY falls back to lexical BM25F when
12502
- * the per-workspace index isn't ready (building / stale / unavailable /
12503
- * failed) or colgrep isn't provisioned on this host. The forced lexical
12504
- * family (`lexical|exact|regex|ast`) never touches colgrep.
12505
- *
12506
- * Under `--bluebird` (`state.bluebirdEnabled`), the `semantic` and
12507
- * `lexical` modes route through
12508
- * the Bluebird Azure DevOps MCP server instead (the unified `code_search`
12509
- * tool, with legacy tool-name compatibility); `exact|regex|ast` stay local, and
12510
- * Bluebird errors surface as `source:"error"` with NO silent local
12511
- * fallback.
13347
+ * Relay-safe result capping for the worker MCP boundary.
12512
13348
  *
12513
- * Provenance is carried in a FOUR-valued `source` field, independent of
12514
- * `notice`:
12515
- * - "semantic" colgrep/Bluebird ran and the index was fresh
12516
- * - "lexical" the caller explicitly forced a lexical mode
12517
- * - "lexical-fallback" a semantic/default query degraded to lexical
12518
- * because the index wasn't ready
12519
- * - "error" the Bluebird backend failed after retries; the
12520
- * response carries `notice` with the cause
12521
- * `notice` keeps the lexical backend's size-cap > structural priority, so
12522
- * on a hit-heavy fallback the urgent size notice can win; `source` still
12523
- * conveys "this was a fallback" unambiguously, and never conflates a
12524
- * degraded result with a deliberately-forced lexical search.
13349
+ * Claude Code hard-caps an MCP tool result at `MAX_MCP_OUTPUT_TOKENS`
13350
+ * (default 25,000 tokens ≈ 100KB); a result over that is rejected /
13351
+ * truncated before the lead ever sees it. A worker that emits a large
13352
+ * `finalText` (an explore/review/plan summary, model prose, or a diff a
13353
+ * model pasted inline) would silently lose its output at that boundary.
12525
13354
  *
12526
- * Contract split vs. `runSemanticSearch`: the runner itself stays
12527
- * NO-FALLBACK (it returns honest status, never another engine). The
12528
- * fallback lives only here, at the merged-tool layer.
13355
+ * `relaySafeText` is the LAST transform applied to a worker's assembled
13356
+ * result text at each MCP boundary (`runWorkerToolCall`,
13357
+ * `runBrowseToolCall`) — AFTER any `clampNote` prefix and the browse
13358
+ * `[browse session: id]` suffix are appended, so nothing can push a
13359
+ * just-capped string back over the limit. When the text exceeds the cap
13360
+ * it is written IN FULL to a durable router-owned file and the caller
13361
+ * gets a bounded head preview + the file path, so the output is
13362
+ * recoverable rather than destroyed.
12529
13363
  *
12530
- * Import-cycle note: this module imports ONLY from `./code-search`,
12531
- * `./colbert`, `./bluebird-client`, and `./state`. It must NOT import
12532
- * `./mcp-capabilities`; that would close a cycle through `worker-agent`.
12533
- * The colbert-availability decision is read from the leaf
12534
- * `colbertSearchEnabled()`. (`./state` reaches `./bluebird-client` by
12535
- * type-only import, and `./bluebird-client` reaches this module by
12536
- * type-only import, so neither edge exists at runtime.)
13364
+ * Byte cap as a proxy for the TOKEN limit: worst-case dense output
13365
+ * (base64 / hex / minified) approaches ~1 byte/token, so the clamp
13366
+ * ceiling (20480 B ≈ 20k tokens) stays safely under the 25k-token cap
13367
+ * with headroom. The env override can never widen it past that ceiling,
13368
+ * so a misconfiguration cannot reintroduce the overflow.
12537
13369
  */
12538
- /** Map the unified mode onto `searchCode`'s internal `mode` enum. */
12539
- function lexicalSearchCodeMode(mode) {
12540
- switch (mode) {
12541
- case "exact": return "literal";
12542
- case "regex": return "regex";
12543
- default: return "ranked";
12544
- }
12545
- }
13370
+ /** Default relay-safe byte budget for a worker result. */
13371
+ const DEFAULT_MAX_RESULT_BYTES = 16384;
13372
+ /** Lower clamp — below this a preview is barely useful. */
13373
+ const MIN_MAX_RESULT_BYTES = 8192;
12546
13374
  /**
12547
- * Status-specific, actionable fallback hint. The semantic index isn't ready,
12548
- * so the model got LEXICAL results (great for exact symbols, sparse for a
12549
- * natural-language phrase since the lexical backend matches literally). Tell
12550
- * it both levers: retry `mode:"semantic"` (the index is self-healing in the
12551
- * background) OR re-query now with specific symbol/keyword terms.
12552
- *
12553
- * "shortly" was too vague and cost a real recovery. A build takes MINUTES on a
12554
- * large repo, and after a failed build the FIRST query is consumed triggering
12555
- * the re-kick and still returns a fallback. So a caller who retried once,
12556
- * seconds later, saw a second fallback and concluded the tool was broken
12557
- * rather than mid-repair. Observed end to end on this repo: query, then
12558
- * ~5 minutes of `building`, then `ready`. Naming the timescale and the
12559
- * one-query-to-trigger behaviour is what turns "it's still broken" into
12560
- * "it's coming back".
12561
- *
12562
- * The wording stays a range rather than a number: build time scales with
12563
- * repository size, so a hard figure would be wrong for most callers.
13375
+ * Upper clamp. 20480 B ≈ 20k tokens even at the ~1 byte/token dense
13376
+ * worst case, comfortably under Claude Code's 25k-token result cap. The
13377
+ * env override is clamped to this, so it can never reintroduce the
13378
+ * overflow the cap exists to prevent.
12564
13379
  */
12565
- const FALLBACK_GUIDANCE_MARKER = "retry mode:\"semantic\"";
12566
- const FALLBACK_GUIDANCE = `${FALLBACK_GUIDANCE_MARKER} in minutes or use exact symbols`;
12567
- function fallbackNoticeFor(status) {
12568
- const tail = FALLBACK_GUIDANCE;
12569
- switch (status) {
12570
- case "building": return `semantic index building — returned lexical matches; ${tail}`;
12571
- case "stale": return `semantic index stale (HEAD moved) — re-index started, returned lexical matches; ${tail}`;
12572
- case "unavailable": return `no semantic index yet — build started, returned lexical matches; ${tail}`;
12573
- case "failed": return `semantic index failed — this query started a background rebuild, returned lexical matches; ${tail}`;
12574
- default: return "returned lexical results";
12575
- }
12576
- }
13380
+ const MAX_MAX_RESULT_BYTES = 20480;
12577
13381
  /**
12578
- * Combine the lexical backend's own notice (size-cap / structural, the
12579
- * urgent "you're missing results" signal) with a fallback hint, keeping a
12580
- * single string. The lexical notice stays primary; the hint is appended so
12581
- * neither is lost.
13382
+ * Age at which a spilled `.patch`/`.txt` is swept. Matches the worktree
13383
+ * dir age sweep in `worktree.ts`.
12582
13384
  */
12583
- function joinNotice(primary, secondary) {
12584
- if (primary && secondary) return `${primary} (${secondary})`;
12585
- return primary || secondary || void 0;
13385
+ const AGE_SWEEP_MS$1 = 6048e5;
13386
+ /** Min interval between throttled hot-path sweeps (see `sweepAgedWorkerDiffs`). */
13387
+ const SWEEP_THROTTLE_MS = 6e4;
13388
+ let lastThrottledSweepAt = 0;
13389
+ /**
13390
+ * Strict name pattern for router-written overflow files:
13391
+ * `<pid>-<8hex>.(patch|txt)`. Shared by the sweep so it NEVER removes a
13392
+ * file it didn't write (a user could drop something else under the dir).
13393
+ */
13394
+ const WORKER_DIFF_NAME_RE = /^\d+-[0-9a-f]{8}\.(?:patch|txt)$/;
13395
+ /** Resolve the relay-safe byte cap from env, clamped to the safe range. */
13396
+ function resolveMaxResultBytes() {
13397
+ const raw = process$1.env.GH_ROUTER_WORKER_MAX_RESULT_BYTES;
13398
+ if (raw === void 0) return DEFAULT_MAX_RESULT_BYTES;
13399
+ const n = Number(raw);
13400
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) return DEFAULT_MAX_RESULT_BYTES;
13401
+ return Math.min(MAX_MAX_RESULT_BYTES, Math.max(MIN_MAX_RESULT_BYTES, n));
12586
13402
  }
12587
- /** Preserve runner-specific context while guaranteeing actionable guidance once. */
12588
- function semanticFallbackNotice(sem) {
12589
- if (!sem.notice) return fallbackNoticeFor(sem.status);
12590
- if (sem.notice.includes(FALLBACK_GUIDANCE_MARKER)) return sem.notice;
12591
- return `${sem.notice} — ${FALLBACK_GUIDANCE}`;
13403
+ /**
13404
+ * Return the longest prefix of `text` whose UTF-8 encoding is at most
13405
+ * `maxBytes` long, cut on a codepoint boundary (never mid-multibyte).
13406
+ */
13407
+ function utf8HeadPreview(text, maxBytes) {
13408
+ if (maxBytes <= 0) return "";
13409
+ const buf = Buffer.from(text, "utf8");
13410
+ if (buf.length <= maxBytes) return text;
13411
+ let end = maxBytes;
13412
+ while (end > 0 && (buf[end] & 192) === 128) end--;
13413
+ return buf.subarray(0, end).toString("utf8");
12592
13414
  }
12593
- async function outlinesForSemanticResults(input, results, signal) {
12594
- if (input.summary === false) return void 0;
12595
- const seen = /* @__PURE__ */ new Set();
12596
- const files = [];
12597
- for (const result of results) {
12598
- if (seen.has(result.file)) continue;
12599
- seen.add(result.file);
12600
- files.push(result.file);
12601
- if (files.length >= 10) break;
13415
+ /**
13416
+ * Best-effort age sweep of router-written overflow files under
13417
+ * `WORKER_DIFFS_DIR`. Only removes entries whose NAME matches
13418
+ * `WORKER_DIFF_NAME_RE` and whose mtime is older than 7 days — a fresh
13419
+ * file a concurrent worker just wrote (new mtime) is never touched, and
13420
+ * a locked file just skips. Errors are swallowed so a sweep never blocks
13421
+ * the write it precedes.
13422
+ *
13423
+ * `opts.throttle` (used by the write hot path) skips the readdir/stat scan
13424
+ * when a throttled sweep ran within the last minute, so concurrent overflow
13425
+ * writes don't each re-scan the directory. Direct callers (and tests) sweep
13426
+ * unconditionally.
13427
+ */
13428
+ async function sweepAgedWorkerDiffs(opts = {}) {
13429
+ if (opts.throttle) {
13430
+ const now = Date.now();
13431
+ if (now - lastThrottledSweepAt < SWEEP_THROTTLE_MS) return;
13432
+ lastThrottledSweepAt = now;
12602
13433
  }
12603
- const outlines = [];
12604
- const deadline = Date.now() + 2e3;
12605
- const workspace = path.resolve(input.workspace);
12606
- for (const file of files) {
12607
- if (signal?.aborted || Date.now() > deadline) break;
12608
- const normalized = file.replaceAll("\\", "/").replace(/^\/+/, "");
12609
- if (!normalized || normalized.includes("\0") || /^[A-Za-z]:/.test(normalized) || normalized.startsWith("//")) continue;
12610
- if (normalized.split("/").some((part) => part === "..")) continue;
12611
- const abs = path.resolve(workspace, normalized);
12612
- const rel = path.relative(workspace, abs);
12613
- if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) continue;
13434
+ let entries;
13435
+ try {
13436
+ entries = await fs$1.readdir(PATHS.WORKER_DIFFS_DIR);
13437
+ } catch {
13438
+ return;
13439
+ }
13440
+ const now = Date.now();
13441
+ for (const name of entries) {
13442
+ if (!WORKER_DIFF_NAME_RE.test(name)) continue;
13443
+ const full = path.join(PATHS.WORKER_DIFFS_DIR, name);
12614
13444
  try {
12615
- const outlined = await outlineFile(abs, signal);
12616
- outlines.push({
12617
- file: normalized,
12618
- outline: outlined.outline.slice(0, 60)
12619
- });
13445
+ if (now - (await fs$1.stat(full)).mtimeMs < AGE_SWEEP_MS$1) continue;
13446
+ await fs$1.rm(full, { force: true }).catch(() => {});
12620
13447
  } catch {}
12621
13448
  }
12622
- return outlines;
12623
- }
12624
- async function runLexical(input, mode, source, signal) {
12625
- const isAst = mode === "ast";
12626
- const resp = await searchCode({
12627
- query: input.query,
12628
- workspace: input.workspace,
12629
- mode: lexicalSearchCodeMode(mode),
12630
- file_glob: input.file_glob,
12631
- limit: input.limit,
12632
- context_lines: input.context_lines,
12633
- structural: input.structural,
12634
- summary: input.summary,
12635
- complete: input.complete,
12636
- multiline: input.multiline,
12637
- scan: input.scan,
12638
- ast_pattern: isAst ? input.ast_pattern : void 0,
12639
- ast_lang: isAst ? input.ast_lang : void 0
12640
- }, signal);
12641
- return {
12642
- source,
12643
- results: resp.results.map((h) => ({
12644
- file: h.file,
12645
- line: h.line,
12646
- snippet: h.snippet,
12647
- ...h.role ? { role: h.role } : {}
12648
- })),
12649
- notice: joinNotice(resp.notice ?? void 0, emptyPhraseHint(input, resp.results.length)),
12650
- outlines: resp.outlines,
12651
- truncated: resp.truncated
12652
- };
12653
13449
  }
12654
13450
  /**
12655
- * Hint emitted when a multi-word lexical query matches nothing.
12656
- *
12657
- * Observed, and only this much is verified: a natural-language multi-word query
12658
- * can return `results: []` on this backend even when the individual words all
12659
- * appear in the repository, and the same question answered instantly via a
12660
- * single identifier or a plain `Grep`. A blind capability audit hit exactly that
12661
- * on a real lookup and concluded the code did not exist.
12662
- *
12663
- * The mechanism is NOT fully characterised. The audit proposed contiguous-phrase
12664
- * matching; that explanation does not survive testing, because other multi-word
12665
- * queries whose words are spread across lines do return hits. So this hint
12666
- * deliberately describes the SYMPTOM and the recovery, and claims nothing about
12667
- * the cause.
12668
- *
12669
- * It is worth emitting regardless of mechanism: a bare empty result reads as
12670
- * "not in this repository" rather than "that query shape did not work", and this
12671
- * project's own guidance steers callers here before `Grep`. A silently empty
12672
- * result is worse than a missing tool, because a missing tool routes you
12673
- * elsewhere and an empty one convinces you. The advice it gives (retry a single
12674
- * identifier, or use regex) is correct for a genuine no-match too, so the hint
12675
- * costs nothing when the repository really lacks the term.
13451
+ * Write `text` in full to a durable `.txt` under `WORKER_DIFFS_DIR` and
13452
+ * return its absolute path. Unique `<pid>-<8hex>.txt` name, `0o600`,
13453
+ * exclusive-create (`wx`) so it never clobbers a pre-existing file /
13454
+ * symlink. Retries on the (astronomically rare) name collision with a
13455
+ * fresh suffix. Sweeps aged files first (throttled, best-effort).
12676
13456
  */
12677
- function emptyPhraseHint(input, hitCount) {
12678
- if (hitCount > 0) return void 0;
12679
- if (input.mode === "regex" || input.mode === "ast") return void 0;
12680
- const terms = input.query.trim().split(/\s+/).filter(Boolean);
12681
- if (terms.length < 2) return void 0;
12682
- const candidate = terms.map((t) => t.replace(/[^A-Za-z0-9_]/g, "")).filter((t) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)).sort((a, b) => b.length - a.length)[0];
12683
- return `no hits for a multi-word query. This can happen even when the words all appear in the repository, so do NOT read this as "not present". Retry with a single identifier${candidate ? ` (e.g. \`${candidate}\`)` : ""}, or use \`mode: "regex"\` or grep, before concluding the code is absent.`;
13457
+ async function saveOverflowResult(text) {
13458
+ await sweepAgedWorkerDiffs({ throttle: true });
13459
+ await fs$1.mkdir(PATHS.WORKER_DIFFS_DIR, { recursive: true });
13460
+ let lastErr;
13461
+ for (let attempt = 0; attempt < 5; attempt++) {
13462
+ const name = `${process$1.pid}-${randomBytes(4).toString("hex")}.txt`;
13463
+ const outPath = path.join(PATHS.WORKER_DIFFS_DIR, name);
13464
+ try {
13465
+ await fs$1.writeFile(outPath, text, {
13466
+ mode: 384,
13467
+ flag: "wx"
13468
+ });
13469
+ return outPath;
13470
+ } catch (err) {
13471
+ if (err.code !== "EEXIST") throw err;
13472
+ lastErr = err;
13473
+ }
13474
+ }
13475
+ throw lastErr instanceof Error ? lastErr : /* @__PURE__ */ new Error("saveOverflowResult: exhausted unique-name retries");
12684
13476
  }
12685
13477
  /**
12686
- * Bluebird backend for the `semantic` and `lexical` modes. `exact|regex|ast`
12687
- * never reach here (they stay local by contract). Errors surface as
12688
- * `source:"error"` — the `--bluebird` promise is "Bluebird or a visible
12689
- * error", never a silent local fallback that would mask an auth/outage
12690
- * problem as a relevance problem.
13478
+ * Cap a worker result to a relay-safe size. `reservedBytes` is the UTF-8
13479
+ * byte length of any must-survive envelope the caller will add OUTSIDE this
13480
+ * result (a `clampNote`/`worktreeNote` prefix, or the browse
13481
+ * `[browse session: id]` suffix), so the caller's final `envelope + result`
13482
+ * (or `result + envelope`) is guaranteed `<=` the configured cap.
13483
+ *
13484
+ * If the text fits under the effective cap it is returned unchanged.
13485
+ * Otherwise the FULL text is spilled to a durable file and a bounded
13486
+ * UTF-8-safe head preview + the file path is returned. On write failure the
13487
+ * preview is still returned with an explicit failure note — NEVER the
13488
+ * oversized original (that would re-trigger the overflow this guard prevents).
12691
13489
  */
12692
- async function runBluebird(input, mode, signal) {
12693
- const limit = input.limit ?? 200;
13490
+ async function relaySafeText(text, reservedBytes = 0) {
13491
+ const cap = Math.max(0, resolveMaxResultBytes() - Math.max(0, reservedBytes));
13492
+ if (Buffer.byteLength(text, "utf8") <= cap) return text;
13493
+ let savedPath = null;
13494
+ let saveError = null;
12694
13495
  try {
12695
- const workspace = validateWorkspace(input.workspace);
12696
- if (!workspace.ok || !workspace.canonical) throw new Error(workspace.error ?? "workspace path is not accessible");
12697
- const client = await ensureBluebirdClient(workspace.canonical, signal);
12698
- const results = (mode === "semantic" ? await client.doVectorSearch(input.query, {
12699
- limit,
12700
- file_glob: input.file_glob,
12701
- signal
12702
- }) : await client.searchFileContent(input.query, {
12703
- limit,
12704
- file_glob: input.file_glob,
12705
- signal
12706
- })).slice(0, limit).map((r) => ({
12707
- file: r.file,
12708
- line: r.line,
12709
- snippet: r.snippet,
12710
- ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
12711
- ...r.name !== void 0 ? { name: r.name } : {},
12712
- ...r.score !== void 0 ? { score: r.score } : {}
12713
- }));
12714
- const outlines = await outlinesForSemanticResults(input, results, signal);
12715
- return {
12716
- source: mode,
12717
- results,
12718
- ...outlines ? { outlines } : {}
12719
- };
13496
+ savedPath = await saveOverflowResult(text);
12720
13497
  } catch (err) {
12721
- if (signal?.aborted) throw err;
12722
- return {
12723
- source: "error",
12724
- results: [],
12725
- notice: `Bluebird ${mode} search failed: ${err instanceof BluebirdError ? err.message : err instanceof Error ? err.message : String(err)} (no local fallback under --bluebird; retry, or use mode:"exact"/"regex"/"ast" for the local engine)`
12726
- };
13498
+ saveError = err instanceof Error ? err.message : String(err);
12727
13499
  }
13500
+ const trailer = savedPath !== null ? `\n\n[result truncated to fit the relay; full result saved to: ${savedPath}]` : `\n\n[result truncated to fit the relay; saving the full result failed: ${saveError ?? "unknown"}]`;
13501
+ const out = utf8HeadPreview(text, Math.max(0, cap - Buffer.byteLength(trailer, "utf8"))) + trailer;
13502
+ return Buffer.byteLength(out, "utf8") <= cap ? out : utf8HeadPreview(out, cap);
13503
+ }
13504
+ //#endregion
13505
+ //#region src/lib/kusto-tools.ts
13506
+ const KUSTO_GROUP = "kusto";
13507
+ /**
13508
+ * One process-lifetime client per resolved cluster, keyed on the NORMALIZED
13509
+ * origin so `name`, `name/` and a full https form share one entry.
13510
+ *
13511
+ * Keyed on the cluster URI because that is also the token audience: a second
13512
+ * cluster needs a second token, and a client answering for a cluster other than
13513
+ * the one its token was minted for would silently report the wrong data.
13514
+ *
13515
+ * Deliberately UNCAPPED. A `KustoClient` is a pure value (origin plus a default
13516
+ * database name); the material per-cluster object is the access token, and that
13517
+ * already lives uncapped for the process's lifetime in the shared
13518
+ * `AzCliAccessTokenCache` in `./kusto-client`. A cap here would bound a few
13519
+ * hundred bytes while inviting a false reading that the per-cluster footprint
13520
+ * is bounded. See the docs' note on a per-session distinct-cluster budget.
13521
+ */
13522
+ const clients = /* @__PURE__ */ new Map();
13523
+ /**
13524
+ * The cluster a call runs against: the call's own `cluster` first, else the
13525
+ * launch's `--kusto-cluster`. Resolved synchronously, before a handler awaits
13526
+ * anything, so a shape error costs no token mint and no request.
13527
+ */
13528
+ function resolveCluster(args) {
13529
+ const value = args.cluster;
13530
+ if (value !== void 0) {
13531
+ if (typeof value !== "string" || !value.trim()) throw new KustoError("`cluster` must be a non-empty string when provided.", { retriable: false });
13532
+ return normalizeKustoCallClusterUri(value);
13533
+ }
13534
+ const launch = state.kustoCluster;
13535
+ if (!launch) throw new KustoError("No Kusto cluster selected. Pass `cluster` (a host such as <name>.<region>.kusto.windows.net, or a full https URI), or launch with `--kusto-cluster <uri>`.", { retriable: false });
13536
+ return normalizeKustoClusterUri(launch);
13537
+ }
13538
+ function kustoClient(clusterUri) {
13539
+ const existing = clients.get(clusterUri);
13540
+ if (existing) return existing;
13541
+ const client = new KustoClient({
13542
+ clusterUri,
13543
+ ...state.kustoDatabase ? { database: state.kustoDatabase } : {}
13544
+ });
13545
+ clients.set(clusterUri, client);
13546
+ return client;
12728
13547
  }
12729
13548
  /**
12730
- * Route a unified code-search request. Throws only on input/workspace
12731
- * validation failure (propagated from `searchCode`); callers wrap in
12732
- * try/catch exactly as they do today for `searchCode`.
13549
+ * MCP result envelope for one tool answer, relay-safe.
12733
13550
  *
12734
- * Under `--bluebird` (initialized client present), `semantic` (the
12735
- * default) and `lexical` route through Bluebird; `exact|regex|ast` stay
12736
- * local. Bluebird failures return `source:"error"` with the cause in
12737
- * `notice` — never a silent local fallback.
13551
+ * A grid rendered to the row/character cap, and a large schema, both exceed
13552
+ * the relay ceiling Claude Code applies to an MCP result. `relaySafeText` is
13553
+ * therefore the LAST transform: over the cap the full text is written to a
13554
+ * file and the model gets a bounded preview plus that path, instead of a
13555
+ * result the client silently clips. It sits here rather than in the Kusto
13556
+ * client because the client's own cap bounds RENDERING work, and its trailer
13557
+ * says so, while this one bounds what the model is asked to read.
12738
13558
  */
12739
- async function runUnifiedCodeSearch(input, signal) {
12740
- const mode = input.mode ?? "semantic";
12741
- if (state.bluebirdEnabled === true && (mode === "semantic" || mode === "lexical")) return runBluebird(input, mode, signal);
12742
- if (mode !== "semantic") return runLexical(input, mode, "lexical", signal);
12743
- if (!colbertSearchEnabled()) {
12744
- const r = await runLexical(input, "lexical", "lexical-fallback", signal);
12745
- return {
12746
- ...r,
12747
- notice: joinNotice(r.notice, "semantic search is off (launch with --search to enable); returned lexical results")
12748
- };
12749
- }
12750
- if (serviceBackendEnabled()) try {
12751
- const svc = await runServiceSearch({
12752
- query: input.query,
12753
- workspace: input.workspace,
12754
- limit: input.limit,
12755
- signal
12756
- });
12757
- if (svc.status === "ready") {
12758
- const results = (svc.results ?? []).map((r) => ({
12759
- file: r.file,
12760
- line: r.line,
12761
- snippet: r.snippet,
12762
- ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
12763
- ...r.name !== void 0 ? { name: r.name } : {},
12764
- ...r.score !== void 0 ? { score: r.score } : {}
12765
- }));
12766
- return {
12767
- source: "semantic",
12768
- results,
12769
- outlines: await outlinesForSemanticResults(input, results, signal),
12770
- ...svc.freshness ? { freshness: svc.freshness } : {},
12771
- ...svc.stale_files !== void 0 ? { stale_files: svc.stale_files } : {}
12772
- };
13559
+ async function text(value) {
13560
+ return { content: [{
13561
+ type: "text",
13562
+ text: await relaySafeText(value)
13563
+ }] };
13564
+ }
13565
+ /** Optional `database`, present in the schema only as a free string. */
13566
+ function databaseArg(args) {
13567
+ const value = args.database;
13568
+ if (value === void 0) return {};
13569
+ if (typeof value !== "string" || !value.trim()) throw new KustoError("`database` must be a non-empty string when provided.", { retriable: false });
13570
+ return { database: value };
13571
+ }
13572
+ const DATABASE_PROPERTY = { database: {
13573
+ type: "string",
13574
+ description: "Database to run against. Defaults to the launch's --kusto-database, and is required when that was not set."
13575
+ } };
13576
+ /**
13577
+ * The outer scope, so it precedes `database` in every tool that takes both:
13578
+ * a table name means nothing without the cluster it lives in. Any cluster the
13579
+ * current Azure identity can read may be named here, so a question that spans
13580
+ * two clusters is answered by two calls with different `cluster` values.
13581
+ */
13582
+ const CLUSTER_PROPERTY = { cluster: {
13583
+ type: "string",
13584
+ description: "Kusto cluster to query, e.g. https://example.kusto.windows.net. Defaults to the launch's --kusto-cluster, and is required when that was not set."
13585
+ } };
13586
+ const READ_ONLY_NOTE = " Read-only: the request runs under service-enforced read-only mode, so a mutating command is refused by Kusto rather than by this proxy.";
13587
+ const KUSTO_TOOLS = Object.freeze([
13588
+ {
13589
+ toolNameHttp: "databases",
13590
+ group: KUSTO_GROUP,
13591
+ capability: "kusto",
13592
+ description: "List the Kusto databases the current Azure identity can see in one cluster. Call this first when you do not know which database to query, or before reporting that a database does not exist. This proxy cannot list clusters, so when the cluster is not already known, ask the user which one to query." + READ_ONLY_NOTE,
13593
+ inputSchema: {
13594
+ type: "object",
13595
+ additionalProperties: false,
13596
+ properties: { ...CLUSTER_PROPERTY }
13597
+ },
13598
+ async handler(args, signal) {
13599
+ return text(await kustoClient(resolveCluster(args)).databasesList(signal));
13600
+ }
13601
+ },
13602
+ {
13603
+ toolNameHttp: "tables",
13604
+ group: KUSTO_GROUP,
13605
+ capability: "kusto",
13606
+ description: "List the tables and stored functions in a Kusto database. Use it to find the entity to query or to enumerate a schema you do not know." + READ_ONLY_NOTE,
13607
+ inputSchema: {
13608
+ type: "object",
13609
+ additionalProperties: false,
13610
+ properties: {
13611
+ ...CLUSTER_PROPERTY,
13612
+ ...DATABASE_PROPERTY
13613
+ }
13614
+ },
13615
+ async handler(args, signal) {
13616
+ const cluster = resolveCluster(args);
13617
+ const { database } = databaseArg(args);
13618
+ return text(await kustoClient(cluster).tablesList(database, signal));
13619
+ }
13620
+ },
13621
+ {
13622
+ toolNameHttp: "schema",
13623
+ group: KUSTO_GROUP,
13624
+ capability: "kusto",
13625
+ description: "Column names and types for one Kusto table or function. Use it before writing a query so the column names and types are real rather than guessed." + READ_ONLY_NOTE,
13626
+ inputSchema: {
13627
+ type: "object",
13628
+ required: ["table"],
13629
+ additionalProperties: false,
13630
+ properties: {
13631
+ table: {
13632
+ type: "string",
13633
+ description: "Table or function name (a simple identifier)."
13634
+ },
13635
+ ...CLUSTER_PROPERTY,
13636
+ ...DATABASE_PROPERTY
13637
+ }
13638
+ },
13639
+ async handler(args, signal) {
13640
+ const cluster = resolveCluster(args);
13641
+ const { database } = databaseArg(args);
13642
+ return text(await kustoClient(cluster).tableSchema(String(args.table ?? ""), database, signal));
13643
+ }
13644
+ },
13645
+ {
13646
+ toolNameHttp: "sample",
13647
+ group: KUSTO_GROUP,
13648
+ capability: "kusto",
13649
+ description: "The first N rows of a Kusto table, rendered as a grid. Use it to learn the shape and flavour of the data before writing a real query, so an aggregation is built against values that exist." + READ_ONLY_NOTE,
13650
+ inputSchema: {
13651
+ type: "object",
13652
+ required: ["table"],
13653
+ additionalProperties: false,
13654
+ properties: {
13655
+ table: {
13656
+ type: "string",
13657
+ description: "Table name (a simple identifier)."
13658
+ },
13659
+ rows: {
13660
+ type: "number",
13661
+ description: "How many rows to return, 1-100. Default 10."
13662
+ },
13663
+ ...CLUSTER_PROPERTY,
13664
+ ...DATABASE_PROPERTY
13665
+ }
13666
+ },
13667
+ async handler(args, signal) {
13668
+ const cluster = resolveCluster(args);
13669
+ const { database } = databaseArg(args);
13670
+ const rows = typeof args.rows === "number" ? args.rows : 10;
13671
+ return text(await kustoClient(cluster).sample(String(args.table ?? ""), rows, database, signal));
13672
+ }
13673
+ },
13674
+ {
13675
+ toolNameHttp: "query",
13676
+ group: KUSTO_GROUP,
13677
+ capability: "kusto",
13678
+ description: "Run KQL against a Kusto database and get a rendered grid back. The result is capped by row count and rendered size, with an explicit truncation trailer, so a broad query returns a bounded answer rather than an error." + READ_ONLY_NOTE,
13679
+ inputSchema: {
13680
+ type: "object",
13681
+ required: ["csl"],
13682
+ additionalProperties: false,
13683
+ properties: {
13684
+ csl: {
13685
+ type: "string",
13686
+ description: "The KQL to run. A leading '.' makes it a management command (e.g. `.show tables`); everything else is a query."
13687
+ },
13688
+ ...CLUSTER_PROPERTY,
13689
+ ...DATABASE_PROPERTY
13690
+ }
13691
+ },
13692
+ async handler(args, signal) {
13693
+ const cluster = resolveCluster(args);
13694
+ const { database } = databaseArg(args);
13695
+ const csl = typeof args.csl === "string" ? args.csl : "";
13696
+ if (!csl.trim()) throw new KustoError("`csl` must be a non-empty KQL query.", { retriable: false });
13697
+ return text(renderKustoResponse(await kustoClient(cluster).runCsl(csl, {
13698
+ ...database ? { database } : {},
13699
+ ...signal ? { signal } : {}
13700
+ })));
12773
13701
  }
12774
- } catch {}
12775
- let sem;
12776
- try {
12777
- sem = await runSemanticSearch({
12778
- query: input.query,
12779
- workspace: input.workspace,
12780
- limit: input.limit,
12781
- pattern: input.pattern,
12782
- signal,
12783
- serveStale: true
12784
- });
12785
- } catch {
12786
- const r = await runLexical(input, "lexical", "lexical-fallback", signal);
12787
- return {
12788
- ...r,
12789
- notice: joinNotice(r.notice, "semantic search errored; returned lexical results")
12790
- };
12791
- }
12792
- if (sem.status === "ready") {
12793
- const results = (sem.results ?? []).map((r) => ({
12794
- file: r.file,
12795
- line: r.line,
12796
- snippet: r.snippet,
12797
- ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
12798
- ...r.name !== void 0 ? { name: r.name } : {},
12799
- ...r.score !== void 0 ? { score: r.score } : {}
12800
- }));
12801
- return {
12802
- source: "semantic",
12803
- results,
12804
- outlines: await outlinesForSemanticResults(input, results, signal),
12805
- ...sem.notice ? { notice: sem.notice } : {},
12806
- ...sem.freshness ? { freshness: sem.freshness } : {},
12807
- ...sem.stale_files !== void 0 ? { stale_files: sem.stale_files } : {}
12808
- };
12809
13702
  }
12810
- const r = await runLexical(input, "lexical", "lexical-fallback", signal);
12811
- return {
12812
- ...r,
12813
- notice: joinNotice(r.notice, semanticFallbackNotice(sem))
12814
- };
12815
- }
13703
+ ]);
12816
13704
  //#endregion
12817
13705
  //#region src/lib/browser-mcp/browser-detect.ts
12818
13706
  let cached;
@@ -14270,7 +15158,7 @@ function logAudit$1(record) {
14270
15158
  try {
14271
15159
  const fs = await import("node:fs/promises");
14272
15160
  const path = await import("node:path");
14273
- const { PATHS } = await import("./paths-Dfivvq21.js");
15161
+ const { PATHS } = await import("./paths-C9x5U3dO.js");
14274
15162
  const dir = path.join(PATHS.APP_DIR, "browser-mcp");
14275
15163
  await fs.mkdir(dir, { recursive: true });
14276
15164
  const line = JSON.stringify({
@@ -18139,6 +19027,125 @@ buildProviderErrorPattern([
18139
19027
  "ResourceExhausted"
18140
19028
  ]);
18141
19029
  //#endregion
19030
+ //#region src/vendor/pi/ai/utils/text.ts
19031
+ /** Extract and join text from message content. */
19032
+ function contentText(content, separator = "\n") {
19033
+ if (typeof content === "string") return content;
19034
+ return content.filter((block) => block.type === "text").map((block) => block.text).join(separator);
19035
+ }
19036
+ /** Render a system message as a complete prompt: its content followed by its sections. */
19037
+ function getSystemMessageText(message) {
19038
+ const parts = [contentText(message.content)];
19039
+ for (const text of Object.values(message.sections ?? {})) if (text !== null) parts.push(text);
19040
+ return parts.filter((part) => part.length > 0).join("\n\n");
19041
+ }
19042
+ //#endregion
19043
+ //#region src/vendor/pi/ai/utils/transcript.ts
19044
+ /**
19045
+ * Build the leading system message for a prompt and tool set. Returns undefined when
19046
+ * both are empty, so an empty transcript stays empty.
19047
+ */
19048
+ function createInitialSystemMessage(systemPrompt, tools) {
19049
+ const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;
19050
+ const hasTools = tools !== void 0 && tools.length > 0;
19051
+ if (!hasSystemPrompt && !hasTools) return void 0;
19052
+ return {
19053
+ role: "system",
19054
+ content: systemPrompt ?? "",
19055
+ ...hasTools ? { toolsAdded: tools } : {},
19056
+ timestamp: 0
19057
+ };
19058
+ }
19059
+ /**
19060
+ * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.
19061
+ * This is the only entry point that produces a {@link TranscriptContext}; every
19062
+ * provider-facing function expects the result.
19063
+ */
19064
+ function normalizeContext(context) {
19065
+ const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
19066
+ return { messages: initialMessage ? [initialMessage, ...context.messages] : context.messages };
19067
+ }
19068
+ function isSystemMessage$1(message) {
19069
+ return message.role === "system";
19070
+ }
19071
+ /** Resolve the tools available after applying every transcript delta in order. */
19072
+ function getCurrentTools(messages) {
19073
+ const tools = /* @__PURE__ */ new Map();
19074
+ for (const message of messages) {
19075
+ if (!isSystemMessage$1(message)) continue;
19076
+ for (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);
19077
+ for (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);
19078
+ }
19079
+ return [...tools.values()];
19080
+ }
19081
+ /**
19082
+ * Replay every system message into one leading system message holding the current
19083
+ * prompt and tools. Later `content` is appended to the base prompt, `sections` are
19084
+ * patched by name, and tools are resolved with {@link getCurrentTools}.
19085
+ */
19086
+ function getCurrentSystemMessage(messages) {
19087
+ const content = [];
19088
+ const sections = /* @__PURE__ */ new Map();
19089
+ let timestamp;
19090
+ for (const message of messages) {
19091
+ if (!isSystemMessage$1(message)) continue;
19092
+ timestamp ??= message.timestamp;
19093
+ const text = contentText(message.content);
19094
+ if (text.length > 0) content.push(text);
19095
+ for (const [name, value] of Object.entries(message.sections ?? {})) if (value === null) sections.delete(name);
19096
+ else sections.set(name, value);
19097
+ }
19098
+ const tools = getCurrentTools(messages);
19099
+ if (timestamp === void 0 && tools.length === 0) return void 0;
19100
+ return {
19101
+ role: "system",
19102
+ content: content.join("\n\n"),
19103
+ ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {},
19104
+ ...tools.length > 0 ? { toolsAdded: tools } : {},
19105
+ timestamp: timestamp ?? 0
19106
+ };
19107
+ }
19108
+ /** Render the current system prompt text after replaying every system message. */
19109
+ function getCurrentSystemPrompt(messages) {
19110
+ const message = getCurrentSystemMessage(messages);
19111
+ return message ? getSystemMessageText(message) : "";
19112
+ }
19113
+ /** Strip executable and display-only fields from a tool before transcript comparison or persistence. */
19114
+ function toToolDeclaration(tool) {
19115
+ return {
19116
+ name: tool.name,
19117
+ description: tool.description,
19118
+ parameters: JSON.parse(JSON.stringify(tool.parameters)),
19119
+ ...tool.constrainedSampling === void 0 ? {} : { constrainedSampling: tool.constrainedSampling }
19120
+ };
19121
+ }
19122
+ /**
19123
+ * Whether two tools declare the same interface to the model.
19124
+ *
19125
+ * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the
19126
+ * typebox symbol keys and `undefined` fields that a structural comparison would see, and
19127
+ * builds both objects with the same key order, so comparing the serialized declarations
19128
+ * is exact. This avoids a deep-equal dependency in a browser-safe package.
19129
+ */
19130
+ function declarationsEqual(left, right) {
19131
+ return JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));
19132
+ }
19133
+ /** Compare two complete tool states. A changed definition is a removal followed by an addition. */
19134
+ function getToolStateChanges(previous, current) {
19135
+ const previousTools = new Map(previous.map((tool) => [tool.name, tool]));
19136
+ const currentTools = new Map(current.map((tool) => [tool.name, tool]));
19137
+ return {
19138
+ toolsAdded: current.filter((tool) => {
19139
+ const previousTool = previousTools.get(tool.name);
19140
+ return previousTool === void 0 || !declarationsEqual(previousTool, tool);
19141
+ }).map(toToolDeclaration),
19142
+ toolsRemoved: previous.filter((tool) => {
19143
+ const currentTool = currentTools.get(tool.name);
19144
+ return currentTool === void 0 || !declarationsEqual(tool, currentTool);
19145
+ }).map((tool) => ({ name: tool.name }))
19146
+ };
19147
+ }
19148
+ //#endregion
18142
19149
  //#region src/vendor/pi/ai/utils/validation.ts
18143
19150
  const validatorCache = /* @__PURE__ */ new WeakMap();
18144
19151
  const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
@@ -18284,10 +19291,12 @@ function validateToolArguments(tool, toolCall) {
18284
19291
  const validator = getValidator(tool.parameters);
18285
19292
  if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {
18286
19293
  const coerced = coerceWithJsonSchema(args, tool.parameters);
18287
- if (coerced !== args) if (typeof args === "object" && args !== null && typeof coerced === "object" && coerced !== null) {
18288
- for (const key of Object.keys(args)) delete args[key];
18289
- Object.assign(args, coerced);
18290
- } else return validator.Check(coerced) ? coerced : args;
19294
+ if (coerced !== args) {
19295
+ if (typeof args === "object" && args !== null && typeof coerced === "object" && coerced !== null) {
19296
+ for (const key of Object.keys(args)) delete args[key];
19297
+ Object.assign(args, coerced);
19298
+ } else return validator.Check(coerced) ? coerced : args;
19299
+ }
18291
19300
  }
18292
19301
  if (validator.Check(args)) return args;
18293
19302
  const errors = validator.Errors(args).map((error) => ` - ${formatValidationPath(error)}: ${error.message}`).join("\n") || "Unknown validation error";
@@ -18304,21 +19313,22 @@ function getDefaultStreamFn() {
18304
19313
  * Transforms to Message[] only at the LLM call boundary.
18305
19314
  */
18306
19315
  async function runAgentLoop(prompts, context, config, emit, signal, streamFn) {
18307
- const newMessages = [...prompts];
19316
+ const initialMessages = declareToolChanges(context, prompts);
19317
+ const newMessages = [...initialMessages];
18308
19318
  const currentContext = {
18309
19319
  ...context,
18310
- messages: [...context.messages, ...prompts]
19320
+ messages: [...context.messages, ...initialMessages]
18311
19321
  };
18312
19322
  await emit({ type: "agent_start" });
18313
19323
  await emit({ type: "turn_start" });
18314
- for (const prompt of prompts) {
19324
+ for (const message of initialMessages) {
18315
19325
  await emit({
18316
19326
  type: "message_start",
18317
- message: prompt
19327
+ message
18318
19328
  });
18319
19329
  await emit({
18320
19330
  type: "message_end",
18321
- message: prompt
19331
+ message
18322
19332
  });
18323
19333
  }
18324
19334
  await runLoop(currentContext, newMessages, config, signal, emit, streamFn ?? getDefaultStreamFn());
@@ -18340,31 +19350,63 @@ async function runAgentLoopContinue(context, config, emit, signal, streamFn) {
18340
19350
  async function runLoop(initialContext, newMessages, initialConfig, signal, emit, streamFunction) {
18341
19351
  let currentContext = initialContext;
18342
19352
  let config = initialConfig;
18343
- let firstTurn = true;
19353
+ let lastCompletedTurn;
19354
+ let explicitContinuation = false;
18344
19355
  let pendingMessages = await config.getSteeringMessages?.() || [];
18345
19356
  while (true) {
18346
19357
  let hasMoreToolCalls = true;
18347
19358
  while (hasMoreToolCalls || pendingMessages.length > 0) {
18348
- if (!firstTurn) await emit({ type: "turn_start" });
18349
- else firstTurn = false;
18350
- if (pendingMessages.length > 0) {
18351
- for (const message of pendingMessages) {
18352
- await emit({
18353
- type: "message_start",
18354
- message
18355
- });
18356
- await emit({
18357
- type: "message_end",
18358
- message
18359
- });
18360
- currentContext.messages.push(message);
18361
- newMessages.push(message);
19359
+ let preparedMessages = [];
19360
+ if (lastCompletedTurn) {
19361
+ const nextTurnSnapshot = await config.prepareNextTurn?.(lastCompletedTurn);
19362
+ if (nextTurnSnapshot) {
19363
+ currentContext = nextTurnSnapshot.context ?? currentContext;
19364
+ preparedMessages = nextTurnSnapshot.messages ?? [];
19365
+ config = {
19366
+ ...config,
19367
+ model: nextTurnSnapshot.model ?? config.model,
19368
+ reasoning: nextTurnSnapshot.thinkingLevel === void 0 ? config.reasoning : nextTurnSnapshot.thinkingLevel === "off" ? void 0 : nextTurnSnapshot.thinkingLevel
19369
+ };
18362
19370
  }
18363
- pendingMessages = [];
19371
+ if (pendingMessages.length === 0) pendingMessages = await config.getSteeringMessages?.() || [];
19372
+ await emit({ type: "turn_start" });
19373
+ }
19374
+ for (const message of declareToolChanges(currentContext, [...preparedMessages, ...pendingMessages])) {
19375
+ await emit({
19376
+ type: "message_start",
19377
+ message
19378
+ });
19379
+ await emit({
19380
+ type: "message_end",
19381
+ message
19382
+ });
19383
+ currentContext.messages.push(message);
19384
+ newMessages.push(message);
19385
+ }
19386
+ pendingMessages = [];
19387
+ const requestUpdate = await config.prepareRequest?.({
19388
+ context: currentContext,
19389
+ model: config.model,
19390
+ thinkingLevel: config.reasoning ?? "off"
19391
+ }, signal);
19392
+ if (requestUpdate) {
19393
+ currentContext = requestUpdate.context ?? currentContext;
19394
+ config = {
19395
+ ...config,
19396
+ model: requestUpdate.model ?? config.model,
19397
+ reasoning: requestUpdate.thinkingLevel === void 0 ? config.reasoning : requestUpdate.thinkingLevel === "off" ? void 0 : requestUpdate.thinkingLevel
19398
+ };
18364
19399
  }
18365
19400
  const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFunction);
18366
19401
  newMessages.push(message);
18367
19402
  if (message.stopReason === "error" || message.stopReason === "aborted") {
19403
+ lastCompletedTurn = {
19404
+ message,
19405
+ toolResults: [],
19406
+ context: currentContext,
19407
+ newMessages
19408
+ };
19409
+ await config.finishTurn?.(lastCompletedTurn, signal);
18368
19410
  await emit({
18369
19411
  type: "turn_end",
18370
19412
  message,
@@ -18388,45 +19430,39 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
18388
19430
  newMessages.push(result);
18389
19431
  }
18390
19432
  }
18391
- await emit({
18392
- type: "turn_end",
18393
- message,
18394
- toolResults
18395
- });
18396
- const nextTurnContext = {
19433
+ lastCompletedTurn = {
18397
19434
  message,
18398
19435
  toolResults,
18399
19436
  context: currentContext,
18400
19437
  newMessages
18401
19438
  };
18402
- const nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);
18403
- if (nextTurnSnapshot) {
18404
- currentContext = nextTurnSnapshot.context ?? currentContext;
18405
- config = {
18406
- ...config,
18407
- model: nextTurnSnapshot.model ?? config.model,
18408
- reasoning: nextTurnSnapshot.thinkingLevel === void 0 ? config.reasoning : nextTurnSnapshot.thinkingLevel === "off" ? void 0 : nextTurnSnapshot.thinkingLevel
18409
- };
18410
- }
18411
- if (await config.shouldStopAfterTurn?.({
19439
+ const decision = await config.finishTurn?.(lastCompletedTurn, signal);
19440
+ await emit({
19441
+ type: "turn_end",
18412
19442
  message,
18413
- toolResults,
18414
- context: currentContext,
18415
- newMessages
18416
- })) {
19443
+ toolResults
19444
+ });
19445
+ if (decision?.action === "end") {
18417
19446
  await emit({
18418
19447
  type: "agent_end",
18419
19448
  messages: newMessages
18420
19449
  });
18421
19450
  return;
18422
19451
  }
19452
+ explicitContinuation = decision?.action === "continue";
18423
19453
  pendingMessages = await config.getSteeringMessages?.() || [];
19454
+ if (hasMoreToolCalls || pendingMessages.length > 0) explicitContinuation = false;
18424
19455
  }
18425
19456
  const followUpMessages = await config.getFollowUpMessages?.() || [];
18426
19457
  if (followUpMessages.length > 0) {
19458
+ explicitContinuation = false;
18427
19459
  pendingMessages = followUpMessages;
18428
19460
  continue;
18429
19461
  }
19462
+ if (explicitContinuation) {
19463
+ explicitContinuation = false;
19464
+ continue;
19465
+ }
18430
19466
  break;
18431
19467
  }
18432
19468
  await emit({
@@ -18435,24 +19471,71 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
18435
19471
  });
18436
19472
  }
18437
19473
  /**
19474
+ * Declare tool loadout changes to the model.
19475
+ *
19476
+ * `context.tools` is what the runtime can execute; the transcript's system messages declare
19477
+ * what the model may call. Before each request the difference becomes `toolsAdded` and
19478
+ * `toolsRemoved` on a system message. When a pending system message exists, its tool fields
19479
+ * are treated as intent and replaced with the delta between the committed transcript and
19480
+ * the executable set, so replay always yields exactly `context.tools`. Otherwise a new
19481
+ * system message is inserted before the first non-system pending message.
19482
+ */
19483
+ function declareToolChanges(context, pendingMessages) {
19484
+ let systemIndex = -1;
19485
+ for (let i = pendingMessages.length - 1; i >= 0; i--) if (pendingMessages[i].role === "system") {
19486
+ systemIndex = i;
19487
+ break;
19488
+ }
19489
+ const pending = pendingMessages[systemIndex];
19490
+ const baseline = pending ? pendingMessages.map((message, index) => index === systemIndex ? withToolChanges(pending, NO_CHANGES) : message) : pendingMessages;
19491
+ const changes = getToolStateChanges(getCurrentTools([...context.messages, ...baseline]), (context.tools ?? []).map(toToolDeclaration));
19492
+ const unchanged = changes.toolsAdded.length === 0 && changes.toolsRemoved.length === 0;
19493
+ if (pending) {
19494
+ if (unchanged && !pending.toolsAdded?.length && !pending.toolsRemoved?.length) return pendingMessages;
19495
+ return baseline.map((message, index) => index === systemIndex ? withToolChanges(pending, changes) : message);
19496
+ }
19497
+ if (unchanged) return pendingMessages;
19498
+ const update = withToolChanges({
19499
+ role: "system",
19500
+ content: "",
19501
+ timestamp: Date.now()
19502
+ }, changes);
19503
+ const insertIndex = pendingMessages.findIndex((message) => message.role !== "system");
19504
+ const index = insertIndex === -1 ? pendingMessages.length : insertIndex;
19505
+ return [
19506
+ ...pendingMessages.slice(0, index),
19507
+ update,
19508
+ ...pendingMessages.slice(index)
19509
+ ];
19510
+ }
19511
+ const NO_CHANGES = {
19512
+ toolsAdded: [],
19513
+ toolsRemoved: []
19514
+ };
19515
+ /** Copy a system message with its tool fields replaced by `changes`; empty lists omit the field. */
19516
+ function withToolChanges(message, { toolsAdded, toolsRemoved }) {
19517
+ const { toolsAdded: _added, toolsRemoved: _removed, ...rest } = message;
19518
+ return {
19519
+ ...rest,
19520
+ ...toolsAdded.length > 0 ? { toolsAdded } : {},
19521
+ ...toolsRemoved.length > 0 ? { toolsRemoved } : {}
19522
+ };
19523
+ }
19524
+ /**
18438
19525
  * Stream an assistant response from the LLM.
18439
19526
  * This is where AgentMessage[] gets transformed to Message[] for the LLM.
18440
19527
  */
18441
19528
  async function streamAssistantResponse(context, config, signal, emit, streamFunction) {
18442
19529
  let messages = context.messages;
18443
19530
  if (config.transformContext) messages = await config.transformContext(messages, signal);
18444
- const llmMessages = await config.convertToLlm(messages);
18445
- const llmContext = {
18446
- systemPrompt: context.systemPrompt,
18447
- messages: llmMessages,
18448
- tools: context.tools
18449
- };
19531
+ const llmContext = normalizeContext({ messages: await config.convertToLlm(messages) });
18450
19532
  const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : void 0) || config.apiKey;
18451
19533
  const response = await streamFunction(config.model, llmContext, {
18452
19534
  ...config,
18453
19535
  apiKey: resolvedApiKey,
18454
19536
  signal
18455
19537
  });
19538
+ const result = async () => Object.assign(await response.result(), { thinkingLevel: config.reasoning ?? "off" });
18456
19539
  let partialMessage = null;
18457
19540
  let addedPartial = false;
18458
19541
  for await (const event of response) switch (event.type) {
@@ -18486,7 +19569,7 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc
18486
19569
  break;
18487
19570
  case "done":
18488
19571
  case "error": {
18489
- const finalMessage = await response.result();
19572
+ const finalMessage = await result();
18490
19573
  if (addedPartial) context.messages[context.messages.length - 1] = finalMessage;
18491
19574
  else context.messages.push(finalMessage);
18492
19575
  if (!addedPartial) await emit({
@@ -18500,7 +19583,7 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc
18500
19583
  return finalMessage;
18501
19584
  }
18502
19585
  }
18503
- const finalMessage = await response.result();
19586
+ const finalMessage = await result();
18504
19587
  if (addedPartial) context.messages[context.messages.length - 1] = finalMessage;
18505
19588
  else {
18506
19589
  context.messages.push(finalMessage);
@@ -18572,7 +19655,7 @@ async function executeToolCallsSequential(currentContext, assistantMessage, tool
18572
19655
  result: preparation.result,
18573
19656
  isError: preparation.isError
18574
19657
  };
18575
- else finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, await executePreparedToolCall(preparation, signal, emit), config, signal);
19658
+ else finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit)), config, signal);
18576
19659
  await emitToolExecutionEnd(finalized, emit);
18577
19660
  const toolResultMessage = createToolResultMessage(finalized);
18578
19661
  await emitToolResultMessage(toolResultMessage, emit);
@@ -18607,7 +19690,16 @@ async function executeToolCallsParallel(currentContext, assistantMessage, toolCa
18607
19690
  continue;
18608
19691
  }
18609
19692
  finalizedCalls.push(async () => {
18610
- const executed = await executePreparedToolCall(preparation, signal, emit);
19693
+ if (signal?.aborted) {
19694
+ const finalized = {
19695
+ toolCall,
19696
+ result: createErrorToolResult("Operation aborted"),
19697
+ isError: true
19698
+ };
19699
+ await emitToolExecutionEnd(finalized, emit);
19700
+ return finalized;
19701
+ }
19702
+ const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
18611
19703
  const finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
18612
19704
  await emitToolExecutionEnd(finalized, emit);
18613
19705
  return finalized;
@@ -18638,8 +19730,8 @@ function prepareToolCallArguments(tool, toolCall) {
18638
19730
  arguments: preparedArguments
18639
19731
  };
18640
19732
  }
18641
- async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal) {
18642
- const tool = currentContext.tools?.find((t) => t.name === toolCall.name);
19733
+ async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal, tools = currentContext.tools ?? []) {
19734
+ const tool = tools.find((t) => t.name === toolCall.name);
18643
19735
  if (!tool) return {
18644
19736
  kind: "immediate",
18645
19737
  result: createErrorToolResult(`Tool ${toolCall.name} not found`),
@@ -18659,11 +19751,15 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
18659
19751
  result: createErrorToolResult("Operation aborted"),
18660
19752
  isError: true
18661
19753
  };
18662
- if (beforeResult?.block) return {
18663
- kind: "immediate",
18664
- result: createErrorToolResult(beforeResult.reason || "Tool execution was blocked"),
18665
- isError: true
18666
- };
19754
+ if (beforeResult?.block) {
19755
+ const result = createErrorToolResult(beforeResult.reason || "Tool execution was blocked");
19756
+ if (beforeResult.terminate === true) result.terminate = true;
19757
+ return {
19758
+ kind: "immediate",
19759
+ result,
19760
+ isError: true
19761
+ };
19762
+ }
18667
19763
  }
18668
19764
  if (signal?.aborted) return {
18669
19765
  kind: "immediate",
@@ -18684,32 +19780,41 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
18684
19780
  };
18685
19781
  }
18686
19782
  }
18687
- async function executePreparedToolCall(prepared, signal, emit) {
19783
+ function emitToolExecutionUpdate(toolCall, emit) {
19784
+ return (partialResult) => emit({
19785
+ type: "tool_execution_update",
19786
+ toolCallId: toolCall.id,
19787
+ toolName: toolCall.name,
19788
+ args: toolCall.arguments,
19789
+ partialResult
19790
+ });
19791
+ }
19792
+ async function executePreparedToolCall(prepared, signal, onUpdate) {
18688
19793
  const updateEvents = [];
18689
19794
  let acceptingUpdates = true;
19795
+ const startedAt = performance.now();
19796
+ const elapsed = () => Math.round(performance.now() - startedAt);
18690
19797
  try {
18691
19798
  const result = await prepared.tool.execute(prepared.toolCall.id, prepared.args, signal, (partialResult) => {
18692
19799
  if (!acceptingUpdates) return;
18693
- updateEvents.push(Promise.resolve(emit({
18694
- type: "tool_execution_update",
18695
- toolCallId: prepared.toolCall.id,
18696
- toolName: prepared.toolCall.name,
18697
- args: prepared.toolCall.arguments,
18698
- partialResult
18699
- })));
19800
+ updateEvents.push(Promise.resolve(onUpdate(partialResult)));
18700
19801
  });
19802
+ const durationMs = elapsed();
18701
19803
  acceptingUpdates = false;
18702
19804
  await Promise.all(updateEvents);
18703
19805
  return {
18704
19806
  result,
18705
- isError: false
19807
+ isError: result.isError === true,
19808
+ durationMs
18706
19809
  };
18707
19810
  } catch (error) {
19811
+ const durationMs = elapsed();
18708
19812
  acceptingUpdates = false;
18709
19813
  await Promise.all(updateEvents);
18710
19814
  return {
18711
19815
  result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
18712
- isError: true
19816
+ isError: true,
19817
+ durationMs
18713
19818
  };
18714
19819
  } finally {
18715
19820
  acceptingUpdates = false;
@@ -18728,6 +19833,7 @@ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepar
18728
19833
  context: currentContext
18729
19834
  }, signal);
18730
19835
  if (afterResult) {
19836
+ const structuredContent = afterResult.structuredContent ?? (afterResult.content ? void 0 : result.structuredContent);
18731
19837
  result = {
18732
19838
  ...result,
18733
19839
  content: afterResult.content ?? result.content,
@@ -18735,6 +19841,8 @@ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepar
18735
19841
  usage: afterResult.usage ?? result.usage,
18736
19842
  terminate: afterResult.terminate ?? result.terminate
18737
19843
  };
19844
+ if (structuredContent === void 0) delete result.structuredContent;
19845
+ else result.structuredContent = structuredContent;
18738
19846
  isError = afterResult.isError ?? isError;
18739
19847
  }
18740
19848
  } catch (error) {
@@ -18744,7 +19852,8 @@ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepar
18744
19852
  return {
18745
19853
  toolCall: prepared.toolCall,
18746
19854
  result,
18747
- isError
19855
+ isError,
19856
+ durationMs: executed.durationMs
18748
19857
  };
18749
19858
  }
18750
19859
  function createErrorToolResult(message) {
@@ -18762,7 +19871,8 @@ async function emitToolExecutionEnd(finalized, emit) {
18762
19871
  toolCallId: finalized.toolCall.id,
18763
19872
  toolName: finalized.toolCall.name,
18764
19873
  result: finalized.result,
18765
- isError: finalized.isError
19874
+ isError: finalized.isError,
19875
+ ...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs }
18766
19876
  });
18767
19877
  }
18768
19878
  function createToolResultMessage(finalized) {
@@ -18773,8 +19883,8 @@ function createToolResultMessage(finalized) {
18773
19883
  content: finalized.result.content ?? [],
18774
19884
  details: finalized.result.details,
18775
19885
  usage: finalized.result.usage,
18776
- ...finalized.result.addedToolNames?.length ? { addedToolNames: finalized.result.addedToolNames } : {},
18777
19886
  isError: finalized.isError,
19887
+ ...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs },
18778
19888
  timestamp: Date.now()
18779
19889
  };
18780
19890
  }
@@ -18791,7 +19901,7 @@ async function emitToolResultMessage(toolResultMessage, emit) {
18791
19901
  //#endregion
18792
19902
  //#region src/vendor/pi/agent/agent.ts
18793
19903
  function defaultConvertToLlm(messages) {
18794
- return messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
19904
+ return messages.filter((message) => message.role === "system" || message.role === "user" || message.role === "assistant" || message.role === "toolResult");
18795
19905
  }
18796
19906
  const EMPTY_USAGE = {
18797
19907
  input: 0,
@@ -18827,8 +19937,12 @@ const DEFAULT_MODEL = {
18827
19937
  function createMutableAgentState(initialState) {
18828
19938
  let tools = initialState?.tools?.slice() ?? [];
18829
19939
  let messages = initialState?.messages?.slice() ?? [];
19940
+ const initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));
19941
+ if (messages[0]?.role !== "system" && initialMessage) messages.unshift(initialMessage);
18830
19942
  return {
18831
- systemPrompt: initialState?.systemPrompt ?? "",
19943
+ get systemPrompt() {
19944
+ return getCurrentSystemPrompt(messages);
19945
+ },
18832
19946
  model: initialState?.model ?? DEFAULT_MODEL,
18833
19947
  thinkingLevel: initialState?.thinkingLevel ?? "off",
18834
19948
  get tools() {
@@ -18861,16 +19975,15 @@ var PendingMessageQueue = class {
18861
19975
  hasItems() {
18862
19976
  return this.messages.length > 0;
18863
19977
  }
18864
- drain() {
18865
- if (this.mode === "all") {
18866
- const drained = this.messages.slice();
18867
- this.messages = [];
18868
- return drained;
18869
- }
19978
+ peek() {
19979
+ if (this.mode === "all") return this.messages.slice();
18870
19980
  const first = this.messages[0];
18871
- if (!first) return [];
18872
- this.messages = this.messages.slice(1);
18873
- return [first];
19981
+ return first ? [first] : [];
19982
+ }
19983
+ drain() {
19984
+ const drained = this.peek();
19985
+ this.messages = this.messages.slice(drained.length);
19986
+ return drained;
18874
19987
  }
18875
19988
  clear() {
18876
19989
  this.messages = [];
@@ -18893,9 +20006,11 @@ var Agent$1 = class {
18893
20006
  getApiKey;
18894
20007
  onPayload;
18895
20008
  onResponse;
20009
+ onProviderStreamEvent;
18896
20010
  beforeToolCall;
18897
20011
  afterToolCall;
18898
- shouldStopAfterTurn;
20012
+ finishTurn;
20013
+ prepareRequest;
18899
20014
  prepareNextTurn;
18900
20015
  prepareNextTurnWithContext;
18901
20016
  activeRun;
@@ -18918,9 +20033,11 @@ var Agent$1 = class {
18918
20033
  this.getApiKey = runtimeOptions.getApiKey;
18919
20034
  this.onPayload = runtimeOptions.onPayload;
18920
20035
  this.onResponse = runtimeOptions.onResponse;
20036
+ this.onProviderStreamEvent = runtimeOptions.onProviderStreamEvent;
18921
20037
  this.beforeToolCall = runtimeOptions.beforeToolCall;
18922
20038
  this.afterToolCall = runtimeOptions.afterToolCall;
18923
- this.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;
20039
+ this.finishTurn = runtimeOptions.finishTurn;
20040
+ this.prepareRequest = runtimeOptions.prepareRequest;
18924
20041
  this.prepareNextTurn = runtimeOptions.prepareNextTurn;
18925
20042
  this.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;
18926
20043
  this.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? "one-at-a-time");
@@ -18992,6 +20109,11 @@ var Agent$1 = class {
18992
20109
  hasQueuedMessages() {
18993
20110
  return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
18994
20111
  }
20112
+ /** Preview the messages selected for the next turn without consuming them. */
20113
+ peekQueuedMessages() {
20114
+ const steering = this.steeringQueue.peek();
20115
+ return steering.length > 0 ? steering : this.followUpQueue.peek();
20116
+ }
18995
20117
  /** Active abort signal for the current run, if any. */
18996
20118
  get signal() {
18997
20119
  return this.activeRun?.abortController.signal;
@@ -19008,9 +20130,11 @@ var Agent$1 = class {
19008
20130
  waitForIdle() {
19009
20131
  return this.activeRun?.promise ?? Promise.resolve();
19010
20132
  }
19011
- /** Clear transcript state, runtime state, and queued messages. */
20133
+ /** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */
19012
20134
  reset() {
19013
- this._state.messages = [];
20135
+ if (this.activeRun) throw new Error("Agent is already processing. Wait for completion before resetting.");
20136
+ const baseline = getCurrentSystemMessage(this._state.messages);
20137
+ this._state.messages = baseline ? [baseline] : [];
19014
20138
  this._state.isStreaming = false;
19015
20139
  this._state.streamingMessage = void 0;
19016
20140
  this._state.pendingToolCalls = /* @__PURE__ */ new Set();
@@ -19027,7 +20151,7 @@ var Agent$1 = class {
19027
20151
  async continue() {
19028
20152
  if (this.activeRun) throw new Error("Agent is already processing. Wait for completion before continuing.");
19029
20153
  const lastMessage = this._state.messages[this._state.messages.length - 1];
19030
- if (!lastMessage) throw new Error("No messages to continue from");
20154
+ if (!lastMessage || this._state.messages.every((message) => message.role === "system")) throw new Error("No messages to continue from");
19031
20155
  if (lastMessage.role === "assistant") {
19032
20156
  const queuedSteering = this.steeringQueue.drain();
19033
20157
  if (queuedSteering.length > 0) {
@@ -19069,7 +20193,6 @@ var Agent$1 = class {
19069
20193
  }
19070
20194
  createContextSnapshot() {
19071
20195
  return {
19072
- systemPrompt: this._state.systemPrompt,
19073
20196
  messages: this._state.messages.slice(),
19074
20197
  tools: this._state.tools.slice()
19075
20198
  };
@@ -19082,13 +20205,15 @@ var Agent$1 = class {
19082
20205
  sessionId: this.sessionId,
19083
20206
  onPayload: this.onPayload,
19084
20207
  onResponse: this.onResponse,
20208
+ onProviderStreamEvent: this.onProviderStreamEvent,
19085
20209
  transport: this.transport,
19086
20210
  thinkingBudgets: this.thinkingBudgets,
19087
20211
  maxRetryDelayMs: this.maxRetryDelayMs,
19088
20212
  toolExecution: this.toolExecution,
19089
20213
  beforeToolCall: this.beforeToolCall,
19090
20214
  afterToolCall: this.afterToolCall,
19091
- shouldStopAfterTurn: this.shouldStopAfterTurn,
20215
+ finishTurn: this.finishTurn,
20216
+ prepareRequest: this.prepareRequest,
19092
20217
  prepareNextTurn: this.prepareNextTurnWithContext || this.prepareNextTurn ? async (context) => {
19093
20218
  if (this.prepareNextTurnWithContext) return await this.prepareNextTurnWithContext(context, this.signal);
19094
20219
  return await this.prepareNextTurn?.(this.signal);
@@ -19210,30 +20335,6 @@ var Agent$1 = class {
19210
20335
  for (const listener of this.listeners) await listener(event, signal);
19211
20336
  }
19212
20337
  };
19213
- globalThis.Buffer;
19214
- Type.Object({
19215
- command: Type.String({ description: "Bash command to execute" }),
19216
- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" }))
19217
- });
19218
- //#endregion
19219
- //#region src/vendor/pi/agent/harness/tools/edit.ts
19220
- const replaceEditSchema = Type.Object({
19221
- oldText: Type.String({ description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call." }),
19222
- newText: Type.String({ description: "Replacement text for this targeted edit." })
19223
- }, {});
19224
- Type.Object({
19225
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
19226
- edits: Type.Array(replaceEditSchema, { description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead." })
19227
- }, {});
19228
- Type.Object({
19229
- path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
19230
- offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })),
19231
- limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" }))
19232
- });
19233
- Type.Object({
19234
- path: Type.String({ description: "Path to the file to write (relative or absolute)" }),
19235
- content: Type.String({ description: "Content to write to the file" })
19236
- });
19237
20338
  //#endregion
19238
20339
  //#region src/lib/worker-agent/budget.ts
19239
20340
  const DEFAULT_MAX_TURNS = 500;
@@ -20449,10 +21550,12 @@ async function runStreamLoop(stream, context, opts, options) {
20449
21550
  const { resolved } = opts;
20450
21551
  if (opts.contextBudget) {
20451
21552
  const assembledTokens = tokensFromBytes(estimateContextBytes(context));
20452
- if (assembledTokens > opts.contextBudget.inputHardLimitTokens) if (!opts.contextBudget.windowKnown) consola.warn(`[worker] assembled request estimate ${assembledTokens} tokens exceeds fallback input limit ${opts.contextBudget.inputHardLimitTokens}; proceeding because the catalog window is unknown`);
20453
- else {
20454
- pushBackstopDiagnostic(stream, resolved, assembledTokens, opts.contextBudget.inputHardLimitTokens);
20455
- return;
21553
+ if (assembledTokens > opts.contextBudget.inputHardLimitTokens) {
21554
+ if (!opts.contextBudget.windowKnown) consola.warn(`[worker] assembled request estimate ${assembledTokens} tokens exceeds fallback input limit ${opts.contextBudget.inputHardLimitTokens}; proceeding because the catalog window is unknown`);
21555
+ else {
21556
+ pushBackstopDiagnostic(stream, resolved, assembledTokens, opts.contextBudget.inputHardLimitTokens);
21557
+ return;
21558
+ }
20456
21559
  }
20457
21560
  }
20458
21561
  const resolution = resolveEndpointForModelId(resolved.modelId);
@@ -20631,12 +21734,13 @@ async function runChatAttempt(stream, payload, opts, signal, state) {
20631
21734
  }
20632
21735
  function buildPayload(context, resolved) {
20633
21736
  const messages = [];
20634
- if (context.systemPrompt) messages.push({
21737
+ const systemPrompt = getCurrentSystemPrompt(context.messages);
21738
+ if (systemPrompt) messages.push({
20635
21739
  role: "system",
20636
- content: context.systemPrompt
21740
+ content: systemPrompt
20637
21741
  });
20638
21742
  messages.push(...translateMessages(context.messages));
20639
- const tools = translateTools(context.tools);
21743
+ const tools = translateTools(getCurrentTools(context.messages));
20640
21744
  const payload = {
20641
21745
  model: resolved.modelId,
20642
21746
  messages,
@@ -20693,6 +21797,7 @@ function translateMessages(messages) {
20693
21797
  continue;
20694
21798
  }
20695
21799
  flushImages();
21800
+ if (m.role === "system") continue;
20696
21801
  if (m.role === "user") out.push(translateUser(m));
20697
21802
  else if (m.role === "assistant") out.push(translateAssistant(m));
20698
21803
  }
@@ -21060,9 +22165,9 @@ function buildResponsesPayload(context, resolved) {
21060
22165
  const messages = piMessagesToNeutral(context.messages);
21061
22166
  return assembleResponsesPayload({
21062
22167
  model: resolved.modelId,
21063
- instructions: context.systemPrompt || void 0,
22168
+ instructions: getCurrentSystemPrompt(context.messages) || void 0,
21064
22169
  messages,
21065
- tools: piToolsToNeutral(context.tools),
22170
+ tools: piToolsToNeutral(getCurrentTools(context.messages)),
21066
22171
  reasoningEffort: resolved.thinking,
21067
22172
  cachePolicy: { workload: "conversation" },
21068
22173
  stream: true
@@ -21104,27 +22209,28 @@ function piMessagesToNeutral(messages) {
21104
22209
  continue;
21105
22210
  }
21106
22211
  flushImages();
21107
- if (m.role === "user") if (typeof m.content === "string") out.push({
21108
- role: "user",
21109
- content: m.content
21110
- });
21111
- else {
21112
- const parts = [];
21113
- for (const c of m.content) if (c.type === "text") parts.push({
21114
- type: "text",
21115
- text: c.text
21116
- });
21117
- else if (c.type === "image") parts.push({
21118
- type: "image",
21119
- mimeType: c.mimeType,
21120
- data: c.data
21121
- });
21122
- out.push({
22212
+ if (m.role === "user") {
22213
+ if (typeof m.content === "string") out.push({
21123
22214
  role: "user",
21124
- content: parts
22215
+ content: m.content
21125
22216
  });
21126
- }
21127
- else if (m.role === "assistant") {
22217
+ else {
22218
+ const parts = [];
22219
+ for (const c of m.content) if (c.type === "text") parts.push({
22220
+ type: "text",
22221
+ text: c.text
22222
+ });
22223
+ else if (c.type === "image") parts.push({
22224
+ type: "image",
22225
+ mimeType: c.mimeType,
22226
+ data: c.data
22227
+ });
22228
+ out.push({
22229
+ role: "user",
22230
+ content: parts
22231
+ });
22232
+ }
22233
+ } else if (m.role === "assistant") {
21128
22234
  const parts = [];
21129
22235
  for (const c of m.content) if (c.type === "text") parts.push({
21130
22236
  type: "text",
@@ -21338,13 +22444,20 @@ function pushTerminalError(stream, resolved, err) {
21338
22444
  * parts by their bytes keeps it consistent with the compactor. Never throws.
21339
22445
  */
21340
22446
  function estimateContextBytes(context) {
21341
- let bytes = Buffer.byteLength(context.systemPrompt ?? "", "utf8");
22447
+ let bytes = Buffer.byteLength(getCurrentSystemPrompt(context.messages), "utf8");
21342
22448
  try {
21343
- bytes += Buffer.byteLength(JSON.stringify(context.tools ?? []), "utf8");
22449
+ bytes += Buffer.byteLength(JSON.stringify(getCurrentTools(context.messages)), "utf8");
21344
22450
  } catch {}
21345
- for (const m of context.messages ?? []) bytes += messageWireBytes(m);
22451
+ for (const m of context.messages ?? []) {
22452
+ if (isSystemMessage(m)) continue;
22453
+ bytes += messageWireBytes(m);
22454
+ }
21346
22455
  return bytes;
21347
22456
  }
22457
+ /** True for the transcript's `role: "system"` message(s), counted separately above. */
22458
+ function isSystemMessage(m) {
22459
+ return m !== null && typeof m === "object" && m.role === "system";
22460
+ }
21348
22461
  /** Bytes of one wire message: text content + per-image equivalent + bulk fields. */
21349
22462
  function messageWireBytes(m) {
21350
22463
  if (!m || typeof m !== "object") return 0;
@@ -21790,12 +22903,14 @@ function makeBrowserTool(meta, parameters, dispatch, sessionId) {
21790
22903
  parameters,
21791
22904
  async execute(_toolCallId, params, signal) {
21792
22905
  const args = argsRecord(params);
21793
- if (sessionId) if (policy === "uses") {
21794
- if (!Number.isInteger(args.tabId)) throw new Error(`${wireName}: a valid tabId is required in a browse session`);
21795
- assertSessionOwnsTab(sessionId, args.tabId);
21796
- } else if (policy === "opens") {
21797
- if (args.reuseActive === true) throw new Error("open_tab: reuseActive is disabled in a browse session (it would adopt a tab outside the session); open a fresh tab instead");
21798
- } else for (const tabId of toNumberArray(args.tabIds)) assertSessionOwnsTab(sessionId, tabId);
22906
+ if (sessionId) {
22907
+ if (policy === "uses") {
22908
+ if (!Number.isInteger(args.tabId)) throw new Error(`${wireName}: a valid tabId is required in a browse session`);
22909
+ assertSessionOwnsTab(sessionId, args.tabId);
22910
+ } else if (policy === "opens") {
22911
+ if (args.reuseActive === true) throw new Error("open_tab: reuseActive is disabled in a browse session (it would adopt a tab outside the session); open a fresh tab instead");
22912
+ } else for (const tabId of toNumberArray(args.tabIds)) assertSessionOwnsTab(sessionId, tabId);
22913
+ }
21799
22914
  const env = await dispatch(wireName, args, signal);
21800
22915
  const text = joinEnvelopeText(env);
21801
22916
  if (env.isError) throw new Error(text || `${wireName} failed`);
@@ -21888,7 +23003,8 @@ function messageTextBytes(m) {
21888
23003
  switch (msg.role) {
21889
23004
  case "user":
21890
23005
  case "custom":
21891
- case "toolResult": return contentBytes(msg.content);
23006
+ case "toolResult":
23007
+ case "system": return contentBytes(msg.content);
21892
23008
  case "assistant": {
21893
23009
  const content = msg.content;
21894
23010
  if (!Array.isArray(content)) return 0;
@@ -23493,6 +24609,383 @@ function browseAgentEnabled() {
23493
24609
  if (!found) return false;
23494
24610
  return pickEndpoint(found) !== void 0;
23495
24611
  }
24612
+ /**
24613
+ * Gate for the Azure DevOps MCP group (`mcp__ado__*`).
24614
+ *
24615
+ * Returns true iff `setupAndServe` resolved the group ON. The flag is the
24616
+ * whole predicate: unlike `browserToolsEnabled()` there is no separate
24617
+ * installed-dependency probe, because the launch path already performed the
24618
+ * only availability check that matters — it fetched the upstream `tools/list`
24619
+ * and turned the group off when that failed (see `provisionAdoTools` in
24620
+ * `~/lib/ado-tools`). Re-deriving reachability here would either duplicate a
24621
+ * network call on every `tools/list` or disagree with the snapshot that
24622
+ * `tools/list` is about to serve.
24623
+ */
24624
+ function adoToolsEnabled() {
24625
+ return state.adoEnabled;
24626
+ }
24627
+ /**
24628
+ * Gate for the Kusto MCP group (`mcp__kusto__*`).
24629
+ *
24630
+ * Returns true iff `setupAndServe` resolved the group ON, exactly like
24631
+ * `adoToolsEnabled()`. It once ALSO required a configured cluster, on the
24632
+ * grounds that five tools whose every call fails with "no cluster configured"
24633
+ * are the empty-server smell. Per-call clusters retire that: the group is
24634
+ * useful with no launch cluster at all, because the CALL names one, so the old
24635
+ * arm would hide a working capability.
24636
+ *
24637
+ * The removed normalize probe has a replacement, and it is not a weaker one: a
24638
+ * malformed launch cluster used to make the whole group vanish silently, while
24639
+ * now the group lists and only the call that actually falls back to the bad
24640
+ * default fails, with the normalizer's own message naming the expectation. That
24641
+ * is a strictly better signal, and it costs nothing on a session that passes an
24642
+ * explicit `cluster`.
24643
+ */
24644
+ function kustoToolsEnabled() {
24645
+ return state.kustoEnabled;
24646
+ }
24647
+ const ADO_TOKEN_RESOURCE = "2a72489c-aab2-4b65-b93a-a91edccf33b8";
24648
+ const ADO_PROTOCOL_VERSION = "2025-06-18";
24649
+ const ADO_TOKEN_ENV = "ADO_MCP_TOKEN";
24650
+ /**
24651
+ * Toolset names the remote server accepts in `X-MCP-Toolsets`. Microsoft's
24652
+ * documented list; `core` / `repositories` are NOT valid values (they were a
24653
+ * wrong guess in an earlier draft of this work and are rejected here so the
24654
+ * mistake cannot reach the wire).
24655
+ */
24656
+ const ADO_TOOLSET_VALUES = [
24657
+ "all",
24658
+ "repos",
24659
+ "advsec",
24660
+ "wit",
24661
+ "pipelines",
24662
+ "wiki",
24663
+ "work",
24664
+ "testplan",
24665
+ "elm"
24666
+ ];
24667
+ /**
24668
+ * The curated default: pull requests and files, work items, builds, and wiki.
24669
+ * Deliberately excludes `advsec` / `work` / `testplan` / `elm`, whose tools are
24670
+ * off the main repository loop.
24671
+ */
24672
+ const ADO_DEFAULT_TOOLSETS = [
24673
+ "repos",
24674
+ "wit",
24675
+ "pipelines",
24676
+ "wiki"
24677
+ ];
24678
+ /**
24679
+ * No result cap here, deliberately.
24680
+ *
24681
+ * A character cap at this boundary would truncate a large upstream result
24682
+ * BEFORE the `/mcp` relay could spill it, so the model would receive a
24683
+ * preview plus a path to a file that is itself truncated while the trailer
24684
+ * promises the full result. The model-facing bound belongs at the relay
24685
+ * boundary, which `ado-tools` applies through `relaySafeText`: over the cap
24686
+ * the FULL text is written to a file and a bounded preview plus that path is
24687
+ * returned, which is recoverable rather than clipped. Bounds on upstream
24688
+ * payloads still exist, just where they can be honoured: the transport's
24689
+ * per-attempt timeouts and the service's own paging arguments.
24690
+ */
24691
+ var AdoError = class extends RemoteMcpError {
24692
+ constructor(message, opts = {}) {
24693
+ super(message, opts);
24694
+ this.name = "AdoError";
24695
+ }
24696
+ };
24697
+ /**
24698
+ * Validate an organization name. It becomes a URL path segment, so anything
24699
+ * outside the character set Azure DevOps issues is rejected rather than
24700
+ * encoded — a `.` or `/` here would silently address a different endpoint.
24701
+ */
24702
+ function normalizeAdoOrganization(org) {
24703
+ const trimmed = org.trim();
24704
+ if (!trimmed) throw new AdoError("Azure DevOps organization is empty.", { retriable: false });
24705
+ if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,63}$/.test(trimmed)) throw new AdoError("Azure DevOps organization must be 1-64 characters of letters, digits, or hyphens.", { retriable: false });
24706
+ return trimmed;
24707
+ }
24708
+ /** Parse and validate a comma-separated toolset list. */
24709
+ function normalizeAdoToolsets(value) {
24710
+ const parts = [...typeof value === "string" ? value.split(",") : value].map((part) => part.trim().toLowerCase()).filter((part) => part.length > 0);
24711
+ if (parts.length === 0) throw new AdoError("Azure DevOps toolset list is empty.", { retriable: false });
24712
+ const unknown = parts.filter((part) => !ADO_TOOLSET_VALUES.includes(part));
24713
+ if (unknown.length > 0) throw new AdoError(`Unknown Azure DevOps toolset(s): ${unknown.join(", ")}. Valid values: ${ADO_TOOLSET_VALUES.join(", ")}.`, { retriable: false });
24714
+ if (parts.includes("all")) return ["all"];
24715
+ return [...new Set(parts)];
24716
+ }
24717
+ /**
24718
+ * The `X-MCP-Toolsets` header value, or `undefined` when the selection is
24719
+ * "all" (the header is omitted so the server applies its own default).
24720
+ */
24721
+ function adoToolsetHeader(toolsets) {
24722
+ if (toolsets.length === 0) return void 0;
24723
+ if (toolsets.length === 1 && toolsets[0] === "all") return void 0;
24724
+ return toolsets.join(",");
24725
+ }
24726
+ /** Process-lifetime token cache for this audience. */
24727
+ const adoTokenCache = new AzCliAccessTokenCache();
24728
+ /** Token source: explicit env first (tests/manual), else the `az` ladder. */
24729
+ async function getAdoToken(signal, opts = {}) {
24730
+ if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
24731
+ const env = process.env[ADO_TOKEN_ENV]?.trim();
24732
+ if (env) return env;
24733
+ try {
24734
+ return await adoTokenCache.get(ADO_TOKEN_RESOURCE, {
24735
+ ...signal ? { signal } : {},
24736
+ ...opts.allowInteractiveLogin ? { allowInteractiveLogin: true } : {},
24737
+ ...opts.forceRefresh ? { forceRefresh: true } : {}
24738
+ });
24739
+ } catch (err) {
24740
+ if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
24741
+ throw new AdoError(describeAzFailure("Azure DevOps", err), { retriable: false });
24742
+ }
24743
+ }
24744
+ var AdoMcpClient = class extends RemoteMcpClient {
24745
+ organization;
24746
+ readOnly;
24747
+ toolsets;
24748
+ constructor(opts) {
24749
+ const organization = normalizeAdoOrganization(opts.organization);
24750
+ const readOnly = opts.readOnly !== false;
24751
+ const toolsets = [...opts.toolsets ?? ADO_DEFAULT_TOOLSETS];
24752
+ const toolsetHeader = adoToolsetHeader(toolsets);
24753
+ super({
24754
+ label: "Azure DevOps",
24755
+ baseUrl: `${opts.baseUrl ?? "https://mcp.dev.azure.com"}/${organization}`,
24756
+ protocolVersion: ADO_PROTOCOL_VERSION,
24757
+ clientName: "github-router",
24758
+ clientVersion: "ado",
24759
+ errorClass: AdoError,
24760
+ token: opts.token,
24761
+ tokenProvider: opts.tokenProvider ?? ((signal) => {
24762
+ consola.warn(`Azure DevOps rejected the access token (401). Re-minting for resource 2a72489c-aab2-4b65-b93a-a91edccf33b8 through the Azure CLI; if this is a stale session, run \`az login\`.`);
24763
+ return getAdoToken(signal, {
24764
+ forceRefresh: true,
24765
+ allowInteractiveLogin: true
24766
+ });
24767
+ }),
24768
+ staticHeaders: () => ({
24769
+ ...readOnly ? { "X-MCP-Readonly": "true" } : {},
24770
+ ...toolsetHeader ? { "X-MCP-Toolsets": toolsetHeader } : {}
24771
+ })
24772
+ });
24773
+ this.organization = organization;
24774
+ this.readOnly = readOnly;
24775
+ this.toolsets = toolsets;
24776
+ }
24777
+ /** The tools the server advertised, in the order it listed them. */
24778
+ listAdoTools() {
24779
+ return [...this.toolSchemas.values()].map((tool) => ({
24780
+ name: tool.name,
24781
+ description: tool.description ?? "",
24782
+ inputSchema: isRecord$3(tool.inputSchema) ? tool.inputSchema : {
24783
+ type: "object",
24784
+ properties: {}
24785
+ }
24786
+ }));
24787
+ }
24788
+ /** True iff the server advertised `name`. Guards a call the model invented. */
24789
+ hasTool(name) {
24790
+ return this.toolSchemas.has(name);
24791
+ }
24792
+ /**
24793
+ * One `tools/call`, normalized to the MCP result envelope the `/mcp` handler
24794
+ * forwards. A tool-level `isError` result is passed through as such (the
24795
+ * server's refusal IS the answer); only a transport/protocol failure throws.
24796
+ */
24797
+ async callAdoTool(name, args, signal) {
24798
+ await this.initialize(signal);
24799
+ if (!this.hasTool(name)) throw new AdoError(`Azure DevOps MCP does not advertise a tool named "${name}". Advertised tools: ${[...this.toolSchemas.keys()].sort().join(", ")}.`, { retriable: false });
24800
+ const result = await this.callTool(name, args, signal);
24801
+ if (!isRecord$3(result)) throw new AdoError("Azure DevOps returned an empty result.", { retriable: true });
24802
+ const texts = [];
24803
+ if (Array.isArray(result.content)) {
24804
+ for (const block of result.content) if (isRecord$3(block) && typeof block.text === "string" && block.text.trim()) texts.push(block.text);
24805
+ }
24806
+ const envelope = { content: [{
24807
+ type: "text",
24808
+ text: texts.join("\n\n") || "Azure DevOps returned an empty result."
24809
+ }] };
24810
+ if (result.isError === true) envelope.isError = true;
24811
+ return envelope;
24812
+ }
24813
+ };
24814
+ //#endregion
24815
+ //#region src/lib/ado-tools.ts
24816
+ /**
24817
+ * The `ado` MCP group: the tool surface Azure DevOps itself advertises.
24818
+ *
24819
+ * **Why this group is dynamic.** Every other group in `NON_PERSONA_MCP_TOOLS`
24820
+ * is a frozen array of hand-written entries, pinned at boot by
24821
+ * `assertMcpToolSurfaceConsistent()`. This one cannot be: the remote server
24822
+ * owns the tool set, it is large (20 tools under the curated toolsets, 31
24823
+ * without read-only, 43 with every toolset), and its names and descriptions
24824
+ * change on Microsoft's schedule. Freezing twenty entries would mean a
24825
+ * transcription that drifts silently and a proxy release for every upstream
24826
+ * rename. So `tools/list` is forwarded from the upstream `tools/list`,
24827
+ * filtered only by the two headers that already define the surface
24828
+ * (`X-MCP-Toolsets` and `X-MCP-Readonly`) — see `./ado-client` for the live
24829
+ * measurement that established those headers ARE the filter.
24830
+ *
24831
+ * What the static contract still guarantees, with the dynamic group folded in:
24832
+ *
24833
+ * - **Name uniqueness.** `assertMcpToolSurfaceConsistent()` sees the static
24834
+ * registry only, so the dynamic entries are checked against it here at
24835
+ * snapshot time, and a collision drops the upstream tool with a warning
24836
+ * rather than shadowing a proxy tool. A duplicate would be worse than a
24837
+ * missing tool: the model would call one name and reach the other's code.
24838
+ * - **Scope and capability symmetry.** Each dynamic entry carries
24839
+ * `group: "ado"` and `capability: "ado"`, so the same `tools/list` filter
24840
+ * and the same call-time gate apply to it as to any static tool.
24841
+ * - **Read-only default.** The read-only subset is not computed here; it is
24842
+ * whatever the server returned after being told `X-MCP-Readonly: true`.
24843
+ *
24844
+ * The snapshot is taken ONCE at launch, awaited before the child process
24845
+ * starts, because `toolEntries()` is synchronous and cannot fetch. A failure
24846
+ * disables the group with an actionable warning rather than leaving an empty
24847
+ * group advertised — a server that lists zero tools is indistinguishable from
24848
+ * a broken one, and neither is worth the bytes.
24849
+ */
24850
+ /** Bound on the launch-time `initialize` + `tools/list` round trip. */
24851
+ const PROVISION_TIMEOUT_MS = 2e4;
24852
+ const ADO_GROUP = "ado";
24853
+ let client = null;
24854
+ let inflight = null;
24855
+ let snapshot = [];
24856
+ /** Close the upstream session. Best-effort; safe when nothing was created. */
24857
+ async function disposeAdoClients() {
24858
+ const current = client;
24859
+ client = null;
24860
+ snapshot = [];
24861
+ if (current) await current.dispose().catch(() => {});
24862
+ }
24863
+ /**
24864
+ * The one process-lifetime ADO client, constructed from `state`. Single-flight
24865
+ * so concurrent first calls cannot mint two clients (and two `az` tokens).
24866
+ *
24867
+ * `signal` bounds the CONSTRUCTION only (the token mint and the MCP
24868
+ * `initialize`/`tools/list` round trip), which is where the unbounded wait
24869
+ * lives: `az account get-access-token` and a first `initialize` against a
24870
+ * unreachable server can each hang for minutes. Once the client is memoized
24871
+ * every later caller returns immediately and the signal is unused, so a
24872
+ * request-end abort cannot tear down a client other calls are using.
24873
+ */
24874
+ async function ensureAdoClient(signal) {
24875
+ if (client) return client;
24876
+ const existing = inflight;
24877
+ if (existing) return existing;
24878
+ const promise = (async () => {
24879
+ const organization = state.adoOrganization;
24880
+ if (!organization) throw new Error("No Azure DevOps organization is configured. Launch with `--ado-org <org>` or run inside a checkout whose git remotes point at Azure DevOps.");
24881
+ const token = await getAdoToken(signal);
24882
+ const created = new AdoMcpClient({
24883
+ organization,
24884
+ readOnly: state.adoReadOnly,
24885
+ toolsets: state.adoToolsets.length > 0 ? state.adoToolsets : void 0,
24886
+ token
24887
+ });
24888
+ await created.initialize(signal);
24889
+ client = created;
24890
+ return created;
24891
+ })();
24892
+ inflight = promise;
24893
+ try {
24894
+ return await promise;
24895
+ } finally {
24896
+ if (inflight === promise) inflight = null;
24897
+ }
24898
+ }
24899
+ /**
24900
+ * Resolve the ADO tool surface and snapshot it for this process.
24901
+ *
24902
+ * Called from `setupAndServe` before the child spawns. Never throws: the
24903
+ * launch is not the right place to fail over a network dependency. On failure
24904
+ * the group is turned OFF, because an `ado` server that advertises no tools is
24905
+ * worse than an absent one — the model would see the group, find nothing
24906
+ * usable in it, and have no way to tell whether the group or its own query was
24907
+ * wrong.
24908
+ */
24909
+ async function provisionAdoTools() {
24910
+ if (!state.adoEnabled) return {
24911
+ ok: false,
24912
+ reason: "ado group is not enabled"
24913
+ };
24914
+ const timer = new AbortController();
24915
+ const handle = setTimeout(() => timer.abort(/* @__PURE__ */ new Error("Azure DevOps MCP provisioning timed out")), PROVISION_TIMEOUT_MS);
24916
+ handle.unref?.();
24917
+ try {
24918
+ const created = await ensureAdoClient(timer.signal);
24919
+ if (timer.signal.aborted) throw new Error("Azure DevOps MCP provisioning timed out");
24920
+ snapshot = buildAdoToolEntries(created.listAdoTools());
24921
+ if (snapshot.length === 0) throw new Error("Azure DevOps advertised no tools for the selected toolsets");
24922
+ return {
24923
+ ok: true,
24924
+ toolCount: snapshot.length
24925
+ };
24926
+ } catch (err) {
24927
+ const reason = sanitizeRemoteDetail(err);
24928
+ state.adoEnabled = false;
24929
+ await disposeAdoClients();
24930
+ consola.warn(`Azure DevOps MCP group disabled: ${reason} Verify \`az login\` targets the tenant that owns this organization, then relaunch.`);
24931
+ return {
24932
+ ok: false,
24933
+ reason
24934
+ };
24935
+ } finally {
24936
+ clearTimeout(handle);
24937
+ }
24938
+ }
24939
+ /**
24940
+ * Map the upstream descriptors onto the proxy's non-persona tool shape.
24941
+ *
24942
+ * Exported for tests, which feed recorded fixtures through it to pin the
24943
+ * filtering and the collision behaviour without a live endpoint.
24944
+ */
24945
+ function buildAdoToolEntries(tools) {
24946
+ const proxyOwned = proxyOwnedMcpToolNames();
24947
+ const seen = /* @__PURE__ */ new Set();
24948
+ const entries = [];
24949
+ for (const tool of tools) {
24950
+ const name = tool.name?.trim();
24951
+ if (!name) continue;
24952
+ if (proxyOwned.has(name)) {
24953
+ consola.warn(`Azure DevOps tool "${name}" was dropped: the proxy already serves a tool by that name.`);
24954
+ continue;
24955
+ }
24956
+ if (seen.has(name)) continue;
24957
+ seen.add(name);
24958
+ entries.push({
24959
+ toolNameHttp: name,
24960
+ group: ADO_GROUP,
24961
+ capability: "ado",
24962
+ description: tool.description || `Azure DevOps tool ${name}.`,
24963
+ inputSchema: tool.inputSchema,
24964
+ async handler(args, signal) {
24965
+ const result = await (await ensureAdoClient(signal)).callAdoTool(name, args, signal);
24966
+ if (result.isError === true) return {
24967
+ content: result.content,
24968
+ isError: true
24969
+ };
24970
+ return { content: [{
24971
+ type: "text",
24972
+ text: await relaySafeText(result.content.map((block) => block.text).join(""))
24973
+ }] };
24974
+ }
24975
+ });
24976
+ }
24977
+ return entries;
24978
+ }
24979
+ /**
24980
+ * The ADO tools for THIS process, or an empty array when the group is off or
24981
+ * its snapshot never landed. Read by `tools/list` and `tools/call` through one
24982
+ * accessor in the handler so the two surfaces cannot disagree about which
24983
+ * tools exist.
24984
+ */
24985
+ function adoMcpToolEntries() {
24986
+ if (!state.adoEnabled) return [];
24987
+ return snapshot;
24988
+ }
23496
24989
  //#endregion
23497
24990
  //#region src/routes/mcp/handler.ts
23498
24991
  const MCP_PROTOCOL_VERSION = "2025-06-18";
@@ -23629,6 +25122,38 @@ function checkAuth(c) {
23629
25122
  };
23630
25123
  }
23631
25124
  /**
25125
+ * The non-persona tool registry for this process: the static array plus any
25126
+ * group whose surface an upstream server advertises at runtime.
25127
+ *
25128
+ * Every consumer — `tools/list`, the `tools/call` lookup, the max/fast
25129
+ * profile allow-list checks — goes through here rather than reading
25130
+ * `NON_PERSONA_MCP_TOOLS` directly, so the two surfaces cannot disagree about
25131
+ * which tools exist. Reading the static array in one place and this in another
25132
+ * is exactly how a tool becomes listed-but-uncallable.
25133
+ *
25134
+ * Returns the static array itself (not a copy) when the dynamic group is off,
25135
+ * which is every launch unless `--ado` resolved on.
25136
+ */
25137
+ function allNonPersonaTools() {
25138
+ const dynamic = adoMcpToolEntries();
25139
+ if (dynamic.length === 0) return NON_PERSONA_MCP_TOOLS;
25140
+ return [...NON_PERSONA_MCP_TOOLS, ...dynamic];
25141
+ }
25142
+ /**
25143
+ * The LIST surface only: `allNonPersonaTools()` minus hook-channel tools.
25144
+ *
25145
+ * Every `toolEntries()` path reads this; every `tools/call` lookup reads
25146
+ * `allNonPersonaTools()`. That asymmetry is the whole point of `hookOnly` (see
25147
+ * the field doc in `peer-mcp-personas`): the Pi extension must be able to CALL
25148
+ * `prompt_brief` over the authenticated hook channel, while the model must not
25149
+ * see a name it is never supposed to use. Splitting the two accessors keeps the
25150
+ * list/call surfaces from disagreeing about the tools that ARE gated, which is
25151
+ * the property the capability chain already relies on.
25152
+ */
25153
+ function listableNonPersonaTools() {
25154
+ return allNonPersonaTools().filter((tool) => tool.hookOnly !== true);
25155
+ }
25156
+ /**
23632
25157
  * opus_critic's effective model, resolved against the live catalog.
23633
25158
  *
23634
25159
  * Prefers `claude-opus-5.5` — the dotted catalog id that is natively 1M
@@ -23764,6 +25289,8 @@ function maxToolIsEnabled(tool) {
23764
25289
  if (tool.capability === "fleet") return fleetToolsEnabled();
23765
25290
  if (tool.capability === "agents") return agentToolsEnabled();
23766
25291
  if (tool.capability === "artifact") return artifactToolsEnabled();
25292
+ if (tool.group === "ado") return adoToolsEnabled();
25293
+ if (tool.group === "kusto") return kustoToolsEnabled();
23767
25294
  return true;
23768
25295
  }
23769
25296
  /**
@@ -23787,6 +25314,8 @@ function fastToolIsEnabled(tool) {
23787
25314
  if (tool.group === "search") return true;
23788
25315
  if (tool.group === "peers") return tool.capability === "artifact" && artifactToolsEnabled();
23789
25316
  if (tool.group === "workers") return tool.toolNameHttp === "browse" && tool.capability === "browse_agent" && browseAgentEnabled();
25317
+ if (tool.group === "ado") return adoToolsEnabled();
25318
+ if (tool.group === "kusto") return kustoToolsEnabled();
23790
25319
  if (tool.group !== "browser") return false;
23791
25320
  if (!browserToolsEnabled()) return false;
23792
25321
  if (tool.capability === "browser_compound") return browserCompoundToolsEnabled();
@@ -23836,7 +25365,7 @@ function toolEntries(scope, launch, audience = "shared") {
23836
25365
  }
23837
25366
  }
23838
25367
  }));
23839
- const nonPersonaEntries = NON_PERSONA_MCP_TOOLS.filter((tool) => maxAllowsTool(scope, launch, {
25368
+ const nonPersonaEntries = listableNonPersonaTools().filter((tool) => maxAllowsTool(scope, launch, {
23840
25369
  group: tool.group,
23841
25370
  name: tool.toolNameHttp,
23842
25371
  tool
@@ -23861,7 +25390,7 @@ function toolEntries(scope, launch, audience = "shared") {
23861
25390
  const entries = [];
23862
25391
  if ((scope === "all" || scope === "peers") && launch.allowedGroups?.has("peers") && launch.allowedPersonas?.has("oracle") && oracleGate) entries.push(oracleToolEntry(isCheap, astraAvailable, oracleDescriptor));
23863
25392
  if ((scope === "all" || scope === "peers") && launch.allowedGroups?.has("peers") && launch.allowedPersonas?.has("astra") && audience === "lead-peers" && astraWired && (isCheap ? cheapAstraModel() : fastAstraModel())) entries.push(astraToolEntry(isCheap));
23864
- for (const tool of NON_PERSONA_MCP_TOOLS) {
25393
+ for (const tool of listableNonPersonaTools()) {
23865
25394
  if (!fastAllowsTool(scope, launch, {
23866
25395
  group: tool.group,
23867
25396
  name: tool.toolNameHttp,
@@ -23900,7 +25429,7 @@ function toolEntries(scope, launch, audience = "shared") {
23900
25429
  }
23901
25430
  }
23902
25431
  })) : [];
23903
- const nonPersonaEntries = NON_PERSONA_MCP_TOOLS.filter((t) => {
25432
+ const nonPersonaEntries = listableNonPersonaTools().filter((t) => {
23904
25433
  if (scope !== "all" && t.group !== scope) return false;
23905
25434
  if (launch.allowedGroups && !launch.allowedGroups.has(t.group)) return false;
23906
25435
  if (t.capability === "worker") return workerToolsEnabled();
@@ -23910,6 +25439,8 @@ function toolEntries(scope, launch, audience = "shared") {
23910
25439
  if (t.capability === "fleet") return fleetToolsEnabled();
23911
25440
  if (t.capability === "agents") return agentToolsEnabled();
23912
25441
  if (t.capability === "artifact") return artifactToolsEnabled();
25442
+ if (t.capability === "ado") return adoToolsEnabled();
25443
+ if (t.capability === "kusto") return kustoToolsEnabled();
23913
25444
  if (t.capability === "browser_compound") return browserToolsEnabled() && browserCompoundToolsEnabled();
23914
25445
  if (t.capability === "browser_power") return browserToolsEnabled() && browserPowerToolsEnabled();
23915
25446
  return true;
@@ -24257,7 +25788,7 @@ function logTelemetry(t) {
24257
25788
  process.stderr.write(parts.join(" ") + "\n");
24258
25789
  }
24259
25790
  function toolAcceptsWorkspace(tool) {
24260
- return tool.capability === "worker" || tool.toolNameHttp === "code" || tool.toolNameHttp === "run_workflow";
25791
+ return tool.capability === "worker" || tool.toolNameHttp === "code" || tool.toolNameHttp === "run_workflow" || tool.toolNameHttp === "prompt_brief";
24261
25792
  }
24262
25793
  /**
24263
25794
  * Fold the per-session `X-GH-Workspace` header into `args.workspace` when the
@@ -24287,7 +25818,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24287
25818
  if (!name) return rpcError(body.id, RPC_INVALID_PARAMS, "tools/call missing name");
24288
25819
  if (launch.profileId === "max") {
24289
25820
  const maxPersona = activePersonas(launch).find((persona) => persona.toolNameHttp === name);
24290
- const maxTool = NON_PERSONA_MCP_TOOLS.find((tool) => tool.toolNameHttp === name);
25821
+ const maxTool = allNonPersonaTools().find((tool) => tool.toolNameHttp === name);
24291
25822
  if (!(maxPersona ? maxAllowsTool(scope, launch, {
24292
25823
  group: "peers",
24293
25824
  name,
@@ -24300,7 +25831,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24300
25831
  }
24301
25832
  if ((launch.profileId === "fast" || launch.profileId === "cheap" || launch.profileId === "cheap1m" || launch.profileId === "cheapest" || launch.profileId === "balanced") && name !== "oracle" && name !== "astra") {
24302
25833
  const fastPersona = activePersonas(launch).find((persona) => persona.toolNameHttp === name);
24303
- const fastTool = NON_PERSONA_MCP_TOOLS.find((tool) => tool.toolNameHttp === name);
25834
+ const fastTool = allNonPersonaTools().find((tool) => tool.toolNameHttp === name);
24304
25835
  if (!(fastPersona ? fastAllowsTool(scope, launch, {
24305
25836
  group: "peers",
24306
25837
  name,
@@ -24459,7 +25990,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24459
25990
  }
24460
25991
  if ((launch.profileId === "fast" || launch.profileId === "cheap" || launch.profileId === "cheap1m" || launch.profileId === "cheapest" || launch.profileId === "balanced") && PERSONAS_READ.some((p) => p.toolNameHttp === name)) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24461
25992
  const persona = activePersonas(launch).find((p) => p.toolNameHttp === name);
24462
- const nonPersonaTool = persona ? void 0 : NON_PERSONA_MCP_TOOLS.find((t) => t.toolNameHttp === name);
25993
+ const nonPersonaTool = persona ? void 0 : allNonPersonaTools().find((t) => t.toolNameHttp === name);
24463
25994
  if (!persona && !nonPersonaTool) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24464
25995
  const toolGroup = persona ? "peers" : nonPersonaTool.group;
24465
25996
  if (scope !== "all" && toolGroup !== scope) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
@@ -24474,6 +26005,8 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24474
26005
  if (nonPersonaTool && nonPersonaTool.capability === "artifact" && !artifactToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24475
26006
  if (nonPersonaTool && nonPersonaTool.capability === "browser_compound" && !(browserToolsEnabled() && browserCompoundToolsEnabled())) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24476
26007
  if (nonPersonaTool && nonPersonaTool.capability === "browser_power" && !(browserToolsEnabled() && browserPowerToolsEnabled())) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
26008
+ if (nonPersonaTool && nonPersonaTool.capability === "ado" && !adoToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
26009
+ if (nonPersonaTool && nonPersonaTool.capability === "kusto" && !kustoToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24477
26010
  let personaPrompt;
24478
26011
  let personaContext;
24479
26012
  let personaEffort;
@@ -25814,7 +27347,7 @@ function isAdvisorRequested(rawBetaHeader) {
25814
27347
  * blocks the client expects.
25815
27348
  */
25816
27349
  function injectAdvisorTool(rawBody, instructions = ADVISOR_TOOL_INSTRUCTIONS) {
25817
- if (instructions === ADVISOR_TOOL_INSTRUCTIONS && rawBody.includes(`"name":"__anthropic_advisor"`) && !rawBody.includes("\"advisor_")) return rawBody;
27350
+ if (instructions === "# Advisor Tool\n\nYou have access to an `advisor` tool backed by a stronger reviewer model. It takes NO parameters -- when you call it, your entire conversation history is automatically forwarded. The advisor sees the task, every tool call you've made, every result you've seen.\n\nCall advisor BEFORE substantive work -- before writing code, before committing to an interpretation, before building on an assumption. If the task requires orientation first (finding files, reading code, seeing what's there), do that, then call advisor. Orientation is not substantive work. Writing, editing, and declaring an answer are.\n\nAlso call advisor:\n- When you believe the task is complete. BEFORE this call, make your deliverable durable: write the file, stage the change, save the result. The advisor call takes time; if the session ends during it, a durable result persists and an unwritten one doesn't.\n- When stuck -- errors recurring, approach not converging, results that don't fit.\n- When considering a change of approach.\n\nOn tasks longer than a few steps, call advisor at least once before committing to an approach and once before declaring done. On short reactive tasks where the next action is dictated by tool output you just read, you don't need to keep calling -- the advisor adds most of its value on the first call, before the approach crystallizes.\n\nGive the advice serious weight. If you follow a step and it fails empirically, or you have primary-source evidence that contradicts a specific claim (the file says X, the code does Y), adapt. A passing self-test is not evidence the advice is wrong -- it's evidence your test doesn't check what the advice is checking.\n\nIf you've already retrieved data pointing one way and the advisor points another: don't silently switch. Surface the conflict in one more advisor call -- \"I found X, you suggest Y, which constraint breaks the tie?\" The advisor saw your evidence but may have underweighted it; a reconcile call is cheaper than committing to the wrong branch." && rawBody.includes(`"name":"__anthropic_advisor"`) && !rawBody.includes("\"advisor_")) return rawBody;
25818
27351
  let parsed;
25819
27352
  try {
25820
27353
  parsed = JSON.parse(rawBody);
@@ -27882,13 +29415,13 @@ function atomicWriteSync(absPath, contents) {
27882
29415
  throw err;
27883
29416
  }
27884
29417
  }
27885
- const READ_PARAMS = Type$1.Object({
27886
- path: Type$1.String({ description: "Workspace-relative or absolute path." }),
27887
- offset: Type$1.Optional(Type$1.Integer({
29418
+ const READ_PARAMS = Type.Object({
29419
+ path: Type.String({ description: "Workspace-relative or absolute path." }),
29420
+ offset: Type.Optional(Type.Integer({
27888
29421
  minimum: 0,
27889
29422
  description: "Line offset (0-indexed)."
27890
29423
  })),
27891
- limit: Type$1.Optional(Type$1.Integer({
29424
+ limit: Type.Optional(Type.Integer({
27892
29425
  minimum: 1,
27893
29426
  description: "Max lines to return."
27894
29427
  }))
@@ -27944,9 +29477,9 @@ function readTool(workspace) {
27944
29477
  }
27945
29478
  };
27946
29479
  }
27947
- const GLOB_PARAMS = Type$1.Object({
27948
- pattern: Type$1.String({ description: "ripgrep glob pattern, e.g. `src/**/*.ts`." }),
27949
- limit: Type$1.Optional(Type$1.Integer({
29480
+ const GLOB_PARAMS = Type.Object({
29481
+ pattern: Type.String({ description: "ripgrep glob pattern, e.g. `src/**/*.ts`." }),
29482
+ limit: Type.Optional(Type.Integer({
27950
29483
  minimum: 1,
27951
29484
  maximum: SEARCH_HARD_MAX
27952
29485
  }))
@@ -27973,11 +29506,11 @@ function globTool(workspace) {
27973
29506
  }
27974
29507
  };
27975
29508
  }
27976
- const GREP_PARAMS = Type$1.Object({
27977
- query: Type$1.String({ description: "Pattern to search for." }),
27978
- mode: Type$1.Optional(Type$1.Union([Type$1.Literal("literal"), Type$1.Literal("regex")], { description: "`literal` (default) = fixed-string; `regex` = PCRE2." })),
27979
- file_glob: Type$1.Optional(Type$1.String({ description: "ripgrep glob filter, e.g. `*.ts`." })),
27980
- limit: Type$1.Optional(Type$1.Integer({
29509
+ const GREP_PARAMS = Type.Object({
29510
+ query: Type.String({ description: "Pattern to search for." }),
29511
+ mode: Type.Optional(Type.Union([Type.Literal("literal"), Type.Literal("regex")], { description: "`literal` (default) = fixed-string; `regex` = PCRE2." })),
29512
+ file_glob: Type.Optional(Type.String({ description: "ripgrep glob filter, e.g. `*.ts`." })),
29513
+ limit: Type.Optional(Type.Integer({
27981
29514
  minimum: 1,
27982
29515
  maximum: SEARCH_HARD_MAX
27983
29516
  }))
@@ -28013,10 +29546,10 @@ function grepTool(workspace) {
28013
29546
  }
28014
29547
  };
28015
29548
  }
28016
- const EDIT_PARAMS = Type$1.Object({
28017
- path: Type$1.String({ description: "Workspace-relative or absolute path." }),
28018
- old_string: Type$1.String({ description: "Exact text to find. Must match exactly once; tool returns `not found` (0 matches) or `matches N times` (>1) without editing." }),
28019
- new_string: Type$1.String({ description: "Replacement text. May be empty (deletes old_string)." })
29549
+ const EDIT_PARAMS = Type.Object({
29550
+ path: Type.String({ description: "Workspace-relative or absolute path." }),
29551
+ old_string: Type.String({ description: "Exact text to find. Must match exactly once; tool returns `not found` (0 matches) or `matches N times` (>1) without editing." }),
29552
+ new_string: Type.String({ description: "Replacement text. May be empty (deletes old_string)." })
28020
29553
  });
28021
29554
  function editTool(workspace) {
28022
29555
  return {
@@ -28044,9 +29577,9 @@ function editTool(workspace) {
28044
29577
  }
28045
29578
  };
28046
29579
  }
28047
- const WRITE_PARAMS = Type$1.Object({
28048
- path: Type$1.String({ description: "Workspace-relative or absolute path." }),
28049
- contents: Type$1.String({ description: "Full file contents. Refused if >10 MiB." })
29580
+ const WRITE_PARAMS = Type.Object({
29581
+ path: Type.String({ description: "Workspace-relative or absolute path." }),
29582
+ contents: Type.String({ description: "Full file contents. Refused if >10 MiB." })
28050
29583
  });
28051
29584
  function writeTool(workspace) {
28052
29585
  return {
@@ -28062,9 +29595,9 @@ function writeTool(workspace) {
28062
29595
  }
28063
29596
  };
28064
29597
  }
28065
- const BASH_PARAMS = Type$1.Object({
28066
- cmd: Type$1.String({ description: "Shell command line." }),
28067
- timeout_ms: Type$1.Optional(Type$1.Integer({
29598
+ const BASH_PARAMS = Type.Object({
29599
+ cmd: Type.String({ description: "Shell command line." }),
29600
+ timeout_ms: Type.Optional(Type.Integer({
28068
29601
  minimum: 100,
28069
29602
  maximum: BASH_MAX_TIMEOUT_MS,
28070
29603
  description: `Per-call timeout (default ${BASH_DEFAULT_TIMEOUT_MS} ms).`
@@ -28097,7 +29630,7 @@ function bashTool(workspace) {
28097
29630
  }
28098
29631
  };
28099
29632
  }
28100
- const WEB_SEARCH_PARAMS = Type$1.Object({ query: Type$1.String({ description: "Natural-language search query." }) });
29633
+ const WEB_SEARCH_PARAMS = Type.Object({ query: Type.String({ description: "Natural-language search query." }) });
28101
29634
  function webSearchTool() {
28102
29635
  return {
28103
29636
  name: "web_search",
@@ -28113,7 +29646,7 @@ function webSearchTool() {
28113
29646
  }
28114
29647
  };
28115
29648
  }
28116
- const FETCH_URL_PARAMS = Type$1.Object({ url: Type$1.String({ description: "Absolute URL (http/https only)." }) });
29649
+ const FETCH_URL_PARAMS = Type.Object({ url: Type.String({ description: "Absolute URL (http/https only)." }) });
28117
29650
  function fetchUrlTool() {
28118
29651
  return {
28119
29652
  name: "fetch_url",
@@ -28176,26 +29709,26 @@ function fetchUrlTool() {
28176
29709
  function buildCodeSearchParams(searchEnabled, bluebirdEnabled) {
28177
29710
  const queryDescription = searchEnabled || bluebirdEnabled ? "Search text. Natural-language intent in the default `semantic` mode; a literal string in `lexical`/`exact`; a PCRE2 regex in `regex`." : "Search text. A literal string in `lexical`/`exact`; a PCRE2 regex in `regex`.";
28178
29711
  const modeDescription = bluebirdEnabled ? "Search mode. `semantic` (DEFAULT): Bluebird meaning-based search over the Azure DevOps index. `lexical`: Bluebird indexed keyword search. Bluebird failures surface as `source:\"error\"` with no local fallback. `exact`: local fixed-string. `regex`: local PCRE2. `ast`: local ast-grep structural (needs `ast_pattern` + `ast_lang`)." : searchEnabled ? "Search mode. `semantic` (DEFAULT): ColBERT meaning-based ranking, falls back to lexical when the index isn't ready (response `source` says which engine ran). `lexical`: BM25F + tree-sitter (best for exact symbols). `exact`: fixed-string. `regex`: PCRE2. `ast`: ast-grep structural (needs `ast_pattern` + `ast_lang`)." : "Search mode. `lexical` (DEFAULT when semantic search is off): BM25F + tree-sitter (best for exact symbols). `semantic` is accepted and runs the lexical engine. `exact`: fixed-string. `regex`: PCRE2. `ast`: ast-grep structural (needs `ast_pattern` + `ast_lang`).";
28179
- return Type$1.Object({
28180
- query: Type$1.String({ description: queryDescription }),
28181
- mode: Type$1.Optional(Type$1.Union([
28182
- Type$1.Literal("semantic"),
28183
- Type$1.Literal("lexical"),
28184
- Type$1.Literal("exact"),
28185
- Type$1.Literal("regex"),
28186
- Type$1.Literal("ast")
29712
+ return Type.Object({
29713
+ query: Type.String({ description: queryDescription }),
29714
+ mode: Type.Optional(Type.Union([
29715
+ Type.Literal("semantic"),
29716
+ Type.Literal("lexical"),
29717
+ Type.Literal("exact"),
29718
+ Type.Literal("regex"),
29719
+ Type.Literal("ast")
28187
29720
  ], { description: modeDescription })),
28188
- pattern: Type$1.Optional(Type$1.String({ description: "Local ColBERT semantic mode only: regex pre-filter (colgrep -e) — grep first, then rank semantically. Ignored in Bluebird and lexical modes." })),
28189
- file_glob: Type$1.Optional(Type$1.String({ description: "ripgrep glob filter." })),
28190
- limit: Type$1.Optional(Type$1.Integer({
29721
+ pattern: Type.Optional(Type.String({ description: "Local ColBERT semantic mode only: regex pre-filter (colgrep -e) — grep first, then rank semantically. Ignored in Bluebird and lexical modes." })),
29722
+ file_glob: Type.Optional(Type.String({ description: "ripgrep glob filter." })),
29723
+ limit: Type.Optional(Type.Integer({
28191
29724
  minimum: 1,
28192
29725
  description: "Max hits to return."
28193
29726
  })),
28194
- structural: Type$1.Optional(Type$1.Union([Type$1.Literal("full"), Type$1.Literal("topN")], { description: "Structural-ranking depth (lexical mode only)." })),
28195
- complete: Type$1.Optional(Type$1.Boolean({ description: "Lexical mode: when true, return the COMPLETE match set (every line ripgrep would find, capped only by `limit`) — disables the default precision shoulder cut + per-file cap. Use it when you must not miss any occurrence (every caller of X, a rename, an audit). The default response `notice` says when matches were hidden." })),
28196
- multiline: Type$1.Optional(Type$1.Boolean({ description: "Set true with mode:'regex' to let a pattern span newlines (ripgrep -U), e.g. 'foo[\\s\\S]*?bar' across lines. (literal/lexical queries can't contain a newline.)" })),
28197
- ast_pattern: Type$1.Optional(Type$1.String({ description: "mode:'ast' structural pattern (e.g. 'function $F($$$) { $$$ }'). Matches come from ast-grep instead of ripgrep — for multi-line AST shapes the regex modes can't express. Takes precedence over `query`. REQUIRES `ast_lang`. If ast-grep isn't installed you get a `notice`; it never falls back to regex." })),
28198
- ast_lang: Type$1.Optional(Type$1.String({ description: "Language grammar for `ast_pattern` (REQUIRED with it): 'ts' | 'tsx' | 'js' | 'py' | 'rust' | 'go' | … Without it ast-grep cross-matches every language and returns garbage." }))
29727
+ structural: Type.Optional(Type.Union([Type.Literal("full"), Type.Literal("topN")], { description: "Structural-ranking depth (lexical mode only)." })),
29728
+ complete: Type.Optional(Type.Boolean({ description: "Lexical mode: when true, return the COMPLETE match set (every line ripgrep would find, capped only by `limit`) — disables the default precision shoulder cut + per-file cap. Use it when you must not miss any occurrence (every caller of X, a rename, an audit). The default response `notice` says when matches were hidden." })),
29729
+ multiline: Type.Optional(Type.Boolean({ description: "Set true with mode:'regex' to let a pattern span newlines (ripgrep -U), e.g. 'foo[\\s\\S]*?bar' across lines. (literal/lexical queries can't contain a newline.)" })),
29730
+ ast_pattern: Type.Optional(Type.String({ description: "mode:'ast' structural pattern (e.g. 'function $F($$$) { $$$ }'). Matches come from ast-grep instead of ripgrep — for multi-line AST shapes the regex modes can't express. Takes precedence over `query`. REQUIRES `ast_lang`. If ast-grep isn't installed you get a `notice`; it never falls back to regex." })),
29731
+ ast_lang: Type.Optional(Type.String({ description: "Language grammar for `ast_pattern` (REQUIRED with it): 'ts' | 'tsx' | 'js' | 'py' | 'rust' | 'go' | … Without it ast-grep cross-matches every language and returns garbage." }))
28199
29732
  });
28200
29733
  }
28201
29734
  function codeSearchToolDescription(searchEnabled, bluebirdEnabled) {
@@ -28365,9 +29898,9 @@ const GIT_DIFF_PRODUCING = /* @__PURE__ */ new Set([
28365
29898
  "show",
28366
29899
  "diff"
28367
29900
  ]);
28368
- const TOOLBELT_PARAMS = Type$1.Object({
28369
- tool: Type$1.Union(TOOLBELT_TOOLS.map((t) => Type$1.Literal(t)), { description: "Which read-only analysis CLI to run: rg (ripgrep search), fd (file find), sg (ast-grep structural search), jq (JSON), yq (YAML/TOML/XML), gron (flatten JSON to greppable lines), scc (code stats: LOC + complexity), tokei (code stats), difft (difftastic structural diff), git (read-only subcommands only)." }),
28370
- args: Type$1.Optional(Type$1.Array(Type$1.String(), { description: "Arguments passed LITERALLY to the tool (no shell: no pipes, redirects, chaining, or glob expansion). For git, args[0] must be a read-only subcommand (log/show/diff/blame/ls-files/…)." }))
29901
+ const TOOLBELT_PARAMS = Type.Object({
29902
+ tool: Type.Union(TOOLBELT_TOOLS.map((t) => Type.Literal(t)), { description: "Which read-only analysis CLI to run: rg (ripgrep search), fd (file find), sg (ast-grep structural search), jq (JSON), yq (YAML/TOML/XML), gron (flatten JSON to greppable lines), scc (code stats: LOC + complexity), tokei (code stats), difft (difftastic structural diff), git (read-only subcommands only)." }),
29903
+ args: Type.Optional(Type.Array(Type.String(), { description: "Arguments passed LITERALLY to the tool (no shell: no pipes, redirects, chaining, or glob expansion). For git, args[0] must be a read-only subcommand (log/show/diff/blame/ls-files/…)." }))
28371
29904
  });
28372
29905
  /**
28373
29906
  * True iff `arg` triggers a denied flag. Long flags (`--foo`) match on the
@@ -28477,10 +30010,10 @@ function toolbeltTool(workspace) {
28477
30010
  };
28478
30011
  }
28479
30012
  const PEER_CRITIC_TUPLE = [
28480
- Type$1.Literal("codex_critic"),
28481
- Type$1.Literal("gemini_critic"),
28482
- Type$1.Literal("codex_reviewer"),
28483
- Type$1.Literal("opus_critic")
30013
+ Type.Literal("codex_critic"),
30014
+ Type.Literal("gemini_critic"),
30015
+ Type.Literal("codex_reviewer"),
30016
+ Type.Literal("opus_critic")
28484
30017
  ];
28485
30018
  /**
28486
30019
  * Critic names accepted by `peer_review.critic`. Exported for the
@@ -28488,17 +30021,17 @@ const PEER_CRITIC_TUPLE = [
28488
30021
  * against `PERSONAS_READ` from `~/lib/peer-mcp-personas`.
28489
30022
  */
28490
30023
  const PEER_CRITIC_NAMES = PEER_CRITIC_TUPLE.map((l) => l.const);
28491
- const PEER_EFFORT_UNION = Type$1.Union([
28492
- Type$1.Literal("low"),
28493
- Type$1.Literal("medium"),
28494
- Type$1.Literal("high"),
28495
- Type$1.Literal("xhigh")
30024
+ const PEER_EFFORT_UNION = Type.Union([
30025
+ Type.Literal("low"),
30026
+ Type.Literal("medium"),
30027
+ Type.Literal("high"),
30028
+ Type.Literal("xhigh")
28496
30029
  ], { description: "Reasoning depth. Per-critic allowedEfforts gate; out-of-band values are clamped to the critic's default." });
28497
- Type$1.Object({
28498
- critic: Type$1.Union([...PEER_CRITIC_TUPLE], { description: "Critic tool name. One of " + PEER_CRITIC_NAMES.map((n) => `\`${n}\``).join(", ") + ". `gemini_critic` is only valid when gemini-3.x is in the Copilot catalog; otherwise the call is refused." }),
28499
- prompt: Type$1.String({ description: "The brief — artifact under review plus constraints. Pasted verbatim into the critic's user message." }),
28500
- context: Type$1.Optional(Type$1.String({ description: "Optional extra context concatenated to the brief." })),
28501
- effort: Type$1.Optional(PEER_EFFORT_UNION)
30030
+ Type.Object({
30031
+ critic: Type.Union([...PEER_CRITIC_TUPLE], { description: "Critic tool name. One of " + PEER_CRITIC_NAMES.map((n) => `\`${n}\``).join(", ") + ". `gemini_critic` is only valid when gemini-3.x is in the Copilot catalog; otherwise the call is refused." }),
30032
+ prompt: Type.String({ description: "The brief — artifact under review plus constraints. Pasted verbatim into the critic's user message." }),
30033
+ context: Type.Optional(Type.String({ description: "Optional extra context concatenated to the brief." })),
30034
+ effort: Type.Optional(PEER_EFFORT_UNION)
28502
30035
  });
28503
30036
  function lookupPersona(critic) {
28504
30037
  const persona = PERSONAS_READ.find((p) => p.toolNameHttp === critic);
@@ -28519,10 +30052,10 @@ function lookupPersona(critic) {
28519
30052
  * `acquireInFlightSlot`, and `callPersona` keeps the slot accounting,
28520
30053
  * effort clamping, and isError-promotion semantics identical.
28521
30054
  */
28522
- const CODEX_REVIEW_PARAMS = Type$1.Object({
28523
- prompt: Type$1.String({ description: "The code-review brief — diff or single file under review plus constraints. Pasted verbatim into codex-reviewer's user message." }),
28524
- context: Type$1.Optional(Type$1.String({ description: "Optional extra context concatenated to the brief." })),
28525
- effort: Type$1.Optional(PEER_EFFORT_UNION)
30055
+ const CODEX_REVIEW_PARAMS = Type.Object({
30056
+ prompt: Type.String({ description: "The code-review brief — diff or single file under review plus constraints. Pasted verbatim into codex-reviewer's user message." }),
30057
+ context: Type.Optional(Type.String({ description: "Optional extra context concatenated to the brief." })),
30058
+ effort: Type.Optional(PEER_EFFORT_UNION)
28526
30059
  });
28527
30060
  function codexReviewTool() {
28528
30061
  return {
@@ -28556,7 +30089,7 @@ function geminiInCatalog() {
28556
30089
  if (!models) return false;
28557
30090
  return models.some((m) => /^gemini-3\..*pro/i.test(m.id));
28558
30091
  }
28559
- const ADVISOR_PARAMS = Type$1.Object({ concern: Type$1.String({
30092
+ const ADVISOR_PARAMS = Type.Object({ concern: Type.String({
28560
30093
  description: "What you want a second pair of eyes on — your current approach, the blocker you're stuck on, or the decision you're about to commit. Required: the advisor needs a focal point.",
28561
30094
  minLength: 1
28562
30095
  }) });
@@ -28685,22 +30218,22 @@ function advisorTool(getMessages) {
28685
30218
  }
28686
30219
  };
28687
30220
  }
28688
- const UPDATE_PLAN_PARAMS = Type$1.Object({
28689
- steps: Type$1.Array(Type$1.Object({
28690
- title: Type$1.String({
30221
+ const UPDATE_PLAN_PARAMS = Type.Object({
30222
+ steps: Type.Array(Type.Object({
30223
+ title: Type.String({
28691
30224
  minLength: 1,
28692
30225
  description: "Short imperative description of the step."
28693
30226
  }),
28694
- status: Type$1.Union([
28695
- Type$1.Literal("pending"),
28696
- Type$1.Literal("in_progress"),
28697
- Type$1.Literal("completed")
30227
+ status: Type.Union([
30228
+ Type.Literal("pending"),
30229
+ Type.Literal("in_progress"),
30230
+ Type.Literal("completed")
28698
30231
  ], { description: "Current status of this step." })
28699
30232
  }), {
28700
30233
  minItems: 1,
28701
30234
  description: "The FULL ordered plan. Each call replaces the previous plan, so always send every step (not just the changed one)."
28702
30235
  }),
28703
- explanation: Type$1.Optional(Type$1.String({ description: "Optional one-line note on what changed this update." }))
30236
+ explanation: Type.Optional(Type.String({ description: "Optional one-line note on what changed this update." }))
28704
30237
  });
28705
30238
  function createPlanState() {
28706
30239
  return { current: [] };
@@ -28793,166 +30326,6 @@ function buildWorkerTools(opts) {
28793
30326
  ];
28794
30327
  }
28795
30328
  //#endregion
28796
- //#region src/lib/worker-agent/relay-cap.ts
28797
- /**
28798
- * Relay-safe result capping for the worker MCP boundary.
28799
- *
28800
- * Claude Code hard-caps an MCP tool result at `MAX_MCP_OUTPUT_TOKENS`
28801
- * (default 25,000 tokens ≈ 100KB); a result over that is rejected /
28802
- * truncated before the lead ever sees it. A worker that emits a large
28803
- * `finalText` (an explore/review/plan summary, model prose, or a diff a
28804
- * model pasted inline) would silently lose its output at that boundary.
28805
- *
28806
- * `relaySafeText` is the LAST transform applied to a worker's assembled
28807
- * result text at each MCP boundary (`runWorkerToolCall`,
28808
- * `runBrowseToolCall`) — AFTER any `clampNote` prefix and the browse
28809
- * `[browse session: id]` suffix are appended, so nothing can push a
28810
- * just-capped string back over the limit. When the text exceeds the cap
28811
- * it is written IN FULL to a durable router-owned file and the caller
28812
- * gets a bounded head preview + the file path, so the output is
28813
- * recoverable rather than destroyed.
28814
- *
28815
- * Byte cap as a proxy for the TOKEN limit: worst-case dense output
28816
- * (base64 / hex / minified) approaches ~1 byte/token, so the clamp
28817
- * ceiling (20480 B ≈ 20k tokens) stays safely under the 25k-token cap
28818
- * with headroom. The env override can never widen it past that ceiling,
28819
- * so a misconfiguration cannot reintroduce the overflow.
28820
- */
28821
- /** Default relay-safe byte budget for a worker result. */
28822
- const DEFAULT_MAX_RESULT_BYTES = 16384;
28823
- /** Lower clamp — below this a preview is barely useful. */
28824
- const MIN_MAX_RESULT_BYTES = 8192;
28825
- /**
28826
- * Upper clamp. 20480 B ≈ 20k tokens even at the ~1 byte/token dense
28827
- * worst case, comfortably under Claude Code's 25k-token result cap. The
28828
- * env override is clamped to this, so it can never reintroduce the
28829
- * overflow the cap exists to prevent.
28830
- */
28831
- const MAX_MAX_RESULT_BYTES = 20480;
28832
- /**
28833
- * Age at which a spilled `.patch`/`.txt` is swept. Matches the worktree
28834
- * dir age sweep in `worktree.ts`.
28835
- */
28836
- const AGE_SWEEP_MS$1 = 6048e5;
28837
- /** Min interval between throttled hot-path sweeps (see `sweepAgedWorkerDiffs`). */
28838
- const SWEEP_THROTTLE_MS = 6e4;
28839
- let lastThrottledSweepAt = 0;
28840
- /**
28841
- * Strict name pattern for router-written overflow files:
28842
- * `<pid>-<8hex>.(patch|txt)`. Shared by the sweep so it NEVER removes a
28843
- * file it didn't write (a user could drop something else under the dir).
28844
- */
28845
- const WORKER_DIFF_NAME_RE = /^\d+-[0-9a-f]{8}\.(?:patch|txt)$/;
28846
- /** Resolve the relay-safe byte cap from env, clamped to the safe range. */
28847
- function resolveMaxResultBytes() {
28848
- const raw = process$1.env.GH_ROUTER_WORKER_MAX_RESULT_BYTES;
28849
- if (raw === void 0) return DEFAULT_MAX_RESULT_BYTES;
28850
- const n = Number(raw);
28851
- if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) return DEFAULT_MAX_RESULT_BYTES;
28852
- return Math.min(MAX_MAX_RESULT_BYTES, Math.max(MIN_MAX_RESULT_BYTES, n));
28853
- }
28854
- /**
28855
- * Return the longest prefix of `text` whose UTF-8 encoding is at most
28856
- * `maxBytes` long, cut on a codepoint boundary (never mid-multibyte).
28857
- */
28858
- function utf8HeadPreview(text, maxBytes) {
28859
- if (maxBytes <= 0) return "";
28860
- const buf = Buffer.from(text, "utf8");
28861
- if (buf.length <= maxBytes) return text;
28862
- let end = maxBytes;
28863
- while (end > 0 && (buf[end] & 192) === 128) end--;
28864
- return buf.subarray(0, end).toString("utf8");
28865
- }
28866
- /**
28867
- * Best-effort age sweep of router-written overflow files under
28868
- * `WORKER_DIFFS_DIR`. Only removes entries whose NAME matches
28869
- * `WORKER_DIFF_NAME_RE` and whose mtime is older than 7 days — a fresh
28870
- * file a concurrent worker just wrote (new mtime) is never touched, and
28871
- * a locked file just skips. Errors are swallowed so a sweep never blocks
28872
- * the write it precedes.
28873
- *
28874
- * `opts.throttle` (used by the write hot path) skips the readdir/stat scan
28875
- * when a throttled sweep ran within the last minute, so concurrent overflow
28876
- * writes don't each re-scan the directory. Direct callers (and tests) sweep
28877
- * unconditionally.
28878
- */
28879
- async function sweepAgedWorkerDiffs(opts = {}) {
28880
- if (opts.throttle) {
28881
- const now = Date.now();
28882
- if (now - lastThrottledSweepAt < SWEEP_THROTTLE_MS) return;
28883
- lastThrottledSweepAt = now;
28884
- }
28885
- let entries;
28886
- try {
28887
- entries = await fs$1.readdir(PATHS.WORKER_DIFFS_DIR);
28888
- } catch {
28889
- return;
28890
- }
28891
- const now = Date.now();
28892
- for (const name of entries) {
28893
- if (!WORKER_DIFF_NAME_RE.test(name)) continue;
28894
- const full = path.join(PATHS.WORKER_DIFFS_DIR, name);
28895
- try {
28896
- if (now - (await fs$1.stat(full)).mtimeMs < AGE_SWEEP_MS$1) continue;
28897
- await fs$1.rm(full, { force: true }).catch(() => {});
28898
- } catch {}
28899
- }
28900
- }
28901
- /**
28902
- * Write `text` in full to a durable `.txt` under `WORKER_DIFFS_DIR` and
28903
- * return its absolute path. Unique `<pid>-<8hex>.txt` name, `0o600`,
28904
- * exclusive-create (`wx`) so it never clobbers a pre-existing file /
28905
- * symlink. Retries on the (astronomically rare) name collision with a
28906
- * fresh suffix. Sweeps aged files first (throttled, best-effort).
28907
- */
28908
- async function saveOverflowResult(text) {
28909
- await sweepAgedWorkerDiffs({ throttle: true });
28910
- await fs$1.mkdir(PATHS.WORKER_DIFFS_DIR, { recursive: true });
28911
- let lastErr;
28912
- for (let attempt = 0; attempt < 5; attempt++) {
28913
- const name = `${process$1.pid}-${randomBytes(4).toString("hex")}.txt`;
28914
- const outPath = path.join(PATHS.WORKER_DIFFS_DIR, name);
28915
- try {
28916
- await fs$1.writeFile(outPath, text, {
28917
- mode: 384,
28918
- flag: "wx"
28919
- });
28920
- return outPath;
28921
- } catch (err) {
28922
- if (err.code !== "EEXIST") throw err;
28923
- lastErr = err;
28924
- }
28925
- }
28926
- throw lastErr instanceof Error ? lastErr : /* @__PURE__ */ new Error("saveOverflowResult: exhausted unique-name retries");
28927
- }
28928
- /**
28929
- * Cap a worker result to a relay-safe size. `reservedBytes` is the UTF-8
28930
- * byte length of any must-survive envelope the caller will add OUTSIDE this
28931
- * result (a `clampNote`/`worktreeNote` prefix, or the browse
28932
- * `[browse session: id]` suffix), so the caller's final `envelope + result`
28933
- * (or `result + envelope`) is guaranteed `<=` the configured cap.
28934
- *
28935
- * If the text fits under the effective cap it is returned unchanged.
28936
- * Otherwise the FULL text is spilled to a durable file and a bounded
28937
- * UTF-8-safe head preview + the file path is returned. On write failure the
28938
- * preview is still returned with an explicit failure note — NEVER the
28939
- * oversized original (that would re-trigger the overflow this guard prevents).
28940
- */
28941
- async function relaySafeText(text, reservedBytes = 0) {
28942
- const cap = Math.max(0, resolveMaxResultBytes() - Math.max(0, reservedBytes));
28943
- if (Buffer.byteLength(text, "utf8") <= cap) return text;
28944
- let savedPath = null;
28945
- let saveError = null;
28946
- try {
28947
- savedPath = await saveOverflowResult(text);
28948
- } catch (err) {
28949
- saveError = err instanceof Error ? err.message : String(err);
28950
- }
28951
- const trailer = savedPath !== null ? `\n\n[result truncated to fit the relay; full result saved to: ${savedPath}]` : `\n\n[result truncated to fit the relay; saving the full result failed: ${saveError ?? "unknown"}]`;
28952
- const out = utf8HeadPreview(text, Math.max(0, cap - Buffer.byteLength(trailer, "utf8"))) + trailer;
28953
- return Buffer.byteLength(out, "utf8") <= cap ? out : utf8HeadPreview(out, cap);
28954
- }
28955
- //#endregion
28956
30329
  //#region src/lib/worker-agent/worktree.ts
28957
30330
  /**
28958
30331
  * Git worktree provisioning for `worker_implement({worktree: true})`.
@@ -29773,7 +31146,7 @@ async function runWorkerAgentOnce(opts) {
29773
31146
  if (a.trim()) terminalText = a;
29774
31147
  }
29775
31148
  },
29776
- shouldStopAfterTurn: () => budget.hardStopReason !== null,
31149
+ finishTurn: () => budget.hardStopReason !== null ? { action: "end" } : void 0,
29777
31150
  afterToolCall: async (ctx) => {
29778
31151
  budget.recordToolBytes(ctx.result);
29779
31152
  if (ctxBudget) {
@@ -31359,7 +32732,9 @@ const MCP_GROUPS = Object.freeze([
31359
32732
  "browser",
31360
32733
  "decide",
31361
32734
  "fleet",
31362
- "first-mate"
32735
+ "first-mate",
32736
+ "ado",
32737
+ "kusto"
31363
32738
  ]);
31364
32739
  const GROUP_META = Object.freeze({
31365
32740
  peers: {
@@ -31401,6 +32776,16 @@ const GROUP_META = Object.freeze({
31401
32776
  preferredKey: "first-mate",
31402
32777
  urlSuffix: "first-mate",
31403
32778
  serverInfoName: "github-router-first-mate"
32779
+ },
32780
+ ado: {
32781
+ preferredKey: "ado",
32782
+ urlSuffix: "ado",
32783
+ serverInfoName: "github-router-ado"
32784
+ },
32785
+ kusto: {
32786
+ preferredKey: "kusto",
32787
+ urlSuffix: "kusto",
32788
+ serverInfoName: "github-router-kusto"
31404
32789
  }
31405
32790
  });
31406
32791
  /** True iff `s` is a registered group name (route `:group` param validation). */
@@ -32132,6 +33517,34 @@ function formatWebSearchResult(results) {
32132
33517
  return `${results.content}\n\n## References\n${refsLine}`;
32133
33518
  }
32134
33519
  /**
33520
+ * Model-override tier ladder surfaced on the read-heavy workers
33521
+ * (explore / implement / review). The caller picks a model by task weight;
33522
+ * all three tiers are 1M-context, and `high` is the recommended reasoning
33523
+ * depth for the ladder (sol/terra go higher if the caller wants). Appended to
33524
+ * those tools' `model` param description so the lead has actionable override
33525
+ * guidance instead of a bare free string. Luna owns the light tier because it
33526
+ * is both cheaper and faster than the prior Gemini Flash entry; no quality
33527
+ * ranking is implied.
33528
+ */
33529
+ const WORKER_TIER_GUIDANCE = " Override by task weight: `gpt-5.6-sol` (heavy/deep), `gpt-5.6-terra` (moderate), `gpt-6-luna` (light/cheap) — all 1M context; pair with thinking:'high'.";
33530
+ /**
33531
+ * Read-only contract, appended to the `explore` / `review` / `plan` tool
33532
+ * descriptions.
33533
+ *
33534
+ * Those three say "read-only" of their TOOLSET, which describes what the worker
33535
+ * may do but not what the caller gets back. The consequence is the part a caller
33536
+ * acts on: the returned text is the ONLY artifact. Nothing is written, nothing
33537
+ * is staged, and the transcript is not persisted — so a caller that wanted a
33538
+ * file changed has to route to `implement`, and a caller that wanted the
33539
+ * findings kept has to keep them itself.
33540
+ *
33541
+ * This is not redundant with "read-only toolset": a model reading "it has
33542
+ * read-only tools" can still reasonably expect the worker to leave something
33543
+ * behind (a report file, a scratch note). Stating the output contract closes
33544
+ * that gap in one clause.
33545
+ */
33546
+ const WORKER_READ_ONLY_NOTE = " Strictly read-only: it changes nothing on disk, and its returned text is the only artifact it produces — route to `implement` or `test` when a file actually needs to change.";
33547
+ /**
32135
33548
  * Build the `code` tool description for the launch's search capability.
32136
33549
  * When semantic search is available the default mode ranks by meaning via
32137
33550
  * ColBERT with transparent lexical fallback; otherwise the tool is described
@@ -32171,6 +33584,23 @@ function buildBluebirdCodeToolDescription() {
32171
33584
  function buildBluebirdCodeModeDescription() {
32172
33585
  return "Search mode. 'semantic' (DEFAULT): Bluebird vector search over the Azure DevOps index (meaning-ranked; failures surface as `source:\"error\"` with no silent local fallback). 'lexical': Bluebird indexed ranked-keyword search — best for exact symbols. 'exact': local fixed-string, ripgrep document order. 'regex': local PCRE2, ripgrep document order. 'ast': local ast-grep structural match (requires `ast_pattern` + `ast_lang`).";
32173
33586
  }
33587
+ /**
33588
+ * Oversized-result contract, appended to EVERY `worker_*` tool description.
33589
+ *
33590
+ * `relaySafeText` (`~/lib/worker-agent/relay-cap`) is the final transform at
33591
+ * the MCP boundary for every worker mode: a result over the relay cap spills IN
33592
+ * FULL to a file and returns a bounded head preview plus that path. The
33593
+ * mechanism already worked; what was missing is that the model was never TOLD,
33594
+ * so a truncated result arrived with a path the model had to infer was real and
33595
+ * readable from the trailer alone.
33596
+ *
33597
+ * It earns its bytes under the "ruthlessly minimal tool surface" rule because
33598
+ * it is directly actionable: on truncation the next call is a `read` of that
33599
+ * path, not a re-run of the worker. That matters most on the read-only modes
33600
+ * (`explore`/`review`/`plan`), where the transcript is never persisted and a
33601
+ * long investigation summarized past the cap is otherwise unrecoverable.
33602
+ */
33603
+ const WORKER_OVERSIZED_RESULT_NOTE = " If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.";
32174
33604
  const NON_PERSONA_MCP_TOOLS = Object.freeze([
32175
33605
  {
32176
33606
  toolNameHttp: "web",
@@ -32360,6 +33790,73 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32360
33790
  }
32361
33791
  }
32362
33792
  },
33793
+ {
33794
+ toolNameHttp: "prompt_brief",
33795
+ group: "search",
33796
+ hookOnly: true,
33797
+ description: "Internal hook channel: returns the cheapest-profile grounded execution brief for one user prompt. Called by the Pi extension's before_agent_start handler, never by the model. Returns an empty text block when the profile is not cheapest, the prompt is trivial, the session already spent its rewrite, or the rewrite missed.",
33798
+ inputSchema: {
33799
+ type: "object",
33800
+ required: ["prompt", "session_id"],
33801
+ additionalProperties: false,
33802
+ properties: {
33803
+ prompt: {
33804
+ type: "string",
33805
+ description: "The user prompt to brief, verbatim."
33806
+ },
33807
+ session_id: {
33808
+ type: "string",
33809
+ description: "Pi session id. Keys the one-shot per-session rewrite flag, so the first non-trivial prompt of a session spends the rewrite and later prompts reuse the brief the model already has."
33810
+ },
33811
+ workspace: {
33812
+ type: "string",
33813
+ description: "Absolute path to search for grounding. Defaults to the session workspace header when omitted."
33814
+ }
33815
+ }
33816
+ },
33817
+ async handler(args, signal, ctx) {
33818
+ const prompt = typeof args.prompt === "string" ? args.prompt : "";
33819
+ const sessionId = typeof args.session_id === "string" ? args.session_id : "";
33820
+ const workspace = typeof args.workspace === "string" ? args.workspace : "";
33821
+ if (prompt.trim().length === 0 || sessionId.trim().length === 0) return {
33822
+ content: [{
33823
+ type: "text",
33824
+ text: "prompt_brief: arguments.prompt and arguments.session_id are required (non-empty strings)"
33825
+ }],
33826
+ isError: true
33827
+ };
33828
+ try {
33829
+ return { content: [{
33830
+ type: "text",
33831
+ text: (await runHookPromptBrief({
33832
+ prompt,
33833
+ sessionId,
33834
+ workspace,
33835
+ profile: ctx?.profileId ?? "standard",
33836
+ searchEnabled: state.searchEnabled === true,
33837
+ bluebirdEnabled: state.bluebirdEnabled === true,
33838
+ signal,
33839
+ infer: (system, user, callSignal) => dispatchModelCall({
33840
+ model: "gpt-5.6-sol",
33841
+ endpoint: "/v1/responses",
33842
+ instructions: system,
33843
+ userText: user,
33844
+ effort: "medium",
33845
+ signal: callSignal
33846
+ })
33847
+ })).brief ?? ""
33848
+ }] };
33849
+ } catch (err) {
33850
+ return {
33851
+ content: [{
33852
+ type: "text",
33853
+ text: `prompt_brief failed: ${err instanceof Error ? err.message : String(err)}`
33854
+ }],
33855
+ isError: true
33856
+ };
33857
+ }
33858
+ }
33859
+ },
32363
33860
  {
32364
33861
  toolNameHttp: "worker_defaults",
32365
33862
  group: "workers",
@@ -32438,7 +33935,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32438
33935
  toolNameHttp: "explore",
32439
33936
  group: "workers",
32440
33937
  capability: "worker",
32441
- description: "Runs as the background `worker-explore` agent. Dispatch via the Agent tool (subagent_type: worker-explore) so the turn is never blocked; the result arrives as a completion notification. Read-only investigation by an autonomous worker (Pi runtime; default model `gpt-6-luna` at high reasoning, override via the `model` arg with any Copilot-catalog model that advertises `tool_calls`). It has read, glob, grep, semantic-first code search, web search, fetch_url, advisor, update_plan, and read-only toolbelt tools, and it returns a single text answer. Use for bounded research, repo discovery, dependency investigation, or multi-file reading that would otherwise consume the lead context window. Not for implementation, test authoring, or verification of a concrete diff; use implement, test, or review for those scopes. Brief the investigation goal and constraints, not step-by-step tool semantics. Strictly read-only: it changes nothing on disk, and its returned text is the only artifact it produces — route to `implement` or `test` when a file actually needs to change. If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.",
33938
+ description: "Runs as the background `worker-explore` agent. Dispatch via the Agent tool (subagent_type: worker-explore) so the turn is never blocked; the result arrives as a completion notification. Read-only investigation by an autonomous worker (Pi runtime; default model `gpt-6-luna` at high reasoning, override via the `model` arg with any Copilot-catalog model that advertises `tool_calls`). It has read, glob, grep, semantic-first code search, web search, fetch_url, advisor, update_plan, and read-only toolbelt tools, and it returns a single text answer. Use for bounded research, repo discovery, dependency investigation, or multi-file reading that would otherwise consume the lead context window. Not for implementation, test authoring, or verification of a concrete diff; use implement, test, or review for those scopes. Brief the investigation goal and constraints, not step-by-step tool semantics." + WORKER_READ_ONLY_NOTE + WORKER_OVERSIZED_RESULT_NOTE,
32442
33939
  inputSchema: {
32443
33940
  type: "object",
32444
33941
  required: ["prompt"],
@@ -32450,7 +33947,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32450
33947
  },
32451
33948
  model: {
32452
33949
  type: "string",
32453
- description: "Optional Copilot catalog model id (defaults to gpt-6-luna). Must advertise tool_calls support; the engine emits an isError envelope listing the eligible catalog models on mismatch. Override by task weight: `gpt-5.6-sol` (heavy/deep), `gpt-5.6-terra` (moderate), `gpt-6-luna` (light/cheap) — all 1M context; pair with thinking:'high'."
33950
+ description: "Optional Copilot catalog model id (defaults to gpt-6-luna). Must advertise tool_calls support; the engine emits an isError envelope listing the eligible catalog models on mismatch." + WORKER_TIER_GUIDANCE
32454
33951
  },
32455
33952
  thinking: {
32456
33953
  type: "string",
@@ -32480,7 +33977,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32480
33977
  toolNameHttp: "implement",
32481
33978
  group: "workers",
32482
33979
  capability: "worker",
32483
- description: "Runs as the background `worker-implement` agent. Dispatch via the Agent tool (subagent_type: worker-implement) so the turn is never blocked; the result arrives as a completion notification. Delegates a scoped coding task to an autonomous worker (Pi runtime; default model `gpt-5.6-sol` at high reasoning, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has the explore read-only tools plus edit, write, bash, and codex_review, and it returns its final text with any changed files or worktree diff. Use for bounded implementation work that may take a while or benefits from isolated worker context. Not for pure research, planning, review, or independent test authoring; use explore, plan, review, or test for those scopes. ALWAYS runs in an isolated git worktree and returns the diff via a saved patch file (a `--stat` summary + a bounded preview + the patch path; a small diff is inlined in full) — it never edits your working tree, and it HARD-ERRORS if the workspace is not a git repository. For in-place edits, use the native `implementer` subagent. If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.",
33980
+ description: "Runs as the background `worker-implement` agent. Dispatch via the Agent tool (subagent_type: worker-implement) so the turn is never blocked; the result arrives as a completion notification. Delegates a scoped coding task to an autonomous worker (Pi runtime; default model `gpt-5.6-sol` at high reasoning, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has the explore read-only tools plus edit, write, bash, and codex_review, and it returns its final text with any changed files or worktree diff. Use for bounded implementation work that may take a while or benefits from isolated worker context. Not for pure research, planning, review, or independent test authoring; use explore, plan, review, or test for those scopes. ALWAYS runs in an isolated git worktree and returns the diff via a saved patch file (a `--stat` summary + a bounded preview + the patch path; a small diff is inlined in full) — it never edits your working tree, and it HARD-ERRORS if the workspace is not a git repository. For in-place edits, use the native `implementer` subagent." + WORKER_OVERSIZED_RESULT_NOTE,
32484
33981
  inputSchema: {
32485
33982
  type: "object",
32486
33983
  required: ["prompt"],
@@ -32496,7 +33993,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32496
33993
  },
32497
33994
  model: {
32498
33995
  type: "string",
32499
- description: "Optional Copilot catalog model id (defaults to gpt-5.6-sol). Must advertise tool_calls support; the engine emits an isError envelope listing the eligible catalog models on mismatch. Override by task weight: `gpt-5.6-sol` (heavy/deep), `gpt-5.6-terra` (moderate), `gpt-6-luna` (light/cheap) — all 1M context; pair with thinking:'high'."
33996
+ description: "Optional Copilot catalog model id (defaults to gpt-5.6-sol). Must advertise tool_calls support; the engine emits an isError envelope listing the eligible catalog models on mismatch." + WORKER_TIER_GUIDANCE
32500
33997
  },
32501
33998
  thinking: {
32502
33999
  type: "string",
@@ -32526,7 +34023,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32526
34023
  toolNameHttp: "review",
32527
34024
  group: "workers",
32528
34025
  capability: "worker",
32529
- description: "Runs as the background `worker-review` agent. Dispatch via the Agent tool (subagent_type: worker-review) so the turn is never blocked; the result arrives as a completion notification. Code review by an autonomous worker (Pi runtime; default model `gemini-3.1-pro-preview`, default thinking xhigh clamped to high for that model, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has explore's read-and-search tools PLUS `bash`, so it verifies claims by running them — reproducing a failure or running the build or suite — rather than only reading, and returns severity-ranked findings with `file:line` citations. It gets no edit/write tools unless you pass `worktree: true`, but `bash` runs real commands in the workspace, so a build or test it invokes can touch the tree. Use for reviewing a change, diff, or correctness claim when the reviewer should read the code itself rather than trusting a pasted artifact. Not for architecture critique, implementation, or test authoring; use codex_critic or gemini_critic for design review, implement for edits, and test for independent test creation. If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.",
34026
+ description: "Runs as the background `worker-review` agent. Dispatch via the Agent tool (subagent_type: worker-review) so the turn is never blocked; the result arrives as a completion notification. Code review by an autonomous worker (Pi runtime; default model `gemini-3.1-pro-preview`, default thinking xhigh clamped to high for that model, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has explore's read-and-search tools PLUS `bash`, so it verifies claims by running them — reproducing a failure or running the build or suite — rather than only reading, and returns severity-ranked findings with `file:line` citations. It gets no edit/write tools unless you pass `worktree: true`, but `bash` runs real commands in the workspace, so a build or test it invokes can touch the tree. Use for reviewing a change, diff, or correctness claim when the reviewer should read the code itself rather than trusting a pasted artifact. Not for architecture critique, implementation, or test authoring; use codex_critic or gemini_critic for design review, implement for edits, and test for independent test creation." + WORKER_OVERSIZED_RESULT_NOTE,
32530
34027
  inputSchema: {
32531
34028
  type: "object",
32532
34029
  required: ["prompt"],
@@ -32538,7 +34035,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32538
34035
  },
32539
34036
  model: {
32540
34037
  type: "string",
32541
- description: "Optional Copilot catalog model id (defaults to gemini-3.1-pro-preview). Must advertise tool_calls support; the engine emits an isError envelope listing the eligible catalog models on mismatch. Override by task weight: `gpt-5.6-sol` (heavy/deep), `gpt-5.6-terra` (moderate), `gpt-6-luna` (light/cheap) — all 1M context; pair with thinking:'high'."
34038
+ description: "Optional Copilot catalog model id (defaults to gemini-3.1-pro-preview). Must advertise tool_calls support; the engine emits an isError envelope listing the eligible catalog models on mismatch." + WORKER_TIER_GUIDANCE
32542
34039
  },
32543
34040
  thinking: {
32544
34041
  type: "string",
@@ -32572,7 +34069,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32572
34069
  toolNameHttp: "plan",
32573
34070
  group: "workers",
32574
34071
  capability: "worker",
32575
- description: "Runs as the background `worker-plan` agent. Dispatch via the Agent tool (subagent_type: worker-plan) so the turn is never blocked; the result arrives as a completion notification. Read-only implementation planning by an autonomous worker (Pi runtime; default model `claude-opus-5.5` at high reasoning, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has the same read-only toolset as explore and returns a concrete, ordered implementation plan covering files, approach, risks, and how acceptance criteria will be verified. Use before coding when the task needs repo-grounded sequencing or acceptance criteria translated into implementation steps. Not for editing files, running an implementation, writing tests, or adversarial review; use implement, test, or review for those scopes. Strictly read-only: it changes nothing on disk, and its returned text is the only artifact it produces — route to `implement` or `test` when a file actually needs to change. If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.",
34072
+ description: "Runs as the background `worker-plan` agent. Dispatch via the Agent tool (subagent_type: worker-plan) so the turn is never blocked; the result arrives as a completion notification. Read-only implementation planning by an autonomous worker (Pi runtime; default model `claude-opus-5.5` at high reasoning, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has the same read-only toolset as explore and returns a concrete, ordered implementation plan covering files, approach, risks, and how acceptance criteria will be verified. Use before coding when the task needs repo-grounded sequencing or acceptance criteria translated into implementation steps. Not for editing files, running an implementation, writing tests, or adversarial review; use implement, test, or review for those scopes." + WORKER_READ_ONLY_NOTE + WORKER_OVERSIZED_RESULT_NOTE,
32576
34073
  inputSchema: {
32577
34074
  type: "object",
32578
34075
  required: ["prompt"],
@@ -32614,7 +34111,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32614
34111
  toolNameHttp: "test",
32615
34112
  group: "workers",
32616
34113
  capability: "worker",
32617
- description: "Runs as the background `worker-test` agent. Dispatch via the Agent tool (subagent_type: worker-test) so the turn is never blocked; the result arrives as a completion notification. Independent adversarial test authoring by an autonomous worker (Pi runtime; default model `gpt-5.6-sol` at high reasoning, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has the same read/write toolset as implement and writes tests that try to break the implementation through edge cases, error paths, and acceptance criteria, then runs them and reports pass/fail. Use when a separate test author should challenge an implementation without modifying the production code to make tests pass. Not for implementing fixes, broad research, or code review; use implement, explore, or review for those scopes. ALWAYS runs in an isolated git worktree and returns the test diff via a saved patch file (a `--stat` summary + a bounded preview + the patch path; a small diff is inlined in full) — it never edits your working tree, and it HARD-ERRORS if the workspace is not a git repository. For in-place test authoring, use the native `implementer` subagent. If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.",
34114
+ description: "Runs as the background `worker-test` agent. Dispatch via the Agent tool (subagent_type: worker-test) so the turn is never blocked; the result arrives as a completion notification. Independent adversarial test authoring by an autonomous worker (Pi runtime; default model `gpt-5.6-sol` at high reasoning, override via `model` with any Copilot-catalog model that advertises `tool_calls`). It has the same read/write toolset as implement and writes tests that try to break the implementation through edge cases, error paths, and acceptance criteria, then runs them and reports pass/fail. Use when a separate test author should challenge an implementation without modifying the production code to make tests pass. Not for implementing fixes, broad research, or code review; use implement, explore, or review for those scopes. ALWAYS runs in an isolated git worktree and returns the test diff via a saved patch file (a `--stat` summary + a bounded preview + the patch path; a small diff is inlined in full) — it never edits your working tree, and it HARD-ERRORS if the workspace is not a git repository. For in-place test authoring, use the native `implementer` subagent." + WORKER_OVERSIZED_RESULT_NOTE,
32618
34115
  inputSchema: {
32619
34116
  type: "object",
32620
34117
  required: ["prompt"],
@@ -32862,7 +34359,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32862
34359
  toolNameHttp: "browse",
32863
34360
  group: "workers",
32864
34361
  capability: "browse_agent",
32865
- description: "Runs as the background `worker-browse` agent. Dispatch via the Agent tool (subagent_type: worker-browse) so the turn is never blocked; the result arrives as a completion notification. A Pi-driven autonomous browser worker (default model `gpt-6-luna`) drives a real browser to accomplish `task`, keeps raw DOM and page snapshots inside its own context, and returns a single text result. Use for delegated multi-step web tasks such as comparing prices, logging into a dashboard, or summarizing pages when the lead does not need to steer each click. Not for direct in-context browser control, screenshots, or precise element interactions; use the `browser` MCP tools for those. Pass `sessionId` to continue a prior browse session, or omit it for a fresh isolated session; multiple calls run as parallel sessions on the shared browser. If the result is too large to relay it is truncated to a preview and the FULL text is written to a file, whose absolute path is in the returned text; read that file rather than re-running the worker.",
34362
+ description: "Runs as the background `worker-browse` agent. Dispatch via the Agent tool (subagent_type: worker-browse) so the turn is never blocked; the result arrives as a completion notification. A Pi-driven autonomous browser worker (default model `gpt-6-luna`) drives a real browser to accomplish `task`, keeps raw DOM and page snapshots inside its own context, and returns a single text result. Use for delegated multi-step web tasks such as comparing prices, logging into a dashboard, or summarizing pages when the lead does not need to steer each click. Not for direct in-context browser control, screenshots, or precise element interactions; use the `browser` MCP tools for those. Pass `sessionId` to continue a prior browse session, or omit it for a fresh isolated session; multiple calls run as parallel sessions on the shared browser." + WORKER_OVERSIZED_RESULT_NOTE,
32866
34363
  inputSchema: {
32867
34364
  type: "object",
32868
34365
  required: ["task"],
@@ -32946,9 +34443,26 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32946
34443
  ...t,
32947
34444
  group: "browser",
32948
34445
  toolNameHttp: t.toolNameHttp.replace(/^browser_/, "")
32949
- }))
34446
+ })),
34447
+ ...KUSTO_TOOLS
32950
34448
  ]);
32951
34449
  /**
34450
+ * Every MCP tool name the proxy serves itself: the personas (definitionally the
34451
+ * `peers` group) plus the non-persona utilities.
34452
+ *
34453
+ * Exported because a dynamic upstream listing has to refuse these too. The
34454
+ * Azure DevOps server forwards `tools/list` verbatim, so an upstream rename
34455
+ * could hand back a name this proxy already owns; `handleToolsCall` keys
34456
+ * dispatch on the bare name, so the caller would see the tool listed and reach
34457
+ * the proxy's own handler instead.
34458
+ */
34459
+ function proxyOwnedMcpToolNames() {
34460
+ const names = /* @__PURE__ */ new Set();
34461
+ for (const p of [...PERSONAS_READ, ...PERSONAS_WRITE]) names.add(p.toolNameHttp);
34462
+ for (const t of NON_PERSONA_MCP_TOOLS) names.add(t.toolNameHttp);
34463
+ return names;
34464
+ }
34465
+ /**
32952
34466
  * Startup invariant: every MCP tool name must be unique within its group
32953
34467
  * AND across the unscoped `/mcp` union. `handleToolsCall` keys dispatch on
32954
34468
  * the bare tool name, so a duplicate would silently shadow — this assertion
@@ -33337,6 +34851,6 @@ function enumerateInjectedMcpToolNames(groupKeys, opts = {}) {
33337
34851
  return [...new Set(names)];
33338
34852
  }
33339
34853
  //#endregion
33340
- export { readIteratorWithTimeout as $, createChatCompletions as $t, TOOLBELT_TOOLS$1 as A, oneMContextDisabled as An, generalPurposeFastModel as At, injectAdvisorTool as B, CHEAPEST_PROFILE_ORACLE_EFFORT as Bn, shimDefaultsToXhigh as Bt, runWorkerAgent as C, isBudgetClaudeLead as Cn, fastGeneralPurposeModel as Ct, toolbeltEnabled as D, upstreamMaxConnections as Dn, fastScoutModel as Dt, buildToolbeltAwareness as E, upstreamAllowH2 as En, fastReviewerModel as Et, ADVISOR_TOOL_INSTRUCTIONS as F, CHEAPEST_PROFILE_ADVISOR_MODEL as Fn, reviewerModel as Ft, formatThinkingRepairDecline as G, CHEAP_PROFILE_NATIVE_AGENT_NAMES as Gn, getTokenizerFromModel as Gt, resolveAdvisorEffort as H, CHEAPEST_PROFILE_SUBAGENT_CONTEXT_TOKENS as Hn, createMessages as Ht, CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS as I, CHEAPEST_PROFILE_MODELS as In, scoutModel as It, repairRejectedThinkingHistory as J, CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS as Jn, unregisterLaunch as Jt, rememberThinkingHistoryRepair as K, CHEAP_PROFILE_NATIVE_EFFORTS as Kn, findLaunchBySecret as Kt, CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS as L, CHEAPEST_PROFILE_NATIVE_AGENT_NAMES as Ln, scribeModel as Lt, satisfiesMinVersion as M, withOneMSuffixForLead as Mn, nativeSubagentModel as Mt, searchWeb as N, CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL as Nn, resolveGeminiReviewModel as Nt, toolbeltSkipSet as O, classifyMessagesRoute as On, fleetToolsEnabled as Ot, ADVISOR_INTERNAL_TOOL_NAME as P, CHEAPEST_PROFILE_ADVISOR_EFFORT as Pn, reviewerFastModel as Pt, logStreamError as Q, createResponses as Qt, FAST_ADVISOR_TOOL_INSTRUCTIONS as R, CHEAPEST_PROFILE_NATIVE_EFFORTS as Rn, standInToolEnabled as Rt, resolveWorkerRunOpts as S, generateRandomPort as Sn, fastAstraModel as St, availableToolCommands as T, resolveLeadSlugArg as Tn, fastPlanModel as Tt, resolveAdvisorModel as U, CHEAP_PROFILE_ADVISOR_CLIENT_MODEL as Un, getTextTokenCount as Ut, isAdvisorRequested as V, CHEAPEST_PROFILE_ORACLE_MODEL as Vn, countTokens as Vt, resolveCheapestAdvisorModel as W, CHEAP_PROFILE_MODELS as Wn, getTokenCount as Wt, buildOpenAIErrorEvent as X, warnOnTokenPriceDrift as Xt, buildAnthropicErrorEvent as Y, assembleResponsesPayload as Yt, isControllerClosedError as Z, resolveMcpToolTimeoutMs as Zt, REVIEW_DEFAULT_MODEL as _, DEFAULT_CODEX_MODEL as _n, cheapReviewerModel as _t, buildAgentPrompt as a, hasSupportedBrowserInstalled as an, handleMcpDelete as at, resolveDefaultModel as b, UPSTREAM_FETCH_TIMEOUT_MS as bn, cheapestReviewerModel as bt, enumerateInjectedMcpToolNames as c, semanticSearchOptedIn as cn, artifactToolsEnabled as ct, BROWSE_DEFAULT_MODEL as d, shouldUseInsecureTls as dn, brainstormModel as dt, MAX_RESPONSE_BODY_BYTES as en, relayAnthropicStream as et, DEFAULT_MODEL_CHAIN as f, collapsePathKeys as fn, browseAgentEnabled as ft, PLAN_DEFAULT_MODEL as g, DEFAULT_CLAUDE_MODEL_FALLBACKS as gn, cheapOracleModel as gt, IMPLEMENT_DEFAULT_MODEL as h, BUDGET_SMALL_FAST_SLUG as hn, cheapAdvisorModel as ht, assertMcpToolSurfaceConsistent as i, provisionBrowserAssets as in, clampEffort as it, assetFor as j, withOneMSuffix as jn, implementerFastModel as jt, vscodeRipgrepPath as k, catalogAdvertises1M as kn, geminiAvailable as kt, maxPersonasFor as l, CONDENSED_OPERATING_SEQUENCE as ln, balancedOracleModel as lt, EXPLORE_DEFAULT_THINKING as m, BUDGET_SMALL_FAST_CATALOG_ID as mn, browserToolsEnabled as mt, MCP_GROUPS as n, parseJsonOrDiagnose as nn, UNKNOWN_EFFORT_ANCHOR as nt, buildPeerAwarenessSnippet as o, colbertDegradedWarning as on, handleMcpPost as ot, EXPLORE_DEFAULT_MODEL as p, toolbeltPathOverride as pn, browserCompoundToolsEnabled as pt, repairKnownThinkingHistory as q, CHEAP_PROFILE_NATIVE_MODELS as qn, registerLaunch as qt, agentNamesForToolAllowlist as r, normalizeOpenAIUsage as rn, bucketEffort as rt, buildPeerAwarenessSummary as s, provisionAndIndexColbert as sn, agentToolsEnabled as st, GROUP_META as t, readResponseBodyCapped as tn, EFFORT_ORDER as tt, personasFor as u, DEFINITION_OF_GREATNESS as un, balancedReviewerModel as ut, TEST_DEFAULT_MODEL as v, DEFAULT_CODEX_MODEL_FALLBACKS as vn, cheapestAdvisorModel as vt, buildEnv as w, pickClaudeDefault as wn, fastOracleModel as wt, resolveModeDefaults as x, UPSTREAM_INACTIVITY_TIMEOUT_MS as xn, fastAdvisorModel as xt, appendPlanReminder as y, DEFAULT_PORT as yn, cheapestOracleModel as yt, buildAdvisorStream as z, CHEAPEST_PROFILE_NATIVE_MODELS as zn, workerToolsEnabled as zt };
34854
+ export { readIteratorWithTimeout as $, CHEAP_PROFILE_MODELS as $n, getTokenizerFromModel as $t, TOOLBELT_TOOLS$1 as A, UPSTREAM_INACTIVITY_TIMEOUT_MS as An, fastGeneralPurposeModel as At, injectAdvisorTool as B, withOneMSuffix as Bn, nativeSubagentModel as Bt, runWorkerAgent as C, BUDGET_SMALL_FAST_CATALOG_ID as Cn, cheapOracleModel as Ct, toolbeltEnabled as D, DEFAULT_CODEX_MODEL_FALLBACKS as Dn, cheapestReviewerModel as Dt, buildToolbeltAwareness as E, DEFAULT_CODEX_MODEL as En, cheapestOracleModel as Et, ADVISOR_TOOL_INSTRUCTIONS as F, upstreamAllowH2 as Fn, fleetToolsEnabled as Ft, formatThinkingRepairDecline as G, CHEAPEST_PROFILE_MODELS as Gn, scribeModel as Gt, resolveAdvisorEffort as H, CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL as Hn, reviewerFastModel as Ht, CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS as I, upstreamMaxConnections as In, geminiAvailable as It, repairRejectedThinkingHistory as J, CHEAPEST_PROFILE_NATIVE_MODELS as Jn, shimDefaultsToXhigh as Jt, rememberThinkingHistoryRepair as K, CHEAPEST_PROFILE_NATIVE_AGENT_NAMES as Kn, standInToolEnabled as Kt, CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS as L, classifyMessagesRoute as Ln, generalPurposeFastModel as Lt, satisfiesMinVersion as M, isBudgetClaudeLead as Mn, fastPlanModel as Mt, searchWeb as N, pickClaudeDefault as Nn, fastReviewerModel as Nt, toolbeltSkipSet as O, DEFAULT_PORT as On, fastAdvisorModel as Ot, ADVISOR_INTERNAL_TOOL_NAME as P, resolveLeadSlugArg as Pn, fastScoutModel as Pt, logStreamError as Q, CHEAP_PROFILE_ADVISOR_CLIENT_MODEL as Qn, getTokenCount as Qt, FAST_ADVISOR_TOOL_INSTRUCTIONS as R, catalogAdvertises1M as Rn, implementerFastModel as Rt, resolveWorkerRunOpts as S, toolbeltPathOverride as Sn, cheapAdvisorModel as St, availableToolCommands as T, DEFAULT_CLAUDE_MODEL_FALLBACKS as Tn, cheapestAdvisorModel as Tt, resolveAdvisorModel as U, CHEAPEST_PROFILE_ADVISOR_EFFORT as Un, reviewerModel as Ut, isAdvisorRequested as V, withOneMSuffixForLead as Vn, resolveGeminiReviewModel as Vt, resolveCheapestAdvisorModel as W, CHEAPEST_PROFILE_ADVISOR_MODEL as Wn, scoutModel as Wt, buildOpenAIErrorEvent as X, CHEAPEST_PROFILE_ORACLE_MODEL as Xn, createMessages as Xt, buildAnthropicErrorEvent as Y, CHEAPEST_PROFILE_ORACLE_EFFORT as Yn, countTokens as Yt, isControllerClosedError as Z, CHEAPEST_PROFILE_SUBAGENT_CONTEXT_TOKENS as Zn, getTextTokenCount as Zt, REVIEW_DEFAULT_MODEL as _, colbertDegradedWarning as _n, balancedReviewerModel as _t, buildAgentPrompt as a, resolveMcpToolTimeoutMs as an, handleMcpDelete as at, resolveDefaultModel as b, shouldUseInsecureTls as bn, browserCompoundToolsEnabled as bt, enumerateInjectedMcpToolNames as c, MAX_RESPONSE_BODY_BYTES as cn, buildAdoToolEntries as ct, BROWSE_DEFAULT_MODEL as d, normalizeOpenAIUsage as dn, ADO_DEFAULT_TOOLSETS as dt, findLaunchBySecret as en, CHEAP_PROFILE_NATIVE_AGENT_NAMES as er, relayAnthropicStream as et, DEFAULT_MODEL_CHAIN as f, provisionBrowserAssets as fn, normalizeAdoToolsets as ft, PLAN_DEFAULT_MODEL as g, DEFINITION_OF_GREATNESS as gn, balancedOracleModel as gt, IMPLEMENT_DEFAULT_MODEL as h, CONDENSED_OPERATING_SEQUENCE as hn, artifactToolsEnabled as ht, assertMcpToolSurfaceConsistent as i, warnOnTokenPriceDrift as in, clampEffort as it, assetFor as j, generateRandomPort as jn, fastOracleModel as jt, vscodeRipgrepPath as k, UPSTREAM_FETCH_TIMEOUT_MS as kn, fastAstraModel as kt, maxPersonasFor as l, readResponseBodyCapped as ln, disposeAdoClients as lt, EXPLORE_DEFAULT_THINKING as m, normalizeKustoClusterUri as mn, agentToolsEnabled as mt, MCP_GROUPS as n, unregisterLaunch as nn, CHEAP_PROFILE_NATIVE_MODELS as nr, UNKNOWN_EFFORT_ANCHOR as nt, buildPeerAwarenessSnippet as o, createResponses as on, handleMcpPost as ot, EXPLORE_DEFAULT_MODEL as p, hasSupportedBrowserInstalled as pn, adoToolsEnabled as pt, repairKnownThinkingHistory as q, CHEAPEST_PROFILE_NATIVE_EFFORTS as qn, workerToolsEnabled as qt, agentNamesForToolAllowlist as r, assembleResponsesPayload as rn, CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS as rr, bucketEffort as rt, buildPeerAwarenessSummary as s, createChatCompletions as sn, adoMcpToolEntries as st, GROUP_META as t, registerLaunch as tn, CHEAP_PROFILE_NATIVE_EFFORTS as tr, EFFORT_ORDER as tt, personasFor as u, parseJsonOrDiagnose as un, provisionAdoTools as ut, TEST_DEFAULT_MODEL as v, provisionAndIndexColbert as vn, brainstormModel as vt, buildEnv as w, BUDGET_SMALL_FAST_SLUG as wn, cheapReviewerModel as wt, resolveModeDefaults as x, collapsePathKeys as xn, browserToolsEnabled as xt, appendPlanReminder as y, semanticSearchOptedIn as yn, browseAgentEnabled as yt, buildAdvisorStream as z, oneMContextDisabled as zn, kustoToolsEnabled as zt };
33341
34855
 
33342
- //# sourceMappingURL=peer-mcp-personas-BwwSNnBC.js.map
34856
+ //# sourceMappingURL=peer-mcp-personas-DDMKRFFG.js.map