github-router 0.3.350 → 0.3.352
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +72 -0
- package/README.md +19 -0
- package/dist/ado-tools-xbuVU7YN.js +1 -0
- package/dist/{aic-ledger-D4oMcg7c.js → aic-ledger-BdvCgRmx.js} +3 -3
- package/dist/{aic-ledger-D4oMcg7c.js.map → aic-ledger-BdvCgRmx.js.map} +1 -1
- package/dist/{aic-statusline-settings-DCFywz3N.js → aic-statusline-settings-LnoxjBPe.js} +2 -2
- package/dist/{aic-statusline-settings-DCFywz3N.js.map → aic-statusline-settings-LnoxjBPe.js.map} +1 -1
- package/dist/{attribution-settings-B9T-EsEs.js → attribution-settings-ul6VU6iP.js} +11 -650
- package/dist/attribution-settings-ul6VU6iP.js.map +1 -0
- package/dist/{auth-Cgsy2T0s.js → auth-a_1lXYZ1.js} +4 -4
- package/dist/{auth-Cgsy2T0s.js.map → auth-a_1lXYZ1.js.map} +1 -1
- package/dist/{bluebird-client-DpYl1YmJ.js → bluebird-client-ltPIiyJU.js} +1103 -499
- package/dist/bluebird-client-ltPIiyJU.js.map +1 -0
- package/dist/bluebird-client-mr3M67k-.js +1 -0
- package/dist/browser-bridge/index.js +116 -98
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-26G2hw_F.js → check-usage-Bsbc-Sn6.js} +4 -4
- package/dist/{check-usage-26G2hw_F.js.map → check-usage-Bsbc-Sn6.js.map} +1 -1
- package/dist/claude-md-injection-BoXOsg7h.js +669 -0
- package/dist/claude-md-injection-BoXOsg7h.js.map +1 -0
- package/dist/{claude-BY4e9ueE.js → claude-xO1XW-Nn.js} +79 -51
- package/dist/claude-xO1XW-Nn.js.map +1 -0
- package/dist/{codex-BOugL-uX.js → codex-DzUR40JA.js} +10 -8
- package/dist/{codex-BOugL-uX.js.map → codex-DzUR40JA.js.map} +1 -1
- package/dist/{copilot-discount-CilBhKQW.js → copilot-discount-C3jfysK-.js} +2 -2
- package/dist/{copilot-discount-CilBhKQW.js.map → copilot-discount-C3jfysK-.js.map} +1 -1
- package/dist/{debug-CigFsS-h.js → debug-BtqbflcL.js} +2 -2
- package/dist/{debug-CigFsS-h.js.map → debug-BtqbflcL.js.map} +1 -1
- package/dist/engine-DwLIk1Zn.js +1 -0
- package/dist/{exec-MCU1H-KZ.js → exec-Bf8g_bIR.js} +27 -2
- package/dist/exec-Bf8g_bIR.js.map +1 -0
- package/dist/{gate-discovery-BFqulsWz.js → gate-discovery-Cvdko01z.js} +6 -6
- package/dist/{gate-discovery-BFqulsWz.js.map → gate-discovery-Cvdko01z.js.map} +1 -1
- package/dist/{get-copilot-usage-C_6ast5h.js → get-copilot-usage-0_S8pRWJ.js} +3 -3
- package/dist/{get-copilot-usage-C_6ast5h.js.map → get-copilot-usage-0_S8pRWJ.js.map} +1 -1
- package/dist/{hook-mcp-client-BRL_y-bz.js → hook-mcp-client-DERIkeR7.js} +5 -3
- package/dist/{hook-mcp-client-BRL_y-bz.js.map → hook-mcp-client-DERIkeR7.js.map} +1 -1
- package/dist/hooks.mjs +10998 -6840
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-DXYWgKS6.js → index-cmd-CJXUOH4q.js} +5 -5
- package/dist/{index-cmd-DXYWgKS6.js.map → index-cmd-CJXUOH4q.js.map} +1 -1
- package/dist/{internal-aic-status-lM0YNDaH.js → internal-aic-status-Dmi2bCsR.js} +4 -4
- package/dist/{internal-aic-status-lM0YNDaH.js.map → internal-aic-status-Dmi2bCsR.js.map} +1 -1
- package/dist/{internal-artifact-open-DErO3WpR.js → internal-artifact-open-C67gDjKo.js} +2 -2
- package/dist/{internal-artifact-open-DErO3WpR.js.map → internal-artifact-open-C67gDjKo.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-DRsZJ-Rg.js → internal-fast-dispatch-guard-BQm1MI9d.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-DRsZJ-Rg.js.map → internal-fast-dispatch-guard-BQm1MI9d.js.map} +1 -1
- package/dist/internal-fast-dispatch-guard-Cv7zf0ZI.js +1 -0
- package/dist/{internal-first-mate-guard-BEwDjHfX.js → internal-first-mate-guard-BJvCsVlU.js} +3 -3
- package/dist/{internal-first-mate-guard-BEwDjHfX.js.map → internal-first-mate-guard-BJvCsVlU.js.map} +1 -1
- package/dist/internal-first-mate-guard-D-IQGiTs.js +1 -0
- package/dist/{internal-max-dispatch-guard-DSjJwVH2.js → internal-max-dispatch-guard-DkJixDmG.js} +7 -5
- package/dist/{internal-max-dispatch-guard-DSjJwVH2.js.map → internal-max-dispatch-guard-DkJixDmG.js.map} +1 -1
- package/dist/internal-max-dispatch-guard-T-M7DRIW.js +1 -0
- package/dist/{internal-plan-review-DbX-mr9i.js → internal-plan-review-DIvaBBUd.js} +4 -4
- package/dist/{internal-plan-review-DbX-mr9i.js.map → internal-plan-review-DIvaBBUd.js.map} +1 -1
- package/dist/internal-prompt-submit-6OXEdQCK.js +2 -0
- package/dist/internal-prompt-submit-B9MJxc3K.js +194 -0
- package/dist/internal-prompt-submit-B9MJxc3K.js.map +1 -0
- package/dist/{internal-rebrief-BH9PMJhF.js → internal-rebrief-zIdunX3R.js} +6 -6
- package/dist/{internal-rebrief-BH9PMJhF.js.map → internal-rebrief-zIdunX3R.js.map} +1 -1
- package/dist/{internal-session-bind-DxdVbJ7x.js → internal-session-bind-CQLDPuTx.js} +2 -2
- package/dist/{internal-session-bind-DxdVbJ7x.js.map → internal-session-bind-CQLDPuTx.js.map} +1 -1
- package/dist/{internal-stop-hook-DlGc9WwJ.js → internal-stop-hook-DGcRVh_2.js} +7 -7
- package/dist/{internal-stop-hook-DlGc9WwJ.js.map → internal-stop-hook-DGcRVh_2.js.map} +1 -1
- package/dist/{internal-stop-review-CORT3UGr.js → internal-stop-review-X7zRRhyc.js} +3 -3
- package/dist/{internal-stop-review-CORT3UGr.js.map → internal-stop-review-X7zRRhyc.js.map} +1 -1
- package/dist/{internal-worker-guard-C0FJ4b29.js → internal-worker-guard-wP3UN-3D.js} +2 -2
- package/dist/{internal-worker-guard-C0FJ4b29.js.map → internal-worker-guard-wP3UN-3D.js.map} +1 -1
- package/dist/{internal-workspace-header-tvJVAXpv.js → internal-workspace-header-DiUnkUeU.js} +2 -2
- package/dist/{internal-workspace-header-tvJVAXpv.js.map → internal-workspace-header-DiUnkUeU.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/worker.js +1 -2
- package/dist/{lifecycle-BqWTXaeC.js → lifecycle-BJ83L0tz.js} +3 -3
- package/dist/{lifecycle-BqWTXaeC.js.map → lifecycle-BJ83L0tz.js.map} +1 -1
- package/dist/lifecycle-CVg2-zQ3.js +1 -0
- package/dist/lifecycle-Dk_BHtfz.js +1 -0
- package/dist/{lifecycle-kpLzHUgD.js → lifecycle-aApO0hZW.js} +2 -2
- package/dist/{lifecycle-kpLzHUgD.js.map → lifecycle-aApO0hZW.js.map} +1 -1
- package/dist/main.js +23 -23
- package/dist/{max-profile-contract--dAYkEG1.js → max-profile-contract-DQDEDCsR.js} +2 -2
- package/dist/{max-profile-contract--dAYkEG1.js.map → max-profile-contract-DQDEDCsR.js.map} +1 -1
- package/dist/{mcp-workspace-header-B77WqVFw.js → mcp-workspace-header-DBQugQlQ.js} +2 -2
- package/dist/{mcp-workspace-header-B77WqVFw.js.map → mcp-workspace-header-DBQugQlQ.js.map} +1 -1
- package/dist/{models-BGCeGVXl.js → models-JIvKAGn0.js} +3 -3
- package/dist/{models-BGCeGVXl.js.map → models-JIvKAGn0.js.map} +1 -1
- package/dist/{orchestration-Dkqv-iv0.js → orchestration-D-S_0GVt.js} +3 -3
- package/dist/{orchestration-Dkqv-iv0.js.map → orchestration-D-S_0GVt.js.map} +1 -1
- package/dist/paths-C9x5U3dO.js +1 -0
- package/dist/{paths-CpbTHKeP.js → paths-xTSEAWfN.js} +115 -22
- package/dist/paths-xTSEAWfN.js.map +1 -0
- package/dist/{peer-mcp-personas-BwwSNnBC.js → peer-mcp-personas-DDMKRFFG.js} +2350 -836
- package/dist/peer-mcp-personas-DDMKRFFG.js.map +1 -0
- package/dist/{pi-Dpw8Otxw.js → pi-jVNeQXWf.js} +362 -37
- package/dist/pi-jVNeQXWf.js.map +1 -0
- package/dist/{plan-review-hook-LfG01VMp.js → plan-review-hook-BQ29WGv7.js} +5 -5
- package/dist/{plan-review-hook-LfG01VMp.js.map → plan-review-hook-BQ29WGv7.js.map} +1 -1
- package/dist/{provision-9TAIgyL7.js → provision-BtYRtvrj.js} +26 -18
- package/dist/provision-BtYRtvrj.js.map +1 -0
- package/dist/{self-invocation-DIUyoRgL.js → self-invocation-Dr5zlbpM.js} +2 -2
- package/dist/{self-invocation-DIUyoRgL.js.map → self-invocation-Dr5zlbpM.js.map} +1 -1
- package/dist/{serve-BRKRWkd1.js → serve-CmgmxigM.js} +35 -17
- package/dist/serve-CmgmxigM.js.map +1 -0
- package/dist/{server-setup-DXVFE7bf.js → server-setup-DinOFWiC.js} +393 -42
- package/dist/server-setup-DinOFWiC.js.map +1 -0
- package/dist/{service-backend-7SPDLUB9.js → service-backend-DV1u5x0Q.js} +51 -23
- package/dist/service-backend-DV1u5x0Q.js.map +1 -0
- package/dist/{start-CoR3jqUR.js → start-Dgsaz0HM.js} +4 -4
- package/dist/{start-CoR3jqUR.js.map → start-Dgsaz0HM.js.map} +1 -1
- package/dist/{state-CVp30CBF.js → state-CfEVoqBM.js} +8 -1
- package/dist/{state-CVp30CBF.js.map → state-CfEVoqBM.js.map} +1 -1
- package/dist/{prompt-submit-hook-DzhmQRs_.js → static-context-pack-CyucviRD.js} +402 -4
- package/dist/static-context-pack-CyucviRD.js.map +1 -0
- package/dist/{stop-gate-hook-C9VNxmt1.js → stop-gate-hook-BYd0NruJ.js} +4 -4
- package/dist/{stop-gate-hook-C9VNxmt1.js.map → stop-gate-hook-BYd0NruJ.js.map} +1 -1
- package/dist/{stop-gate-policy-DQsfjnsx.js → stop-gate-policy-FGAfpfc-.js} +3 -3
- package/dist/{stop-gate-policy-DQsfjnsx.js.map → stop-gate-policy-FGAfpfc-.js.map} +1 -1
- package/dist/{token-s5Wd-Kwr.js → token-CTf5jCmP.js} +7 -5
- package/dist/{token-s5Wd-Kwr.js.map → token-CTf5jCmP.js.map} +1 -1
- package/dist/{worker-dispatch-lRhno09M.js → worker-dispatch-BjfROaic.js} +2 -2
- package/dist/{worker-dispatch-lRhno09M.js.map → worker-dispatch-BjfROaic.js.map} +1 -1
- package/docs/azure-mcp.md +453 -0
- package/docs/bluebird-search.md +96 -7
- package/package.json +22 -22
- package/dist/attribution-settings-B9T-EsEs.js.map +0 -1
- package/dist/bluebird-client-DpYl1YmJ.js.map +0 -1
- package/dist/bluebird-client-bn9Yv6Cb.js +0 -2
- package/dist/claude-BY4e9ueE.js.map +0 -1
- package/dist/engine-DZfLaVcf.js +0 -2
- package/dist/exec-MCU1H-KZ.js.map +0 -1
- package/dist/internal-fast-dispatch-guard-DeZ6KilC.js +0 -2
- package/dist/internal-first-mate-guard-CAefr6Ce.js +0 -2
- package/dist/internal-max-dispatch-guard-KmbYwh7h.js +0 -2
- package/dist/internal-prompt-submit-CA5Y4DWM.js +0 -2
- package/dist/internal-prompt-submit-UhfnM_qG.js +0 -573
- package/dist/internal-prompt-submit-UhfnM_qG.js.map +0 -1
- package/dist/lifecycle-DMRZswwc.js +0 -2
- package/dist/lifecycle-FT75ohVw.js +0 -2
- package/dist/paths-CpbTHKeP.js.map +0 -1
- package/dist/paths-Dfivvq21.js +0 -2
- package/dist/peer-mcp-personas-BwwSNnBC.js.map +0 -1
- package/dist/pi-Dpw8Otxw.js.map +0 -1
- package/dist/prompt-submit-hook-DzhmQRs_.js.map +0 -1
- package/dist/provision-9TAIgyL7.js.map +0 -1
- package/dist/serve-BRKRWkd1.js.map +0 -1
- package/dist/server-setup-DXVFE7bf.js.map +0 -1
- package/dist/service-backend-7SPDLUB9.js.map +0 -1
|
@@ -1,6 +1,865 @@
|
|
|
1
|
-
import { t as state } from "./state-
|
|
1
|
+
import { t as state } from "./state-CfEVoqBM.js";
|
|
2
2
|
import { i as sanitizeTransportText } from "./upstream-retry-i1k1Xai2.js";
|
|
3
|
-
import {
|
|
3
|
+
import { c as runCommandCapture, l as runCommandInherit, s as resolveExecutable } from "./exec-Bf8g_bIR.js";
|
|
4
|
+
import consola from "consola";
|
|
5
|
+
//#region src/lib/remote-mcp-client.ts
|
|
6
|
+
/**
|
|
7
|
+
* Shared streamable-HTTP MCP transport (protocol 2025-06-18).
|
|
8
|
+
*
|
|
9
|
+
* Extracted from the Bluebird client so the Azure DevOps MCP group can reuse
|
|
10
|
+
* the same JSON-RPC framing, JSON-or-SSE response parsing, stateless-or-session
|
|
11
|
+
* handling, single-flight token refresh, and 401/404 recovery without a second
|
|
12
|
+
* implementation of any of it.
|
|
13
|
+
*
|
|
14
|
+
* What deliberately stays OUT of this file: the endpoint and its auth (a
|
|
15
|
+
* `tokenProvider` closure), any static scope headers, the tool set the server
|
|
16
|
+
* is expected to advertise, and everything about interpreting a `tools/call`
|
|
17
|
+
* result. The transport knows nothing about code search, and a caller that
|
|
18
|
+
* wants a filtered tool listing does the filtering itself.
|
|
19
|
+
*
|
|
20
|
+
* Retry: retriable statuses (429/500/502/503/504) and transport errors are
|
|
21
|
+
* retried up to 3 attempts with exponential backoff (1s/2s/4s); a 401 refreshes
|
|
22
|
+
* the token and re-initializes once; a 404 recreates the session. Anything else
|
|
23
|
+
* throws an instance of the configured `errorClass` for the caller to surface.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Base error for a remote MCP client. Subclasses exist so a caller can catch
|
|
27
|
+
* exactly one service's failures (`BluebirdError`, `AdoError`) while every
|
|
28
|
+
* client shares this class's `retriable`/`status`/`retryAfterMs` contract,
|
|
29
|
+
* which is what the retry and recovery paths actually read.
|
|
30
|
+
*/
|
|
31
|
+
var RemoteMcpError = class extends Error {
|
|
32
|
+
retriable;
|
|
33
|
+
status;
|
|
34
|
+
retryAfterMs;
|
|
35
|
+
constructor(message, opts = {}) {
|
|
36
|
+
super(sanitizeRemoteDetail(message));
|
|
37
|
+
this.name = "RemoteMcpError";
|
|
38
|
+
this.retriable = opts.retriable ?? false;
|
|
39
|
+
if (opts.status !== void 0) this.status = opts.status;
|
|
40
|
+
if (opts.retryAfterMs !== void 0) this.retryAfterMs = opts.retryAfterMs;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
function isRecord(value) {
|
|
44
|
+
return typeof value === "object" && value !== null;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Strip credentials and infrastructure detail from anything that may reach a
|
|
48
|
+
* log or a tool result. Bearer tokens, absolute URLs, and `git@` remotes are
|
|
49
|
+
* replaced wholesale: a sanitizer that tries to keep the "useful" part of a
|
|
50
|
+
* secret is one regex bug away from leaking it.
|
|
51
|
+
*/
|
|
52
|
+
function sanitizeRemoteDetail(value) {
|
|
53
|
+
return sanitizeTransportText(value instanceof Error ? value.message : String(value)).replace(/\bBearer\s+[^\s,;]+/gi, "Bearer [REDACTED]").replace(/\b(?:https?|ssh):\/\/[^\s"'<>]+/gi, "[REDACTED URL]").replace(/\bgit@[^\s:]+:[^\s]+/gi, "[REDACTED REMOTE]");
|
|
54
|
+
}
|
|
55
|
+
function sleep(ms, signal) {
|
|
56
|
+
if (signal?.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
57
|
+
return new Promise((resolve, reject) => {
|
|
58
|
+
let settled = false;
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
settled = true;
|
|
61
|
+
signal?.removeEventListener("abort", onAbort);
|
|
62
|
+
resolve();
|
|
63
|
+
}, ms);
|
|
64
|
+
const onAbort = () => {
|
|
65
|
+
if (settled) return;
|
|
66
|
+
settled = true;
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
signal?.removeEventListener("abort", onAbort);
|
|
69
|
+
reject(signal?.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
70
|
+
};
|
|
71
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function isAbortError(err) {
|
|
75
|
+
return err instanceof Error && (err.name === "AbortError" || err.message === "aborted" || err.message === "This operation was aborted");
|
|
76
|
+
}
|
|
77
|
+
function waitForSignal(promise, signal) {
|
|
78
|
+
if (!signal) return promise;
|
|
79
|
+
if (signal.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
const onAbort = () => {
|
|
82
|
+
signal.removeEventListener("abort", onAbort);
|
|
83
|
+
reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
84
|
+
};
|
|
85
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
86
|
+
promise.then((value) => {
|
|
87
|
+
signal.removeEventListener("abort", onAbort);
|
|
88
|
+
resolve(value);
|
|
89
|
+
}, (err) => {
|
|
90
|
+
signal.removeEventListener("abort", onAbort);
|
|
91
|
+
reject(err);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
function canonicalWorkspace(workspace) {
|
|
96
|
+
return workspace.replace(/[\\/]+$/, "").toLowerCase() || workspace.toLowerCase();
|
|
97
|
+
}
|
|
98
|
+
function scopeFingerprint(workspace, scope) {
|
|
99
|
+
const repos = [...scope.repositories].map((repo) => repo.toLowerCase()).sort().join(",");
|
|
100
|
+
return `${canonicalWorkspace(workspace)}::${scope.organization.toLowerCase()}/${scope.project.toLowerCase()}/${repos}@${(scope.branch ?? "").toLowerCase()}`;
|
|
101
|
+
}
|
|
102
|
+
function sameJsonRpcId(actual, expected) {
|
|
103
|
+
return actual === expected || typeof actual === "number" && typeof expected === "number" && actual === expected;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* `Retry-After` (delta-seconds or HTTP-date) in milliseconds, clamped to
|
|
107
|
+
* 5 minutes. Exported because the Kusto REST client is not an MCP transport
|
|
108
|
+
* but must read the header the same way: two parsers would drift on the
|
|
109
|
+
* clamp and on which malformed values mean "no hint".
|
|
110
|
+
*/
|
|
111
|
+
function parseRetryAfter(value) {
|
|
112
|
+
if (!value) return void 0;
|
|
113
|
+
const seconds = Number(value.trim());
|
|
114
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(3e5, Math.floor(seconds * 1e3));
|
|
115
|
+
const timestamp = Date.parse(value);
|
|
116
|
+
if (!Number.isFinite(timestamp)) return void 0;
|
|
117
|
+
return Math.max(0, Math.min(3e5, timestamp - Date.now()));
|
|
118
|
+
}
|
|
119
|
+
function matchingJsonRpcResponse(candidate, expectedId) {
|
|
120
|
+
if (!isRecord(candidate)) return void 0;
|
|
121
|
+
const response = candidate;
|
|
122
|
+
if (response.result === void 0 && response.error === void 0) return void 0;
|
|
123
|
+
return sameJsonRpcId(response.id, expectedId) ? response : void 0;
|
|
124
|
+
}
|
|
125
|
+
function parseJsonResponse(text, expectedId, errorClass, label) {
|
|
126
|
+
try {
|
|
127
|
+
const response = matchingJsonRpcResponse(JSON.parse(text), expectedId);
|
|
128
|
+
if (response) return response;
|
|
129
|
+
} catch {}
|
|
130
|
+
throw new errorClass(`${label} returned no matching JSON-RPC response.`, { retriable: true });
|
|
131
|
+
}
|
|
132
|
+
async function parseSseResponse(response, expectedId, errorClass, label, signal) {
|
|
133
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
134
|
+
if (!response.body) throw new errorClass(`${label} returned an empty SSE response.`, { retriable: true });
|
|
135
|
+
const reader = response.body.getReader();
|
|
136
|
+
const decoder = new TextDecoder();
|
|
137
|
+
let buffer = "";
|
|
138
|
+
let dataLines = [];
|
|
139
|
+
const inspectEvent = () => {
|
|
140
|
+
if (dataLines.length === 0) return void 0;
|
|
141
|
+
const data = dataLines.join("\n");
|
|
142
|
+
dataLines = [];
|
|
143
|
+
try {
|
|
144
|
+
return matchingJsonRpcResponse(JSON.parse(data), expectedId);
|
|
145
|
+
} catch {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
let abortListener;
|
|
150
|
+
const abortPromise = signal ? new Promise((_, reject) => {
|
|
151
|
+
abortListener = () => {
|
|
152
|
+
reader.cancel().catch(() => {});
|
|
153
|
+
reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
154
|
+
};
|
|
155
|
+
if (signal.aborted) abortListener();
|
|
156
|
+
else signal.addEventListener("abort", abortListener, { once: true });
|
|
157
|
+
}) : void 0;
|
|
158
|
+
try {
|
|
159
|
+
while (true) {
|
|
160
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
161
|
+
const readPromise = reader.read();
|
|
162
|
+
readPromise.catch(() => {});
|
|
163
|
+
const { value, done } = abortPromise ? await Promise.race([readPromise, abortPromise]) : await readPromise;
|
|
164
|
+
buffer += decoder.decode(value, { stream: !done });
|
|
165
|
+
let newline;
|
|
166
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
167
|
+
const line = buffer.slice(0, newline).replace(/\r$/, "");
|
|
168
|
+
buffer = buffer.slice(newline + 1);
|
|
169
|
+
if (line === "") {
|
|
170
|
+
const match = inspectEvent();
|
|
171
|
+
if (match) return match;
|
|
172
|
+
} else if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
173
|
+
}
|
|
174
|
+
if (done) {
|
|
175
|
+
if (buffer) {
|
|
176
|
+
const line = buffer.replace(/\r$/, "");
|
|
177
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
178
|
+
}
|
|
179
|
+
const match = inspectEvent();
|
|
180
|
+
if (match) return match;
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
} finally {
|
|
185
|
+
if (signal && abortListener) signal.removeEventListener("abort", abortListener);
|
|
186
|
+
await reader.cancel().catch(() => {});
|
|
187
|
+
reader.releaseLock();
|
|
188
|
+
}
|
|
189
|
+
throw new errorClass(`${label} returned no matching JSON-RPC response.`, { retriable: true });
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* One streamable-HTTP MCP session: `initialize` → `notifications/initialized`
|
|
193
|
+
* → paginated `tools/list` → `tools/call`, with JSON or SSE responses and
|
|
194
|
+
* optional server-assigned session ids.
|
|
195
|
+
*/
|
|
196
|
+
var RemoteMcpClient = class {
|
|
197
|
+
config;
|
|
198
|
+
baseUrl;
|
|
199
|
+
toolSchemas = /* @__PURE__ */ new Map();
|
|
200
|
+
token;
|
|
201
|
+
initialized = false;
|
|
202
|
+
initialization;
|
|
203
|
+
refreshPromise;
|
|
204
|
+
sessionId;
|
|
205
|
+
nextId = 1;
|
|
206
|
+
disposed = false;
|
|
207
|
+
disposalController = new AbortController();
|
|
208
|
+
tokenGeneration = 0;
|
|
209
|
+
sessionGeneration = 0;
|
|
210
|
+
constructor(config) {
|
|
211
|
+
this.config = config;
|
|
212
|
+
this.baseUrl = config.baseUrl;
|
|
213
|
+
this.token = config.token;
|
|
214
|
+
}
|
|
215
|
+
error(message, opts = {}) {
|
|
216
|
+
return new this.config.errorClass(message, opts);
|
|
217
|
+
}
|
|
218
|
+
headers(extra) {
|
|
219
|
+
const headers = {
|
|
220
|
+
"Content-Type": "application/json",
|
|
221
|
+
Accept: "application/json, text/event-stream",
|
|
222
|
+
"MCP-Protocol-Version": this.config.protocolVersion,
|
|
223
|
+
Authorization: `Bearer ${this.token}`,
|
|
224
|
+
...this.config.staticHeaders?.() ?? {},
|
|
225
|
+
...extra
|
|
226
|
+
};
|
|
227
|
+
if (this.sessionId) headers["Mcp-Session-Id"] = this.sessionId;
|
|
228
|
+
return headers;
|
|
229
|
+
}
|
|
230
|
+
composeRequestSignal(caller, timeoutMs = 3e4) {
|
|
231
|
+
const disposal = this.disposalController.signal;
|
|
232
|
+
const controller = new AbortController();
|
|
233
|
+
const onCallerAbort = () => {
|
|
234
|
+
controller.abort(caller?.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
235
|
+
};
|
|
236
|
+
const onDisposalAbort = () => {
|
|
237
|
+
controller.abort(disposal?.reason ?? this.error(`${this.config.label} client has been disposed.`, { retriable: false }));
|
|
238
|
+
};
|
|
239
|
+
if (disposal?.aborted) onDisposalAbort();
|
|
240
|
+
else disposal?.addEventListener("abort", onDisposalAbort, { once: true });
|
|
241
|
+
if (caller?.aborted) onCallerAbort();
|
|
242
|
+
else caller?.addEventListener("abort", onCallerAbort, { once: true });
|
|
243
|
+
const timer = setTimeout(() => {
|
|
244
|
+
controller.abort(/* @__PURE__ */ new Error(`${this.config.label} request timed out`));
|
|
245
|
+
}, timeoutMs);
|
|
246
|
+
timer.unref?.();
|
|
247
|
+
return {
|
|
248
|
+
signal: controller.signal,
|
|
249
|
+
cleanup: () => {
|
|
250
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
251
|
+
caller?.removeEventListener("abort", onCallerAbort);
|
|
252
|
+
disposal?.removeEventListener("abort", onDisposalAbort);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
disposedError() {
|
|
257
|
+
return this.error(`${this.config.label} client has been disposed.`, { retriable: false });
|
|
258
|
+
}
|
|
259
|
+
async post(payload, signal, requestSessionGen) {
|
|
260
|
+
const label = this.config.label;
|
|
261
|
+
if (this.disposed) throw this.disposedError();
|
|
262
|
+
const { signal: requestSignal, cleanup } = this.composeRequestSignal(signal);
|
|
263
|
+
const notification = typeof payload.method === "string" && payload.method.startsWith("notifications/");
|
|
264
|
+
try {
|
|
265
|
+
let res;
|
|
266
|
+
try {
|
|
267
|
+
res = await fetch(this.baseUrl, {
|
|
268
|
+
method: "POST",
|
|
269
|
+
headers: this.headers(),
|
|
270
|
+
body: JSON.stringify(payload),
|
|
271
|
+
signal: requestSignal
|
|
272
|
+
});
|
|
273
|
+
} catch (err) {
|
|
274
|
+
if (this.disposed) throw this.disposedError();
|
|
275
|
+
if (isAbortError(err) || requestSignal.aborted) throw this.error(signal?.aborted ? `${label} request was cancelled.` : `${label} request timed out.`, { retriable: false });
|
|
276
|
+
throw this.error(`${label} transport failed: ${sanitizeRemoteDetail(err)}`, { retriable: true });
|
|
277
|
+
}
|
|
278
|
+
if (this.disposed) throw this.disposedError();
|
|
279
|
+
const session = res.headers.get("mcp-session-id");
|
|
280
|
+
if (session) {
|
|
281
|
+
if (requestSessionGen === void 0 || requestSessionGen === this.sessionGeneration) this.sessionId = session;
|
|
282
|
+
}
|
|
283
|
+
if (res.status === 401) throw this.error(`${label} rejected the access token (401).`, {
|
|
284
|
+
retriable: false,
|
|
285
|
+
status: 401
|
|
286
|
+
});
|
|
287
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
288
|
+
if ([
|
|
289
|
+
429,
|
|
290
|
+
500,
|
|
291
|
+
502,
|
|
292
|
+
503,
|
|
293
|
+
504
|
|
294
|
+
].includes(res.status)) throw this.error(`${label} responded with HTTP ${res.status}.`, {
|
|
295
|
+
retriable: true,
|
|
296
|
+
status: res.status,
|
|
297
|
+
...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
|
|
298
|
+
});
|
|
299
|
+
if (!res.ok) {
|
|
300
|
+
const body = await res.text().catch(() => "");
|
|
301
|
+
const detail = body ? sanitizeTransportText(body).slice(0, 300) : "";
|
|
302
|
+
throw this.error(`${label} responded with HTTP ${res.status}${detail ? `: ${detail}` : ""}.`, {
|
|
303
|
+
retriable: false,
|
|
304
|
+
status: res.status
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
if (notification && (res.status === 202 || res.status === 204)) return { jsonrpc: "2.0" };
|
|
308
|
+
if (res.headers.get("content-type")?.includes("text/event-stream")) try {
|
|
309
|
+
return await parseSseResponse(res, payload.id, this.config.errorClass, label, requestSignal);
|
|
310
|
+
} catch (err) {
|
|
311
|
+
if (this.disposed) throw this.disposedError();
|
|
312
|
+
if (isAbortError(err) || requestSignal.aborted) throw this.error(signal?.aborted ? `${label} request was cancelled.` : `${label} request timed out.`, { retriable: false });
|
|
313
|
+
throw err;
|
|
314
|
+
}
|
|
315
|
+
const text = await res.text();
|
|
316
|
+
if (notification && !text.trim()) return { jsonrpc: "2.0" };
|
|
317
|
+
return parseJsonResponse(text, payload.id, this.config.errorClass, label);
|
|
318
|
+
} finally {
|
|
319
|
+
cleanup();
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** MCP `initialize`, initialized notification, then paginated `tools/list`. */
|
|
323
|
+
async initialize(signal) {
|
|
324
|
+
if (this.disposed) throw this.disposedError();
|
|
325
|
+
if (this.initialized) return;
|
|
326
|
+
if (!this.initialization) this.initialization = this.initializeWithRecovery(this.disposalController.signal).catch((err) => {
|
|
327
|
+
this.initialization = void 0;
|
|
328
|
+
this.initialized = false;
|
|
329
|
+
throw err;
|
|
330
|
+
});
|
|
331
|
+
return waitForSignal(this.initialization, signal);
|
|
332
|
+
}
|
|
333
|
+
resetSession() {
|
|
334
|
+
this.sessionGeneration++;
|
|
335
|
+
this.sessionId = void 0;
|
|
336
|
+
this.initialized = false;
|
|
337
|
+
this.toolSchemas.clear();
|
|
338
|
+
}
|
|
339
|
+
async refreshToken() {
|
|
340
|
+
if (!this.refreshPromise) {
|
|
341
|
+
const tracked = (async () => {
|
|
342
|
+
this.token = await this.config.tokenProvider(this.disposalController.signal);
|
|
343
|
+
this.tokenGeneration++;
|
|
344
|
+
this.resetSession();
|
|
345
|
+
})().finally(() => {
|
|
346
|
+
if (this.refreshPromise === tracked) this.refreshPromise = void 0;
|
|
347
|
+
});
|
|
348
|
+
this.refreshPromise = tracked;
|
|
349
|
+
}
|
|
350
|
+
await this.refreshPromise;
|
|
351
|
+
}
|
|
352
|
+
async initializeWithRecovery(signal) {
|
|
353
|
+
const delays = [
|
|
354
|
+
1e3,
|
|
355
|
+
2e3,
|
|
356
|
+
4e3
|
|
357
|
+
];
|
|
358
|
+
let refreshed = false;
|
|
359
|
+
for (let attempt = 0; attempt <= delays.length; attempt++) try {
|
|
360
|
+
await this.initializeOnce(signal);
|
|
361
|
+
return;
|
|
362
|
+
} catch (err) {
|
|
363
|
+
if (signal?.aborted) throw err;
|
|
364
|
+
this.resetSession();
|
|
365
|
+
if (err instanceof RemoteMcpError && err.status === 401 && !refreshed) {
|
|
366
|
+
refreshed = true;
|
|
367
|
+
await waitForSignal(this.refreshToken(), signal);
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (!(err instanceof RemoteMcpError ? err.retriable : true) || attempt >= delays.length) throw err;
|
|
371
|
+
await sleep((err instanceof RemoteMcpError ? err.retryAfterMs : void 0) ?? delays[attempt], signal);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
async initializeOnce(signal) {
|
|
375
|
+
const label = this.config.label;
|
|
376
|
+
const curSessionGen = this.sessionGeneration;
|
|
377
|
+
const init = await this.post({
|
|
378
|
+
jsonrpc: "2.0",
|
|
379
|
+
id: this.nextId++,
|
|
380
|
+
method: "initialize",
|
|
381
|
+
params: {
|
|
382
|
+
protocolVersion: this.config.protocolVersion,
|
|
383
|
+
capabilities: {},
|
|
384
|
+
clientInfo: {
|
|
385
|
+
name: this.config.clientName,
|
|
386
|
+
version: this.config.clientVersion
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}, signal, curSessionGen);
|
|
390
|
+
if (init.error) throw this.error(`${label} initialize failed: ${init.error.message ?? "unknown error"}`, { retriable: false });
|
|
391
|
+
await this.post({
|
|
392
|
+
jsonrpc: "2.0",
|
|
393
|
+
method: "notifications/initialized"
|
|
394
|
+
}, signal, curSessionGen);
|
|
395
|
+
const stagedSchemas = /* @__PURE__ */ new Map();
|
|
396
|
+
let cursor;
|
|
397
|
+
const seenCursors = /* @__PURE__ */ new Set();
|
|
398
|
+
do {
|
|
399
|
+
const listed = await this.post({
|
|
400
|
+
jsonrpc: "2.0",
|
|
401
|
+
id: this.nextId++,
|
|
402
|
+
method: "tools/list",
|
|
403
|
+
params: cursor ? { cursor } : {}
|
|
404
|
+
}, signal, curSessionGen);
|
|
405
|
+
if (listed.error) throw this.error(`${label} tools/list failed: ${listed.error.message ?? "unknown error"}`, { retriable: false });
|
|
406
|
+
if (!isRecord(listed.result) || !Array.isArray(listed.result.tools)) throw this.error(`${label} tools/list returned an invalid result.`, { retriable: false });
|
|
407
|
+
for (const tool of listed.result.tools) if (isRecord(tool) && typeof tool.name === "string") {
|
|
408
|
+
const entry = {
|
|
409
|
+
name: tool.name,
|
|
410
|
+
inputSchema: tool.inputSchema ?? null
|
|
411
|
+
};
|
|
412
|
+
if (typeof tool.description === "string") entry.description = tool.description;
|
|
413
|
+
stagedSchemas.set(tool.name, entry);
|
|
414
|
+
}
|
|
415
|
+
const nextCursor = listed.result.nextCursor;
|
|
416
|
+
if (nextCursor === void 0 || nextCursor === null || nextCursor === "") cursor = void 0;
|
|
417
|
+
else if (typeof nextCursor !== "string") throw this.error(`${label} tools/list returned an invalid cursor.`, { retriable: false });
|
|
418
|
+
else if (seenCursors.has(nextCursor)) throw this.error(`${label} tools/list repeated a pagination cursor.`, { retriable: false });
|
|
419
|
+
else {
|
|
420
|
+
seenCursors.add(nextCursor);
|
|
421
|
+
cursor = nextCursor;
|
|
422
|
+
}
|
|
423
|
+
} while (cursor);
|
|
424
|
+
this.config.validateTools?.(stagedSchemas);
|
|
425
|
+
if (this.disposed || curSessionGen !== this.sessionGeneration) throw this.error(`${label} client session invalidated during initialization.`, { retriable: false });
|
|
426
|
+
this.toolSchemas = stagedSchemas;
|
|
427
|
+
this.initialized = true;
|
|
428
|
+
}
|
|
429
|
+
/** Resolve an advertised tool name by suffix (server prefixes vary). */
|
|
430
|
+
resolveTool(suffix) {
|
|
431
|
+
for (const name of this.toolSchemas.keys()) if (name === suffix || name.endsWith(`_${suffix}`) || name.endsWith(`-${suffix}`)) return name;
|
|
432
|
+
}
|
|
433
|
+
/** Advertised tools, keyed by name. Empty until `initialize` succeeds. */
|
|
434
|
+
listTools() {
|
|
435
|
+
return this.toolSchemas;
|
|
436
|
+
}
|
|
437
|
+
/** One `tools/call` with 401-refresh / 404-session-recovery / backoff retry. */
|
|
438
|
+
async callTool(tool, args, signal) {
|
|
439
|
+
const label = this.config.label;
|
|
440
|
+
const delays = [
|
|
441
|
+
1e3,
|
|
442
|
+
2e3,
|
|
443
|
+
4e3
|
|
444
|
+
];
|
|
445
|
+
let observedTokenGen = this.tokenGeneration;
|
|
446
|
+
let observedSessionGen = this.sessionGeneration;
|
|
447
|
+
for (let attempt = 0; attempt <= delays.length; attempt++) try {
|
|
448
|
+
const curSessionGen = this.sessionGeneration;
|
|
449
|
+
const res = await this.post({
|
|
450
|
+
jsonrpc: "2.0",
|
|
451
|
+
id: this.nextId++,
|
|
452
|
+
method: "tools/call",
|
|
453
|
+
params: {
|
|
454
|
+
name: tool,
|
|
455
|
+
arguments: args
|
|
456
|
+
}
|
|
457
|
+
}, signal, curSessionGen);
|
|
458
|
+
if (res.error) throw this.error(`${label} tool error: ${res.error.message ?? "unknown error"}`, { retriable: false });
|
|
459
|
+
if (this.disposed || curSessionGen !== this.sessionGeneration) throw this.error(`${label} client session invalidated during request.`, { retriable: false });
|
|
460
|
+
return res.result;
|
|
461
|
+
} catch (err) {
|
|
462
|
+
if (signal?.aborted || this.disposed) throw err;
|
|
463
|
+
if (err instanceof RemoteMcpError && err.status === 401) {
|
|
464
|
+
const staleInit = this.initialization;
|
|
465
|
+
if (this.tokenGeneration === observedTokenGen) await waitForSignal(this.refreshToken(), signal);
|
|
466
|
+
observedTokenGen = this.tokenGeneration;
|
|
467
|
+
observedSessionGen = this.sessionGeneration;
|
|
468
|
+
if (this.initialization === staleInit) this.initialization = void 0;
|
|
469
|
+
await this.initialize(signal);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (err instanceof RemoteMcpError && err.status === 404) {
|
|
473
|
+
if (this.sessionGeneration === observedSessionGen) {
|
|
474
|
+
this.resetSession();
|
|
475
|
+
this.initialization = void 0;
|
|
476
|
+
}
|
|
477
|
+
observedSessionGen = this.sessionGeneration;
|
|
478
|
+
await this.initialize(signal);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (!(err instanceof RemoteMcpError ? err.retriable : true) || attempt >= delays.length) throw err;
|
|
482
|
+
await sleep((err instanceof RemoteMcpError ? err.retryAfterMs : void 0) ?? delays[attempt], signal);
|
|
483
|
+
}
|
|
484
|
+
throw this.error(`${label} request failed after retries.`, { retriable: false });
|
|
485
|
+
}
|
|
486
|
+
/** Best-effort MCP session teardown for manager-owned clients. */
|
|
487
|
+
async dispose() {
|
|
488
|
+
if (this.disposed) return;
|
|
489
|
+
this.disposed = true;
|
|
490
|
+
this.disposalController.abort(this.error(`${this.config.label} client has been disposed.`, { retriable: false }));
|
|
491
|
+
this.sessionGeneration++;
|
|
492
|
+
const sessionId = this.sessionId;
|
|
493
|
+
this.sessionId = void 0;
|
|
494
|
+
this.initialized = false;
|
|
495
|
+
this.toolSchemas.clear();
|
|
496
|
+
if (!sessionId) return;
|
|
497
|
+
const controller = new AbortController();
|
|
498
|
+
const timer = setTimeout(() => controller.abort(), 3e3);
|
|
499
|
+
timer.unref?.();
|
|
500
|
+
try {
|
|
501
|
+
await fetch(this.baseUrl, {
|
|
502
|
+
method: "DELETE",
|
|
503
|
+
headers: {
|
|
504
|
+
Accept: "application/json, text/event-stream",
|
|
505
|
+
"MCP-Protocol-Version": this.config.protocolVersion,
|
|
506
|
+
Authorization: `Bearer ${this.token}`,
|
|
507
|
+
"Mcp-Session-Id": sessionId
|
|
508
|
+
},
|
|
509
|
+
signal: controller.signal
|
|
510
|
+
});
|
|
511
|
+
} catch {} finally {
|
|
512
|
+
clearTimeout(timer);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
//#endregion
|
|
517
|
+
//#region src/lib/azure-cli-token.ts
|
|
518
|
+
/**
|
|
519
|
+
* `az account get-access-token` plumbing shared by every router-owned Azure
|
|
520
|
+
* client (Bluebird, Azure DevOps MCP, Kusto).
|
|
521
|
+
*
|
|
522
|
+
* Three layers live here, in order of escalation:
|
|
523
|
+
*
|
|
524
|
+
* 1. `runAzCliAccessToken` — one silent `az account get-access-token`.
|
|
525
|
+
* 2. `acquireAzToken` — the ladder: a silent mint, then (only for a
|
|
526
|
+
* credential-shaped failure, and only when the caller allows it) ONE
|
|
527
|
+
* interactive `az login`, then one re-mint.
|
|
528
|
+
* 3. `AzCliAccessTokenCache` — the process-lifetime cache over (2).
|
|
529
|
+
*
|
|
530
|
+
* Failures are classified (`classifyAzFailure`) because the remedy differs:
|
|
531
|
+
* a dead session needs `az login`, a tenant that does not contain the resource
|
|
532
|
+
* needs a different account or `AZURE_TENANT_ID`, and a missing `az` needs an
|
|
533
|
+
* install. The interactive ladder fires for exactly one of those classes.
|
|
534
|
+
*
|
|
535
|
+
* The functions here throw a plain `Error` carrying an already-sanitized,
|
|
536
|
+
* credential-free detail; each caller wraps it in its own error class so a
|
|
537
|
+
* failure is attributed to the service that asked for the token. Nothing here
|
|
538
|
+
* ever logs, returns, or embeds the token in a message.
|
|
539
|
+
*/
|
|
540
|
+
/** Azure CLI invocation budget: a hung `az` must not wedge a tool call. */
|
|
541
|
+
const AZ_TIMEOUT_MS = 2e4;
|
|
542
|
+
const AZ_MAX_STDOUT_BYTES = 1048576;
|
|
543
|
+
let execDeps = {
|
|
544
|
+
resolveExecutable,
|
|
545
|
+
runCommandCapture,
|
|
546
|
+
runCommandInherit
|
|
547
|
+
};
|
|
548
|
+
const AZ_LOGIN_DEVICE_CODE_TIMEOUT_MS = 3e5;
|
|
549
|
+
/**
|
|
550
|
+
* Tenant knob. Every resource this module mints for lives in one tenant; when
|
|
551
|
+
* the signed-in account is in another, `az` can be told which tenant to use
|
|
552
|
+
* without a second `az login` (which would just re-select the same default).
|
|
553
|
+
*/
|
|
554
|
+
const AZURE_TENANT_ENV = "AZURE_TENANT_ID";
|
|
555
|
+
/** Refresh this far ahead of the reported expiry. */
|
|
556
|
+
const AZ_TOKEN_REFRESH_MARGIN_MS = 3e5;
|
|
557
|
+
/** Carries the classification alongside the message so callers need no re-parse. */
|
|
558
|
+
var AzCliFailure = class extends Error {
|
|
559
|
+
kind;
|
|
560
|
+
constructor(kind, message) {
|
|
561
|
+
super(message);
|
|
562
|
+
this.name = "AzCliFailure";
|
|
563
|
+
this.kind = kind;
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
/**
|
|
567
|
+
* Observed `az` stderr shapes. These are fixtures, not guesses:
|
|
568
|
+
*
|
|
569
|
+
* - `ERROR: Please run 'az login' to setup account.` (dead session)
|
|
570
|
+
* - `ERROR: V2Error: invalid_resource AADSTS500011: The resource principal
|
|
571
|
+
* named <id> was not found in the tenant named <t>. You might have sent
|
|
572
|
+
* your authentication request to the wrong tenant.` (wrong tenant)
|
|
573
|
+
*
|
|
574
|
+
* The AADSTS codes are the ones that mean "the session cannot produce a token
|
|
575
|
+
* any more" rather than "the token was refused": the refresh token expired or
|
|
576
|
+
* was revoked, or Conditional Access demanded interactive auth.
|
|
577
|
+
*/
|
|
578
|
+
const TENANT_FAILURE_PATTERNS = [
|
|
579
|
+
/invalid_resource/i,
|
|
580
|
+
/AADSTS500011/i,
|
|
581
|
+
/wrong tenant/i
|
|
582
|
+
];
|
|
583
|
+
const LOGIN_REQUIRED_PATTERNS = [
|
|
584
|
+
/az login/i,
|
|
585
|
+
/AADSTS(?:50078|50158|50173|53000|53003|65001|70043|700082|700084)/i,
|
|
586
|
+
/refresh token (?:has expired|is not valid|expired)/i,
|
|
587
|
+
/interactive authentication is needed/i,
|
|
588
|
+
/token request failed/i
|
|
589
|
+
];
|
|
590
|
+
/**
|
|
591
|
+
* Classify a mint failure. A typed `AzCliFailure` answers directly; anything
|
|
592
|
+
* else is matched against the observed CLI text, because callers legitimately
|
|
593
|
+
* pass wrapped errors (`describeAzFailure(label, err)` receives whatever the
|
|
594
|
+
* inner path threw).
|
|
595
|
+
*/
|
|
596
|
+
function classifyAzFailure(err) {
|
|
597
|
+
if (err instanceof AzCliFailure) return err.kind;
|
|
598
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
599
|
+
if (/not found on PATH/.test(text)) return "az-missing";
|
|
600
|
+
if (TENANT_FAILURE_PATTERNS.some((re) => re.test(text))) return "tenant";
|
|
601
|
+
if (LOGIN_REQUIRED_PATTERNS.some((re) => re.test(text))) return "login-required";
|
|
602
|
+
if (/timed out/i.test(text)) return "timeout";
|
|
603
|
+
return "unknown";
|
|
604
|
+
}
|
|
605
|
+
/** `--tenant <id>` when configured. Applied to the mint and to interactive login. */
|
|
606
|
+
function azTenantArgs() {
|
|
607
|
+
const tenant = process.env[AZURE_TENANT_ENV]?.trim();
|
|
608
|
+
return tenant ? ["--tenant", tenant] : [];
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Parse the `expires_on` / `expiresOn` fields of `az account get-access-token
|
|
612
|
+
* --output json`. `expires_on` (epoch seconds) is present on modern az; the
|
|
613
|
+
* older `expiresOn` string is local-time-without-zone, so it is only a
|
|
614
|
+
* fallback and is parsed as local time. An unparseable value yields `null`,
|
|
615
|
+
* never a fabricated deadline — a wrong deadline in either direction is worse
|
|
616
|
+
* than none (too late sends a dead token, too early mints tokens in a loop).
|
|
617
|
+
*/
|
|
618
|
+
function parseAzExpiry(payload) {
|
|
619
|
+
const epoch = payload.expires_on;
|
|
620
|
+
if (typeof epoch === "number" && Number.isFinite(epoch) && epoch > 0) {
|
|
621
|
+
const ms = epoch > 1e11 ? epoch : epoch * 1e3;
|
|
622
|
+
if (ms > Date.now() - 864e5) return ms;
|
|
623
|
+
}
|
|
624
|
+
if (typeof epoch === "string" && /^\d+$/.test(epoch.trim())) {
|
|
625
|
+
const n = Number(epoch.trim());
|
|
626
|
+
const ms = n > 1e11 ? n : n * 1e3;
|
|
627
|
+
if (Number.isFinite(ms) && ms > Date.now() - 864e5) return ms;
|
|
628
|
+
}
|
|
629
|
+
const text = payload.expiresOn;
|
|
630
|
+
if (typeof text === "string") {
|
|
631
|
+
const parsed = Date.parse(text);
|
|
632
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
633
|
+
}
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Acquire an access token for `resource` through Azure CLI. `withExpiry` asks
|
|
638
|
+
* for the JSON envelope so the caller can cache against a real deadline; the
|
|
639
|
+
* default keeps the minimal `--query accessToken --output tsv` invocation.
|
|
640
|
+
*
|
|
641
|
+
* SILENT: this never starts an interactive login. Use `acquireAzToken` for the
|
|
642
|
+
* escalation ladder.
|
|
643
|
+
*/
|
|
644
|
+
async function runAzCliAccessToken(resource, opts = {}) {
|
|
645
|
+
const { signal } = opts;
|
|
646
|
+
const executable = execDeps.resolveExecutable("az");
|
|
647
|
+
if (!executable) throw new AzCliFailure("az-missing", "Azure CLI executable `az` was not found on PATH.");
|
|
648
|
+
const args = [
|
|
649
|
+
"account",
|
|
650
|
+
"get-access-token",
|
|
651
|
+
"--resource",
|
|
652
|
+
resource,
|
|
653
|
+
...azTenantArgs()
|
|
654
|
+
];
|
|
655
|
+
if (opts.withExpiry) args.push("--output", "json");
|
|
656
|
+
else args.push("--query", "accessToken", "--output", "tsv");
|
|
657
|
+
const result = await execDeps.runCommandCapture([executable, ...args], {
|
|
658
|
+
timeoutMs: AZ_TIMEOUT_MS,
|
|
659
|
+
maxStdoutBytes: AZ_MAX_STDOUT_BYTES,
|
|
660
|
+
...signal ? { signal } : {}
|
|
661
|
+
});
|
|
662
|
+
if (result.timedOut) throw new AzCliFailure("timeout", "timed out");
|
|
663
|
+
if (result.code !== 0) {
|
|
664
|
+
const detail = result.stderr.trim() || result.stdout.trim();
|
|
665
|
+
const message = `exited with code ${result.code ?? "unknown"}${detail ? `: ${detail.slice(0, 500)}` : ""}`;
|
|
666
|
+
throw new AzCliFailure(classifyAzFailure(message), message);
|
|
667
|
+
}
|
|
668
|
+
const stdout = result.stdout.trim();
|
|
669
|
+
if (!opts.withExpiry) {
|
|
670
|
+
if (!stdout) throw new AzCliFailure("login-required", "az returned an empty access token");
|
|
671
|
+
return {
|
|
672
|
+
token: stdout,
|
|
673
|
+
expiresAtMs: null
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
let payload;
|
|
677
|
+
try {
|
|
678
|
+
payload = JSON.parse(stdout);
|
|
679
|
+
} catch {
|
|
680
|
+
throw new AzCliFailure("unknown", "az returned an unparseable access-token response");
|
|
681
|
+
}
|
|
682
|
+
if (typeof payload !== "object" || payload === null) throw new AzCliFailure("unknown", "az returned an unparseable access-token response");
|
|
683
|
+
const record = payload;
|
|
684
|
+
const token = typeof record.accessToken === "string" ? record.accessToken.trim() : "";
|
|
685
|
+
if (!token) throw new AzCliFailure("login-required", "az returned an empty access token");
|
|
686
|
+
return {
|
|
687
|
+
token,
|
|
688
|
+
expiresAtMs: parseAzExpiry(record)
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
/** Per-stage outcome, kept tiny so tests can drive the ladder without a real az. */
|
|
692
|
+
async function attemptAzLogin(executable, args, timeoutMs, signal) {
|
|
693
|
+
try {
|
|
694
|
+
return (await execDeps.runCommandInherit([executable, ...args], {
|
|
695
|
+
timeoutMs,
|
|
696
|
+
...signal ? { signal } : {}
|
|
697
|
+
})).code === 0;
|
|
698
|
+
} catch (err) {
|
|
699
|
+
consola.debug("azure-cli-token: `az login` could not be run:", err);
|
|
700
|
+
return false;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* One interactive login: the browser flow first, then device code. Returns
|
|
705
|
+
* `false` (never throws) when neither completed, so the caller keeps the
|
|
706
|
+
* ORIGINAL mint error as the reported cause rather than a login error that
|
|
707
|
+
* describes only the fallback.
|
|
708
|
+
*/
|
|
709
|
+
async function runAzInteractiveLogin(signal) {
|
|
710
|
+
const executable = execDeps.resolveExecutable("az");
|
|
711
|
+
if (!executable) return false;
|
|
712
|
+
consola.warn("Azure CLI has no usable session. Starting an interactive `az login`; if the browser cannot complete the sign-in, a device-code login follows.");
|
|
713
|
+
const tenant = azTenantArgs();
|
|
714
|
+
if (await attemptAzLogin(executable, ["login", ...tenant], 12e4, signal)) return true;
|
|
715
|
+
if (signal?.aborted) return false;
|
|
716
|
+
consola.warn("Browser sign-in did not complete. Falling back to `az login --use-device-code`; open the printed URL and enter the printed code.");
|
|
717
|
+
return attemptAzLogin(executable, [
|
|
718
|
+
"login",
|
|
719
|
+
"--use-device-code",
|
|
720
|
+
...tenant
|
|
721
|
+
], AZ_LOGIN_DEVICE_CODE_TIMEOUT_MS, signal);
|
|
722
|
+
}
|
|
723
|
+
const interactiveLoginState = {
|
|
724
|
+
inflight: null,
|
|
725
|
+
succeeded: false,
|
|
726
|
+
failedAtMs: null
|
|
727
|
+
};
|
|
728
|
+
/**
|
|
729
|
+
* The once-per-process gate around `runAzInteractiveLogin`.
|
|
730
|
+
*
|
|
731
|
+
* Two properties are load-bearing. **Completed attempts only**: the guard is
|
|
732
|
+
* written when an attempt SETTLES, so an interrupted caller cannot consume it
|
|
733
|
+
* (a guard burned by an abort is indistinguishable from a permanent failure,
|
|
734
|
+
* which is the one case this exists to survive). **Shared flight**: concurrent
|
|
735
|
+
* callers await one login instead of opening two browsers.
|
|
736
|
+
*
|
|
737
|
+
* The login runs under its OWN controller rather than the caller's signal for
|
|
738
|
+
* the same reason: one caller giving up must not kill a sign-in the others are
|
|
739
|
+
* waiting on. Waiters still detach on their own signal via `waitForSignal`.
|
|
740
|
+
*/
|
|
741
|
+
async function interactiveLoginOnce(signal) {
|
|
742
|
+
if (signal?.aborted) return false;
|
|
743
|
+
const state = interactiveLoginState;
|
|
744
|
+
if (state.succeeded) return false;
|
|
745
|
+
if (state.failedAtMs !== null && Date.now() - state.failedAtMs < 3e5) return false;
|
|
746
|
+
return waitForSignal(state.inflight ?? startInteractiveLoginAttempt(), signal);
|
|
747
|
+
}
|
|
748
|
+
/** Start (and publish) the shared login flight. Never called with one in flight. */
|
|
749
|
+
function startInteractiveLoginAttempt() {
|
|
750
|
+
const state = interactiveLoginState;
|
|
751
|
+
const tracked = runAzInteractiveLogin(new AbortController().signal).then((ok) => {
|
|
752
|
+
if (ok) {
|
|
753
|
+
state.succeeded = true;
|
|
754
|
+
state.failedAtMs = null;
|
|
755
|
+
} else state.failedAtMs = Date.now();
|
|
756
|
+
return ok;
|
|
757
|
+
}, (err) => {
|
|
758
|
+
state.failedAtMs = Date.now();
|
|
759
|
+
throw err;
|
|
760
|
+
}).finally(() => {
|
|
761
|
+
if (state.inflight === tracked) state.inflight = null;
|
|
762
|
+
});
|
|
763
|
+
state.inflight = tracked;
|
|
764
|
+
return tracked;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* The ladder: silent mint → (optional, credential-shaped only) interactive
|
|
768
|
+
* login → one re-mint. The original error survives any login failure, because
|
|
769
|
+
* it is the one that names the real cause.
|
|
770
|
+
*
|
|
771
|
+
* Never escalates for `az-missing` (that needs an install), for `tenant` (a
|
|
772
|
+
* login would re-select the same tenant), or for a timeout.
|
|
773
|
+
*/
|
|
774
|
+
async function acquireAzToken(resource, opts = {}) {
|
|
775
|
+
try {
|
|
776
|
+
return await runAzCliAccessToken(resource, opts);
|
|
777
|
+
} catch (err) {
|
|
778
|
+
if (opts.signal?.aborted) throw opts.signal.reason ?? err;
|
|
779
|
+
if (!opts.allowInteractiveLogin) throw err;
|
|
780
|
+
if (classifyAzFailure(err) !== "login-required") throw err;
|
|
781
|
+
if (!execDeps.resolveExecutable("az")) throw err;
|
|
782
|
+
if (!await interactiveLoginOnce(opts.signal)) throw err;
|
|
783
|
+
return await runAzCliAccessToken(resource, opts);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Process-lifetime access-token cache keyed by resource (Kusto keys on the
|
|
788
|
+
* cluster URI, which is its audience).
|
|
789
|
+
*
|
|
790
|
+
* Two properties matter and both are load-bearing:
|
|
791
|
+
*
|
|
792
|
+
* - **Single-flight refresh.** Concurrent callers that see the same expired
|
|
793
|
+
* entry await ONE `az` invocation. Without this, a burst of tool calls
|
|
794
|
+
* spawns a burst of `az` processes, each of which is a `.cmd` shim on
|
|
795
|
+
* Windows.
|
|
796
|
+
* - **Never cache an unknown deadline.** When `az` does not report an expiry
|
|
797
|
+
* the token is used but not cached, because a cache entry with no deadline
|
|
798
|
+
* can only be either immortal (serving a dead token) or arbitrary (minting
|
|
799
|
+
* in a loop).
|
|
800
|
+
*
|
|
801
|
+
* Caching moves refresh from reactive to proactive, so an invalidate path is
|
|
802
|
+
* required alongside it: a 401 means the cached token is dead, and a retry that
|
|
803
|
+
* reads the same entry returns the same rejected value until it expires. Every
|
|
804
|
+
* caller of this cache invalidates at its own 401 arm (`forceRefresh` here, or
|
|
805
|
+
* `invalidate` from a client that owns that decision).
|
|
806
|
+
*/
|
|
807
|
+
var AzCliAccessTokenCache = class {
|
|
808
|
+
entries = /* @__PURE__ */ new Map();
|
|
809
|
+
flights = /* @__PURE__ */ new Map();
|
|
810
|
+
marginMs;
|
|
811
|
+
constructor(marginMs = AZ_TOKEN_REFRESH_MARGIN_MS) {
|
|
812
|
+
this.marginMs = marginMs;
|
|
813
|
+
}
|
|
814
|
+
/** Cached-or-fresh token for `resource`. */
|
|
815
|
+
async get(resource, opts = {}) {
|
|
816
|
+
const { signal } = opts;
|
|
817
|
+
if (opts.forceRefresh) this.entries.delete(resource);
|
|
818
|
+
const cached = this.entries.get(resource);
|
|
819
|
+
if (cached && cached.expiresAtMs - this.marginMs > Date.now()) return cached.token;
|
|
820
|
+
const existing = this.flights.get(resource);
|
|
821
|
+
if (existing) return (await waitForSignal(existing, signal)).token;
|
|
822
|
+
const allowInteractiveLogin = opts.allowInteractiveLogin === true;
|
|
823
|
+
const tracked = (async () => {
|
|
824
|
+
const minted = await acquireAzToken(resource, {
|
|
825
|
+
withExpiry: true,
|
|
826
|
+
allowInteractiveLogin
|
|
827
|
+
});
|
|
828
|
+
if (minted.expiresAtMs !== null) this.entries.set(resource, {
|
|
829
|
+
token: minted.token,
|
|
830
|
+
expiresAtMs: minted.expiresAtMs
|
|
831
|
+
});
|
|
832
|
+
return minted;
|
|
833
|
+
})().finally(() => {
|
|
834
|
+
if (this.flights.get(resource) === tracked) this.flights.delete(resource);
|
|
835
|
+
});
|
|
836
|
+
this.flights.set(resource, tracked);
|
|
837
|
+
return (await waitForSignal(tracked, signal)).token;
|
|
838
|
+
}
|
|
839
|
+
/** Drop a cached token so the next `get` re-mints (used on a 401). */
|
|
840
|
+
invalidate(resource) {
|
|
841
|
+
this.entries.delete(resource);
|
|
842
|
+
}
|
|
843
|
+
clear() {
|
|
844
|
+
this.entries.clear();
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
/**
|
|
848
|
+
* Standard wrapping of an `az` failure into a caller-owned error class, with
|
|
849
|
+
* per-class advice: the whole point of classifying is that "run `az login`"
|
|
850
|
+
* is the wrong instruction for a tenant or install problem.
|
|
851
|
+
*/
|
|
852
|
+
function describeAzFailure(label, err) {
|
|
853
|
+
const detail = sanitizeRemoteDetail(err);
|
|
854
|
+
switch (classifyAzFailure(err)) {
|
|
855
|
+
case "az-missing": return `${label} token acquisition failed (${detail}). Install the Azure CLI, then run \`az login\` and retry.`;
|
|
856
|
+
case "login-required": return `${label} token acquisition failed (${detail}). The Azure CLI session is missing or expired; run \`az login\` and retry.`;
|
|
857
|
+
case "tenant": return `${label} token acquisition failed (${detail}). The signed-in account's tenant does not hold ${label}; sign in with an account from the tenant that owns it, or set ${AZURE_TENANT_ENV}, then retry.`;
|
|
858
|
+
case "timeout": return `${label} token acquisition failed (${detail}). The Azure CLI did not answer; retry, and run \`az login\` if the session is stale.`;
|
|
859
|
+
default: return `${label} token acquisition failed (${detail}). Run \`az login\` and retry.`;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
//#endregion
|
|
4
863
|
//#region src/lib/azure-repo.ts
|
|
5
864
|
/**
|
|
6
865
|
* Azure DevOps repository detection for the `--bluebird` flag.
|
|
@@ -304,7 +1163,7 @@ async function getDefaultBranch(info, cwd, signal) {
|
|
|
304
1163
|
//#endregion
|
|
305
1164
|
//#region src/lib/bluebird-client.ts
|
|
306
1165
|
/**
|
|
307
|
-
*
|
|
1166
|
+
* Bluebird code-search MCP client (Streamable HTTP, MCP 2025-06-18).
|
|
308
1167
|
*
|
|
309
1168
|
* The proxy keeps its own `mcp__search__code` schema; this client speaks to
|
|
310
1169
|
* the upstream Bluebird server (`https://mcp.bluebird-ai.net/`) and returns
|
|
@@ -312,230 +1171,100 @@ async function getDefaultBranch(info, cwd, signal) {
|
|
|
312
1171
|
* at runtime from `tools/list` (candidate-key matching) rather than
|
|
313
1172
|
* hard-coded, because the server is versioned independently of this repo.
|
|
314
1173
|
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
1174
|
+
* Transport (JSON-RPC framing, SSE parsing, session handling, retry, token
|
|
1175
|
+
* refresh, 401/404 recovery) lives in `./remote-mcp-client`; this module owns
|
|
1176
|
+
* the Bluebird endpoint, its scope headers, its required tool set, and the
|
|
1177
|
+
* interpretation of a search result.
|
|
319
1178
|
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
*
|
|
323
|
-
*
|
|
1179
|
+
* Auth: `az account get-access-token`, for TWO audiences (see the constants
|
|
1180
|
+
* below): the Bluebird MCP endpoint (`f8efec34-…`) and, for the branch-index
|
|
1181
|
+
* probe alone, the Azure DevOps resource (`499b84ac-…`). `BLUEBIRD_TOKEN` env
|
|
1182
|
+
* overrides both for tests and manual runs. A 401 drops the cached token,
|
|
1183
|
+
* re-mints, and retries the request once.
|
|
324
1184
|
*/
|
|
325
1185
|
const BLUEBIRD_MCP_URL = "https://mcp.bluebird-ai.net/";
|
|
326
|
-
|
|
1186
|
+
/**
|
|
1187
|
+
* Two resources, one flow. They are NOT interchangeable, and sending one where
|
|
1188
|
+
* the other belongs is the exact failure this constant pair exists to prevent:
|
|
1189
|
+
* `mcp.bluebird-ai.net` answers 401 to a token minted for the Azure DevOps
|
|
1190
|
+
* resource, and `almsearch.dev.azure.com` answers 302-sign-in to a token minted
|
|
1191
|
+
* for the Bluebird one. The MCP endpoint declares its audience at
|
|
1192
|
+
* `https://mcp.bluebird-ai.net/.well-known/oauth-protected-resource`
|
|
1193
|
+
* (`scopes_supported: ["f8efec34-…/.default"]`).
|
|
1194
|
+
*/
|
|
1195
|
+
const BLUEBIRD_MCP_TOKEN_RESOURCE = "f8efec34-6ac0-4538-8a18-ee59319d7338";
|
|
1196
|
+
/**
|
|
1197
|
+
* Azure DevOps, for the branch-index probe (`checkBranchIndexStatus` →
|
|
1198
|
+
* `almsearch.dev.azure.com`). Minted only when that probe actually runs.
|
|
1199
|
+
*
|
|
1200
|
+
* Deliberately a different id from `ADO_TOKEN_RESOURCE` in `ado-client.ts`
|
|
1201
|
+
* (`2a72489c-…`, the `mcp.dev.azure.com` audience): same vendor, different
|
|
1202
|
+
* audience, and neither substitutes for the other.
|
|
1203
|
+
*/
|
|
1204
|
+
const ADO_CODE_SEARCH_TOKEN_RESOURCE = "499b84ac-1321-427f-aa17-267ca6975798";
|
|
327
1205
|
const BLUEBIRD_PROTOCOL_VERSION = "2025-06-18";
|
|
328
|
-
var BluebirdError = class extends
|
|
329
|
-
retriable;
|
|
330
|
-
status;
|
|
331
|
-
retryAfterMs;
|
|
1206
|
+
var BluebirdError = class extends RemoteMcpError {
|
|
332
1207
|
constructor(message, opts = {}) {
|
|
333
|
-
super(
|
|
1208
|
+
super(message, opts);
|
|
334
1209
|
this.name = "BluebirdError";
|
|
335
|
-
this.retriable = opts.retriable ?? false;
|
|
336
|
-
if (opts.status !== void 0) this.status = opts.status;
|
|
337
|
-
if (opts.retryAfterMs !== void 0) this.retryAfterMs = opts.retryAfterMs;
|
|
338
1210
|
}
|
|
339
1211
|
};
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
signal?.removeEventListener("abort", onAbort);
|
|
347
|
-
resolve();
|
|
348
|
-
}, ms);
|
|
349
|
-
const onAbort = () => {
|
|
350
|
-
if (settled) return;
|
|
351
|
-
settled = true;
|
|
352
|
-
clearTimeout(timer);
|
|
353
|
-
signal?.removeEventListener("abort", onAbort);
|
|
354
|
-
reject(signal?.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
355
|
-
};
|
|
356
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
function composeRequestSignal(caller, disposal, timeoutMs = 3e4) {
|
|
360
|
-
const controller = new AbortController();
|
|
361
|
-
const onCallerAbort = () => {
|
|
362
|
-
controller.abort(caller?.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
1212
|
+
/** Scope headers every Bluebird request carries. */
|
|
1213
|
+
function bluebirdScopeHeaders(scope) {
|
|
1214
|
+
const headers = {
|
|
1215
|
+
"x-mcp-ec-organization": scope.organization,
|
|
1216
|
+
"x-mcp-ec-project": scope.project,
|
|
1217
|
+
"x-mcp-ec-repository": scope.repositories.join(",")
|
|
363
1218
|
};
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
};
|
|
367
|
-
if (disposal?.aborted) onDisposalAbort();
|
|
368
|
-
else disposal?.addEventListener("abort", onDisposalAbort, { once: true });
|
|
369
|
-
if (caller?.aborted) onCallerAbort();
|
|
370
|
-
else caller?.addEventListener("abort", onCallerAbort, { once: true });
|
|
371
|
-
const timer = setTimeout(() => {
|
|
372
|
-
controller.abort(/* @__PURE__ */ new Error("Bluebird request timed out"));
|
|
373
|
-
}, timeoutMs);
|
|
374
|
-
timer.unref?.();
|
|
375
|
-
return {
|
|
376
|
-
signal: controller.signal,
|
|
377
|
-
cleanup: () => {
|
|
378
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
379
|
-
caller?.removeEventListener("abort", onCallerAbort);
|
|
380
|
-
disposal?.removeEventListener("abort", onDisposalAbort);
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
function isAbortError(err) {
|
|
385
|
-
return err instanceof Error && (err.name === "AbortError" || err.message === "aborted" || err.message === "This operation was aborted");
|
|
386
|
-
}
|
|
387
|
-
function waitForSignal(promise, signal) {
|
|
388
|
-
if (!signal) return promise;
|
|
389
|
-
if (signal.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
390
|
-
return new Promise((resolve, reject) => {
|
|
391
|
-
const onAbort = () => {
|
|
392
|
-
signal.removeEventListener("abort", onAbort);
|
|
393
|
-
reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
394
|
-
};
|
|
395
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
396
|
-
promise.then((value) => {
|
|
397
|
-
signal.removeEventListener("abort", onAbort);
|
|
398
|
-
resolve(value);
|
|
399
|
-
}, (err) => {
|
|
400
|
-
signal.removeEventListener("abort", onAbort);
|
|
401
|
-
reject(err);
|
|
402
|
-
});
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
function canonicalWorkspace(workspace) {
|
|
406
|
-
return workspace.replace(/[\\/]+$/, "").toLowerCase() || workspace.toLowerCase();
|
|
407
|
-
}
|
|
408
|
-
function scopeFingerprint(workspace, scope) {
|
|
409
|
-
const repos = [...scope.repositories].map((repo) => repo.toLowerCase()).sort().join(",");
|
|
410
|
-
return `${canonicalWorkspace(workspace)}::${scope.organization.toLowerCase()}/${scope.project.toLowerCase()}/${repos}@${(scope.branch ?? "").toLowerCase()}`;
|
|
1219
|
+
if (scope.branch) headers["x-mcp-ec-branch"] = scope.branch;
|
|
1220
|
+
return headers;
|
|
411
1221
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
1222
|
+
/**
|
|
1223
|
+
* Process-lifetime caches, one per audience. Keyed by resource inside the
|
|
1224
|
+
* shared cache class, but separate instances so a future `clear` on one cannot
|
|
1225
|
+
* silently drop the other's entry.
|
|
1226
|
+
*/
|
|
1227
|
+
const bluebirdTokenCache = new AzCliAccessTokenCache();
|
|
1228
|
+
const adoCodeSearchTokenCache = new AzCliAccessTokenCache();
|
|
1229
|
+
/**
|
|
1230
|
+
* Token source: explicit env first (tests/manual), else the `az` ladder.
|
|
1231
|
+
*
|
|
1232
|
+
* `BLUEBIRD_TOKEN` is a single override serving BOTH audiences in this file.
|
|
1233
|
+
* That is only safe because it exists for tests and for an operator who is
|
|
1234
|
+
* deliberately pinning one — a real Bluebird deployment never sets it.
|
|
1235
|
+
*/
|
|
1236
|
+
async function getBluebirdToken(signal, opts = {}) {
|
|
1237
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
1238
|
+
const env = process.env.BLUEBIRD_TOKEN?.trim();
|
|
1239
|
+
if (env) return env;
|
|
418
1240
|
try {
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
"--resource",
|
|
424
|
-
BLUEBIRD_TOKEN_RESOURCE,
|
|
425
|
-
"--query",
|
|
426
|
-
"accessToken",
|
|
427
|
-
"--output",
|
|
428
|
-
"tsv"
|
|
429
|
-
], {
|
|
430
|
-
timeoutMs: 2e4,
|
|
431
|
-
maxStdoutBytes: 1048576,
|
|
432
|
-
...signal ? { signal } : {}
|
|
1241
|
+
return await bluebirdTokenCache.get(BLUEBIRD_MCP_TOKEN_RESOURCE, {
|
|
1242
|
+
...signal ? { signal } : {},
|
|
1243
|
+
...opts.allowInteractiveLogin ? { allowInteractiveLogin: true } : {},
|
|
1244
|
+
...opts.forceRefresh ? { forceRefresh: true } : {}
|
|
433
1245
|
});
|
|
434
|
-
if (result.timedOut) throw new Error("timed out");
|
|
435
|
-
if (result.code !== 0) {
|
|
436
|
-
const detail = result.stderr.trim() || result.stdout.trim();
|
|
437
|
-
throw new Error(`exited with code ${result.code ?? "unknown"}${detail ? `: ${detail.slice(0, 500)}` : ""}`);
|
|
438
|
-
}
|
|
439
|
-
const token = result.stdout.trim();
|
|
440
|
-
if (!token) throw new Error("az returned an empty access token");
|
|
441
|
-
return token;
|
|
442
1246
|
} catch (err) {
|
|
443
1247
|
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
444
|
-
throw new BluebirdError(
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
function sameJsonRpcId(actual, expected) {
|
|
448
|
-
return actual === expected || typeof actual === "number" && typeof expected === "number" && actual === expected;
|
|
449
|
-
}
|
|
450
|
-
function parseRetryAfter(value) {
|
|
451
|
-
if (!value) return void 0;
|
|
452
|
-
const seconds = Number(value.trim());
|
|
453
|
-
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(3e5, Math.floor(seconds * 1e3));
|
|
454
|
-
const timestamp = Date.parse(value);
|
|
455
|
-
if (!Number.isFinite(timestamp)) return void 0;
|
|
456
|
-
return Math.max(0, Math.min(3e5, timestamp - Date.now()));
|
|
457
|
-
}
|
|
458
|
-
function matchingJsonRpcResponse(candidate, expectedId) {
|
|
459
|
-
if (!isRecord(candidate)) return void 0;
|
|
460
|
-
const response = candidate;
|
|
461
|
-
if (response.result === void 0 && response.error === void 0) return void 0;
|
|
462
|
-
return sameJsonRpcId(response.id, expectedId) ? response : void 0;
|
|
463
|
-
}
|
|
464
|
-
function parseJsonResponse(text, expectedId) {
|
|
465
|
-
try {
|
|
466
|
-
const response = matchingJsonRpcResponse(JSON.parse(text), expectedId);
|
|
467
|
-
if (response) return response;
|
|
468
|
-
} catch {}
|
|
469
|
-
throw new BluebirdError("Bluebird returned no matching JSON-RPC response.", { retriable: true });
|
|
470
|
-
}
|
|
471
|
-
async function parseSseResponse(response, expectedId, signal) {
|
|
472
|
-
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
473
|
-
if (!response.body) throw new BluebirdError("Bluebird returned an empty SSE response.", { retriable: true });
|
|
474
|
-
const reader = response.body.getReader();
|
|
475
|
-
const decoder = new TextDecoder();
|
|
476
|
-
let buffer = "";
|
|
477
|
-
let dataLines = [];
|
|
478
|
-
const inspectEvent = () => {
|
|
479
|
-
if (dataLines.length === 0) return void 0;
|
|
480
|
-
const data = dataLines.join("\n");
|
|
481
|
-
dataLines = [];
|
|
482
|
-
try {
|
|
483
|
-
return matchingJsonRpcResponse(JSON.parse(data), expectedId);
|
|
484
|
-
} catch {
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
};
|
|
488
|
-
let abortListener;
|
|
489
|
-
const abortPromise = signal ? new Promise((_, reject) => {
|
|
490
|
-
abortListener = () => {
|
|
491
|
-
reader.cancel().catch(() => {});
|
|
492
|
-
reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
493
|
-
};
|
|
494
|
-
if (signal.aborted) abortListener();
|
|
495
|
-
else signal.addEventListener("abort", abortListener, { once: true });
|
|
496
|
-
}) : void 0;
|
|
497
|
-
try {
|
|
498
|
-
while (true) {
|
|
499
|
-
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
500
|
-
const readPromise = reader.read();
|
|
501
|
-
readPromise.catch(() => {});
|
|
502
|
-
const { value, done } = abortPromise ? await Promise.race([readPromise, abortPromise]) : await readPromise;
|
|
503
|
-
buffer += decoder.decode(value, { stream: !done });
|
|
504
|
-
let newline;
|
|
505
|
-
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
506
|
-
const line = buffer.slice(0, newline).replace(/\r$/, "");
|
|
507
|
-
buffer = buffer.slice(newline + 1);
|
|
508
|
-
if (line === "") {
|
|
509
|
-
const match = inspectEvent();
|
|
510
|
-
if (match) return match;
|
|
511
|
-
} else if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
512
|
-
}
|
|
513
|
-
if (done) {
|
|
514
|
-
if (buffer) {
|
|
515
|
-
const line = buffer.replace(/\r$/, "");
|
|
516
|
-
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
517
|
-
}
|
|
518
|
-
const match = inspectEvent();
|
|
519
|
-
if (match) return match;
|
|
520
|
-
break;
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
} finally {
|
|
524
|
-
if (signal && abortListener) signal.removeEventListener("abort", abortListener);
|
|
525
|
-
await reader.cancel().catch(() => {});
|
|
526
|
-
reader.releaseLock();
|
|
1248
|
+
throw new BluebirdError(describeAzFailure("Bluebird", err), { retriable: false });
|
|
527
1249
|
}
|
|
528
|
-
throw new BluebirdError("Bluebird returned no matching JSON-RPC response.", { retriable: true });
|
|
529
1250
|
}
|
|
530
|
-
/**
|
|
531
|
-
|
|
1251
|
+
/**
|
|
1252
|
+
* The ADO-audience token, for the branch-index probe only. Same env override as
|
|
1253
|
+
* `getBluebirdToken` (see the note there).
|
|
1254
|
+
*/
|
|
1255
|
+
async function getAdoCodeSearchToken(signal) {
|
|
532
1256
|
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
533
1257
|
const env = process.env.BLUEBIRD_TOKEN?.trim();
|
|
534
|
-
if (env) return env;
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
1258
|
+
if (env) return env;
|
|
1259
|
+
try {
|
|
1260
|
+
return await adoCodeSearchTokenCache.get(ADO_CODE_SEARCH_TOKEN_RESOURCE, {
|
|
1261
|
+
...signal ? { signal } : {},
|
|
1262
|
+
allowInteractiveLogin: true
|
|
1263
|
+
});
|
|
1264
|
+
} catch (err) {
|
|
1265
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
1266
|
+
throw new BluebirdError(describeAzFailure("Azure DevOps code search", err), { retriable: false });
|
|
1267
|
+
}
|
|
539
1268
|
}
|
|
540
1269
|
const QUERY_KEYS = [
|
|
541
1270
|
"query",
|
|
@@ -643,7 +1372,120 @@ function rowsFromArray(items) {
|
|
|
643
1372
|
if (!recognized) throw new BluebirdError("Bluebird returned no parseable code hits (unexpected result array shape).", { retriable: false });
|
|
644
1373
|
return rows;
|
|
645
1374
|
}
|
|
646
|
-
|
|
1375
|
+
/**
|
|
1376
|
+
* The deployed `code_search` answers with human-readable reports, not JSON:
|
|
1377
|
+
* the lexical method replies with per-file sections of context lines, the
|
|
1378
|
+
* semantic method with ranked windows in fenced code blocks. Both shapes were
|
|
1379
|
+
* read off the live service (Bluebird 1.0.32298816); a text-only response is
|
|
1380
|
+
* what made every search fail with "unexpected tool result shape". The JSON
|
|
1381
|
+
* shapes above stay supported because the wire contract is versioned upstream
|
|
1382
|
+
* and older deployments did return machine-readable arrays.
|
|
1383
|
+
*/
|
|
1384
|
+
const KEYWORD_SECTION_RE = /^Repository:\s*(.+?),\s*Path:\s*(.+?)\s+[—–-]\s/;
|
|
1385
|
+
const KEYWORD_LINE_RE = /^Line\s+(\d+):\s?(.*)$/;
|
|
1386
|
+
const SEMANTIC_HEADER_RE = /^\[(\d+)\]\s+\S+\s+(\S+)\s+\(lines?\s+(\d+)(?:\s*-\s*(\d+))?\)\s+similarity=([\d.]+)\s*$/;
|
|
1387
|
+
const SEMANTIC_FILE_RE = /^File:\s*`(.+)`\s*$/;
|
|
1388
|
+
/** One displayed source line; such a line can embed a whole JSON blob. */
|
|
1389
|
+
const REPORT_LINE_CAP = 2e3;
|
|
1390
|
+
/** A semantic window is ~20 lines of source; this bounds a pathological one. */
|
|
1391
|
+
const REPORT_WINDOW_CAP = 8e3;
|
|
1392
|
+
function positiveInt(value) {
|
|
1393
|
+
const parsed = Number.parseInt(value ?? "", 10);
|
|
1394
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Lexical report: `Line 48: <code>` entries under `Repository: …, Path: …`
|
|
1398
|
+
* headers, with non-matching context lines interleaved and `... (13 lines
|
|
1399
|
+
* omitted)` elisions. The service does not mark which displayed lines matched,
|
|
1400
|
+
* so the query is the only signal available: a line containing it is a hit. A
|
|
1401
|
+
* query that cannot match textually (an `OR`/`NOT` expression, a
|
|
1402
|
+
* natural-language phrase) keeps the server's own context selection rather
|
|
1403
|
+
* than reporting nothing.
|
|
1404
|
+
*/
|
|
1405
|
+
function rowsFromKeywordReport(text, query) {
|
|
1406
|
+
const rows = [];
|
|
1407
|
+
let file = null;
|
|
1408
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1409
|
+
const section = KEYWORD_SECTION_RE.exec(line);
|
|
1410
|
+
if (section?.[2]) {
|
|
1411
|
+
file = normalizeRemotePath(section[2]);
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
const numbered = KEYWORD_LINE_RE.exec(line);
|
|
1415
|
+
if (!numbered || !file) continue;
|
|
1416
|
+
const lineNumber = positiveInt(numbered[1]);
|
|
1417
|
+
const snippet = (numbered[2] ?? "").slice(0, REPORT_LINE_CAP);
|
|
1418
|
+
if (lineNumber === null || !snippet.trim()) continue;
|
|
1419
|
+
rows.push({
|
|
1420
|
+
file,
|
|
1421
|
+
line: lineNumber,
|
|
1422
|
+
snippet
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
if (rows.length === 0) return null;
|
|
1426
|
+
const needle = query.trim().toLowerCase();
|
|
1427
|
+
if (!needle) return rows;
|
|
1428
|
+
const matching = rows.filter((row) => row.snippet.toLowerCase().includes(needle));
|
|
1429
|
+
return matching.length > 0 ? matching : rows;
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* Semantic report: `[1] repo /path (lines 54-74) similarity=0.664`, then a
|
|
1433
|
+
* `File: \`/path\`` line, then the window in a fenced block. `//...` elisions
|
|
1434
|
+
* inside a window are the server's own, and are kept as-is.
|
|
1435
|
+
*/
|
|
1436
|
+
function rowsFromSemanticReport(text) {
|
|
1437
|
+
const rows = [];
|
|
1438
|
+
let pending = null;
|
|
1439
|
+
let window = [];
|
|
1440
|
+
let inFence = false;
|
|
1441
|
+
const flush = () => {
|
|
1442
|
+
const record = pending;
|
|
1443
|
+
if (!record) return;
|
|
1444
|
+
const snippet = window.join("\n").trim();
|
|
1445
|
+
rows.push({
|
|
1446
|
+
file: record.file,
|
|
1447
|
+
line: record.line,
|
|
1448
|
+
...record.endLine !== void 0 ? { endLine: record.endLine } : {},
|
|
1449
|
+
...record.score !== void 0 ? { score: record.score } : {},
|
|
1450
|
+
snippet: (snippet || `${record.file}:${record.line}`).slice(0, REPORT_WINDOW_CAP)
|
|
1451
|
+
});
|
|
1452
|
+
pending = null;
|
|
1453
|
+
window = [];
|
|
1454
|
+
};
|
|
1455
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1456
|
+
if (inFence) {
|
|
1457
|
+
if (line.trimStart().startsWith("```")) inFence = false;
|
|
1458
|
+
else window.push(line);
|
|
1459
|
+
continue;
|
|
1460
|
+
}
|
|
1461
|
+
const header = SEMANTIC_HEADER_RE.exec(line);
|
|
1462
|
+
if (header) {
|
|
1463
|
+
flush();
|
|
1464
|
+
const file = normalizeRemotePath(header[2] ?? "");
|
|
1465
|
+
const lineNumber = positiveInt(header[3]);
|
|
1466
|
+
if (!file || lineNumber === null) continue;
|
|
1467
|
+
const endLine = positiveInt(header[4]);
|
|
1468
|
+
const score = Number.parseFloat(header[5] ?? "");
|
|
1469
|
+
pending = {
|
|
1470
|
+
file,
|
|
1471
|
+
line: lineNumber,
|
|
1472
|
+
...endLine !== null ? { endLine } : {},
|
|
1473
|
+
...Number.isFinite(score) ? { score } : {}
|
|
1474
|
+
};
|
|
1475
|
+
continue;
|
|
1476
|
+
}
|
|
1477
|
+
const fileLine = SEMANTIC_FILE_RE.exec(line);
|
|
1478
|
+
if (fileLine && pending) {
|
|
1479
|
+
const named = normalizeRemotePath(fileLine[1] ?? "");
|
|
1480
|
+
if (named) pending.file = named;
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
if (line.trimStart().startsWith("```")) inFence = true;
|
|
1484
|
+
}
|
|
1485
|
+
flush();
|
|
1486
|
+
return rows.length > 0 ? rows : null;
|
|
1487
|
+
}
|
|
1488
|
+
function rowsFromCallResult(result, query) {
|
|
647
1489
|
if (Array.isArray(result)) return rowsFromArray(result);
|
|
648
1490
|
if (!isRecord(result)) throw new BluebirdError("Bluebird returned an empty result.", { retriable: true });
|
|
649
1491
|
if (result.isError === true) {
|
|
@@ -662,7 +1504,11 @@ function rowsFromCallResult(result) {
|
|
|
662
1504
|
}
|
|
663
1505
|
for (const text of texts) {
|
|
664
1506
|
const trimmed = text.trim();
|
|
665
|
-
if (!trimmed.startsWith("{") && !trimmed.startsWith("["))
|
|
1507
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
|
|
1508
|
+
const report = rowsFromKeywordReport(trimmed, query ?? "") ?? rowsFromSemanticReport(trimmed);
|
|
1509
|
+
if (report) return report;
|
|
1510
|
+
continue;
|
|
1511
|
+
}
|
|
666
1512
|
let parsed;
|
|
667
1513
|
try {
|
|
668
1514
|
parsed = JSON.parse(trimmed);
|
|
@@ -684,215 +1530,46 @@ function rowsFromCallResult(result) {
|
|
|
684
1530
|
const arr = Array.isArray(parsed) ? parsed : isRecord(parsed) && Array.isArray(parsed.results) ? parsed.results : isRecord(parsed) && Array.isArray(parsed.items) ? parsed.items : null;
|
|
685
1531
|
if (arr) return rowsFromArray(arr);
|
|
686
1532
|
}
|
|
687
|
-
|
|
1533
|
+
const head = sanitizeTransportText((texts[0] ?? "").trim().replace(/\s+/g, " ").slice(0, 160));
|
|
1534
|
+
throw new BluebirdError(`Bluebird returned no parseable code hits (unexpected tool result shape${head ? `: ${head}` : ""}).`, { retriable: false });
|
|
688
1535
|
}
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
1536
|
+
/**
|
|
1537
|
+
* Bluebird must advertise the unified `code_search` tool, or both legacy
|
|
1538
|
+
* search tools. Anything else means the deployment changed shape under us and
|
|
1539
|
+
* a search would silently degrade.
|
|
1540
|
+
*/
|
|
1541
|
+
function validateBluebirdTools(tools) {
|
|
1542
|
+
const resolveFromStaged = (suffix) => {
|
|
1543
|
+
for (const name of tools.keys()) if (name === suffix || name.endsWith(`_${suffix}`) || name.endsWith(`-${suffix}`)) return name;
|
|
1544
|
+
};
|
|
1545
|
+
const unified = resolveFromStaged(UNIFIED_SEARCH_TOOL);
|
|
1546
|
+
const semantic = resolveFromStaged(LEGACY_SEMANTIC_TOOL);
|
|
1547
|
+
const lexical = resolveFromStaged(LEGACY_LEXICAL_TOOL);
|
|
1548
|
+
if (!unified && (!semantic || !lexical)) throw new BluebirdError("Bluebird tools/list did not advertise code_search or both legacy semantic and lexical search tools.", { retriable: false });
|
|
1549
|
+
}
|
|
1550
|
+
var BluebirdMcpClient = class extends RemoteMcpClient {
|
|
703
1551
|
constructor(scope, token, baseUrl = BLUEBIRD_MCP_URL) {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
...extra
|
|
718
|
-
};
|
|
719
|
-
if (this.scope.branch) headers["x-mcp-ec-branch"] = this.scope.branch;
|
|
720
|
-
if (this.sessionId) headers["Mcp-Session-Id"] = this.sessionId;
|
|
721
|
-
return headers;
|
|
722
|
-
}
|
|
723
|
-
async post(payload, signal, requestSessionGen) {
|
|
724
|
-
if (this.disposed) throw new BluebirdError("Bluebird client has been disposed.", { retriable: false });
|
|
725
|
-
const { signal: requestSignal, cleanup } = composeRequestSignal(signal, this.disposalController.signal);
|
|
726
|
-
const notification = typeof payload.method === "string" && payload.method.startsWith("notifications/");
|
|
727
|
-
try {
|
|
728
|
-
let res;
|
|
729
|
-
try {
|
|
730
|
-
res = await fetch(this.baseUrl, {
|
|
731
|
-
method: "POST",
|
|
732
|
-
headers: this.headers(),
|
|
733
|
-
body: JSON.stringify(payload),
|
|
734
|
-
signal: requestSignal
|
|
735
|
-
});
|
|
736
|
-
} catch (err) {
|
|
737
|
-
if (this.disposed) throw new BluebirdError("Bluebird client has been disposed.", { retriable: false });
|
|
738
|
-
if (isAbortError(err) || requestSignal.aborted) throw new BluebirdError(signal?.aborted ? "Bluebird request was cancelled." : "Bluebird request timed out.", { retriable: false });
|
|
739
|
-
throw new BluebirdError(`Bluebird transport failed: ${sanitizeBluebirdDetail(err)}`, { retriable: true });
|
|
740
|
-
}
|
|
741
|
-
if (this.disposed) throw new BluebirdError("Bluebird client has been disposed.", { retriable: false });
|
|
742
|
-
const session = res.headers.get("mcp-session-id");
|
|
743
|
-
if (session) {
|
|
744
|
-
if (requestSessionGen === void 0 || requestSessionGen === this.sessionGeneration) this.sessionId = session;
|
|
745
|
-
}
|
|
746
|
-
if (res.status === 401) throw new BluebirdError("Bluebird rejected the access token (401).", {
|
|
747
|
-
retriable: false,
|
|
748
|
-
status: 401
|
|
749
|
-
});
|
|
750
|
-
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
751
|
-
if ([
|
|
752
|
-
429,
|
|
753
|
-
500,
|
|
754
|
-
502,
|
|
755
|
-
503,
|
|
756
|
-
504
|
|
757
|
-
].includes(res.status)) throw new BluebirdError(`Bluebird responded with HTTP ${res.status}.`, {
|
|
758
|
-
retriable: true,
|
|
759
|
-
status: res.status,
|
|
760
|
-
...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
|
|
761
|
-
});
|
|
762
|
-
if (!res.ok) {
|
|
763
|
-
const body = await res.text().catch(() => "");
|
|
764
|
-
const detail = body ? sanitizeTransportText(body).slice(0, 300) : "";
|
|
765
|
-
throw new BluebirdError(`Bluebird responded with HTTP ${res.status}${detail ? `: ${detail}` : ""}.`, {
|
|
766
|
-
retriable: false,
|
|
767
|
-
status: res.status
|
|
1552
|
+
super({
|
|
1553
|
+
label: "Bluebird",
|
|
1554
|
+
baseUrl,
|
|
1555
|
+
protocolVersion: BLUEBIRD_PROTOCOL_VERSION,
|
|
1556
|
+
clientName: "github-router",
|
|
1557
|
+
clientVersion: "bluebird",
|
|
1558
|
+
errorClass: BluebirdError,
|
|
1559
|
+
token,
|
|
1560
|
+
tokenProvider: (signal) => {
|
|
1561
|
+
consola.warn(`Bluebird rejected the access token (401). Re-minting for resource ${BLUEBIRD_MCP_TOKEN_RESOURCE} through the Azure CLI; if this is a stale session, run \`az login\`.`);
|
|
1562
|
+
return getBluebirdToken(signal, {
|
|
1563
|
+
forceRefresh: true,
|
|
1564
|
+
allowInteractiveLogin: true
|
|
768
1565
|
});
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
return await parseSseResponse(res, payload.id, requestSignal);
|
|
773
|
-
} catch (err) {
|
|
774
|
-
if (this.disposed) throw new BluebirdError("Bluebird client has been disposed.", { retriable: false });
|
|
775
|
-
if (isAbortError(err) || requestSignal.aborted) throw new BluebirdError(signal?.aborted ? "Bluebird request was cancelled." : "Bluebird request timed out.", { retriable: false });
|
|
776
|
-
throw err;
|
|
777
|
-
}
|
|
778
|
-
const text = await res.text();
|
|
779
|
-
if (notification && !text.trim()) return { jsonrpc: "2.0" };
|
|
780
|
-
return parseJsonResponse(text, payload.id);
|
|
781
|
-
} finally {
|
|
782
|
-
cleanup();
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
/** MCP `initialize`, initialized notification, then paginated `tools/list`. */
|
|
786
|
-
async initialize(signal) {
|
|
787
|
-
if (this.disposed) throw new BluebirdError("Bluebird client has been disposed.", { retriable: false });
|
|
788
|
-
if (this.initialized) return;
|
|
789
|
-
if (!this.initialization) this.initialization = this.initializeWithRecovery(this.disposalController.signal).catch((err) => {
|
|
790
|
-
this.initialization = void 0;
|
|
791
|
-
this.initialized = false;
|
|
792
|
-
throw err;
|
|
1566
|
+
},
|
|
1567
|
+
staticHeaders: () => bluebirdScopeHeaders(scope),
|
|
1568
|
+
validateTools: validateBluebirdTools
|
|
793
1569
|
});
|
|
794
|
-
return waitForSignal(this.initialization, signal);
|
|
795
|
-
}
|
|
796
|
-
resetSession() {
|
|
797
|
-
this.sessionGeneration++;
|
|
798
|
-
this.sessionId = void 0;
|
|
799
|
-
this.initialized = false;
|
|
800
|
-
this.toolSchemas.clear();
|
|
801
|
-
}
|
|
802
|
-
async refreshToken() {
|
|
803
|
-
if (!this.refreshPromise) {
|
|
804
|
-
const tracked = (async () => {
|
|
805
|
-
this.token = await getBluebirdToken(this.disposalController.signal);
|
|
806
|
-
this.tokenGeneration++;
|
|
807
|
-
this.resetSession();
|
|
808
|
-
})().finally(() => {
|
|
809
|
-
if (this.refreshPromise === tracked) this.refreshPromise = void 0;
|
|
810
|
-
});
|
|
811
|
-
this.refreshPromise = tracked;
|
|
812
|
-
}
|
|
813
|
-
await this.refreshPromise;
|
|
814
|
-
}
|
|
815
|
-
async initializeWithRecovery(signal) {
|
|
816
|
-
const delays = [
|
|
817
|
-
1e3,
|
|
818
|
-
2e3,
|
|
819
|
-
4e3
|
|
820
|
-
];
|
|
821
|
-
let refreshed = false;
|
|
822
|
-
for (let attempt = 0; attempt <= delays.length; attempt++) try {
|
|
823
|
-
await this.initializeOnce(signal);
|
|
824
|
-
return;
|
|
825
|
-
} catch (err) {
|
|
826
|
-
if (signal?.aborted) throw err;
|
|
827
|
-
this.resetSession();
|
|
828
|
-
if (err instanceof BluebirdError && err.status === 401 && !refreshed) {
|
|
829
|
-
refreshed = true;
|
|
830
|
-
await waitForSignal(this.refreshToken(), signal);
|
|
831
|
-
continue;
|
|
832
|
-
}
|
|
833
|
-
if (!(err instanceof BluebirdError ? err.retriable : true) || attempt >= delays.length) throw err;
|
|
834
|
-
await sleep((err instanceof BluebirdError ? err.retryAfterMs : void 0) ?? delays[attempt], signal);
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
async initializeOnce(signal) {
|
|
838
|
-
const curSessionGen = this.sessionGeneration;
|
|
839
|
-
const init = await this.post({
|
|
840
|
-
jsonrpc: "2.0",
|
|
841
|
-
id: this.nextId++,
|
|
842
|
-
method: "initialize",
|
|
843
|
-
params: {
|
|
844
|
-
protocolVersion: BLUEBIRD_PROTOCOL_VERSION,
|
|
845
|
-
capabilities: {},
|
|
846
|
-
clientInfo: {
|
|
847
|
-
name: "github-router",
|
|
848
|
-
version: "bluebird"
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
}, signal, curSessionGen);
|
|
852
|
-
if (init.error) throw new BluebirdError(`Bluebird initialize failed: ${init.error.message ?? "unknown error"}`, { retriable: false });
|
|
853
|
-
await this.post({
|
|
854
|
-
jsonrpc: "2.0",
|
|
855
|
-
method: "notifications/initialized"
|
|
856
|
-
}, signal, curSessionGen);
|
|
857
|
-
const stagedSchemas = /* @__PURE__ */ new Map();
|
|
858
|
-
let cursor;
|
|
859
|
-
const seenCursors = /* @__PURE__ */ new Set();
|
|
860
|
-
do {
|
|
861
|
-
const listed = await this.post({
|
|
862
|
-
jsonrpc: "2.0",
|
|
863
|
-
id: this.nextId++,
|
|
864
|
-
method: "tools/list",
|
|
865
|
-
params: cursor ? { cursor } : {}
|
|
866
|
-
}, signal, curSessionGen);
|
|
867
|
-
if (listed.error) throw new BluebirdError(`Bluebird tools/list failed: ${listed.error.message ?? "unknown error"}`, { retriable: false });
|
|
868
|
-
if (!isRecord(listed.result) || !Array.isArray(listed.result.tools)) throw new BluebirdError("Bluebird tools/list returned an invalid result.", { retriable: false });
|
|
869
|
-
for (const tool of listed.result.tools) if (isRecord(tool) && typeof tool.name === "string") stagedSchemas.set(tool.name, tool.inputSchema ?? null);
|
|
870
|
-
const nextCursor = listed.result.nextCursor;
|
|
871
|
-
if (nextCursor === void 0 || nextCursor === null || nextCursor === "") cursor = void 0;
|
|
872
|
-
else if (typeof nextCursor !== "string") throw new BluebirdError("Bluebird tools/list returned an invalid cursor.", { retriable: false });
|
|
873
|
-
else if (seenCursors.has(nextCursor)) throw new BluebirdError("Bluebird tools/list repeated a pagination cursor.", { retriable: false });
|
|
874
|
-
else {
|
|
875
|
-
seenCursors.add(nextCursor);
|
|
876
|
-
cursor = nextCursor;
|
|
877
|
-
}
|
|
878
|
-
} while (cursor);
|
|
879
|
-
const resolveFromStaged = (suffix) => {
|
|
880
|
-
for (const name of stagedSchemas.keys()) if (name === suffix || name.endsWith(`_${suffix}`) || name.endsWith(`-${suffix}`)) return name;
|
|
881
|
-
};
|
|
882
|
-
const unified = resolveFromStaged(UNIFIED_SEARCH_TOOL);
|
|
883
|
-
const semantic = resolveFromStaged(LEGACY_SEMANTIC_TOOL);
|
|
884
|
-
const lexical = resolveFromStaged(LEGACY_LEXICAL_TOOL);
|
|
885
|
-
if (!unified && (!semantic || !lexical)) throw new BluebirdError("Bluebird tools/list did not advertise code_search or both legacy semantic and lexical search tools.", { retriable: false });
|
|
886
|
-
if (this.disposed || curSessionGen !== this.sessionGeneration) throw new BluebirdError("Bluebird client session invalidated during initialization.", { retriable: false });
|
|
887
|
-
this.toolSchemas = stagedSchemas;
|
|
888
|
-
this.initialized = true;
|
|
889
|
-
}
|
|
890
|
-
/** Resolve an advertised tool name by suffix (server prefixes vary). */
|
|
891
|
-
resolveTool(suffix) {
|
|
892
|
-
for (const name of this.toolSchemas.keys()) if (name === suffix || name.endsWith(`_${suffix}`) || name.endsWith(`-${suffix}`)) return name;
|
|
893
1570
|
}
|
|
894
1571
|
shapeArgs(tool, query, opts, mode) {
|
|
895
|
-
const schema = this.toolSchemas.get(tool);
|
|
1572
|
+
const schema = this.toolSchemas.get(tool)?.inputSchema;
|
|
896
1573
|
const args = {};
|
|
897
1574
|
const queryKey = pickKey(schema, QUERY_KEYS) ?? "query";
|
|
898
1575
|
args[queryKey] = query;
|
|
@@ -919,121 +1596,48 @@ var BluebirdMcpClient = class {
|
|
|
919
1596
|
if (legacy) return legacy;
|
|
920
1597
|
throw new BluebirdError(`Bluebird does not advertise a ${mode} code-search tool.`, { retriable: false });
|
|
921
1598
|
}
|
|
922
|
-
async callWithRetry(tool, args, signal) {
|
|
923
|
-
const delays = [
|
|
924
|
-
1e3,
|
|
925
|
-
2e3,
|
|
926
|
-
4e3
|
|
927
|
-
];
|
|
928
|
-
let observedTokenGen = this.tokenGeneration;
|
|
929
|
-
let observedSessionGen = this.sessionGeneration;
|
|
930
|
-
for (let attempt = 0; attempt <= delays.length; attempt++) try {
|
|
931
|
-
const curSessionGen = this.sessionGeneration;
|
|
932
|
-
const res = await this.post({
|
|
933
|
-
jsonrpc: "2.0",
|
|
934
|
-
id: this.nextId++,
|
|
935
|
-
method: "tools/call",
|
|
936
|
-
params: {
|
|
937
|
-
name: tool,
|
|
938
|
-
arguments: args
|
|
939
|
-
}
|
|
940
|
-
}, signal, curSessionGen);
|
|
941
|
-
if (res.error) throw new BluebirdError(`Bluebird tool error: ${res.error.message ?? "unknown error"}`, { retriable: false });
|
|
942
|
-
if (this.disposed || curSessionGen !== this.sessionGeneration) throw new BluebirdError("Bluebird client session invalidated during request.", { retriable: false });
|
|
943
|
-
return res.result;
|
|
944
|
-
} catch (err) {
|
|
945
|
-
if (signal?.aborted || this.disposed) throw err;
|
|
946
|
-
if (err instanceof BluebirdError && err.status === 401) {
|
|
947
|
-
const staleInit = this.initialization;
|
|
948
|
-
if (this.tokenGeneration === observedTokenGen) await waitForSignal(this.refreshToken(), signal);
|
|
949
|
-
observedTokenGen = this.tokenGeneration;
|
|
950
|
-
observedSessionGen = this.sessionGeneration;
|
|
951
|
-
if (this.initialization === staleInit) this.initialization = void 0;
|
|
952
|
-
await this.initialize(signal);
|
|
953
|
-
continue;
|
|
954
|
-
}
|
|
955
|
-
if (err instanceof BluebirdError && err.status === 404) {
|
|
956
|
-
if (this.sessionGeneration === observedSessionGen) {
|
|
957
|
-
this.resetSession();
|
|
958
|
-
this.initialization = void 0;
|
|
959
|
-
}
|
|
960
|
-
observedSessionGen = this.sessionGeneration;
|
|
961
|
-
await this.initialize(signal);
|
|
962
|
-
continue;
|
|
963
|
-
}
|
|
964
|
-
if (!(err instanceof BluebirdError ? err.retriable : true) || attempt >= delays.length) throw err;
|
|
965
|
-
await sleep((err instanceof BluebirdError ? err.retryAfterMs : void 0) ?? delays[attempt], signal);
|
|
966
|
-
}
|
|
967
|
-
throw new BluebirdError("Bluebird request failed after retries.", { retriable: false });
|
|
968
|
-
}
|
|
969
1599
|
/** Lexical path: indexed keyword search. */
|
|
970
1600
|
async searchFileContent(query, opts = {}) {
|
|
971
1601
|
await this.initialize(opts.signal);
|
|
972
1602
|
const tool = this.searchTool("lexical");
|
|
973
|
-
const rows = rowsFromCallResult(await this.
|
|
1603
|
+
const rows = rowsFromCallResult(await this.callTool(tool, this.shapeArgs(tool, query, opts, "lexical"), opts.signal), query);
|
|
974
1604
|
return opts.limit !== void 0 ? rows.slice(0, opts.limit) : rows;
|
|
975
1605
|
}
|
|
976
1606
|
/** Semantic path: code-aware vector search. */
|
|
977
1607
|
async doVectorSearch(query, opts = {}) {
|
|
978
1608
|
await this.initialize(opts.signal);
|
|
979
1609
|
const tool = this.searchTool("semantic");
|
|
980
|
-
const rows = rowsFromCallResult(await this.
|
|
1610
|
+
const rows = rowsFromCallResult(await this.callTool(tool, this.shapeArgs(tool, query, opts, "semantic"), opts.signal), query);
|
|
981
1611
|
return opts.limit !== void 0 ? rows.slice(0, opts.limit) : rows;
|
|
982
1612
|
}
|
|
983
|
-
/** Best-effort MCP session teardown for manager-owned clients. */
|
|
984
|
-
async dispose() {
|
|
985
|
-
if (this.disposed) return;
|
|
986
|
-
this.disposed = true;
|
|
987
|
-
this.disposalController.abort(new BluebirdError("Bluebird client has been disposed.", { retriable: false }));
|
|
988
|
-
this.sessionGeneration++;
|
|
989
|
-
const sessionId = this.sessionId;
|
|
990
|
-
this.sessionId = void 0;
|
|
991
|
-
this.initialized = false;
|
|
992
|
-
this.toolSchemas.clear();
|
|
993
|
-
if (!sessionId) return;
|
|
994
|
-
const controller = new AbortController();
|
|
995
|
-
const timer = setTimeout(() => controller.abort(), 3e3);
|
|
996
|
-
timer.unref?.();
|
|
997
|
-
try {
|
|
998
|
-
await fetch(this.baseUrl, {
|
|
999
|
-
method: "DELETE",
|
|
1000
|
-
headers: {
|
|
1001
|
-
Accept: "application/json, text/event-stream",
|
|
1002
|
-
"MCP-Protocol-Version": BLUEBIRD_PROTOCOL_VERSION,
|
|
1003
|
-
Authorization: `Bearer ${this.token}`,
|
|
1004
|
-
"Mcp-Session-Id": sessionId
|
|
1005
|
-
},
|
|
1006
|
-
signal: controller.signal
|
|
1007
|
-
});
|
|
1008
|
-
} catch {} finally {
|
|
1009
|
-
clearTimeout(timer);
|
|
1010
|
-
}
|
|
1011
|
-
}
|
|
1012
1613
|
};
|
|
1013
1614
|
async function resolveBluebirdProvisionFromWorkspace(workspace, signal) {
|
|
1014
1615
|
let primary;
|
|
1015
1616
|
try {
|
|
1016
1617
|
primary = await getAzureRepoFromGit(workspace, signal);
|
|
1017
1618
|
} catch (err) {
|
|
1018
|
-
throw err instanceof BluebirdError ? err : new BluebirdError(
|
|
1619
|
+
throw err instanceof BluebirdError ? err : new BluebirdError(sanitizeRemoteDetail(err), { retriable: false });
|
|
1019
1620
|
}
|
|
1020
1621
|
const repositories = [primary.repository];
|
|
1021
1622
|
let token;
|
|
1022
1623
|
try {
|
|
1023
|
-
token = await getBluebirdToken(signal);
|
|
1624
|
+
token = await getBluebirdToken(signal, { allowInteractiveLogin: true });
|
|
1024
1625
|
} catch (err) {
|
|
1025
|
-
throw err instanceof BluebirdError ? err : new BluebirdError(`Bluebird auth failed: ${
|
|
1626
|
+
throw err instanceof BluebirdError ? err : new BluebirdError(`Bluebird auth failed: ${sanitizeRemoteDetail(err)}`, { retriable: false });
|
|
1026
1627
|
}
|
|
1027
1628
|
let branch;
|
|
1028
1629
|
try {
|
|
1029
1630
|
const current = await getCurrentBranch(workspace, signal);
|
|
1030
1631
|
if (current) {
|
|
1031
|
-
const
|
|
1632
|
+
const indexToken = await getAdoCodeSearchToken(signal);
|
|
1633
|
+
const status = await checkBranchIndexStatus(primary, current, indexToken, signal);
|
|
1032
1634
|
branch = status.isIndexed ? status.branch : await getDefaultBranch(primary, workspace, signal);
|
|
1033
1635
|
} else branch = await getDefaultBranch(primary, workspace, signal);
|
|
1034
1636
|
} catch (err) {
|
|
1035
1637
|
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
1036
|
-
|
|
1638
|
+
if (err instanceof BluebirdError) throw err;
|
|
1639
|
+
const advice = classifyAzFailure(err) === "login-required" ? " Run `az login` and retry." : "";
|
|
1640
|
+
throw new BluebirdError(`${sanitizeRemoteDetail(err)}${advice}`, { retriable: false });
|
|
1037
1641
|
}
|
|
1038
1642
|
return {
|
|
1039
1643
|
organization: primary.organization,
|
|
@@ -1158,6 +1762,6 @@ async function ensureBluebirdClient(workspace, signal) {
|
|
|
1158
1762
|
return client;
|
|
1159
1763
|
}
|
|
1160
1764
|
//#endregion
|
|
1161
|
-
export {
|
|
1765
|
+
export { isRecord as _, BluebirdClientManager as a, sleep as b, disposeBluebirdClients as c, getBluebirdToken as d, getAzureRepoFromGit as f, RemoteMcpError as g, RemoteMcpClient as h, BLUEBIRD_PROTOCOL_VERSION as i, ensureBluebirdClient as l, describeAzFailure as m, BLUEBIRD_MCP_TOKEN_RESOURCE as n, BluebirdError as o, AzCliAccessTokenCache as p, BLUEBIRD_MCP_URL as r, BluebirdMcpClient as s, ADO_CODE_SEARCH_TOKEN_RESOURCE as t, getAdoCodeSearchToken as u, parseRetryAfter as v, sanitizeRemoteDetail as y };
|
|
1162
1766
|
|
|
1163
|
-
//# sourceMappingURL=bluebird-client-
|
|
1767
|
+
//# sourceMappingURL=bluebird-client-ltPIiyJU.js.map
|