github-router 0.3.351 → 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-DE0207hK.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-YVz8FA1M.js → claude-xO1XW-Nn.js} +60 -48
  22. package/dist/claude-xO1XW-Nn.js.map +1 -0
  23. package/dist/{codex-B-znDU1X.js → codex-DzUR40JA.js} +10 -8
  24. package/dist/{codex-B-znDU1X.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-D--As1HS.js → gate-discovery-Cvdko01z.js} +6 -6
  33. package/dist/{gate-discovery-D--As1HS.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-DJAFilW6.js → internal-stop-hook-DGcRVh_2.js} +7 -7
  65. package/dist/{internal-stop-hook-DJAFilW6.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-D_gRB57l.js → peer-mcp-personas-DDMKRFFG.js} +2336 -834
  92. package/dist/peer-mcp-personas-DDMKRFFG.js.map +1 -0
  93. package/dist/{pi-DpVcRXlA.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-CCLXOWVZ.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-D7aq-iiE.js → serve-CmgmxigM.js} +35 -17
  102. package/dist/serve-CmgmxigM.js.map +1 -0
  103. package/dist/{server-setup-B8LyRuEN.js → server-setup-DinOFWiC.js} +352 -27
  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-BVP3nqIr.js → start-Dgsaz0HM.js} +4 -4
  108. package/dist/{start-BVP3nqIr.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-DE0207hK.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-YVz8FA1M.js.map +0 -1
  128. package/dist/engine-Bbhs1trv.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-D_gRB57l.js.map +0 -1
  141. package/dist/pi-DpVcRXlA.js.map +0 -1
  142. package/dist/prompt-submit-hook-DzhmQRs_.js.map +0 -1
  143. package/dist/provision-CCLXOWVZ.js.map +0 -1
  144. package/dist/serve-D7aq-iiE.js.map +0 -1
  145. package/dist/server-setup-B8LyRuEN.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
@@ -1152,6 +1150,537 @@ function enumProp$1(values, description) {
1152
1150
  };
1153
1151
  }
1154
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
1155
1684
  //#region src/lib/gemini-review-model.ts
1156
1685
  const GEMINI_REVIEW_DEFAULT_MODEL = "gemini-3.1-pro-preview";
1157
1686
  //#endregion
@@ -4081,9 +4610,11 @@ async function getRequiredChecksForSha(repo, sha) {
4081
4610
  const anyPending = runningCount > 0 || legacyPending || checkRunsIncomplete;
4082
4611
  const anySignal = checkRuns.length > 0 || hasLegacyStatuses || checkRunsIncomplete;
4083
4612
  let rollup = "none";
4084
- if (anySignal) if (anyFailing) rollup = "failing";
4085
- else if (anyPending) rollup = "pending";
4086
- else rollup = "passing";
4613
+ if (anySignal) {
4614
+ if (anyFailing) rollup = "failing";
4615
+ else if (anyPending) rollup = "pending";
4616
+ else rollup = "passing";
4617
+ }
4087
4618
  const checks = checkRuns.slice(0, CHECK_SUMMARY_LIMIT).map((check) => ({
4088
4619
  id: check.id ?? 0,
4089
4620
  name: check.name ?? "",
@@ -7756,25 +8287,26 @@ async function observeBlockedUnit(unit, deps, applied) {
7756
8287
  const mergedPr = observed.prs.find((pr) => pr.merged || pr.state === "MERGED");
7757
8288
  const mergedIsPinned = mergedPr != null && unit.pr != null && mergedPr.number === unit.pr;
7758
8289
  const floorHeadMatches = unit.floorSha != null && unit.floorSha.length > 0 && mergedPr != null && mergedPr.headSha.length > 0 && mergedPr.headSha === unit.floorSha;
7759
- if (mutation === "merged") if (decision?.type === "merge_approval" && mergedIsPinned && floorHeadMatches && unit.validation === "floor_passed") {
7760
- unit.terminal = true;
7761
- unit.phase = "done";
7762
- unit.artifact = "pr_merged";
7763
- unit.validation = "floor_passed";
7764
- unit.blockingDecisionId = null;
7765
- await answer("superseded_external_merge");
7766
- applied.push(`reconciled approved external merge for ${repoLabel$1(unit.repo)}#${unit.pr}`);
7767
- } else {
7768
- unit.terminal = true;
7769
- unit.phase = "done";
7770
- unit.artifact = "pr_merged";
7771
- unit.validation = "external_merge_unverified";
7772
- unit.blockingDecisionId = null;
7773
- await answer("superseded_external_merge_unverified");
7774
- 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`);
7775
- applied.push(`recorded UNVERIFIED external merge for ${repoLabel$1(unit.repo)}#${unit.pr ?? "?"}`);
7776
- }
7777
- 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") {
7778
8310
  unit.terminal = true;
7779
8311
  unit.phase = "done";
7780
8312
  unit.artifact = "pr_closed";
@@ -12393,438 +12925,782 @@ function anyProp(description) {
12393
12925
  return { description };
12394
12926
  }
12395
12927
  //#endregion
12396
- //#region src/lib/colbert/index.ts
12397
- /**
12398
- * ColBERT semantic-search sidecar — public entry points.
12399
- *
12400
- * `provisionAndIndexColbert()` is the fire-and-forget call site the
12401
- * `start` / `claude` / `codex` launchers invoke after `setupAndServe`
12402
- * (mirroring `provisionToolbelt()` / `runSelfUpdate()`):
12403
- * 1. Bail unless opted in (`--search` / `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1`);
12404
- * `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` hard-disables.
12405
- * 2. Register the exit handlers (tree-kill tracked colgrep children).
12406
- * 3. Provision the binary/model/ORT under a lock + smoke test
12407
- * (best-effort, never throws to the launcher).
12408
- * 4. If the launch cwd is a git repo and its index is absent/stale,
12409
- * kick a background `colgrep init` (non-blocking).
12410
- *
12411
- * On-demand indexing for non-cwd workspaces is handled inside the MCP
12412
- * tool handler (`runSemanticSearch` kicks a debounced background init
12413
- * for an unindexed workspace and reports `unavailable` meanwhile).
12414
- */
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
+ ];
12415
12985
  /**
12416
- * True only when the operator opted in via `--search`
12417
- * (`state.searchEnabled`, set by `setupAndServe`) or
12418
- * `GH_ROUTER_ENABLE_SEMANTIC_SEARCH=1`. Semantic search is OFF BY
12419
- * DEFAULT (no auto-provision, no background-index); the capability gate
12420
- * additionally requires the artifacts to be present on disk +
12421
- * smoke-passed, so the `code` tool stays lexical until both the opt-in
12422
- * and provisioning have completed.
12423
- *
12424
- * `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` hard-disables and wins over every
12425
- * opt-in signal (escape hatch for tests and managed environments).
12426
- */
12427
- function semanticSearchOptedIn() {
12428
- if (parseBoolEnv(process$1.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) return false;
12429
- 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;
12430
13006
  }
12431
13007
  /**
12432
- * Availability predicate for ColBERT semantic search — the single
12433
- * source of truth, living in this leaf module so callers that must not
12434
- * import `mcp-capabilities` (notably the unified code-search helper)
12435
- * can read it without closing an import cycle through `worker-agent`.
13008
+ * Normalize an operator-supplied cluster reference into an origin.
12436
13009
  *
12437
- * True iff the operator hasn't opted out AND the colgrep binary + model
12438
- * + ORT are provisioned on disk AND the post-provision smoke test
12439
- * 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.
12440
13015
  */
12441
- function colbertSearchEnabled() {
12442
- return semanticSearchOptedIn() && colbertArtifactsPresent() && colbertSmokeOk();
12443
- }
12444
- let _started = false;
12445
- /**
12446
- * Fire-and-forget provision + background-index. Never throws; safe to
12447
- * `void`-call from a launcher right after the server is listening.
12448
- * Idempotent within a proxy run (subsequent calls no-op).
12449
- */
12450
- async function provisionAndIndexColbert(opts = {}) {
12451
- if (!semanticSearchOptedIn()) return;
12452
- if (_started) return;
12453
- _started = true;
12454
- registerColbertExitHandlers();
12455
- 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;
12456
13021
  try {
12457
- const result = await provisionColbert();
12458
- provisioned = result.status === "ready";
12459
- if (result.status === "unsupported") consola.debug("colbert: semantic search unsupported on this platform");
12460
- else if (result.status !== "ready") consola.debug(`colbert: provision not ready (${result.status}: ${result.reason ?? ""})`);
12461
- } catch (err) {
12462
- consola.debug("colbert: provision threw (swallowed):", err);
12463
- 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
+ }
12464
13113
  }
12465
- if (!provisioned) return;
12466
- if (opts.skipCwdIndex) return;
12467
- 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";
12468
13242
  try {
12469
- if ((await gitState(cwd)).isRepo && await startupKickAllowed(cwd)) kickBackgroundInit(cwd);
12470
- } catch (err) {
12471
- 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
+ });
12472
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;
12473
13289
  }
12474
13290
  /**
12475
- * One-line operator warning when this workspace's semantic index is sitting in
12476
- * a terminal `failed` state, or `null` when there is nothing to say.
12477
- *
12478
- * This exists because the failure mode that motivated it was SILENCE: semantic
12479
- * search degraded to lexical on a real repo for an unknown period — possibly
12480
- * weeks — and nobody noticed, because the only signals were a `notice` string
12481
- * the model reads and a `consola.debug` the file logger drops. Neither reaches
12482
- * a human. The launcher writes this to stderr next to the readiness line so a
12483
- * degraded capability is visible at the moment the user starts a session.
12484
- *
12485
- * `logsToFile` says where the failure detail actually went. `claude` and
12486
- * `codex` call `enableFileLogging()`, which redirects warnings to
12487
- * ERROR_LOG_PATH; `start` does not, so its warnings stay on the terminal and
12488
- * 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.
12489
13324
  *
12490
- * Deliberately advisory and best-effort: lexical search still works, so this
12491
- * 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.
12492
13329
  */
12493
- async function colbertDegradedWarning(cwd, opts = {}) {
12494
- 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;
12495
13334
  try {
12496
- const target = cwd ?? process$1.cwd();
12497
- const meta = await readColbertMeta(target);
12498
- if (!meta || meta.status !== "failed") return null;
12499
- const cls = meta.failureClass ?? "error";
12500
- 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." : ""}`;
12501
- } catch {
12502
- 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 });
12503
13342
  }
12504
13343
  }
12505
13344
  //#endregion
12506
- //#region src/lib/unified-code-search.ts
13345
+ //#region src/lib/worker-agent/relay-cap.ts
12507
13346
  /**
12508
- * Unified, semantic-first code search; the single source of truth behind
12509
- * BOTH the MCP `code` tool (`src/lib/peer-mcp-personas.ts`) and the worker
12510
- * subagent's internal `code_search` tool (`src/lib/worker-agent/tools.ts`).
12511
- *
12512
- * Default behaviour (omitted mode or `mode:"semantic"`) ranks by MEANING
12513
- * via ColBERT (colgrep) and TRANSPARENTLY falls back to lexical BM25F when
12514
- * the per-workspace index isn't ready (building / stale / unavailable /
12515
- * failed) or colgrep isn't provisioned on this host. The forced lexical
12516
- * family (`lexical|exact|regex|ast`) never touches colgrep.
12517
- *
12518
- * Under `--bluebird` (`state.bluebirdEnabled`), the `semantic` and
12519
- * `lexical` modes route through
12520
- * the Bluebird Azure DevOps MCP server instead (the unified `code_search`
12521
- * tool, with legacy tool-name compatibility); `exact|regex|ast` stay local, and
12522
- * Bluebird errors surface as `source:"error"` with NO silent local
12523
- * fallback.
13347
+ * Relay-safe result capping for the worker MCP boundary.
12524
13348
  *
12525
- * Provenance is carried in a FOUR-valued `source` field, independent of
12526
- * `notice`:
12527
- * - "semantic" colgrep/Bluebird ran and the index was fresh
12528
- * - "lexical" the caller explicitly forced a lexical mode
12529
- * - "lexical-fallback" a semantic/default query degraded to lexical
12530
- * because the index wasn't ready
12531
- * - "error" the Bluebird backend failed after retries; the
12532
- * response carries `notice` with the cause
12533
- * `notice` keeps the lexical backend's size-cap > structural priority, so
12534
- * on a hit-heavy fallback the urgent size notice can win; `source` still
12535
- * conveys "this was a fallback" unambiguously, and never conflates a
12536
- * 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.
12537
13354
  *
12538
- * Contract split vs. `runSemanticSearch`: the runner itself stays
12539
- * NO-FALLBACK (it returns honest status, never another engine). The
12540
- * 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.
12541
13363
  *
12542
- * Import-cycle note: this module imports ONLY from `./code-search`,
12543
- * `./colbert`, `./bluebird-client`, and `./state`. It must NOT import
12544
- * `./mcp-capabilities`; that would close a cycle through `worker-agent`.
12545
- * The colbert-availability decision is read from the leaf
12546
- * `colbertSearchEnabled()`. (`./state` reaches `./bluebird-client` by
12547
- * type-only import, and `./bluebird-client` reaches this module by
12548
- * 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.
12549
13369
  */
12550
- /** Map the unified mode onto `searchCode`'s internal `mode` enum. */
12551
- function lexicalSearchCodeMode(mode) {
12552
- switch (mode) {
12553
- case "exact": return "literal";
12554
- case "regex": return "regex";
12555
- default: return "ranked";
12556
- }
12557
- }
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;
12558
13374
  /**
12559
- * Status-specific, actionable fallback hint. The semantic index isn't ready,
12560
- * so the model got LEXICAL results (great for exact symbols, sparse for a
12561
- * natural-language phrase since the lexical backend matches literally). Tell
12562
- * it both levers: retry `mode:"semantic"` (the index is self-healing in the
12563
- * background) OR re-query now with specific symbol/keyword terms.
12564
- *
12565
- * "shortly" was too vague and cost a real recovery. A build takes MINUTES on a
12566
- * large repo, and after a failed build the FIRST query is consumed triggering
12567
- * the re-kick and still returns a fallback. So a caller who retried once,
12568
- * seconds later, saw a second fallback and concluded the tool was broken
12569
- * rather than mid-repair. Observed end to end on this repo: query, then
12570
- * ~5 minutes of `building`, then `ready`. Naming the timescale and the
12571
- * one-query-to-trigger behaviour is what turns "it's still broken" into
12572
- * "it's coming back".
12573
- *
12574
- * The wording stays a range rather than a number: build time scales with
12575
- * 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.
12576
13379
  */
12577
- const FALLBACK_GUIDANCE_MARKER = "retry mode:\"semantic\"";
12578
- const FALLBACK_GUIDANCE = `${FALLBACK_GUIDANCE_MARKER} in minutes or use exact symbols`;
12579
- function fallbackNoticeFor(status) {
12580
- const tail = FALLBACK_GUIDANCE;
12581
- switch (status) {
12582
- case "building": return `semantic index building — returned lexical matches; ${tail}`;
12583
- case "stale": return `semantic index stale (HEAD moved) — re-index started, returned lexical matches; ${tail}`;
12584
- case "unavailable": return `no semantic index yet — build started, returned lexical matches; ${tail}`;
12585
- case "failed": return `semantic index failed — this query started a background rebuild, returned lexical matches; ${tail}`;
12586
- default: return "returned lexical results";
12587
- }
12588
- }
13380
+ const MAX_MAX_RESULT_BYTES = 20480;
12589
13381
  /**
12590
- * Combine the lexical backend's own notice (size-cap / structural, the
12591
- * urgent "you're missing results" signal) with a fallback hint, keeping a
12592
- * single string. The lexical notice stays primary; the hint is appended so
12593
- * neither is lost.
13382
+ * Age at which a spilled `.patch`/`.txt` is swept. Matches the worktree
13383
+ * dir age sweep in `worktree.ts`.
12594
13384
  */
12595
- function joinNotice(primary, secondary) {
12596
- if (primary && secondary) return `${primary} (${secondary})`;
12597
- 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));
12598
13402
  }
12599
- /** Preserve runner-specific context while guaranteeing actionable guidance once. */
12600
- function semanticFallbackNotice(sem) {
12601
- if (!sem.notice) return fallbackNoticeFor(sem.status);
12602
- if (sem.notice.includes(FALLBACK_GUIDANCE_MARKER)) return sem.notice;
12603
- 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");
12604
13414
  }
12605
- async function outlinesForSemanticResults(input, results, signal) {
12606
- if (input.summary === false) return void 0;
12607
- const seen = /* @__PURE__ */ new Set();
12608
- const files = [];
12609
- for (const result of results) {
12610
- if (seen.has(result.file)) continue;
12611
- seen.add(result.file);
12612
- files.push(result.file);
12613
- 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;
12614
13433
  }
12615
- const outlines = [];
12616
- const deadline = Date.now() + 2e3;
12617
- const workspace = path.resolve(input.workspace);
12618
- for (const file of files) {
12619
- if (signal?.aborted || Date.now() > deadline) break;
12620
- const normalized = file.replaceAll("\\", "/").replace(/^\/+/, "");
12621
- if (!normalized || normalized.includes("\0") || /^[A-Za-z]:/.test(normalized) || normalized.startsWith("//")) continue;
12622
- if (normalized.split("/").some((part) => part === "..")) continue;
12623
- const abs = path.resolve(workspace, normalized);
12624
- const rel = path.relative(workspace, abs);
12625
- 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);
12626
13444
  try {
12627
- const outlined = await outlineFile(abs, signal);
12628
- outlines.push({
12629
- file: normalized,
12630
- outline: outlined.outline.slice(0, 60)
12631
- });
13445
+ if (now - (await fs$1.stat(full)).mtimeMs < AGE_SWEEP_MS$1) continue;
13446
+ await fs$1.rm(full, { force: true }).catch(() => {});
12632
13447
  } catch {}
12633
13448
  }
12634
- return outlines;
12635
- }
12636
- async function runLexical(input, mode, source, signal) {
12637
- const isAst = mode === "ast";
12638
- const resp = await searchCode({
12639
- query: input.query,
12640
- workspace: input.workspace,
12641
- mode: lexicalSearchCodeMode(mode),
12642
- file_glob: input.file_glob,
12643
- limit: input.limit,
12644
- context_lines: input.context_lines,
12645
- structural: input.structural,
12646
- summary: input.summary,
12647
- complete: input.complete,
12648
- multiline: input.multiline,
12649
- scan: input.scan,
12650
- ast_pattern: isAst ? input.ast_pattern : void 0,
12651
- ast_lang: isAst ? input.ast_lang : void 0
12652
- }, signal);
12653
- return {
12654
- source,
12655
- results: resp.results.map((h) => ({
12656
- file: h.file,
12657
- line: h.line,
12658
- snippet: h.snippet,
12659
- ...h.role ? { role: h.role } : {}
12660
- })),
12661
- notice: joinNotice(resp.notice ?? void 0, emptyPhraseHint(input, resp.results.length)),
12662
- outlines: resp.outlines,
12663
- truncated: resp.truncated
12664
- };
12665
13449
  }
12666
13450
  /**
12667
- * Hint emitted when a multi-word lexical query matches nothing.
12668
- *
12669
- * Observed, and only this much is verified: a natural-language multi-word query
12670
- * can return `results: []` on this backend even when the individual words all
12671
- * appear in the repository, and the same question answered instantly via a
12672
- * single identifier or a plain `Grep`. A blind capability audit hit exactly that
12673
- * on a real lookup and concluded the code did not exist.
12674
- *
12675
- * The mechanism is NOT fully characterised. The audit proposed contiguous-phrase
12676
- * matching; that explanation does not survive testing, because other multi-word
12677
- * queries whose words are spread across lines do return hits. So this hint
12678
- * deliberately describes the SYMPTOM and the recovery, and claims nothing about
12679
- * the cause.
12680
- *
12681
- * It is worth emitting regardless of mechanism: a bare empty result reads as
12682
- * "not in this repository" rather than "that query shape did not work", and this
12683
- * project's own guidance steers callers here before `Grep`. A silently empty
12684
- * result is worse than a missing tool, because a missing tool routes you
12685
- * elsewhere and an empty one convinces you. The advice it gives (retry a single
12686
- * identifier, or use regex) is correct for a genuine no-match too, so the hint
12687
- * 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).
12688
13456
  */
12689
- function emptyPhraseHint(input, hitCount) {
12690
- if (hitCount > 0) return void 0;
12691
- if (input.mode === "regex" || input.mode === "ast") return void 0;
12692
- const terms = input.query.trim().split(/\s+/).filter(Boolean);
12693
- if (terms.length < 2) return void 0;
12694
- 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];
12695
- 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");
12696
13476
  }
12697
13477
  /**
12698
- * Bluebird backend for the `semantic` and `lexical` modes. `exact|regex|ast`
12699
- * never reach here (they stay local by contract). Errors surface as
12700
- * `source:"error"` — the `--bluebird` promise is "Bluebird or a visible
12701
- * error", never a silent local fallback that would mask an auth/outage
12702
- * 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).
12703
13489
  */
12704
- async function runBluebird(input, mode, signal) {
12705
- 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;
12706
13495
  try {
12707
- const workspace = validateWorkspace(input.workspace);
12708
- if (!workspace.ok || !workspace.canonical) throw new Error(workspace.error ?? "workspace path is not accessible");
12709
- const client = await ensureBluebirdClient(workspace.canonical, signal);
12710
- const results = (mode === "semantic" ? await client.doVectorSearch(input.query, {
12711
- limit,
12712
- file_glob: input.file_glob,
12713
- signal
12714
- }) : await client.searchFileContent(input.query, {
12715
- limit,
12716
- file_glob: input.file_glob,
12717
- signal
12718
- })).slice(0, limit).map((r) => ({
12719
- file: r.file,
12720
- line: r.line,
12721
- snippet: r.snippet,
12722
- ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
12723
- ...r.name !== void 0 ? { name: r.name } : {},
12724
- ...r.score !== void 0 ? { score: r.score } : {}
12725
- }));
12726
- const outlines = await outlinesForSemanticResults(input, results, signal);
12727
- return {
12728
- source: mode,
12729
- results,
12730
- ...outlines ? { outlines } : {}
12731
- };
13496
+ savedPath = await saveOverflowResult(text);
12732
13497
  } catch (err) {
12733
- if (signal?.aborted) throw err;
12734
- return {
12735
- source: "error",
12736
- results: [],
12737
- 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)`
12738
- };
13498
+ saveError = err instanceof Error ? err.message : String(err);
12739
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;
12740
13547
  }
12741
13548
  /**
12742
- * Route a unified code-search request. Throws only on input/workspace
12743
- * validation failure (propagated from `searchCode`); callers wrap in
12744
- * try/catch exactly as they do today for `searchCode`.
13549
+ * MCP result envelope for one tool answer, relay-safe.
12745
13550
  *
12746
- * Under `--bluebird` (initialized client present), `semantic` (the
12747
- * default) and `lexical` route through Bluebird; `exact|regex|ast` stay
12748
- * local. Bluebird failures return `source:"error"` with the cause in
12749
- * `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.
12750
13558
  */
12751
- async function runUnifiedCodeSearch(input, signal) {
12752
- const mode = input.mode ?? "semantic";
12753
- if (state.bluebirdEnabled === true && (mode === "semantic" || mode === "lexical")) return runBluebird(input, mode, signal);
12754
- if (mode !== "semantic") return runLexical(input, mode, "lexical", signal);
12755
- if (!colbertSearchEnabled()) {
12756
- const r = await runLexical(input, "lexical", "lexical-fallback", signal);
12757
- return {
12758
- ...r,
12759
- notice: joinNotice(r.notice, "semantic search is off (launch with --search to enable); returned lexical results")
12760
- };
12761
- }
12762
- if (serviceBackendEnabled()) try {
12763
- const svc = await runServiceSearch({
12764
- query: input.query,
12765
- workspace: input.workspace,
12766
- limit: input.limit,
12767
- signal
12768
- });
12769
- if (svc.status === "ready") {
12770
- const results = (svc.results ?? []).map((r) => ({
12771
- file: r.file,
12772
- line: r.line,
12773
- snippet: r.snippet,
12774
- ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
12775
- ...r.name !== void 0 ? { name: r.name } : {},
12776
- ...r.score !== void 0 ? { score: r.score } : {}
12777
- }));
12778
- return {
12779
- source: "semantic",
12780
- results,
12781
- outlines: await outlinesForSemanticResults(input, results, signal),
12782
- ...svc.freshness ? { freshness: svc.freshness } : {},
12783
- ...svc.stale_files !== void 0 ? { stale_files: svc.stale_files } : {}
12784
- };
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
+ })));
12785
13701
  }
12786
- } catch {}
12787
- let sem;
12788
- try {
12789
- sem = await runSemanticSearch({
12790
- query: input.query,
12791
- workspace: input.workspace,
12792
- limit: input.limit,
12793
- pattern: input.pattern,
12794
- signal,
12795
- serveStale: true
12796
- });
12797
- } catch {
12798
- const r = await runLexical(input, "lexical", "lexical-fallback", signal);
12799
- return {
12800
- ...r,
12801
- notice: joinNotice(r.notice, "semantic search errored; returned lexical results")
12802
- };
12803
- }
12804
- if (sem.status === "ready") {
12805
- const results = (sem.results ?? []).map((r) => ({
12806
- file: r.file,
12807
- line: r.line,
12808
- snippet: r.snippet,
12809
- ...r.endLine !== void 0 ? { endLine: r.endLine } : {},
12810
- ...r.name !== void 0 ? { name: r.name } : {},
12811
- ...r.score !== void 0 ? { score: r.score } : {}
12812
- }));
12813
- return {
12814
- source: "semantic",
12815
- results,
12816
- outlines: await outlinesForSemanticResults(input, results, signal),
12817
- ...sem.notice ? { notice: sem.notice } : {},
12818
- ...sem.freshness ? { freshness: sem.freshness } : {},
12819
- ...sem.stale_files !== void 0 ? { stale_files: sem.stale_files } : {}
12820
- };
12821
13702
  }
12822
- const r = await runLexical(input, "lexical", "lexical-fallback", signal);
12823
- return {
12824
- ...r,
12825
- notice: joinNotice(r.notice, semanticFallbackNotice(sem))
12826
- };
12827
- }
13703
+ ]);
12828
13704
  //#endregion
12829
13705
  //#region src/lib/browser-mcp/browser-detect.ts
12830
13706
  let cached;
@@ -14282,7 +15158,7 @@ function logAudit$1(record) {
14282
15158
  try {
14283
15159
  const fs = await import("node:fs/promises");
14284
15160
  const path = await import("node:path");
14285
- const { PATHS } = await import("./paths-Dfivvq21.js");
15161
+ const { PATHS } = await import("./paths-C9x5U3dO.js");
14286
15162
  const dir = path.join(PATHS.APP_DIR, "browser-mcp");
14287
15163
  await fs.mkdir(dir, { recursive: true });
14288
15164
  const line = JSON.stringify({
@@ -18151,6 +19027,125 @@ buildProviderErrorPattern([
18151
19027
  "ResourceExhausted"
18152
19028
  ]);
18153
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
18154
19149
  //#region src/vendor/pi/ai/utils/validation.ts
18155
19150
  const validatorCache = /* @__PURE__ */ new WeakMap();
18156
19151
  const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
@@ -18296,10 +19291,12 @@ function validateToolArguments(tool, toolCall) {
18296
19291
  const validator = getValidator(tool.parameters);
18297
19292
  if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {
18298
19293
  const coerced = coerceWithJsonSchema(args, tool.parameters);
18299
- if (coerced !== args) if (typeof args === "object" && args !== null && typeof coerced === "object" && coerced !== null) {
18300
- for (const key of Object.keys(args)) delete args[key];
18301
- Object.assign(args, coerced);
18302
- } 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
+ }
18303
19300
  }
18304
19301
  if (validator.Check(args)) return args;
18305
19302
  const errors = validator.Errors(args).map((error) => ` - ${formatValidationPath(error)}: ${error.message}`).join("\n") || "Unknown validation error";
@@ -18316,21 +19313,22 @@ function getDefaultStreamFn() {
18316
19313
  * Transforms to Message[] only at the LLM call boundary.
18317
19314
  */
18318
19315
  async function runAgentLoop(prompts, context, config, emit, signal, streamFn) {
18319
- const newMessages = [...prompts];
19316
+ const initialMessages = declareToolChanges(context, prompts);
19317
+ const newMessages = [...initialMessages];
18320
19318
  const currentContext = {
18321
19319
  ...context,
18322
- messages: [...context.messages, ...prompts]
19320
+ messages: [...context.messages, ...initialMessages]
18323
19321
  };
18324
19322
  await emit({ type: "agent_start" });
18325
19323
  await emit({ type: "turn_start" });
18326
- for (const prompt of prompts) {
19324
+ for (const message of initialMessages) {
18327
19325
  await emit({
18328
19326
  type: "message_start",
18329
- message: prompt
19327
+ message
18330
19328
  });
18331
19329
  await emit({
18332
19330
  type: "message_end",
18333
- message: prompt
19331
+ message
18334
19332
  });
18335
19333
  }
18336
19334
  await runLoop(currentContext, newMessages, config, signal, emit, streamFn ?? getDefaultStreamFn());
@@ -18352,31 +19350,63 @@ async function runAgentLoopContinue(context, config, emit, signal, streamFn) {
18352
19350
  async function runLoop(initialContext, newMessages, initialConfig, signal, emit, streamFunction) {
18353
19351
  let currentContext = initialContext;
18354
19352
  let config = initialConfig;
18355
- let firstTurn = true;
19353
+ let lastCompletedTurn;
19354
+ let explicitContinuation = false;
18356
19355
  let pendingMessages = await config.getSteeringMessages?.() || [];
18357
19356
  while (true) {
18358
19357
  let hasMoreToolCalls = true;
18359
19358
  while (hasMoreToolCalls || pendingMessages.length > 0) {
18360
- if (!firstTurn) await emit({ type: "turn_start" });
18361
- else firstTurn = false;
18362
- if (pendingMessages.length > 0) {
18363
- for (const message of pendingMessages) {
18364
- await emit({
18365
- type: "message_start",
18366
- message
18367
- });
18368
- await emit({
18369
- type: "message_end",
18370
- message
18371
- });
18372
- currentContext.messages.push(message);
18373
- 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
+ };
18374
19370
  }
18375
- 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
+ };
18376
19399
  }
18377
19400
  const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFunction);
18378
19401
  newMessages.push(message);
18379
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);
18380
19410
  await emit({
18381
19411
  type: "turn_end",
18382
19412
  message,
@@ -18400,45 +19430,39 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
18400
19430
  newMessages.push(result);
18401
19431
  }
18402
19432
  }
18403
- await emit({
18404
- type: "turn_end",
18405
- message,
18406
- toolResults
18407
- });
18408
- const nextTurnContext = {
19433
+ lastCompletedTurn = {
18409
19434
  message,
18410
19435
  toolResults,
18411
19436
  context: currentContext,
18412
19437
  newMessages
18413
19438
  };
18414
- const nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);
18415
- if (nextTurnSnapshot) {
18416
- currentContext = nextTurnSnapshot.context ?? currentContext;
18417
- config = {
18418
- ...config,
18419
- model: nextTurnSnapshot.model ?? config.model,
18420
- reasoning: nextTurnSnapshot.thinkingLevel === void 0 ? config.reasoning : nextTurnSnapshot.thinkingLevel === "off" ? void 0 : nextTurnSnapshot.thinkingLevel
18421
- };
18422
- }
18423
- if (await config.shouldStopAfterTurn?.({
19439
+ const decision = await config.finishTurn?.(lastCompletedTurn, signal);
19440
+ await emit({
19441
+ type: "turn_end",
18424
19442
  message,
18425
- toolResults,
18426
- context: currentContext,
18427
- newMessages
18428
- })) {
19443
+ toolResults
19444
+ });
19445
+ if (decision?.action === "end") {
18429
19446
  await emit({
18430
19447
  type: "agent_end",
18431
19448
  messages: newMessages
18432
19449
  });
18433
19450
  return;
18434
19451
  }
19452
+ explicitContinuation = decision?.action === "continue";
18435
19453
  pendingMessages = await config.getSteeringMessages?.() || [];
19454
+ if (hasMoreToolCalls || pendingMessages.length > 0) explicitContinuation = false;
18436
19455
  }
18437
19456
  const followUpMessages = await config.getFollowUpMessages?.() || [];
18438
19457
  if (followUpMessages.length > 0) {
19458
+ explicitContinuation = false;
18439
19459
  pendingMessages = followUpMessages;
18440
19460
  continue;
18441
19461
  }
19462
+ if (explicitContinuation) {
19463
+ explicitContinuation = false;
19464
+ continue;
19465
+ }
18442
19466
  break;
18443
19467
  }
18444
19468
  await emit({
@@ -18447,24 +19471,71 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
18447
19471
  });
18448
19472
  }
18449
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
+ /**
18450
19525
  * Stream an assistant response from the LLM.
18451
19526
  * This is where AgentMessage[] gets transformed to Message[] for the LLM.
18452
19527
  */
18453
19528
  async function streamAssistantResponse(context, config, signal, emit, streamFunction) {
18454
19529
  let messages = context.messages;
18455
19530
  if (config.transformContext) messages = await config.transformContext(messages, signal);
18456
- const llmMessages = await config.convertToLlm(messages);
18457
- const llmContext = {
18458
- systemPrompt: context.systemPrompt,
18459
- messages: llmMessages,
18460
- tools: context.tools
18461
- };
19531
+ const llmContext = normalizeContext({ messages: await config.convertToLlm(messages) });
18462
19532
  const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : void 0) || config.apiKey;
18463
19533
  const response = await streamFunction(config.model, llmContext, {
18464
19534
  ...config,
18465
19535
  apiKey: resolvedApiKey,
18466
19536
  signal
18467
19537
  });
19538
+ const result = async () => Object.assign(await response.result(), { thinkingLevel: config.reasoning ?? "off" });
18468
19539
  let partialMessage = null;
18469
19540
  let addedPartial = false;
18470
19541
  for await (const event of response) switch (event.type) {
@@ -18498,7 +19569,7 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc
18498
19569
  break;
18499
19570
  case "done":
18500
19571
  case "error": {
18501
- const finalMessage = await response.result();
19572
+ const finalMessage = await result();
18502
19573
  if (addedPartial) context.messages[context.messages.length - 1] = finalMessage;
18503
19574
  else context.messages.push(finalMessage);
18504
19575
  if (!addedPartial) await emit({
@@ -18512,7 +19583,7 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc
18512
19583
  return finalMessage;
18513
19584
  }
18514
19585
  }
18515
- const finalMessage = await response.result();
19586
+ const finalMessage = await result();
18516
19587
  if (addedPartial) context.messages[context.messages.length - 1] = finalMessage;
18517
19588
  else {
18518
19589
  context.messages.push(finalMessage);
@@ -18584,7 +19655,7 @@ async function executeToolCallsSequential(currentContext, assistantMessage, tool
18584
19655
  result: preparation.result,
18585
19656
  isError: preparation.isError
18586
19657
  };
18587
- 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);
18588
19659
  await emitToolExecutionEnd(finalized, emit);
18589
19660
  const toolResultMessage = createToolResultMessage(finalized);
18590
19661
  await emitToolResultMessage(toolResultMessage, emit);
@@ -18619,7 +19690,16 @@ async function executeToolCallsParallel(currentContext, assistantMessage, toolCa
18619
19690
  continue;
18620
19691
  }
18621
19692
  finalizedCalls.push(async () => {
18622
- 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));
18623
19703
  const finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
18624
19704
  await emitToolExecutionEnd(finalized, emit);
18625
19705
  return finalized;
@@ -18650,8 +19730,8 @@ function prepareToolCallArguments(tool, toolCall) {
18650
19730
  arguments: preparedArguments
18651
19731
  };
18652
19732
  }
18653
- async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal) {
18654
- 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);
18655
19735
  if (!tool) return {
18656
19736
  kind: "immediate",
18657
19737
  result: createErrorToolResult(`Tool ${toolCall.name} not found`),
@@ -18671,11 +19751,15 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
18671
19751
  result: createErrorToolResult("Operation aborted"),
18672
19752
  isError: true
18673
19753
  };
18674
- if (beforeResult?.block) return {
18675
- kind: "immediate",
18676
- result: createErrorToolResult(beforeResult.reason || "Tool execution was blocked"),
18677
- isError: true
18678
- };
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
+ }
18679
19763
  }
18680
19764
  if (signal?.aborted) return {
18681
19765
  kind: "immediate",
@@ -18696,32 +19780,41 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
18696
19780
  };
18697
19781
  }
18698
19782
  }
18699
- 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) {
18700
19793
  const updateEvents = [];
18701
19794
  let acceptingUpdates = true;
19795
+ const startedAt = performance.now();
19796
+ const elapsed = () => Math.round(performance.now() - startedAt);
18702
19797
  try {
18703
19798
  const result = await prepared.tool.execute(prepared.toolCall.id, prepared.args, signal, (partialResult) => {
18704
19799
  if (!acceptingUpdates) return;
18705
- updateEvents.push(Promise.resolve(emit({
18706
- type: "tool_execution_update",
18707
- toolCallId: prepared.toolCall.id,
18708
- toolName: prepared.toolCall.name,
18709
- args: prepared.toolCall.arguments,
18710
- partialResult
18711
- })));
19800
+ updateEvents.push(Promise.resolve(onUpdate(partialResult)));
18712
19801
  });
19802
+ const durationMs = elapsed();
18713
19803
  acceptingUpdates = false;
18714
19804
  await Promise.all(updateEvents);
18715
19805
  return {
18716
19806
  result,
18717
- isError: false
19807
+ isError: result.isError === true,
19808
+ durationMs
18718
19809
  };
18719
19810
  } catch (error) {
19811
+ const durationMs = elapsed();
18720
19812
  acceptingUpdates = false;
18721
19813
  await Promise.all(updateEvents);
18722
19814
  return {
18723
19815
  result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
18724
- isError: true
19816
+ isError: true,
19817
+ durationMs
18725
19818
  };
18726
19819
  } finally {
18727
19820
  acceptingUpdates = false;
@@ -18740,6 +19833,7 @@ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepar
18740
19833
  context: currentContext
18741
19834
  }, signal);
18742
19835
  if (afterResult) {
19836
+ const structuredContent = afterResult.structuredContent ?? (afterResult.content ? void 0 : result.structuredContent);
18743
19837
  result = {
18744
19838
  ...result,
18745
19839
  content: afterResult.content ?? result.content,
@@ -18747,6 +19841,8 @@ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepar
18747
19841
  usage: afterResult.usage ?? result.usage,
18748
19842
  terminate: afterResult.terminate ?? result.terminate
18749
19843
  };
19844
+ if (structuredContent === void 0) delete result.structuredContent;
19845
+ else result.structuredContent = structuredContent;
18750
19846
  isError = afterResult.isError ?? isError;
18751
19847
  }
18752
19848
  } catch (error) {
@@ -18756,7 +19852,8 @@ async function finalizeExecutedToolCall(currentContext, assistantMessage, prepar
18756
19852
  return {
18757
19853
  toolCall: prepared.toolCall,
18758
19854
  result,
18759
- isError
19855
+ isError,
19856
+ durationMs: executed.durationMs
18760
19857
  };
18761
19858
  }
18762
19859
  function createErrorToolResult(message) {
@@ -18774,7 +19871,8 @@ async function emitToolExecutionEnd(finalized, emit) {
18774
19871
  toolCallId: finalized.toolCall.id,
18775
19872
  toolName: finalized.toolCall.name,
18776
19873
  result: finalized.result,
18777
- isError: finalized.isError
19874
+ isError: finalized.isError,
19875
+ ...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs }
18778
19876
  });
18779
19877
  }
18780
19878
  function createToolResultMessage(finalized) {
@@ -18785,8 +19883,8 @@ function createToolResultMessage(finalized) {
18785
19883
  content: finalized.result.content ?? [],
18786
19884
  details: finalized.result.details,
18787
19885
  usage: finalized.result.usage,
18788
- ...finalized.result.addedToolNames?.length ? { addedToolNames: finalized.result.addedToolNames } : {},
18789
19886
  isError: finalized.isError,
19887
+ ...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs },
18790
19888
  timestamp: Date.now()
18791
19889
  };
18792
19890
  }
@@ -18803,7 +19901,7 @@ async function emitToolResultMessage(toolResultMessage, emit) {
18803
19901
  //#endregion
18804
19902
  //#region src/vendor/pi/agent/agent.ts
18805
19903
  function defaultConvertToLlm(messages) {
18806
- 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");
18807
19905
  }
18808
19906
  const EMPTY_USAGE = {
18809
19907
  input: 0,
@@ -18839,8 +19937,12 @@ const DEFAULT_MODEL = {
18839
19937
  function createMutableAgentState(initialState) {
18840
19938
  let tools = initialState?.tools?.slice() ?? [];
18841
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);
18842
19942
  return {
18843
- systemPrompt: initialState?.systemPrompt ?? "",
19943
+ get systemPrompt() {
19944
+ return getCurrentSystemPrompt(messages);
19945
+ },
18844
19946
  model: initialState?.model ?? DEFAULT_MODEL,
18845
19947
  thinkingLevel: initialState?.thinkingLevel ?? "off",
18846
19948
  get tools() {
@@ -18873,16 +19975,15 @@ var PendingMessageQueue = class {
18873
19975
  hasItems() {
18874
19976
  return this.messages.length > 0;
18875
19977
  }
18876
- drain() {
18877
- if (this.mode === "all") {
18878
- const drained = this.messages.slice();
18879
- this.messages = [];
18880
- return drained;
18881
- }
19978
+ peek() {
19979
+ if (this.mode === "all") return this.messages.slice();
18882
19980
  const first = this.messages[0];
18883
- if (!first) return [];
18884
- this.messages = this.messages.slice(1);
18885
- 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;
18886
19987
  }
18887
19988
  clear() {
18888
19989
  this.messages = [];
@@ -18905,9 +20006,11 @@ var Agent$1 = class {
18905
20006
  getApiKey;
18906
20007
  onPayload;
18907
20008
  onResponse;
20009
+ onProviderStreamEvent;
18908
20010
  beforeToolCall;
18909
20011
  afterToolCall;
18910
- shouldStopAfterTurn;
20012
+ finishTurn;
20013
+ prepareRequest;
18911
20014
  prepareNextTurn;
18912
20015
  prepareNextTurnWithContext;
18913
20016
  activeRun;
@@ -18930,9 +20033,11 @@ var Agent$1 = class {
18930
20033
  this.getApiKey = runtimeOptions.getApiKey;
18931
20034
  this.onPayload = runtimeOptions.onPayload;
18932
20035
  this.onResponse = runtimeOptions.onResponse;
20036
+ this.onProviderStreamEvent = runtimeOptions.onProviderStreamEvent;
18933
20037
  this.beforeToolCall = runtimeOptions.beforeToolCall;
18934
20038
  this.afterToolCall = runtimeOptions.afterToolCall;
18935
- this.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;
20039
+ this.finishTurn = runtimeOptions.finishTurn;
20040
+ this.prepareRequest = runtimeOptions.prepareRequest;
18936
20041
  this.prepareNextTurn = runtimeOptions.prepareNextTurn;
18937
20042
  this.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;
18938
20043
  this.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? "one-at-a-time");
@@ -19004,6 +20109,11 @@ var Agent$1 = class {
19004
20109
  hasQueuedMessages() {
19005
20110
  return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
19006
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
+ }
19007
20117
  /** Active abort signal for the current run, if any. */
19008
20118
  get signal() {
19009
20119
  return this.activeRun?.abortController.signal;
@@ -19020,9 +20130,11 @@ var Agent$1 = class {
19020
20130
  waitForIdle() {
19021
20131
  return this.activeRun?.promise ?? Promise.resolve();
19022
20132
  }
19023
- /** Clear transcript state, runtime state, and queued messages. */
20133
+ /** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */
19024
20134
  reset() {
19025
- 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] : [];
19026
20138
  this._state.isStreaming = false;
19027
20139
  this._state.streamingMessage = void 0;
19028
20140
  this._state.pendingToolCalls = /* @__PURE__ */ new Set();
@@ -19039,7 +20151,7 @@ var Agent$1 = class {
19039
20151
  async continue() {
19040
20152
  if (this.activeRun) throw new Error("Agent is already processing. Wait for completion before continuing.");
19041
20153
  const lastMessage = this._state.messages[this._state.messages.length - 1];
19042
- 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");
19043
20155
  if (lastMessage.role === "assistant") {
19044
20156
  const queuedSteering = this.steeringQueue.drain();
19045
20157
  if (queuedSteering.length > 0) {
@@ -19081,7 +20193,6 @@ var Agent$1 = class {
19081
20193
  }
19082
20194
  createContextSnapshot() {
19083
20195
  return {
19084
- systemPrompt: this._state.systemPrompt,
19085
20196
  messages: this._state.messages.slice(),
19086
20197
  tools: this._state.tools.slice()
19087
20198
  };
@@ -19094,13 +20205,15 @@ var Agent$1 = class {
19094
20205
  sessionId: this.sessionId,
19095
20206
  onPayload: this.onPayload,
19096
20207
  onResponse: this.onResponse,
20208
+ onProviderStreamEvent: this.onProviderStreamEvent,
19097
20209
  transport: this.transport,
19098
20210
  thinkingBudgets: this.thinkingBudgets,
19099
20211
  maxRetryDelayMs: this.maxRetryDelayMs,
19100
20212
  toolExecution: this.toolExecution,
19101
20213
  beforeToolCall: this.beforeToolCall,
19102
20214
  afterToolCall: this.afterToolCall,
19103
- shouldStopAfterTurn: this.shouldStopAfterTurn,
20215
+ finishTurn: this.finishTurn,
20216
+ prepareRequest: this.prepareRequest,
19104
20217
  prepareNextTurn: this.prepareNextTurnWithContext || this.prepareNextTurn ? async (context) => {
19105
20218
  if (this.prepareNextTurnWithContext) return await this.prepareNextTurnWithContext(context, this.signal);
19106
20219
  return await this.prepareNextTurn?.(this.signal);
@@ -19222,30 +20335,6 @@ var Agent$1 = class {
19222
20335
  for (const listener of this.listeners) await listener(event, signal);
19223
20336
  }
19224
20337
  };
19225
- globalThis.Buffer;
19226
- Type.Object({
19227
- command: Type.String({ description: "Bash command to execute" }),
19228
- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" }))
19229
- });
19230
- //#endregion
19231
- //#region src/vendor/pi/agent/harness/tools/edit.ts
19232
- const replaceEditSchema = Type.Object({
19233
- 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." }),
19234
- newText: Type.String({ description: "Replacement text for this targeted edit." })
19235
- }, {});
19236
- Type.Object({
19237
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
19238
- 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." })
19239
- }, {});
19240
- Type.Object({
19241
- path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
19242
- offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })),
19243
- limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" }))
19244
- });
19245
- Type.Object({
19246
- path: Type.String({ description: "Path to the file to write (relative or absolute)" }),
19247
- content: Type.String({ description: "Content to write to the file" })
19248
- });
19249
20338
  //#endregion
19250
20339
  //#region src/lib/worker-agent/budget.ts
19251
20340
  const DEFAULT_MAX_TURNS = 500;
@@ -20461,10 +21550,12 @@ async function runStreamLoop(stream, context, opts, options) {
20461
21550
  const { resolved } = opts;
20462
21551
  if (opts.contextBudget) {
20463
21552
  const assembledTokens = tokensFromBytes(estimateContextBytes(context));
20464
- 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`);
20465
- else {
20466
- pushBackstopDiagnostic(stream, resolved, assembledTokens, opts.contextBudget.inputHardLimitTokens);
20467
- 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
+ }
20468
21559
  }
20469
21560
  }
20470
21561
  const resolution = resolveEndpointForModelId(resolved.modelId);
@@ -20643,12 +21734,13 @@ async function runChatAttempt(stream, payload, opts, signal, state) {
20643
21734
  }
20644
21735
  function buildPayload(context, resolved) {
20645
21736
  const messages = [];
20646
- if (context.systemPrompt) messages.push({
21737
+ const systemPrompt = getCurrentSystemPrompt(context.messages);
21738
+ if (systemPrompt) messages.push({
20647
21739
  role: "system",
20648
- content: context.systemPrompt
21740
+ content: systemPrompt
20649
21741
  });
20650
21742
  messages.push(...translateMessages(context.messages));
20651
- const tools = translateTools(context.tools);
21743
+ const tools = translateTools(getCurrentTools(context.messages));
20652
21744
  const payload = {
20653
21745
  model: resolved.modelId,
20654
21746
  messages,
@@ -20705,6 +21797,7 @@ function translateMessages(messages) {
20705
21797
  continue;
20706
21798
  }
20707
21799
  flushImages();
21800
+ if (m.role === "system") continue;
20708
21801
  if (m.role === "user") out.push(translateUser(m));
20709
21802
  else if (m.role === "assistant") out.push(translateAssistant(m));
20710
21803
  }
@@ -21072,9 +22165,9 @@ function buildResponsesPayload(context, resolved) {
21072
22165
  const messages = piMessagesToNeutral(context.messages);
21073
22166
  return assembleResponsesPayload({
21074
22167
  model: resolved.modelId,
21075
- instructions: context.systemPrompt || void 0,
22168
+ instructions: getCurrentSystemPrompt(context.messages) || void 0,
21076
22169
  messages,
21077
- tools: piToolsToNeutral(context.tools),
22170
+ tools: piToolsToNeutral(getCurrentTools(context.messages)),
21078
22171
  reasoningEffort: resolved.thinking,
21079
22172
  cachePolicy: { workload: "conversation" },
21080
22173
  stream: true
@@ -21116,27 +22209,28 @@ function piMessagesToNeutral(messages) {
21116
22209
  continue;
21117
22210
  }
21118
22211
  flushImages();
21119
- if (m.role === "user") if (typeof m.content === "string") out.push({
21120
- role: "user",
21121
- content: m.content
21122
- });
21123
- else {
21124
- const parts = [];
21125
- for (const c of m.content) if (c.type === "text") parts.push({
21126
- type: "text",
21127
- text: c.text
21128
- });
21129
- else if (c.type === "image") parts.push({
21130
- type: "image",
21131
- mimeType: c.mimeType,
21132
- data: c.data
21133
- });
21134
- out.push({
22212
+ if (m.role === "user") {
22213
+ if (typeof m.content === "string") out.push({
21135
22214
  role: "user",
21136
- content: parts
22215
+ content: m.content
21137
22216
  });
21138
- }
21139
- 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") {
21140
22234
  const parts = [];
21141
22235
  for (const c of m.content) if (c.type === "text") parts.push({
21142
22236
  type: "text",
@@ -21350,13 +22444,20 @@ function pushTerminalError(stream, resolved, err) {
21350
22444
  * parts by their bytes keeps it consistent with the compactor. Never throws.
21351
22445
  */
21352
22446
  function estimateContextBytes(context) {
21353
- let bytes = Buffer.byteLength(context.systemPrompt ?? "", "utf8");
22447
+ let bytes = Buffer.byteLength(getCurrentSystemPrompt(context.messages), "utf8");
21354
22448
  try {
21355
- bytes += Buffer.byteLength(JSON.stringify(context.tools ?? []), "utf8");
22449
+ bytes += Buffer.byteLength(JSON.stringify(getCurrentTools(context.messages)), "utf8");
21356
22450
  } catch {}
21357
- 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
+ }
21358
22455
  return bytes;
21359
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
+ }
21360
22461
  /** Bytes of one wire message: text content + per-image equivalent + bulk fields. */
21361
22462
  function messageWireBytes(m) {
21362
22463
  if (!m || typeof m !== "object") return 0;
@@ -21802,12 +22903,14 @@ function makeBrowserTool(meta, parameters, dispatch, sessionId) {
21802
22903
  parameters,
21803
22904
  async execute(_toolCallId, params, signal) {
21804
22905
  const args = argsRecord(params);
21805
- if (sessionId) if (policy === "uses") {
21806
- if (!Number.isInteger(args.tabId)) throw new Error(`${wireName}: a valid tabId is required in a browse session`);
21807
- assertSessionOwnsTab(sessionId, args.tabId);
21808
- } else if (policy === "opens") {
21809
- 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");
21810
- } 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
+ }
21811
22914
  const env = await dispatch(wireName, args, signal);
21812
22915
  const text = joinEnvelopeText(env);
21813
22916
  if (env.isError) throw new Error(text || `${wireName} failed`);
@@ -21900,7 +23003,8 @@ function messageTextBytes(m) {
21900
23003
  switch (msg.role) {
21901
23004
  case "user":
21902
23005
  case "custom":
21903
- case "toolResult": return contentBytes(msg.content);
23006
+ case "toolResult":
23007
+ case "system": return contentBytes(msg.content);
21904
23008
  case "assistant": {
21905
23009
  const content = msg.content;
21906
23010
  if (!Array.isArray(content)) return 0;
@@ -23505,6 +24609,383 @@ function browseAgentEnabled() {
23505
24609
  if (!found) return false;
23506
24610
  return pickEndpoint(found) !== void 0;
23507
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
+ }
23508
24989
  //#endregion
23509
24990
  //#region src/routes/mcp/handler.ts
23510
24991
  const MCP_PROTOCOL_VERSION = "2025-06-18";
@@ -23641,6 +25122,38 @@ function checkAuth(c) {
23641
25122
  };
23642
25123
  }
23643
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
+ /**
23644
25157
  * opus_critic's effective model, resolved against the live catalog.
23645
25158
  *
23646
25159
  * Prefers `claude-opus-5.5` — the dotted catalog id that is natively 1M
@@ -23776,6 +25289,8 @@ function maxToolIsEnabled(tool) {
23776
25289
  if (tool.capability === "fleet") return fleetToolsEnabled();
23777
25290
  if (tool.capability === "agents") return agentToolsEnabled();
23778
25291
  if (tool.capability === "artifact") return artifactToolsEnabled();
25292
+ if (tool.group === "ado") return adoToolsEnabled();
25293
+ if (tool.group === "kusto") return kustoToolsEnabled();
23779
25294
  return true;
23780
25295
  }
23781
25296
  /**
@@ -23799,6 +25314,8 @@ function fastToolIsEnabled(tool) {
23799
25314
  if (tool.group === "search") return true;
23800
25315
  if (tool.group === "peers") return tool.capability === "artifact" && artifactToolsEnabled();
23801
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();
23802
25319
  if (tool.group !== "browser") return false;
23803
25320
  if (!browserToolsEnabled()) return false;
23804
25321
  if (tool.capability === "browser_compound") return browserCompoundToolsEnabled();
@@ -23848,7 +25365,7 @@ function toolEntries(scope, launch, audience = "shared") {
23848
25365
  }
23849
25366
  }
23850
25367
  }));
23851
- const nonPersonaEntries = NON_PERSONA_MCP_TOOLS.filter((tool) => maxAllowsTool(scope, launch, {
25368
+ const nonPersonaEntries = listableNonPersonaTools().filter((tool) => maxAllowsTool(scope, launch, {
23852
25369
  group: tool.group,
23853
25370
  name: tool.toolNameHttp,
23854
25371
  tool
@@ -23873,7 +25390,7 @@ function toolEntries(scope, launch, audience = "shared") {
23873
25390
  const entries = [];
23874
25391
  if ((scope === "all" || scope === "peers") && launch.allowedGroups?.has("peers") && launch.allowedPersonas?.has("oracle") && oracleGate) entries.push(oracleToolEntry(isCheap, astraAvailable, oracleDescriptor));
23875
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));
23876
- for (const tool of NON_PERSONA_MCP_TOOLS) {
25393
+ for (const tool of listableNonPersonaTools()) {
23877
25394
  if (!fastAllowsTool(scope, launch, {
23878
25395
  group: tool.group,
23879
25396
  name: tool.toolNameHttp,
@@ -23912,7 +25429,7 @@ function toolEntries(scope, launch, audience = "shared") {
23912
25429
  }
23913
25430
  }
23914
25431
  })) : [];
23915
- const nonPersonaEntries = NON_PERSONA_MCP_TOOLS.filter((t) => {
25432
+ const nonPersonaEntries = listableNonPersonaTools().filter((t) => {
23916
25433
  if (scope !== "all" && t.group !== scope) return false;
23917
25434
  if (launch.allowedGroups && !launch.allowedGroups.has(t.group)) return false;
23918
25435
  if (t.capability === "worker") return workerToolsEnabled();
@@ -23922,6 +25439,8 @@ function toolEntries(scope, launch, audience = "shared") {
23922
25439
  if (t.capability === "fleet") return fleetToolsEnabled();
23923
25440
  if (t.capability === "agents") return agentToolsEnabled();
23924
25441
  if (t.capability === "artifact") return artifactToolsEnabled();
25442
+ if (t.capability === "ado") return adoToolsEnabled();
25443
+ if (t.capability === "kusto") return kustoToolsEnabled();
23925
25444
  if (t.capability === "browser_compound") return browserToolsEnabled() && browserCompoundToolsEnabled();
23926
25445
  if (t.capability === "browser_power") return browserToolsEnabled() && browserPowerToolsEnabled();
23927
25446
  return true;
@@ -24269,7 +25788,7 @@ function logTelemetry(t) {
24269
25788
  process.stderr.write(parts.join(" ") + "\n");
24270
25789
  }
24271
25790
  function toolAcceptsWorkspace(tool) {
24272
- 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";
24273
25792
  }
24274
25793
  /**
24275
25794
  * Fold the per-session `X-GH-Workspace` header into `args.workspace` when the
@@ -24299,7 +25818,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24299
25818
  if (!name) return rpcError(body.id, RPC_INVALID_PARAMS, "tools/call missing name");
24300
25819
  if (launch.profileId === "max") {
24301
25820
  const maxPersona = activePersonas(launch).find((persona) => persona.toolNameHttp === name);
24302
- const maxTool = NON_PERSONA_MCP_TOOLS.find((tool) => tool.toolNameHttp === name);
25821
+ const maxTool = allNonPersonaTools().find((tool) => tool.toolNameHttp === name);
24303
25822
  if (!(maxPersona ? maxAllowsTool(scope, launch, {
24304
25823
  group: "peers",
24305
25824
  name,
@@ -24312,7 +25831,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24312
25831
  }
24313
25832
  if ((launch.profileId === "fast" || launch.profileId === "cheap" || launch.profileId === "cheap1m" || launch.profileId === "cheapest" || launch.profileId === "balanced") && name !== "oracle" && name !== "astra") {
24314
25833
  const fastPersona = activePersonas(launch).find((persona) => persona.toolNameHttp === name);
24315
- const fastTool = NON_PERSONA_MCP_TOOLS.find((tool) => tool.toolNameHttp === name);
25834
+ const fastTool = allNonPersonaTools().find((tool) => tool.toolNameHttp === name);
24316
25835
  if (!(fastPersona ? fastAllowsTool(scope, launch, {
24317
25836
  group: "peers",
24318
25837
  name,
@@ -24471,7 +25990,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24471
25990
  }
24472
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}"`);
24473
25992
  const persona = activePersonas(launch).find((p) => p.toolNameHttp === name);
24474
- 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);
24475
25994
  if (!persona && !nonPersonaTool) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24476
25995
  const toolGroup = persona ? "peers" : nonPersonaTool.group;
24477
25996
  if (scope !== "all" && toolGroup !== scope) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
@@ -24486,6 +26005,8 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
24486
26005
  if (nonPersonaTool && nonPersonaTool.capability === "artifact" && !artifactToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24487
26006
  if (nonPersonaTool && nonPersonaTool.capability === "browser_compound" && !(browserToolsEnabled() && browserCompoundToolsEnabled())) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
24488
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}"`);
24489
26010
  let personaPrompt;
24490
26011
  let personaContext;
24491
26012
  let personaEffort;
@@ -25826,7 +27347,7 @@ function isAdvisorRequested(rawBetaHeader) {
25826
27347
  * blocks the client expects.
25827
27348
  */
25828
27349
  function injectAdvisorTool(rawBody, instructions = ADVISOR_TOOL_INSTRUCTIONS) {
25829
- 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;
25830
27351
  let parsed;
25831
27352
  try {
25832
27353
  parsed = JSON.parse(rawBody);
@@ -27894,13 +29415,13 @@ function atomicWriteSync(absPath, contents) {
27894
29415
  throw err;
27895
29416
  }
27896
29417
  }
27897
- const READ_PARAMS = Type$1.Object({
27898
- path: Type$1.String({ description: "Workspace-relative or absolute path." }),
27899
- 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({
27900
29421
  minimum: 0,
27901
29422
  description: "Line offset (0-indexed)."
27902
29423
  })),
27903
- limit: Type$1.Optional(Type$1.Integer({
29424
+ limit: Type.Optional(Type.Integer({
27904
29425
  minimum: 1,
27905
29426
  description: "Max lines to return."
27906
29427
  }))
@@ -27956,9 +29477,9 @@ function readTool(workspace) {
27956
29477
  }
27957
29478
  };
27958
29479
  }
27959
- const GLOB_PARAMS = Type$1.Object({
27960
- pattern: Type$1.String({ description: "ripgrep glob pattern, e.g. `src/**/*.ts`." }),
27961
- 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({
27962
29483
  minimum: 1,
27963
29484
  maximum: SEARCH_HARD_MAX
27964
29485
  }))
@@ -27985,11 +29506,11 @@ function globTool(workspace) {
27985
29506
  }
27986
29507
  };
27987
29508
  }
27988
- const GREP_PARAMS = Type$1.Object({
27989
- query: Type$1.String({ description: "Pattern to search for." }),
27990
- mode: Type$1.Optional(Type$1.Union([Type$1.Literal("literal"), Type$1.Literal("regex")], { description: "`literal` (default) = fixed-string; `regex` = PCRE2." })),
27991
- file_glob: Type$1.Optional(Type$1.String({ description: "ripgrep glob filter, e.g. `*.ts`." })),
27992
- 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({
27993
29514
  minimum: 1,
27994
29515
  maximum: SEARCH_HARD_MAX
27995
29516
  }))
@@ -28025,10 +29546,10 @@ function grepTool(workspace) {
28025
29546
  }
28026
29547
  };
28027
29548
  }
28028
- const EDIT_PARAMS = Type$1.Object({
28029
- path: Type$1.String({ description: "Workspace-relative or absolute path." }),
28030
- 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." }),
28031
- 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)." })
28032
29553
  });
28033
29554
  function editTool(workspace) {
28034
29555
  return {
@@ -28056,9 +29577,9 @@ function editTool(workspace) {
28056
29577
  }
28057
29578
  };
28058
29579
  }
28059
- const WRITE_PARAMS = Type$1.Object({
28060
- path: Type$1.String({ description: "Workspace-relative or absolute path." }),
28061
- 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." })
28062
29583
  });
28063
29584
  function writeTool(workspace) {
28064
29585
  return {
@@ -28074,9 +29595,9 @@ function writeTool(workspace) {
28074
29595
  }
28075
29596
  };
28076
29597
  }
28077
- const BASH_PARAMS = Type$1.Object({
28078
- cmd: Type$1.String({ description: "Shell command line." }),
28079
- 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({
28080
29601
  minimum: 100,
28081
29602
  maximum: BASH_MAX_TIMEOUT_MS,
28082
29603
  description: `Per-call timeout (default ${BASH_DEFAULT_TIMEOUT_MS} ms).`
@@ -28109,7 +29630,7 @@ function bashTool(workspace) {
28109
29630
  }
28110
29631
  };
28111
29632
  }
28112
- 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." }) });
28113
29634
  function webSearchTool() {
28114
29635
  return {
28115
29636
  name: "web_search",
@@ -28125,7 +29646,7 @@ function webSearchTool() {
28125
29646
  }
28126
29647
  };
28127
29648
  }
28128
- 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)." }) });
28129
29650
  function fetchUrlTool() {
28130
29651
  return {
28131
29652
  name: "fetch_url",
@@ -28188,26 +29709,26 @@ function fetchUrlTool() {
28188
29709
  function buildCodeSearchParams(searchEnabled, bluebirdEnabled) {
28189
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`.";
28190
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`).";
28191
- return Type$1.Object({
28192
- query: Type$1.String({ description: queryDescription }),
28193
- mode: Type$1.Optional(Type$1.Union([
28194
- Type$1.Literal("semantic"),
28195
- Type$1.Literal("lexical"),
28196
- Type$1.Literal("exact"),
28197
- Type$1.Literal("regex"),
28198
- 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")
28199
29720
  ], { description: modeDescription })),
28200
- 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." })),
28201
- file_glob: Type$1.Optional(Type$1.String({ description: "ripgrep glob filter." })),
28202
- 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({
28203
29724
  minimum: 1,
28204
29725
  description: "Max hits to return."
28205
29726
  })),
28206
- structural: Type$1.Optional(Type$1.Union([Type$1.Literal("full"), Type$1.Literal("topN")], { description: "Structural-ranking depth (lexical mode only)." })),
28207
- 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." })),
28208
- 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.)" })),
28209
- 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." })),
28210
- 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." }))
28211
29732
  });
28212
29733
  }
28213
29734
  function codeSearchToolDescription(searchEnabled, bluebirdEnabled) {
@@ -28377,9 +29898,9 @@ const GIT_DIFF_PRODUCING = /* @__PURE__ */ new Set([
28377
29898
  "show",
28378
29899
  "diff"
28379
29900
  ]);
28380
- const TOOLBELT_PARAMS = Type$1.Object({
28381
- 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)." }),
28382
- 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/…)." }))
28383
29904
  });
28384
29905
  /**
28385
29906
  * True iff `arg` triggers a denied flag. Long flags (`--foo`) match on the
@@ -28489,10 +30010,10 @@ function toolbeltTool(workspace) {
28489
30010
  };
28490
30011
  }
28491
30012
  const PEER_CRITIC_TUPLE = [
28492
- Type$1.Literal("codex_critic"),
28493
- Type$1.Literal("gemini_critic"),
28494
- Type$1.Literal("codex_reviewer"),
28495
- 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")
28496
30017
  ];
28497
30018
  /**
28498
30019
  * Critic names accepted by `peer_review.critic`. Exported for the
@@ -28500,17 +30021,17 @@ const PEER_CRITIC_TUPLE = [
28500
30021
  * against `PERSONAS_READ` from `~/lib/peer-mcp-personas`.
28501
30022
  */
28502
30023
  const PEER_CRITIC_NAMES = PEER_CRITIC_TUPLE.map((l) => l.const);
28503
- const PEER_EFFORT_UNION = Type$1.Union([
28504
- Type$1.Literal("low"),
28505
- Type$1.Literal("medium"),
28506
- Type$1.Literal("high"),
28507
- 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")
28508
30029
  ], { description: "Reasoning depth. Per-critic allowedEfforts gate; out-of-band values are clamped to the critic's default." });
28509
- Type$1.Object({
28510
- 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." }),
28511
- prompt: Type$1.String({ description: "The brief — artifact under review plus constraints. Pasted verbatim into the critic's user message." }),
28512
- context: Type$1.Optional(Type$1.String({ description: "Optional extra context concatenated to the brief." })),
28513
- 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)
28514
30035
  });
28515
30036
  function lookupPersona(critic) {
28516
30037
  const persona = PERSONAS_READ.find((p) => p.toolNameHttp === critic);
@@ -28531,10 +30052,10 @@ function lookupPersona(critic) {
28531
30052
  * `acquireInFlightSlot`, and `callPersona` keeps the slot accounting,
28532
30053
  * effort clamping, and isError-promotion semantics identical.
28533
30054
  */
28534
- const CODEX_REVIEW_PARAMS = Type$1.Object({
28535
- 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." }),
28536
- context: Type$1.Optional(Type$1.String({ description: "Optional extra context concatenated to the brief." })),
28537
- 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)
28538
30059
  });
28539
30060
  function codexReviewTool() {
28540
30061
  return {
@@ -28568,7 +30089,7 @@ function geminiInCatalog() {
28568
30089
  if (!models) return false;
28569
30090
  return models.some((m) => /^gemini-3\..*pro/i.test(m.id));
28570
30091
  }
28571
- const ADVISOR_PARAMS = Type$1.Object({ concern: Type$1.String({
30092
+ const ADVISOR_PARAMS = Type.Object({ concern: Type.String({
28572
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.",
28573
30094
  minLength: 1
28574
30095
  }) });
@@ -28697,22 +30218,22 @@ function advisorTool(getMessages) {
28697
30218
  }
28698
30219
  };
28699
30220
  }
28700
- const UPDATE_PLAN_PARAMS = Type$1.Object({
28701
- steps: Type$1.Array(Type$1.Object({
28702
- title: Type$1.String({
30221
+ const UPDATE_PLAN_PARAMS = Type.Object({
30222
+ steps: Type.Array(Type.Object({
30223
+ title: Type.String({
28703
30224
  minLength: 1,
28704
30225
  description: "Short imperative description of the step."
28705
30226
  }),
28706
- status: Type$1.Union([
28707
- Type$1.Literal("pending"),
28708
- Type$1.Literal("in_progress"),
28709
- Type$1.Literal("completed")
30227
+ status: Type.Union([
30228
+ Type.Literal("pending"),
30229
+ Type.Literal("in_progress"),
30230
+ Type.Literal("completed")
28710
30231
  ], { description: "Current status of this step." })
28711
30232
  }), {
28712
30233
  minItems: 1,
28713
30234
  description: "The FULL ordered plan. Each call replaces the previous plan, so always send every step (not just the changed one)."
28714
30235
  }),
28715
- 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." }))
28716
30237
  });
28717
30238
  function createPlanState() {
28718
30239
  return { current: [] };
@@ -28805,166 +30326,6 @@ function buildWorkerTools(opts) {
28805
30326
  ];
28806
30327
  }
28807
30328
  //#endregion
28808
- //#region src/lib/worker-agent/relay-cap.ts
28809
- /**
28810
- * Relay-safe result capping for the worker MCP boundary.
28811
- *
28812
- * Claude Code hard-caps an MCP tool result at `MAX_MCP_OUTPUT_TOKENS`
28813
- * (default 25,000 tokens ≈ 100KB); a result over that is rejected /
28814
- * truncated before the lead ever sees it. A worker that emits a large
28815
- * `finalText` (an explore/review/plan summary, model prose, or a diff a
28816
- * model pasted inline) would silently lose its output at that boundary.
28817
- *
28818
- * `relaySafeText` is the LAST transform applied to a worker's assembled
28819
- * result text at each MCP boundary (`runWorkerToolCall`,
28820
- * `runBrowseToolCall`) — AFTER any `clampNote` prefix and the browse
28821
- * `[browse session: id]` suffix are appended, so nothing can push a
28822
- * just-capped string back over the limit. When the text exceeds the cap
28823
- * it is written IN FULL to a durable router-owned file and the caller
28824
- * gets a bounded head preview + the file path, so the output is
28825
- * recoverable rather than destroyed.
28826
- *
28827
- * Byte cap as a proxy for the TOKEN limit: worst-case dense output
28828
- * (base64 / hex / minified) approaches ~1 byte/token, so the clamp
28829
- * ceiling (20480 B ≈ 20k tokens) stays safely under the 25k-token cap
28830
- * with headroom. The env override can never widen it past that ceiling,
28831
- * so a misconfiguration cannot reintroduce the overflow.
28832
- */
28833
- /** Default relay-safe byte budget for a worker result. */
28834
- const DEFAULT_MAX_RESULT_BYTES = 16384;
28835
- /** Lower clamp — below this a preview is barely useful. */
28836
- const MIN_MAX_RESULT_BYTES = 8192;
28837
- /**
28838
- * Upper clamp. 20480 B ≈ 20k tokens even at the ~1 byte/token dense
28839
- * worst case, comfortably under Claude Code's 25k-token result cap. The
28840
- * env override is clamped to this, so it can never reintroduce the
28841
- * overflow the cap exists to prevent.
28842
- */
28843
- const MAX_MAX_RESULT_BYTES = 20480;
28844
- /**
28845
- * Age at which a spilled `.patch`/`.txt` is swept. Matches the worktree
28846
- * dir age sweep in `worktree.ts`.
28847
- */
28848
- const AGE_SWEEP_MS$1 = 6048e5;
28849
- /** Min interval between throttled hot-path sweeps (see `sweepAgedWorkerDiffs`). */
28850
- const SWEEP_THROTTLE_MS = 6e4;
28851
- let lastThrottledSweepAt = 0;
28852
- /**
28853
- * Strict name pattern for router-written overflow files:
28854
- * `<pid>-<8hex>.(patch|txt)`. Shared by the sweep so it NEVER removes a
28855
- * file it didn't write (a user could drop something else under the dir).
28856
- */
28857
- const WORKER_DIFF_NAME_RE = /^\d+-[0-9a-f]{8}\.(?:patch|txt)$/;
28858
- /** Resolve the relay-safe byte cap from env, clamped to the safe range. */
28859
- function resolveMaxResultBytes() {
28860
- const raw = process$1.env.GH_ROUTER_WORKER_MAX_RESULT_BYTES;
28861
- if (raw === void 0) return DEFAULT_MAX_RESULT_BYTES;
28862
- const n = Number(raw);
28863
- if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) return DEFAULT_MAX_RESULT_BYTES;
28864
- return Math.min(MAX_MAX_RESULT_BYTES, Math.max(MIN_MAX_RESULT_BYTES, n));
28865
- }
28866
- /**
28867
- * Return the longest prefix of `text` whose UTF-8 encoding is at most
28868
- * `maxBytes` long, cut on a codepoint boundary (never mid-multibyte).
28869
- */
28870
- function utf8HeadPreview(text, maxBytes) {
28871
- if (maxBytes <= 0) return "";
28872
- const buf = Buffer.from(text, "utf8");
28873
- if (buf.length <= maxBytes) return text;
28874
- let end = maxBytes;
28875
- while (end > 0 && (buf[end] & 192) === 128) end--;
28876
- return buf.subarray(0, end).toString("utf8");
28877
- }
28878
- /**
28879
- * Best-effort age sweep of router-written overflow files under
28880
- * `WORKER_DIFFS_DIR`. Only removes entries whose NAME matches
28881
- * `WORKER_DIFF_NAME_RE` and whose mtime is older than 7 days — a fresh
28882
- * file a concurrent worker just wrote (new mtime) is never touched, and
28883
- * a locked file just skips. Errors are swallowed so a sweep never blocks
28884
- * the write it precedes.
28885
- *
28886
- * `opts.throttle` (used by the write hot path) skips the readdir/stat scan
28887
- * when a throttled sweep ran within the last minute, so concurrent overflow
28888
- * writes don't each re-scan the directory. Direct callers (and tests) sweep
28889
- * unconditionally.
28890
- */
28891
- async function sweepAgedWorkerDiffs(opts = {}) {
28892
- if (opts.throttle) {
28893
- const now = Date.now();
28894
- if (now - lastThrottledSweepAt < SWEEP_THROTTLE_MS) return;
28895
- lastThrottledSweepAt = now;
28896
- }
28897
- let entries;
28898
- try {
28899
- entries = await fs$1.readdir(PATHS.WORKER_DIFFS_DIR);
28900
- } catch {
28901
- return;
28902
- }
28903
- const now = Date.now();
28904
- for (const name of entries) {
28905
- if (!WORKER_DIFF_NAME_RE.test(name)) continue;
28906
- const full = path.join(PATHS.WORKER_DIFFS_DIR, name);
28907
- try {
28908
- if (now - (await fs$1.stat(full)).mtimeMs < AGE_SWEEP_MS$1) continue;
28909
- await fs$1.rm(full, { force: true }).catch(() => {});
28910
- } catch {}
28911
- }
28912
- }
28913
- /**
28914
- * Write `text` in full to a durable `.txt` under `WORKER_DIFFS_DIR` and
28915
- * return its absolute path. Unique `<pid>-<8hex>.txt` name, `0o600`,
28916
- * exclusive-create (`wx`) so it never clobbers a pre-existing file /
28917
- * symlink. Retries on the (astronomically rare) name collision with a
28918
- * fresh suffix. Sweeps aged files first (throttled, best-effort).
28919
- */
28920
- async function saveOverflowResult(text) {
28921
- await sweepAgedWorkerDiffs({ throttle: true });
28922
- await fs$1.mkdir(PATHS.WORKER_DIFFS_DIR, { recursive: true });
28923
- let lastErr;
28924
- for (let attempt = 0; attempt < 5; attempt++) {
28925
- const name = `${process$1.pid}-${randomBytes(4).toString("hex")}.txt`;
28926
- const outPath = path.join(PATHS.WORKER_DIFFS_DIR, name);
28927
- try {
28928
- await fs$1.writeFile(outPath, text, {
28929
- mode: 384,
28930
- flag: "wx"
28931
- });
28932
- return outPath;
28933
- } catch (err) {
28934
- if (err.code !== "EEXIST") throw err;
28935
- lastErr = err;
28936
- }
28937
- }
28938
- throw lastErr instanceof Error ? lastErr : /* @__PURE__ */ new Error("saveOverflowResult: exhausted unique-name retries");
28939
- }
28940
- /**
28941
- * Cap a worker result to a relay-safe size. `reservedBytes` is the UTF-8
28942
- * byte length of any must-survive envelope the caller will add OUTSIDE this
28943
- * result (a `clampNote`/`worktreeNote` prefix, or the browse
28944
- * `[browse session: id]` suffix), so the caller's final `envelope + result`
28945
- * (or `result + envelope`) is guaranteed `<=` the configured cap.
28946
- *
28947
- * If the text fits under the effective cap it is returned unchanged.
28948
- * Otherwise the FULL text is spilled to a durable file and a bounded
28949
- * UTF-8-safe head preview + the file path is returned. On write failure the
28950
- * preview is still returned with an explicit failure note — NEVER the
28951
- * oversized original (that would re-trigger the overflow this guard prevents).
28952
- */
28953
- async function relaySafeText(text, reservedBytes = 0) {
28954
- const cap = Math.max(0, resolveMaxResultBytes() - Math.max(0, reservedBytes));
28955
- if (Buffer.byteLength(text, "utf8") <= cap) return text;
28956
- let savedPath = null;
28957
- let saveError = null;
28958
- try {
28959
- savedPath = await saveOverflowResult(text);
28960
- } catch (err) {
28961
- saveError = err instanceof Error ? err.message : String(err);
28962
- }
28963
- 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"}]`;
28964
- const out = utf8HeadPreview(text, Math.max(0, cap - Buffer.byteLength(trailer, "utf8"))) + trailer;
28965
- return Buffer.byteLength(out, "utf8") <= cap ? out : utf8HeadPreview(out, cap);
28966
- }
28967
- //#endregion
28968
30329
  //#region src/lib/worker-agent/worktree.ts
28969
30330
  /**
28970
30331
  * Git worktree provisioning for `worker_implement({worktree: true})`.
@@ -29785,7 +31146,7 @@ async function runWorkerAgentOnce(opts) {
29785
31146
  if (a.trim()) terminalText = a;
29786
31147
  }
29787
31148
  },
29788
- shouldStopAfterTurn: () => budget.hardStopReason !== null,
31149
+ finishTurn: () => budget.hardStopReason !== null ? { action: "end" } : void 0,
29789
31150
  afterToolCall: async (ctx) => {
29790
31151
  budget.recordToolBytes(ctx.result);
29791
31152
  if (ctxBudget) {
@@ -31371,7 +32732,9 @@ const MCP_GROUPS = Object.freeze([
31371
32732
  "browser",
31372
32733
  "decide",
31373
32734
  "fleet",
31374
- "first-mate"
32735
+ "first-mate",
32736
+ "ado",
32737
+ "kusto"
31375
32738
  ]);
31376
32739
  const GROUP_META = Object.freeze({
31377
32740
  peers: {
@@ -31413,6 +32776,16 @@ const GROUP_META = Object.freeze({
31413
32776
  preferredKey: "first-mate",
31414
32777
  urlSuffix: "first-mate",
31415
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"
31416
32789
  }
31417
32790
  });
31418
32791
  /** True iff `s` is a registered group name (route `:group` param validation). */
@@ -32144,6 +33517,34 @@ function formatWebSearchResult(results) {
32144
33517
  return `${results.content}\n\n## References\n${refsLine}`;
32145
33518
  }
32146
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
+ /**
32147
33548
  * Build the `code` tool description for the launch's search capability.
32148
33549
  * When semantic search is available the default mode ranks by meaning via
32149
33550
  * ColBERT with transparent lexical fallback; otherwise the tool is described
@@ -32183,6 +33584,23 @@ function buildBluebirdCodeToolDescription() {
32183
33584
  function buildBluebirdCodeModeDescription() {
32184
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`).";
32185
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.";
32186
33604
  const NON_PERSONA_MCP_TOOLS = Object.freeze([
32187
33605
  {
32188
33606
  toolNameHttp: "web",
@@ -32372,6 +33790,73 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32372
33790
  }
32373
33791
  }
32374
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
+ },
32375
33860
  {
32376
33861
  toolNameHttp: "worker_defaults",
32377
33862
  group: "workers",
@@ -32450,7 +33935,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32450
33935
  toolNameHttp: "explore",
32451
33936
  group: "workers",
32452
33937
  capability: "worker",
32453
- 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,
32454
33939
  inputSchema: {
32455
33940
  type: "object",
32456
33941
  required: ["prompt"],
@@ -32462,7 +33947,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32462
33947
  },
32463
33948
  model: {
32464
33949
  type: "string",
32465
- 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
32466
33951
  },
32467
33952
  thinking: {
32468
33953
  type: "string",
@@ -32492,7 +33977,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32492
33977
  toolNameHttp: "implement",
32493
33978
  group: "workers",
32494
33979
  capability: "worker",
32495
- 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,
32496
33981
  inputSchema: {
32497
33982
  type: "object",
32498
33983
  required: ["prompt"],
@@ -32508,7 +33993,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32508
33993
  },
32509
33994
  model: {
32510
33995
  type: "string",
32511
- 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
32512
33997
  },
32513
33998
  thinking: {
32514
33999
  type: "string",
@@ -32538,7 +34023,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32538
34023
  toolNameHttp: "review",
32539
34024
  group: "workers",
32540
34025
  capability: "worker",
32541
- 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,
32542
34027
  inputSchema: {
32543
34028
  type: "object",
32544
34029
  required: ["prompt"],
@@ -32550,7 +34035,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32550
34035
  },
32551
34036
  model: {
32552
34037
  type: "string",
32553
- 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
32554
34039
  },
32555
34040
  thinking: {
32556
34041
  type: "string",
@@ -32584,7 +34069,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32584
34069
  toolNameHttp: "plan",
32585
34070
  group: "workers",
32586
34071
  capability: "worker",
32587
- 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,
32588
34073
  inputSchema: {
32589
34074
  type: "object",
32590
34075
  required: ["prompt"],
@@ -32626,7 +34111,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32626
34111
  toolNameHttp: "test",
32627
34112
  group: "workers",
32628
34113
  capability: "worker",
32629
- 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,
32630
34115
  inputSchema: {
32631
34116
  type: "object",
32632
34117
  required: ["prompt"],
@@ -32874,7 +34359,7 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32874
34359
  toolNameHttp: "browse",
32875
34360
  group: "workers",
32876
34361
  capability: "browse_agent",
32877
- 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,
32878
34363
  inputSchema: {
32879
34364
  type: "object",
32880
34365
  required: ["task"],
@@ -32958,9 +34443,26 @@ const NON_PERSONA_MCP_TOOLS = Object.freeze([
32958
34443
  ...t,
32959
34444
  group: "browser",
32960
34445
  toolNameHttp: t.toolNameHttp.replace(/^browser_/, "")
32961
- }))
34446
+ })),
34447
+ ...KUSTO_TOOLS
32962
34448
  ]);
32963
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
+ /**
32964
34466
  * Startup invariant: every MCP tool name must be unique within its group
32965
34467
  * AND across the unscoped `/mcp` union. `handleToolsCall` keys dispatch on
32966
34468
  * the bare tool name, so a duplicate would silently shadow — this assertion
@@ -33349,6 +34851,6 @@ function enumerateInjectedMcpToolNames(groupKeys, opts = {}) {
33349
34851
  return [...new Set(names)];
33350
34852
  }
33351
34853
  //#endregion
33352
- 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 };
33353
34855
 
33354
- //# sourceMappingURL=peer-mcp-personas-D_gRB57l.js.map
34856
+ //# sourceMappingURL=peer-mcp-personas-DDMKRFFG.js.map