github-router 0.3.330 → 0.3.332
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/README.md +4 -2
- package/dist/{aic-ledger-CsBx1crE.js → aic-ledger-D4fmThbS.js} +2 -2
- package/dist/{aic-ledger-CsBx1crE.js.map → aic-ledger-D4fmThbS.js.map} +1 -1
- package/dist/{attribution-settings-DepziZU8.js → attribution-settings-BeO1w_DL.js} +62 -51
- package/dist/attribution-settings-BeO1w_DL.js.map +1 -0
- package/dist/{auth-xgFZGZbf.js → auth-DjKEIiqG.js} +4 -4
- package/dist/{auth-xgFZGZbf.js.map → auth-DjKEIiqG.js.map} +1 -1
- package/dist/bluebird-client-DpYl1YmJ.js +1163 -0
- package/dist/bluebird-client-DpYl1YmJ.js.map +1 -0
- package/dist/bluebird-client-bn9Yv6Cb.js +2 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-vUDk6oV7.js → check-usage-B7UrDwD8.js} +4 -4
- package/dist/{check-usage-vUDk6oV7.js.map → check-usage-B7UrDwD8.js.map} +1 -1
- package/dist/{claude-Dw4V8o8l.js → claude-BQQPdXLb.js} +37 -29
- package/dist/claude-BQQPdXLb.js.map +1 -0
- package/dist/{codex-CXOpv4WP.js → codex-fW-hbxtT.js} +12 -8
- package/dist/codex-fW-hbxtT.js.map +1 -0
- package/dist/{copilot-discount-0lG67i9O.js → copilot-discount-BcUa3f-k.js} +2 -2
- package/dist/{copilot-discount-0lG67i9O.js.map → copilot-discount-BcUa3f-k.js.map} +1 -1
- package/dist/{debug-a737qcCC.js → debug-CigFsS-h.js} +2 -2
- package/dist/{debug-a737qcCC.js.map → debug-CigFsS-h.js.map} +1 -1
- package/dist/engine-E4WJGSeg.js +2 -0
- package/dist/{exec-COUT4QsS.js → exec-MCU1H-KZ.js} +63 -13
- package/dist/exec-MCU1H-KZ.js.map +1 -0
- package/dist/{gate-discovery-BGqS7R2g.js → gate-discovery-DbwVeERm.js} +6 -6
- package/dist/{gate-discovery-BGqS7R2g.js.map → gate-discovery-DbwVeERm.js.map} +1 -1
- package/dist/{get-copilot-usage-VKU2IvuE.js → get-copilot-usage-CGaV01dC.js} +4 -3
- package/dist/{get-copilot-usage-VKU2IvuE.js.map → get-copilot-usage-CGaV01dC.js.map} +1 -1
- package/dist/hooks.mjs +90 -27
- package/dist/hooks.sha256 +1 -1
- package/dist/index-cmd-DXYWgKS6.js +330 -0
- package/dist/index-cmd-DXYWgKS6.js.map +1 -0
- package/dist/{internal-aic-status-Cfl5HiAN.js → internal-aic-status-Bma0r0ZS.js} +6 -5
- package/dist/internal-aic-status-Bma0r0ZS.js.map +1 -0
- package/dist/{internal-artifact-open-CX2fRP_D.js → internal-artifact-open-lta2UPnE.js} +2 -2
- package/dist/{internal-artifact-open-CX2fRP_D.js.map → internal-artifact-open-lta2UPnE.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Cxattkm4.js → internal-fast-dispatch-guard-DPR16qUE.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js → internal-fast-dispatch-guard-DoXO3X7P.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js.map → internal-fast-dispatch-guard-DoXO3X7P.js.map} +1 -1
- package/dist/{internal-first-mate-guard-D_JFcrl_.js → internal-first-mate-guard-BEwDjHfX.js} +3 -3
- package/dist/{internal-first-mate-guard-D_JFcrl_.js.map → internal-first-mate-guard-BEwDjHfX.js.map} +1 -1
- package/dist/{internal-first-mate-guard-97qsseTP.js → internal-first-mate-guard-CAefr6Ce.js} +1 -1
- package/dist/{internal-max-dispatch-guard-DQMyOds8.js → internal-max-dispatch-guard-6ZCEanI6.js} +1 -1
- package/dist/{internal-max-dispatch-guard-Cxe8h12x.js → internal-max-dispatch-guard-CtIO7pm1.js} +3 -3
- package/dist/{internal-max-dispatch-guard-Cxe8h12x.js.map → internal-max-dispatch-guard-CtIO7pm1.js.map} +1 -1
- package/dist/{internal-plan-review-O2dwnQv3.js → internal-plan-review-jIts3KYd.js} +3 -3
- package/dist/{internal-plan-review-O2dwnQv3.js.map → internal-plan-review-jIts3KYd.js.map} +1 -1
- package/dist/{internal-prompt-submit-CD0UFkT-.js → internal-prompt-submit-BfoWVyzs.js} +10 -7
- package/dist/internal-prompt-submit-BfoWVyzs.js.map +1 -0
- package/dist/{internal-session-bind-CHIOd5ys.js → internal-session-bind-IpZ5hJzR.js} +2 -2
- package/dist/{internal-session-bind-CHIOd5ys.js.map → internal-session-bind-IpZ5hJzR.js.map} +1 -1
- package/dist/{internal-stop-hook-CH9SKjZ9.js → internal-stop-hook-DO8RKfKB.js} +6 -6
- package/dist/{internal-stop-hook-CH9SKjZ9.js.map → internal-stop-hook-DO8RKfKB.js.map} +1 -1
- package/dist/{internal-stop-review-a3rpzzhd.js → internal-stop-review-BtGDVrv-.js} +2 -2
- package/dist/{internal-stop-review-a3rpzzhd.js.map → internal-stop-review-BtGDVrv-.js.map} +1 -1
- package/dist/{internal-worker-guard-BY5seBqp.js → internal-worker-guard-C0FJ4b29.js} +2 -2
- package/dist/{internal-worker-guard-BY5seBqp.js.map → internal-worker-guard-C0FJ4b29.js.map} +1 -1
- package/dist/{internal-workspace-header-CPZNphnk.js → internal-workspace-header-tvJVAXpv.js} +2 -2
- package/dist/{internal-workspace-header-CPZNphnk.js.map → internal-workspace-header-tvJVAXpv.js.map} +1 -1
- package/dist/{lifecycle-D8vQXfeC.js → lifecycle-BqWTXaeC.js} +3 -3
- package/dist/{lifecycle-D8vQXfeC.js.map → lifecycle-BqWTXaeC.js.map} +1 -1
- package/dist/lifecycle-DMRZswwc.js +2 -0
- package/dist/lifecycle-FT75ohVw.js +2 -0
- package/dist/{lifecycle-MmpJWRcl.js → lifecycle-kpLzHUgD.js} +2 -2
- package/dist/{lifecycle-MmpJWRcl.js.map → lifecycle-kpLzHUgD.js.map} +1 -1
- package/dist/main.js +21 -21
- package/dist/{max-profile-contract-Bl7I_EOC.js → max-profile-contract-MJJt0zm-.js} +2 -2
- package/dist/{max-profile-contract-Bl7I_EOC.js.map → max-profile-contract-MJJt0zm-.js.map} +1 -1
- package/dist/{mcp-workspace-header-DX_mD0JT.js → mcp-workspace-header-B77WqVFw.js} +2 -2
- package/dist/{mcp-workspace-header-DX_mD0JT.js.map → mcp-workspace-header-B77WqVFw.js.map} +1 -1
- package/dist/{models-BjCRO0AC.js → models-68HDOEPK.js} +3 -3
- package/dist/{models-BjCRO0AC.js.map → models-68HDOEPK.js.map} +1 -1
- package/dist/{orchestration-Dn5v8c0a.js → orchestration-Ccmfslh4.js} +3 -3
- package/dist/{orchestration-Dn5v8c0a.js.map → orchestration-Ccmfslh4.js.map} +1 -1
- package/dist/{paths-P5ajjpzU.js → paths-CpbTHKeP.js} +3 -3
- package/dist/{paths-P5ajjpzU.js.map → paths-CpbTHKeP.js.map} +1 -1
- package/dist/paths-Dfivvq21.js +2 -0
- package/dist/{peer-mcp-personas-CnYMTizo.js → peer-mcp-personas-CeB2Kcn2.js} +184 -76
- package/dist/peer-mcp-personas-CeB2Kcn2.js.map +1 -0
- package/dist/{plan-review-hook-CfZBvsHd.js → plan-review-hook-ciat1jgZ.js} +4 -4
- package/dist/{plan-review-hook-CfZBvsHd.js.map → plan-review-hook-ciat1jgZ.js.map} +1 -1
- package/dist/{prompt-submit-hook-CRH6m7Vz.js → prompt-submit-hook-C8q_hDOv.js} +21 -17
- package/dist/prompt-submit-hook-C8q_hDOv.js.map +1 -0
- package/dist/{provision-D5KOOw6n.js → provision-DZLsyRYh.js} +7 -6
- package/dist/provision-DZLsyRYh.js.map +1 -0
- package/dist/{self-invocation-DBWyjvGm.js → self-invocation-DIUyoRgL.js} +2 -2
- package/dist/{self-invocation-DBWyjvGm.js.map → self-invocation-DIUyoRgL.js.map} +1 -1
- package/dist/{serve-fJWhiivo.js → serve-ik_96Q2Z.js} +33 -21
- package/dist/serve-ik_96Q2Z.js.map +1 -0
- package/dist/{server-setup-DHMPOXKT.js → server-setup-CK3O_Hwf.js} +37 -13
- package/dist/{server-setup-DHMPOXKT.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
- package/dist/{service-backend-DYEPoszR.js → service-backend-7SPDLUB9.js} +411 -25
- package/dist/service-backend-7SPDLUB9.js.map +1 -0
- package/dist/{start-Gs4jAwUR.js → start-DPOJJSvp.js} +4 -4
- package/dist/{start-Gs4jAwUR.js.map → start-DPOJJSvp.js.map} +1 -1
- package/dist/{state-BlMpEFAt.js → state-CVp30CBF.js} +7 -1
- package/dist/state-CVp30CBF.js.map +1 -0
- package/dist/{stop-gate-hook-BACb8dlj.js → stop-gate-hook-DZVfKoSh.js} +4 -4
- package/dist/{stop-gate-hook-BACb8dlj.js.map → stop-gate-hook-DZVfKoSh.js.map} +1 -1
- package/dist/{stop-gate-policy-D6jIeOXB.js → stop-gate-policy-Gd_cNT9-.js} +3 -3
- package/dist/{stop-gate-policy-D6jIeOXB.js.map → stop-gate-policy-Gd_cNT9-.js.map} +1 -1
- package/dist/{token-Dlb_84hW.js → token-DATA_OQK.js} +5 -383
- package/dist/token-DATA_OQK.js.map +1 -0
- package/dist/upstream-retry-i1k1Xai2.js +383 -0
- package/dist/upstream-retry-i1k1Xai2.js.map +1 -0
- package/dist/{worker-dispatch-DtjQchvM.js → worker-dispatch-lRhno09M.js} +2 -2
- package/dist/{worker-dispatch-DtjQchvM.js.map → worker-dispatch-lRhno09M.js.map} +1 -1
- package/docs/bluebird-search.md +338 -0
- package/package.json +3 -2
- package/dist/attribution-settings-DepziZU8.js.map +0 -1
- package/dist/claude-Dw4V8o8l.js.map +0 -1
- package/dist/codex-CXOpv4WP.js.map +0 -1
- package/dist/engine-CYba_zi7.js +0 -2
- package/dist/exec-COUT4QsS.js.map +0 -1
- package/dist/index-cmd-DUjQs9zw.js +0 -182
- package/dist/index-cmd-DUjQs9zw.js.map +0 -1
- package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
- package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
- package/dist/lifecycle-B2eB8nRg.js +0 -2
- package/dist/lifecycle-Dz-Rq8pD.js +0 -2
- package/dist/paths-DVXBtLyo.js +0 -2
- package/dist/peer-mcp-personas-CnYMTizo.js.map +0 -1
- package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
- package/dist/provision-D5KOOw6n.js.map +0 -1
- package/dist/serve-fJWhiivo.js.map +0 -1
- package/dist/service-backend-DYEPoszR.js.map +0 -1
- package/dist/state-BlMpEFAt.js.map +0 -1
- package/dist/token-Dlb_84hW.js.map +0 -1
|
@@ -0,0 +1,1163 @@
|
|
|
1
|
+
import { t as state } from "./state-CVp30CBF.js";
|
|
2
|
+
import { i as sanitizeTransportText } from "./upstream-retry-i1k1Xai2.js";
|
|
3
|
+
import { o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
|
|
4
|
+
//#region src/lib/azure-repo.ts
|
|
5
|
+
/**
|
|
6
|
+
* Azure DevOps repository detection for the `--bluebird` flag.
|
|
7
|
+
*
|
|
8
|
+
* Primary source is local git-remotes parsing (instant, offline, no extra
|
|
9
|
+
* dependency), ported from the Bluebird VS Code extension's `parseAzureRepo`
|
|
10
|
+
* (`bluebird-ai-labs.bluebird-vscode` v1.0.0, `dist/extension.js`). The
|
|
11
|
+
* extension is the reference implementation for which remote shapes exist
|
|
12
|
+
* in the wild, so this file mirrors its coverage:
|
|
13
|
+
* - `https://dev.azure.com/{org}/{project}/_git/{repo}`
|
|
14
|
+
* - `git@ssh.dev.azure.com:v3/{org}/{project}/{repo}`
|
|
15
|
+
* - `git@{org}.visualstudio.com:v3/{org}/{project}/{repo}`
|
|
16
|
+
* - legacy `*.visualstudio.com` HTTPS shapes
|
|
17
|
+
* - `_optimized` / `_full` repo-path infixes
|
|
18
|
+
*
|
|
19
|
+
* Git remotes are authoritative. Branch-index awareness
|
|
20
|
+
* (`checkBranchIndexStatus`) also mirrors the extension: it probes the
|
|
21
|
+
* Azure DevOps Search API so the Bluebird `x-mcp-ec-branch` header is only
|
|
22
|
+
* sent when the current branch is actually indexed; otherwise the caller
|
|
23
|
+
* falls back to the repo default branch.
|
|
24
|
+
*/
|
|
25
|
+
const MAX_COMPONENT_LENGTH = 64;
|
|
26
|
+
const MAX_ORG_LENGTH = 50;
|
|
27
|
+
function nonEmpty(value, max) {
|
|
28
|
+
if (!value) return null;
|
|
29
|
+
if (/[\r\n\0]/.test(value)) return null;
|
|
30
|
+
const decoded = safeDecode(value);
|
|
31
|
+
if (!decoded || decoded.length === 0 || decoded.length > max) return null;
|
|
32
|
+
if (/[\r\n\0]/.test(decoded)) return null;
|
|
33
|
+
return decoded;
|
|
34
|
+
}
|
|
35
|
+
function safeDecode(value) {
|
|
36
|
+
try {
|
|
37
|
+
return decodeURIComponent(value);
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Parse an Azure DevOps git remote URL into org/project/repo.
|
|
44
|
+
* Returns `null` for non-Azure remotes (GitHub etc.) or malformed URLs.
|
|
45
|
+
* Pure function — unit-testable without git/`az`.
|
|
46
|
+
*/
|
|
47
|
+
function parseAzureRepo(remoteUrl) {
|
|
48
|
+
if (!remoteUrl) return null;
|
|
49
|
+
const url = remoteUrl.trim();
|
|
50
|
+
if (!url) return null;
|
|
51
|
+
const ssh = url.match(/^git@ssh\.dev\.azure\.com:(?:v3\/)?([^/]+)\/([^/]+)\/(?:_(?:optimized|full)\/)?([^/]+?)(?:\.git)?$/i);
|
|
52
|
+
if (ssh) {
|
|
53
|
+
const organization = nonEmpty(ssh[1], MAX_ORG_LENGTH);
|
|
54
|
+
const project = nonEmpty(ssh[2], MAX_COMPONENT_LENGTH);
|
|
55
|
+
const repository = nonEmpty(ssh[3], MAX_COMPONENT_LENGTH);
|
|
56
|
+
if (organization && project && repository) return {
|
|
57
|
+
organization,
|
|
58
|
+
project,
|
|
59
|
+
repository
|
|
60
|
+
};
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const legacySsh = url.match(/^git@([^.]+)\.visualstudio\.com:v3\/([^/]+)\/([^/]+)\/(?:_(?:optimized|full)\/)?([^/]+?)(?:\.git)?$/i);
|
|
64
|
+
if (legacySsh) {
|
|
65
|
+
const organization = nonEmpty(legacySsh[2], MAX_ORG_LENGTH);
|
|
66
|
+
const project = nonEmpty(legacySsh[3], MAX_COMPONENT_LENGTH);
|
|
67
|
+
const repository = nonEmpty(legacySsh[4], MAX_COMPONENT_LENGTH);
|
|
68
|
+
if (organization && project && repository) return {
|
|
69
|
+
organization,
|
|
70
|
+
project,
|
|
71
|
+
repository
|
|
72
|
+
};
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const parsed = new URL(url);
|
|
77
|
+
const host = parsed.hostname.toLowerCase();
|
|
78
|
+
const segments = parsed.pathname.replace(/\.git$/, "").split("/").filter(Boolean);
|
|
79
|
+
if (host === "dev.azure.com") {
|
|
80
|
+
const gitIdx = segments.findIndex((s) => s.toLowerCase() === "_git");
|
|
81
|
+
if (gitIdx >= 2) {
|
|
82
|
+
const after = segments.slice(gitIdx + 1);
|
|
83
|
+
const repo = after[0]?.toLowerCase() === "_optimized" || after[0]?.toLowerCase() === "_full" ? after[1] : after[0];
|
|
84
|
+
const organization = nonEmpty(segments[0], MAX_ORG_LENGTH);
|
|
85
|
+
const project = nonEmpty(segments[1], MAX_COMPONENT_LENGTH);
|
|
86
|
+
const repository = nonEmpty(repo, MAX_COMPONENT_LENGTH);
|
|
87
|
+
if (organization && project && repository) return {
|
|
88
|
+
organization,
|
|
89
|
+
project,
|
|
90
|
+
repository
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (host.endsWith(".visualstudio.com")) {
|
|
95
|
+
const organization = nonEmpty(host.replace(/\.visualstudio\.com$/, ""), MAX_ORG_LENGTH);
|
|
96
|
+
const gitIdx = segments.findIndex((s) => s.toLowerCase() === "_git");
|
|
97
|
+
if (gitIdx >= 1 && organization) {
|
|
98
|
+
const project = nonEmpty(segments[gitIdx - 1], MAX_COMPONENT_LENGTH);
|
|
99
|
+
const after = segments.slice(gitIdx + 1);
|
|
100
|
+
const repository = nonEmpty(after[0]?.toLowerCase() === "_optimized" || after[0]?.toLowerCase() === "_full" ? after[1] : after[0], MAX_COMPONENT_LENGTH);
|
|
101
|
+
if (project && repository) return {
|
|
102
|
+
organization,
|
|
103
|
+
project,
|
|
104
|
+
repository
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
} catch {}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
async function runCmd(cmd, args, opts) {
|
|
112
|
+
const executable = resolveExecutable(cmd, { cwd: opts.cwd });
|
|
113
|
+
if (!executable) throw new Error(`${cmd} executable was not found on PATH`);
|
|
114
|
+
if (opts.signal?.aborted) throw opts.signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
115
|
+
const result = await runCommandCapture([executable, ...args], {
|
|
116
|
+
cwd: opts.cwd,
|
|
117
|
+
timeoutMs: opts.timeoutMs ?? 15e3,
|
|
118
|
+
maxStdoutBytes: 1048576,
|
|
119
|
+
...opts.signal ? { signal: opts.signal } : {}
|
|
120
|
+
});
|
|
121
|
+
if (opts.signal?.aborted) throw opts.signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
122
|
+
if (result.timedOut) throw new Error(`${cmd} timed out`);
|
|
123
|
+
if (result.code !== 0) {
|
|
124
|
+
const detail = result.stderr.trim() || result.stdout.trim();
|
|
125
|
+
throw new Error(`${cmd} exited with code ${result.code ?? "unknown"}${detail ? `: ${detail.slice(0, 500)}` : ""}`);
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
stdout: result.stdout,
|
|
129
|
+
stderr: result.stderr
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Parse one `git remote -v` line without losing its name or direction. */
|
|
133
|
+
function parseGitRemoteLine(line) {
|
|
134
|
+
const match = line.trim().match(/^(\S+)\s+(.*?)\s+\((fetch|push)\)$/i);
|
|
135
|
+
if (!match) return null;
|
|
136
|
+
return {
|
|
137
|
+
name: match[1],
|
|
138
|
+
url: match[2].trim(),
|
|
139
|
+
type: match[3].toLowerCase()
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function parseGitRemoteOutput(stdout) {
|
|
143
|
+
const entries = [];
|
|
144
|
+
for (const line of stdout.split("\n")) {
|
|
145
|
+
const parsed = parseGitRemoteLine(line);
|
|
146
|
+
if (!parsed) continue;
|
|
147
|
+
entries.push({
|
|
148
|
+
...parsed,
|
|
149
|
+
info: parseAzureRepo(parsed.url)
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return entries;
|
|
153
|
+
}
|
|
154
|
+
function sameAzureRepo(a, b) {
|
|
155
|
+
return a.organization.toLowerCase() === b.organization.toLowerCase() && a.project.toLowerCase() === b.project.toLowerCase() && a.repository.toLowerCase() === b.repository.toLowerCase();
|
|
156
|
+
}
|
|
157
|
+
function distinctAzureRepos(entries) {
|
|
158
|
+
const distinct = [];
|
|
159
|
+
for (const entry of entries) {
|
|
160
|
+
const entryInfo = entry.info;
|
|
161
|
+
if (!entryInfo) continue;
|
|
162
|
+
const existing = distinct.find(({ info }) => sameAzureRepo(info, entryInfo));
|
|
163
|
+
if (existing) existing.remoteNames.add(entry.name);
|
|
164
|
+
else distinct.push({
|
|
165
|
+
info: entryInfo,
|
|
166
|
+
remoteNames: /* @__PURE__ */ new Set([entry.name])
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
return distinct;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Resolve exactly one checked-out Azure DevOps repository from git remotes.
|
|
173
|
+
* An Azure `origin` fetch target is authoritative. Matching fetch/push and
|
|
174
|
+
* duplicate lines collapse; only distinct Azure targets can conflict.
|
|
175
|
+
*/
|
|
176
|
+
function resolveAzureRepoFromRemotes(entries) {
|
|
177
|
+
const originEntries = entries.filter((entry) => entry.name.toLowerCase() === "origin");
|
|
178
|
+
const originFetches = distinctAzureRepos(originEntries.filter((entry) => entry.type === "fetch"));
|
|
179
|
+
if (originFetches.length > 1) throw new Error("Conflicting Azure DevOps repositories configured for origin remote.");
|
|
180
|
+
if (originFetches.length === 1) {
|
|
181
|
+
const selected = originFetches[0].info;
|
|
182
|
+
if (originEntries.some((entry) => entry.info && !sameAzureRepo(entry.info, selected))) throw new Error("Conflicting Azure DevOps repositories configured for origin remote.");
|
|
183
|
+
return selected;
|
|
184
|
+
}
|
|
185
|
+
const distinct = distinctAzureRepos(entries);
|
|
186
|
+
if (distinct.length === 0) throw new Error("No supported Azure DevOps repository remote was found for this workspace. Git remotes are authoritative for Bluebird scope discovery; add a dev.azure.com or visualstudio.com remote. Exact/regex/ast modes still use the local engine.");
|
|
187
|
+
if (distinct.length === 1) return distinct[0].info;
|
|
188
|
+
const remoteNames = [...new Set(distinct.flatMap(({ remoteNames: names }) => [...names]))].sort();
|
|
189
|
+
throw new Error(`Ambiguous Azure DevOps repositories found across remotes: ${remoteNames.join(", ")}.`);
|
|
190
|
+
}
|
|
191
|
+
/** Authoritative Azure DevOps repository from `git remote -v`. */
|
|
192
|
+
async function getAzureRepoFromGit(cwd, signal) {
|
|
193
|
+
const { stdout } = await runCmd("git", ["remote", "-v"], {
|
|
194
|
+
cwd,
|
|
195
|
+
signal
|
|
196
|
+
});
|
|
197
|
+
return resolveAzureRepoFromRemotes(parseGitRemoteOutput(stdout));
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Current branch of the git checkout, or `null` only for detached HEAD.
|
|
201
|
+
* Git failures and cancellation remain visible.
|
|
202
|
+
*/
|
|
203
|
+
async function getCurrentBranch(cwd, signal) {
|
|
204
|
+
const { stdout } = await runCmd("git", [
|
|
205
|
+
"rev-parse",
|
|
206
|
+
"--abbrev-ref",
|
|
207
|
+
"HEAD"
|
|
208
|
+
], {
|
|
209
|
+
cwd,
|
|
210
|
+
signal
|
|
211
|
+
});
|
|
212
|
+
const branch = stdout.trim();
|
|
213
|
+
if (!branch || branch === "HEAD") return null;
|
|
214
|
+
return branch;
|
|
215
|
+
}
|
|
216
|
+
function normalizeBranch(branch) {
|
|
217
|
+
return branch.startsWith("refs/heads/") ? branch.slice(11) : branch;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Probe Azure DevOps Search for indexed branches. Transport, authentication,
|
|
221
|
+
* HTTP, cancellation, timeout, and response-shape failures remain visible.
|
|
222
|
+
*/
|
|
223
|
+
async function checkBranchIndexStatus(info, branch, token, signal) {
|
|
224
|
+
const normalized = normalizeBranch(branch);
|
|
225
|
+
const endpoint = `https://almsearch.dev.azure.com/${encodeURIComponent(info.organization)}/${encodeURIComponent(info.project)}/_apis/search/codesearchresults?api-version=7.1`;
|
|
226
|
+
const timeoutSignal = AbortSignal.timeout(15e3);
|
|
227
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
228
|
+
let response;
|
|
229
|
+
try {
|
|
230
|
+
response = await fetch(endpoint, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: {
|
|
233
|
+
"Content-Type": "application/json",
|
|
234
|
+
Authorization: `Bearer ${token}`
|
|
235
|
+
},
|
|
236
|
+
body: JSON.stringify({
|
|
237
|
+
searchText: "a*",
|
|
238
|
+
$top: 1,
|
|
239
|
+
includeFacets: true,
|
|
240
|
+
filters: {
|
|
241
|
+
Project: [info.project],
|
|
242
|
+
Repository: [info.repository]
|
|
243
|
+
}
|
|
244
|
+
}),
|
|
245
|
+
signal: requestSignal
|
|
246
|
+
});
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Branch index status check cancelled.");
|
|
249
|
+
if (timeoutSignal.aborted) throw new Error("Branch index status check timed out after 15000ms.", { cause: error });
|
|
250
|
+
throw new Error("Branch index status check transport failed.", { cause: error });
|
|
251
|
+
}
|
|
252
|
+
if (response.status === 401 || response.status === 403) throw new Error(`Branch index status check authentication failed with HTTP ${response.status}.`);
|
|
253
|
+
if (!response.ok) throw new Error(`Branch index status check failed with HTTP ${response.status}.`);
|
|
254
|
+
let body;
|
|
255
|
+
try {
|
|
256
|
+
body = await response.json();
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("Branch index status check cancelled.");
|
|
259
|
+
if (timeoutSignal.aborted) throw new Error("Branch index status check timed out after 15000ms.", { cause: error });
|
|
260
|
+
throw new Error("Branch index status check returned malformed JSON.", { cause: error });
|
|
261
|
+
}
|
|
262
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Branch index status check returned an invalid response shape.");
|
|
263
|
+
const facets = body.facets;
|
|
264
|
+
if (!facets || typeof facets !== "object" || Array.isArray(facets)) throw new Error("Branch index status check returned an invalid response shape.");
|
|
265
|
+
const branchFacet = facets.Branch;
|
|
266
|
+
if (!Array.isArray(branchFacet)) throw new Error("Branch index status check returned an invalid response shape.");
|
|
267
|
+
const indexed = [];
|
|
268
|
+
for (const row of branchFacet) {
|
|
269
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) throw new Error("Branch index status check returned an invalid response shape.");
|
|
270
|
+
const name = row.name;
|
|
271
|
+
if (typeof name !== "string" || !name.trim()) throw new Error("Branch index status check returned an invalid response shape.");
|
|
272
|
+
indexed.push(normalizeBranch(name));
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
isIndexed: indexed.some((candidate) => candidate.toLowerCase() === normalized.toLowerCase()),
|
|
276
|
+
branch: normalized,
|
|
277
|
+
indexedBranches: indexed
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
/** Default branch of an Azure DevOps repo via the `az` CLI. */
|
|
281
|
+
async function getDefaultBranch(info, cwd, signal) {
|
|
282
|
+
const { stdout } = await runCmd("az", [
|
|
283
|
+
"repos",
|
|
284
|
+
"show",
|
|
285
|
+
"--repository",
|
|
286
|
+
info.repository,
|
|
287
|
+
"--organization",
|
|
288
|
+
`https://dev.azure.com/${info.organization}`,
|
|
289
|
+
"--project",
|
|
290
|
+
info.project,
|
|
291
|
+
"--query",
|
|
292
|
+
"defaultBranch",
|
|
293
|
+
"--output",
|
|
294
|
+
"tsv"
|
|
295
|
+
], {
|
|
296
|
+
cwd,
|
|
297
|
+
timeoutMs: 2e4,
|
|
298
|
+
signal
|
|
299
|
+
});
|
|
300
|
+
const branch = normalizeBranch(stdout.trim().replace(/^["']|["']$/g, ""));
|
|
301
|
+
if (!branch) throw new Error("Azure CLI returned an empty default branch.");
|
|
302
|
+
return branch;
|
|
303
|
+
}
|
|
304
|
+
//#endregion
|
|
305
|
+
//#region src/lib/bluebird-client.ts
|
|
306
|
+
/**
|
|
307
|
+
* Minimal Bluebird MCP client (Streamable HTTP, MCP 2025-06-18).
|
|
308
|
+
*
|
|
309
|
+
* The proxy keeps its own `mcp__search__code` schema; this client speaks to
|
|
310
|
+
* the upstream Bluebird server (`https://mcp.bluebird-ai.net/`) and returns
|
|
311
|
+
* plain rows the unified helper maps 1:1. Tool parameter shapes are resolved
|
|
312
|
+
* at runtime from `tools/list` (candidate-key matching) rather than
|
|
313
|
+
* hard-coded, because the server is versioned independently of this repo.
|
|
314
|
+
*
|
|
315
|
+
* Auth: `az account get-access-token` for the Azure DevOps resource
|
|
316
|
+
* (`499b84ac-1321-427f-aa17-267ca6975798`). `BLUEBIRD_TOKEN` env overrides
|
|
317
|
+
* for tests and manual runs. 401 refreshes the token and recreates the session
|
|
318
|
+
* once before retrying.
|
|
319
|
+
*
|
|
320
|
+
* Retry: retriable statuses (429/500/502/503/504) and transport errors are
|
|
321
|
+
* retried up to 3 attempts with exponential backoff (1s/2s/4s). Anything
|
|
322
|
+
* else throws a `BluebirdError` the caller surfaces in `notice` — there is
|
|
323
|
+
* deliberately NO silent fallback to the local engine under `--bluebird`.
|
|
324
|
+
*/
|
|
325
|
+
const BLUEBIRD_MCP_URL = "https://mcp.bluebird-ai.net/";
|
|
326
|
+
const BLUEBIRD_TOKEN_RESOURCE = "499b84ac-1321-427f-aa17-267ca6975798";
|
|
327
|
+
const BLUEBIRD_PROTOCOL_VERSION = "2025-06-18";
|
|
328
|
+
var BluebirdError = class extends Error {
|
|
329
|
+
retriable;
|
|
330
|
+
status;
|
|
331
|
+
retryAfterMs;
|
|
332
|
+
constructor(message, opts = {}) {
|
|
333
|
+
super(sanitizeBluebirdDetail(message));
|
|
334
|
+
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
|
+
}
|
|
339
|
+
};
|
|
340
|
+
function sleep(ms, signal) {
|
|
341
|
+
if (signal?.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("aborted"));
|
|
342
|
+
return new Promise((resolve, reject) => {
|
|
343
|
+
let settled = false;
|
|
344
|
+
const timer = setTimeout(() => {
|
|
345
|
+
settled = true;
|
|
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"));
|
|
363
|
+
};
|
|
364
|
+
const onDisposalAbort = () => {
|
|
365
|
+
controller.abort(disposal?.reason ?? new BluebirdError("Bluebird client has been disposed.", { retriable: false }));
|
|
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()}`;
|
|
411
|
+
}
|
|
412
|
+
function sanitizeBluebirdDetail(value) {
|
|
413
|
+
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]");
|
|
414
|
+
}
|
|
415
|
+
async function runAzToken(signal) {
|
|
416
|
+
const executable = resolveExecutable("az");
|
|
417
|
+
if (!executable) throw new BluebirdError("Azure CLI executable `az` was not found on PATH.", { retriable: false });
|
|
418
|
+
try {
|
|
419
|
+
const result = await runCommandCapture([
|
|
420
|
+
executable,
|
|
421
|
+
"account",
|
|
422
|
+
"get-access-token",
|
|
423
|
+
"--resource",
|
|
424
|
+
BLUEBIRD_TOKEN_RESOURCE,
|
|
425
|
+
"--query",
|
|
426
|
+
"accessToken",
|
|
427
|
+
"--output",
|
|
428
|
+
"tsv"
|
|
429
|
+
], {
|
|
430
|
+
timeoutMs: 2e4,
|
|
431
|
+
maxStdoutBytes: 1048576,
|
|
432
|
+
...signal ? { signal } : {}
|
|
433
|
+
});
|
|
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
|
+
} catch (err) {
|
|
443
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
444
|
+
throw new BluebirdError(`az token acquisition failed (${sanitizeBluebirdDetail(err)}). Run \`az login\` and retry.`, { retriable: false });
|
|
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();
|
|
527
|
+
}
|
|
528
|
+
throw new BluebirdError("Bluebird returned no matching JSON-RPC response.", { retriable: true });
|
|
529
|
+
}
|
|
530
|
+
/** Token source: explicit env first (tests/manual), else `az` CLI. */
|
|
531
|
+
async function getBluebirdToken(signal) {
|
|
532
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
533
|
+
const env = process.env.BLUEBIRD_TOKEN?.trim();
|
|
534
|
+
if (env) return env;
|
|
535
|
+
return runAzToken(signal);
|
|
536
|
+
}
|
|
537
|
+
function isRecord(value) {
|
|
538
|
+
return typeof value === "object" && value !== null;
|
|
539
|
+
}
|
|
540
|
+
const QUERY_KEYS = [
|
|
541
|
+
"query",
|
|
542
|
+
"similarity_search_text",
|
|
543
|
+
"searchText",
|
|
544
|
+
"search_text",
|
|
545
|
+
"text",
|
|
546
|
+
"q",
|
|
547
|
+
"question"
|
|
548
|
+
];
|
|
549
|
+
const LIMIT_KEYS = [
|
|
550
|
+
"limit",
|
|
551
|
+
"top",
|
|
552
|
+
"maxResults",
|
|
553
|
+
"max_results",
|
|
554
|
+
"pageSize",
|
|
555
|
+
"count"
|
|
556
|
+
];
|
|
557
|
+
const GLOB_KEYS = [
|
|
558
|
+
"file_glob",
|
|
559
|
+
"fileGlob",
|
|
560
|
+
"filePattern",
|
|
561
|
+
"file_pattern",
|
|
562
|
+
"glob",
|
|
563
|
+
"pathFilter"
|
|
564
|
+
];
|
|
565
|
+
const UNIFIED_SEARCH_TOOL = "code_search";
|
|
566
|
+
const LEGACY_SEMANTIC_TOOL = "do_vector_search";
|
|
567
|
+
const LEGACY_LEXICAL_TOOL = "search_file_content";
|
|
568
|
+
function pickKey(schema, candidates) {
|
|
569
|
+
if (!isRecord(schema)) return null;
|
|
570
|
+
const props = isRecord(schema.properties) ? schema.properties : null;
|
|
571
|
+
if (!props) return candidates[0] ?? null;
|
|
572
|
+
for (const key of candidates) if (key in props) return key;
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
function asNumber(value) {
|
|
576
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
577
|
+
}
|
|
578
|
+
function asString(value) {
|
|
579
|
+
return typeof value === "string" ? value : void 0;
|
|
580
|
+
}
|
|
581
|
+
/** Normalize an upstream repository-relative path without allowing escapes. */
|
|
582
|
+
function normalizeRemotePath(value) {
|
|
583
|
+
if (!value || value.includes("\0")) return null;
|
|
584
|
+
const normalized = value.replaceAll("\\", "/");
|
|
585
|
+
if (/^[A-Za-z]:/.test(normalized) || normalized.startsWith("//")) return null;
|
|
586
|
+
const relative = normalized.replace(/^\/+/, "");
|
|
587
|
+
if (!relative || relative.split("/").some((part) => part === "..")) return null;
|
|
588
|
+
const segments = relative.split("/").filter((part) => part && part !== ".");
|
|
589
|
+
if (segments.length === 0) return null;
|
|
590
|
+
return segments.join("/");
|
|
591
|
+
}
|
|
592
|
+
/** Best-effort normalization of one upstream hit into a unified row. */
|
|
593
|
+
function toRow(item, index) {
|
|
594
|
+
if (!isRecord(item)) {
|
|
595
|
+
if (typeof item === "string" && item.trim()) return {
|
|
596
|
+
file: `bluebird-hit-${index}`,
|
|
597
|
+
line: 1,
|
|
598
|
+
snippet: item.slice(0, 2e3)
|
|
599
|
+
};
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
const file = asString(item.file) ?? asString(item.filePath) ?? asString(item.file_path) ?? asString(item.node_file_path) ?? asString(item.path) ?? asString(item.repoRelativePath);
|
|
603
|
+
const line = asNumber(item.line) ?? asNumber(item.lineNumber) ?? asNumber(item.line_number) ?? asNumber(item.startLine) ?? asNumber(item.start_line) ?? asNumber(item.code_startRow) ?? 1;
|
|
604
|
+
const snippet = asString(item.snippet) ?? asString(item.content) ?? asString(item.text) ?? asString(item.page_content) ?? asString(item.excerpt) ?? asString(item.preview);
|
|
605
|
+
if (!file || !snippet) return null;
|
|
606
|
+
const normalizedFile = normalizeRemotePath(file);
|
|
607
|
+
if (!normalizedFile) return null;
|
|
608
|
+
const row = {
|
|
609
|
+
file: normalizedFile,
|
|
610
|
+
line: Math.max(1, Math.floor(line)),
|
|
611
|
+
snippet
|
|
612
|
+
};
|
|
613
|
+
const score = asNumber(item.score) ?? asNumber(item.relevance) ?? asNumber(item.similarity) ?? asNumber(item.similarity_score);
|
|
614
|
+
if (score !== void 0) row.score = score;
|
|
615
|
+
const endLine = asNumber(item.endLine) ?? asNumber(item.end_line) ?? asNumber(item.code_endRow);
|
|
616
|
+
if (endLine !== void 0) row.endLine = endLine;
|
|
617
|
+
const name = asString(item.name) ?? asString(item.symbol) ?? asString(item.node_name);
|
|
618
|
+
if (name) row.name = name;
|
|
619
|
+
return row;
|
|
620
|
+
}
|
|
621
|
+
/** Extract rows from a `tools/call` result envelope. */
|
|
622
|
+
function rowsFromArray(items) {
|
|
623
|
+
if (items.length === 0) return [];
|
|
624
|
+
const rows = [];
|
|
625
|
+
let recognized = false;
|
|
626
|
+
for (const item of items) {
|
|
627
|
+
if (isRecord(item)) {
|
|
628
|
+
const wrapperKey = "SimilaritySearchResult" in item ? "SimilaritySearchResult" : "FullTextSearchResult" in item ? "FullTextSearchResult" : void 0;
|
|
629
|
+
if (wrapperKey) {
|
|
630
|
+
const nested = item[wrapperKey];
|
|
631
|
+
if (!Array.isArray(nested)) throw new BluebirdError(`Bluebird returned a malformed ${wrapperKey} wrapper.`, { retriable: false });
|
|
632
|
+
recognized = true;
|
|
633
|
+
rows.push(...rowsFromArray(nested));
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const row = toRow(item, rows.length);
|
|
638
|
+
if (row) {
|
|
639
|
+
recognized = true;
|
|
640
|
+
rows.push(row);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
if (!recognized) throw new BluebirdError("Bluebird returned no parseable code hits (unexpected result array shape).", { retriable: false });
|
|
644
|
+
return rows;
|
|
645
|
+
}
|
|
646
|
+
function rowsFromCallResult(result) {
|
|
647
|
+
if (Array.isArray(result)) return rowsFromArray(result);
|
|
648
|
+
if (!isRecord(result)) throw new BluebirdError("Bluebird returned an empty result.", { retriable: true });
|
|
649
|
+
if (result.isError === true) {
|
|
650
|
+
const detail = Array.isArray(result.content) ? result.content.map((c) => isRecord(c) && typeof c.text === "string" ? c.text : "").join(" ").trim() : "";
|
|
651
|
+
throw new BluebirdError(`Bluebird tool error${detail ? `: ${sanitizeTransportText(detail)}` : ""}`, { retriable: false });
|
|
652
|
+
}
|
|
653
|
+
const texts = [];
|
|
654
|
+
if (Array.isArray(result.content)) {
|
|
655
|
+
for (const block of result.content) if (isRecord(block) && typeof block.text === "string" && block.text.trim()) texts.push(block.text);
|
|
656
|
+
}
|
|
657
|
+
const structured = result.structuredContent ?? result.results ?? result.items;
|
|
658
|
+
if (Array.isArray(structured)) return rowsFromArray(structured);
|
|
659
|
+
if (isRecord(structured)) {
|
|
660
|
+
const nested = structured.results ?? structured.items;
|
|
661
|
+
if (Array.isArray(nested)) return rowsFromArray(nested);
|
|
662
|
+
}
|
|
663
|
+
for (const text of texts) {
|
|
664
|
+
const trimmed = text.trim();
|
|
665
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) continue;
|
|
666
|
+
let parsed;
|
|
667
|
+
try {
|
|
668
|
+
parsed = JSON.parse(trimmed);
|
|
669
|
+
} catch {
|
|
670
|
+
const decoder = new TextDecoder();
|
|
671
|
+
const encoded = new TextEncoder().encode(trimmed);
|
|
672
|
+
let parsedPrefix = false;
|
|
673
|
+
for (let end = encoded.length - 1; end > 0; end--) {
|
|
674
|
+
const char = String.fromCharCode(encoded[end]);
|
|
675
|
+
if (char !== "]" && char !== "}") continue;
|
|
676
|
+
try {
|
|
677
|
+
parsed = JSON.parse(decoder.decode(encoded.subarray(0, end + 1)));
|
|
678
|
+
parsedPrefix = true;
|
|
679
|
+
break;
|
|
680
|
+
} catch {}
|
|
681
|
+
}
|
|
682
|
+
if (!parsedPrefix) continue;
|
|
683
|
+
}
|
|
684
|
+
const arr = Array.isArray(parsed) ? parsed : isRecord(parsed) && Array.isArray(parsed.results) ? parsed.results : isRecord(parsed) && Array.isArray(parsed.items) ? parsed.items : null;
|
|
685
|
+
if (arr) return rowsFromArray(arr);
|
|
686
|
+
}
|
|
687
|
+
throw new BluebirdError("Bluebird returned no parseable code hits (unexpected tool result shape).", { retriable: false });
|
|
688
|
+
}
|
|
689
|
+
var BluebirdMcpClient = class {
|
|
690
|
+
token;
|
|
691
|
+
scope;
|
|
692
|
+
baseUrl;
|
|
693
|
+
toolSchemas = /* @__PURE__ */ new Map();
|
|
694
|
+
initialized = false;
|
|
695
|
+
initialization;
|
|
696
|
+
refreshPromise;
|
|
697
|
+
sessionId;
|
|
698
|
+
nextId = 1;
|
|
699
|
+
disposed = false;
|
|
700
|
+
disposalController = new AbortController();
|
|
701
|
+
tokenGeneration = 0;
|
|
702
|
+
sessionGeneration = 0;
|
|
703
|
+
constructor(scope, token, baseUrl = BLUEBIRD_MCP_URL) {
|
|
704
|
+
this.scope = scope;
|
|
705
|
+
this.token = token;
|
|
706
|
+
this.baseUrl = baseUrl;
|
|
707
|
+
}
|
|
708
|
+
headers(extra) {
|
|
709
|
+
const headers = {
|
|
710
|
+
"Content-Type": "application/json",
|
|
711
|
+
Accept: "application/json, text/event-stream",
|
|
712
|
+
"MCP-Protocol-Version": BLUEBIRD_PROTOCOL_VERSION,
|
|
713
|
+
Authorization: `Bearer ${this.token}`,
|
|
714
|
+
"x-mcp-ec-organization": this.scope.organization,
|
|
715
|
+
"x-mcp-ec-project": this.scope.project,
|
|
716
|
+
"x-mcp-ec-repository": this.scope.repositories.join(","),
|
|
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
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
if (notification && (res.status === 202 || res.status === 204)) return { jsonrpc: "2.0" };
|
|
771
|
+
if (res.headers.get("content-type")?.includes("text/event-stream")) try {
|
|
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;
|
|
793
|
+
});
|
|
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
|
+
}
|
|
894
|
+
shapeArgs(tool, query, opts, mode) {
|
|
895
|
+
const schema = this.toolSchemas.get(tool);
|
|
896
|
+
const args = {};
|
|
897
|
+
const queryKey = pickKey(schema, QUERY_KEYS) ?? "query";
|
|
898
|
+
args[queryKey] = query;
|
|
899
|
+
if (tool === this.resolveTool(UNIFIED_SEARCH_TOOL)) {
|
|
900
|
+
args.method = mode === "semantic" ? "semantic" : "keyword";
|
|
901
|
+
if (mode === "semantic" && isRecord(schema)) {
|
|
902
|
+
const props = isRecord(schema.properties) ? schema.properties : void 0;
|
|
903
|
+
if (props && "search_index" in props) args.search_index = "General";
|
|
904
|
+
}
|
|
905
|
+
} else if (mode === "semantic" && isRecord(schema)) {
|
|
906
|
+
const props = isRecord(schema.properties) ? schema.properties : void 0;
|
|
907
|
+
if (props && "search_index" in props) args.search_index = "General";
|
|
908
|
+
}
|
|
909
|
+
const limitKey = pickKey(schema, LIMIT_KEYS);
|
|
910
|
+
if (limitKey && opts.limit !== void 0) args[limitKey] = opts.limit;
|
|
911
|
+
const globKey = pickKey(schema, GLOB_KEYS);
|
|
912
|
+
if (globKey && opts.file_glob) args[globKey] = opts.file_glob;
|
|
913
|
+
return args;
|
|
914
|
+
}
|
|
915
|
+
searchTool(mode) {
|
|
916
|
+
const unified = this.resolveTool(UNIFIED_SEARCH_TOOL);
|
|
917
|
+
if (unified) return unified;
|
|
918
|
+
const legacy = this.resolveTool(mode === "semantic" ? LEGACY_SEMANTIC_TOOL : LEGACY_LEXICAL_TOOL);
|
|
919
|
+
if (legacy) return legacy;
|
|
920
|
+
throw new BluebirdError(`Bluebird does not advertise a ${mode} code-search tool.`, { retriable: false });
|
|
921
|
+
}
|
|
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
|
+
/** Lexical path: indexed keyword search. */
|
|
970
|
+
async searchFileContent(query, opts = {}) {
|
|
971
|
+
await this.initialize(opts.signal);
|
|
972
|
+
const tool = this.searchTool("lexical");
|
|
973
|
+
const rows = rowsFromCallResult(await this.callWithRetry(tool, this.shapeArgs(tool, query, opts, "lexical"), opts.signal));
|
|
974
|
+
return opts.limit !== void 0 ? rows.slice(0, opts.limit) : rows;
|
|
975
|
+
}
|
|
976
|
+
/** Semantic path: code-aware vector search. */
|
|
977
|
+
async doVectorSearch(query, opts = {}) {
|
|
978
|
+
await this.initialize(opts.signal);
|
|
979
|
+
const tool = this.searchTool("semantic");
|
|
980
|
+
const rows = rowsFromCallResult(await this.callWithRetry(tool, this.shapeArgs(tool, query, opts, "semantic"), opts.signal));
|
|
981
|
+
return opts.limit !== void 0 ? rows.slice(0, opts.limit) : rows;
|
|
982
|
+
}
|
|
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
|
+
};
|
|
1013
|
+
async function resolveBluebirdProvisionFromWorkspace(workspace, signal) {
|
|
1014
|
+
let primary;
|
|
1015
|
+
try {
|
|
1016
|
+
primary = await getAzureRepoFromGit(workspace, signal);
|
|
1017
|
+
} catch (err) {
|
|
1018
|
+
throw err instanceof BluebirdError ? err : new BluebirdError(sanitizeBluebirdDetail(err), { retriable: false });
|
|
1019
|
+
}
|
|
1020
|
+
const repositories = [primary.repository];
|
|
1021
|
+
let token;
|
|
1022
|
+
try {
|
|
1023
|
+
token = await getBluebirdToken(signal);
|
|
1024
|
+
} catch (err) {
|
|
1025
|
+
throw err instanceof BluebirdError ? err : new BluebirdError(`Bluebird auth failed: ${sanitizeBluebirdDetail(err)}`, { retriable: false });
|
|
1026
|
+
}
|
|
1027
|
+
let branch;
|
|
1028
|
+
try {
|
|
1029
|
+
const current = await getCurrentBranch(workspace, signal);
|
|
1030
|
+
if (current) {
|
|
1031
|
+
const status = await checkBranchIndexStatus(primary, current, token, signal);
|
|
1032
|
+
branch = status.isIndexed ? status.branch : await getDefaultBranch(primary, workspace, signal);
|
|
1033
|
+
} else branch = await getDefaultBranch(primary, workspace, signal);
|
|
1034
|
+
} catch (err) {
|
|
1035
|
+
if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("aborted");
|
|
1036
|
+
throw err instanceof BluebirdError ? err : new BluebirdError(sanitizeBluebirdDetail(err), { retriable: false });
|
|
1037
|
+
}
|
|
1038
|
+
return {
|
|
1039
|
+
organization: primary.organization,
|
|
1040
|
+
project: primary.project,
|
|
1041
|
+
repositories,
|
|
1042
|
+
branch,
|
|
1043
|
+
token
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
function clientForScope(scope) {
|
|
1047
|
+
return new BluebirdMcpClient({
|
|
1048
|
+
organization: scope.organization,
|
|
1049
|
+
project: scope.project,
|
|
1050
|
+
repositories: scope.repositories,
|
|
1051
|
+
...scope.branch ? { branch: scope.branch } : {}
|
|
1052
|
+
}, scope.token);
|
|
1053
|
+
}
|
|
1054
|
+
function publishScope(entry) {
|
|
1055
|
+
state.bluebirdClient = entry.client;
|
|
1056
|
+
state.bluebirdOrganization = entry.scope.organization;
|
|
1057
|
+
state.bluebirdProject = entry.scope.project;
|
|
1058
|
+
state.bluebirdRepositories = [...entry.scope.repositories];
|
|
1059
|
+
state.bluebirdBranch = entry.scope.branch;
|
|
1060
|
+
}
|
|
1061
|
+
/** Runtime-owned, workspace/scope-isolated Bluebird client registry. */
|
|
1062
|
+
var BluebirdClientManager = class {
|
|
1063
|
+
entries = /* @__PURE__ */ new Map();
|
|
1064
|
+
workspaces = /* @__PURE__ */ new Map();
|
|
1065
|
+
workspaceFlights = /* @__PURE__ */ new Map();
|
|
1066
|
+
activeFlights = /* @__PURE__ */ new Set();
|
|
1067
|
+
activeControllers = /* @__PURE__ */ new Set();
|
|
1068
|
+
resolveProvision;
|
|
1069
|
+
createClient;
|
|
1070
|
+
generation = 0;
|
|
1071
|
+
constructor(resolveProvision = resolveBluebirdProvisionFromWorkspace, createClient = clientForScope) {
|
|
1072
|
+
this.resolveProvision = resolveProvision;
|
|
1073
|
+
this.createClient = createClient;
|
|
1074
|
+
}
|
|
1075
|
+
async getOrCreate(workspace, signal) {
|
|
1076
|
+
const workspaceKey = canonicalWorkspace(workspace);
|
|
1077
|
+
const cached = this.workspaces.get(workspaceKey);
|
|
1078
|
+
if (cached) {
|
|
1079
|
+
publishScope(cached);
|
|
1080
|
+
return waitForSignal(cached.promise, signal);
|
|
1081
|
+
}
|
|
1082
|
+
const existingFlight = this.workspaceFlights.get(workspaceKey);
|
|
1083
|
+
if (existingFlight) return waitForSignal(existingFlight, signal);
|
|
1084
|
+
const generation = this.generation;
|
|
1085
|
+
const flightController = new AbortController();
|
|
1086
|
+
this.activeControllers.add(flightController);
|
|
1087
|
+
let createdClient;
|
|
1088
|
+
const init = (async () => {
|
|
1089
|
+
const scope = await this.resolveProvision(workspace, flightController.signal);
|
|
1090
|
+
if (generation !== this.generation || flightController.signal.aborted) throw new BluebirdError("Bluebird client manager was disposed during provisioning.", { retriable: false });
|
|
1091
|
+
const key = scopeFingerprint(workspaceKey, scope);
|
|
1092
|
+
const existing = this.entries.get(key);
|
|
1093
|
+
if (existing) {
|
|
1094
|
+
this.workspaces.set(workspaceKey, existing);
|
|
1095
|
+
publishScope(existing);
|
|
1096
|
+
return existing.promise;
|
|
1097
|
+
}
|
|
1098
|
+
const client = this.createClient(scope);
|
|
1099
|
+
createdClient = client;
|
|
1100
|
+
const promise = client.initialize(flightController.signal).then(() => {
|
|
1101
|
+
if (generation !== this.generation || flightController.signal.aborted) throw new BluebirdError("Bluebird client manager was disposed during initialization.", { retriable: false });
|
|
1102
|
+
publishScope({
|
|
1103
|
+
promise,
|
|
1104
|
+
client,
|
|
1105
|
+
scope
|
|
1106
|
+
});
|
|
1107
|
+
return client;
|
|
1108
|
+
}).catch(async (err) => {
|
|
1109
|
+
await client.dispose();
|
|
1110
|
+
if (this.entries.get(key)?.client === client) this.entries.delete(key);
|
|
1111
|
+
if (this.workspaces.get(workspaceKey)?.client === client) this.workspaces.delete(workspaceKey);
|
|
1112
|
+
throw err;
|
|
1113
|
+
});
|
|
1114
|
+
const entry = {
|
|
1115
|
+
promise,
|
|
1116
|
+
client,
|
|
1117
|
+
scope
|
|
1118
|
+
};
|
|
1119
|
+
this.entries.set(key, entry);
|
|
1120
|
+
this.workspaces.set(workspaceKey, entry);
|
|
1121
|
+
return promise;
|
|
1122
|
+
})();
|
|
1123
|
+
this.activeFlights.add(init);
|
|
1124
|
+
this.workspaceFlights.set(workspaceKey, init);
|
|
1125
|
+
init.finally(() => {
|
|
1126
|
+
this.activeControllers.delete(flightController);
|
|
1127
|
+
this.activeFlights.delete(init);
|
|
1128
|
+
if (this.workspaceFlights.get(workspaceKey) === init) this.workspaceFlights.delete(workspaceKey);
|
|
1129
|
+
if (generation !== this.generation && createdClient) createdClient.dispose().catch(() => {});
|
|
1130
|
+
}).catch(() => {});
|
|
1131
|
+
return waitForSignal(init, signal);
|
|
1132
|
+
}
|
|
1133
|
+
async disposeAll() {
|
|
1134
|
+
this.generation++;
|
|
1135
|
+
for (const controller of this.activeControllers) controller.abort(new BluebirdError("Bluebird client manager has been disposed.", { retriable: false }));
|
|
1136
|
+
this.activeControllers.clear();
|
|
1137
|
+
this.workspaceFlights.clear();
|
|
1138
|
+
this.workspaces.clear();
|
|
1139
|
+
const entries = [...this.entries.values()];
|
|
1140
|
+
this.entries.clear();
|
|
1141
|
+
state.bluebirdClient = null;
|
|
1142
|
+
state.bluebirdOrganization = null;
|
|
1143
|
+
state.bluebirdProject = null;
|
|
1144
|
+
state.bluebirdRepositories = [];
|
|
1145
|
+
state.bluebirdBranch = null;
|
|
1146
|
+
const pendingFlights = [...this.activeFlights];
|
|
1147
|
+
this.activeFlights.clear();
|
|
1148
|
+
await Promise.allSettled([...entries.map((entry) => entry.client.dispose()), ...pendingFlights]);
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
const bluebirdManager = new BluebirdClientManager();
|
|
1152
|
+
async function disposeBluebirdClients() {
|
|
1153
|
+
await bluebirdManager.disposeAll();
|
|
1154
|
+
}
|
|
1155
|
+
async function ensureBluebirdClient(workspace, signal) {
|
|
1156
|
+
const client = await bluebirdManager.getOrCreate(workspace, signal);
|
|
1157
|
+
state.bluebirdClient = client;
|
|
1158
|
+
return client;
|
|
1159
|
+
}
|
|
1160
|
+
//#endregion
|
|
1161
|
+
export { BluebirdError as a, ensureBluebirdClient as c, BluebirdClientManager as i, getBluebirdToken as l, BLUEBIRD_PROTOCOL_VERSION as n, BluebirdMcpClient as o, BLUEBIRD_TOKEN_RESOURCE as r, disposeBluebirdClients as s, BLUEBIRD_MCP_URL as t };
|
|
1162
|
+
|
|
1163
|
+
//# sourceMappingURL=bluebird-client-DpYl1YmJ.js.map
|