github-router 0.3.369 → 0.3.371
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/dist/ado-tools-512UGB6R.js +1 -0
- package/dist/{aic-ledger-_mvGW2Ev.js → aic-ledger-Cp7Yk9-Q.js} +2 -2
- package/dist/{aic-ledger-_mvGW2Ev.js.map → aic-ledger-Cp7Yk9-Q.js.map} +1 -1
- package/dist/{attribution-settings-zoBxw08y.js → attribution-settings-Beer9wsJ.js} +6 -6
- package/dist/{attribution-settings-zoBxw08y.js.map → attribution-settings-Beer9wsJ.js.map} +1 -1
- package/dist/{auth-B3UvYB2r.js → auth-B1egtvt4.js} +3 -3
- package/dist/{auth-B3UvYB2r.js.map → auth-B1egtvt4.js.map} +1 -1
- package/dist/{bluebird-client-C29-JOkG.js → bluebird-client-ByCRusGQ.js} +3 -3
- package/dist/bluebird-client-ByCRusGQ.js.map +1 -0
- package/dist/bluebird-client-CY6NBHQu.js +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-45vyaLfl.js → check-usage-T_z84Pgc.js} +3 -3
- package/dist/{check-usage-45vyaLfl.js.map → check-usage-T_z84Pgc.js.map} +1 -1
- package/dist/{claude-BbIfnWbm.js → claude-CAYTTiyt.js} +18 -15
- package/dist/claude-CAYTTiyt.js.map +1 -0
- package/dist/{claude-md-injection-BtBG1RBZ.js → claude-md-injection-D1aMjvb_.js} +3 -3
- package/dist/{claude-md-injection-BtBG1RBZ.js.map → claude-md-injection-D1aMjvb_.js.map} +1 -1
- package/dist/{codex-CZVlP2tB.js → codex-CALX-qG4.js} +8 -8
- package/dist/{codex-CZVlP2tB.js.map → codex-CALX-qG4.js.map} +1 -1
- package/dist/{copilot-discount-BuDbQOHq.js → copilot-discount-T-cfWmc4.js} +2 -2
- package/dist/{copilot-discount-BuDbQOHq.js.map → copilot-discount-T-cfWmc4.js.map} +1 -1
- package/dist/engine-CSAEqj2p.js +1 -0
- package/dist/{gate-discovery-BYyYeUnn.js → gate-discovery-CITKjhsD.js} +2 -2
- package/dist/{gate-discovery-BYyYeUnn.js.map → gate-discovery-CITKjhsD.js.map} +1 -1
- package/dist/{get-copilot-usage-BbGmK03C.js → get-copilot-usage-BSXeQEx8.js} +3 -3
- package/dist/{get-copilot-usage-BbGmK03C.js.map → get-copilot-usage-BSXeQEx8.js.map} +1 -1
- package/dist/hooks.mjs +2 -0
- package/dist/hooks.sha256 +1 -1
- package/dist/{internal-aic-status-BAVomi5A.js → internal-aic-status-CY0QxSa7.js} +3 -3
- package/dist/{internal-aic-status-BAVomi5A.js.map → internal-aic-status-CY0QxSa7.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-BodVFHRC.js → internal-max-dispatch-guard-4rh6KSd8.js} +2 -2
- package/dist/{internal-max-dispatch-guard-BodVFHRC.js.map → internal-max-dispatch-guard-4rh6KSd8.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-BB0vwiPx.js → internal-max-dispatch-guard-CKnzgJje.js} +1 -1
- package/dist/{internal-stop-hook-BbyobGUU.js → internal-stop-hook-DT27bzH7.js} +2 -2
- package/dist/{internal-stop-hook-BbyobGUU.js.map → internal-stop-hook-DT27bzH7.js.map} +1 -1
- package/dist/main.js +12 -11
- package/dist/main.js.map +1 -1
- package/dist/{max-profile-contract-Cx5_Z1Y7.js → max-profile-contract-CRj7N211.js} +2 -2
- package/dist/{max-profile-contract-Cx5_Z1Y7.js.map → max-profile-contract-CRj7N211.js.map} +1 -1
- package/dist/{models-BR6i348u.js → models-Ca-HQTYi.js} +2 -2
- package/dist/{models-BR6i348u.js.map → models-Ca-HQTYi.js.map} +1 -1
- package/dist/{peer-mcp-personas-DNtWI2C1.js → peer-mcp-personas-D7vaM-V5.js} +813 -59
- package/dist/peer-mcp-personas-D7vaM-V5.js.map +1 -0
- package/dist/{pi-Bc-MVgAo.js → pi-D4LrdubN.js} +16 -13
- package/dist/{pi-Bc-MVgAo.js.map → pi-D4LrdubN.js.map} +1 -1
- package/dist/{provision-DUWdcY_a.js → provision-DonGTIfK.js} +3 -2
- package/dist/provision-DonGTIfK.js.map +1 -0
- package/dist/{serve-CmWOTR7m.js → serve-jzmQ8KEE.js} +18 -10
- package/dist/serve-jzmQ8KEE.js.map +1 -0
- package/dist/{server-setup-CIzmDJzT.js → server-setup-wWidNq5m.js} +73 -28
- package/dist/server-setup-wWidNq5m.js.map +1 -0
- package/dist/{start-rlpaeAtx.js → start-CTluQxu5.js} +3 -3
- package/dist/{start-rlpaeAtx.js.map → start-CTluQxu5.js.map} +1 -1
- package/dist/{state-CiwCLVDZ.js → state-DzsaGHr9.js} +3 -1
- package/dist/{state-CiwCLVDZ.js.map → state-DzsaGHr9.js.map} +1 -1
- package/dist/token-CVG0yI_j.js +480 -0
- package/dist/token-CVG0yI_j.js.map +1 -0
- package/dist/{token-OTb61rOC.js → token-Dqjs5ixP.js} +3 -3
- package/dist/{token-OTb61rOC.js.map → token-Dqjs5ixP.js.map} +1 -1
- package/dist/workiq-qnJR5_n2.js +144 -0
- package/dist/workiq-qnJR5_n2.js.map +1 -0
- package/dist/workiq-tools-CDLIrILp.js +1 -0
- package/package.json +1 -1
- package/dist/ado-tools-C0sY_rX1.js +0 -1
- package/dist/bluebird-client-C29-JOkG.js.map +0 -1
- package/dist/bluebird-client-DGE3WZqh.js +0 -1
- package/dist/claude-BbIfnWbm.js.map +0 -1
- package/dist/engine-DeIo-VIR.js +0 -1
- package/dist/peer-mcp-personas-DNtWI2C1.js.map +0 -1
- package/dist/provision-DUWdcY_a.js.map +0 -1
- package/dist/serve-CmWOTR7m.js.map +0 -1
- package/dist/server-setup-CIzmDJzT.js.map +0 -1
|
@@ -2,21 +2,22 @@ import { A as validateWorkspace, C as provisionColbert, D as colbertPlatformSupp
|
|
|
2
2
|
import { n as explicitPackageRoot } from "./package-root-B-osctCk.js";
|
|
3
3
|
import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
|
|
4
4
|
import { t as PATHS } from "./paths-C5477RGC.js";
|
|
5
|
-
import { t as state } from "./state-
|
|
6
|
-
import { C as
|
|
5
|
+
import { t as state } from "./state-DzsaGHr9.js";
|
|
6
|
+
import { C as copilotHeaders, E as githubAgentHeaders, S as copilotBaseUrl, T as githubAgentGraphQLHeaders, _ as isAllowedCopilotHost, b as GITHUB_API_BASE_URL, f as resolveModel, i as tryRefreshAndRetry, p as sleep$3, v as HTTPError, w as copilotVersion, x as GITHUB_GRAPHQL_URL } from "./token-Dqjs5ixP.js";
|
|
7
7
|
import { a as withTransientRetry, i as sanitizeTransportText, n as classifyTransportError, r as fetchWithTransientRetry } from "./upstream-retry-i1k1Xai2.js";
|
|
8
8
|
import { a as parseBoolEnv, d as runManagedExeCapture, o as parseIntEnv, s as resolveExecutable } from "./exec-Bf8g_bIR.js";
|
|
9
9
|
import { a as FAST_PROFILE_ASTRA_MODEL, c as FAST_PROFILE_MODELS, d as FAST_PROFILE_NATIVE_MODELS, f as FAST_PROFILE_ORACLE_EFFORT, n as FAST_PROFILE_ADVISOR_EFFORT, p as FAST_PROFILE_ORACLE_MODEL, r as FAST_PROFILE_ADVISOR_MODEL, u as FAST_PROFILE_NATIVE_EFFORTS } from "./fast-profile-contract-JOnZBgFB.js";
|
|
10
10
|
import { A as CHEAPEST_PROFILE_ADVISOR_MODEL, C as BALANCED2_PROFILE_MODELS, M as CHEAPEST_PROFILE_ADVISOR_TRANSCRIPT_TOKENS_MAX, N as CHEAPEST_PROFILE_ADVISOR_TRANSCRIPT_TOKENS_MIN, O as CHEAPEST2_PROFILE_MODELS, P as CHEAPEST_PROFILE_MODELS, S as localContractFor, _ as isCheapestFamily, a as decidePromptSubmitV2, b as isPinnedLaunchProfile, c as CHEAPEST_REWRITE_EFFORT, f as balancedContractFor, g as isBalancedFamily, h as displayModelName, j as CHEAPEST_PROFILE_ADVISOR_TRANSCRIPT_TOKENS_DEFAULT, m as cheapestRewriteModelFor, p as cheapestContractFor, t as buildStaticPack, u as isCheapestRewriteDisabledEnv, v as isCheaplocalProfile, w as LOCAL_PROFILE_LEAD_MODEL, y as isLocalFamily } from "./static-context-pack-DvwLWlbe.js";
|
|
11
11
|
import { r as BALANCED_PROFILE_MODELS } from "./balanced-profile-contract-Dm_usmw7.js";
|
|
12
|
-
import { A as normalizeTrailingOneMSuffix, D as maxPeerInstructions, E as maxPeerDescription, O as fastEndpointForCatalogId, b as MAX_ADVISOR_SYSTEM_PROMPT, f as maxCodexReviewerModel, g as maxProReplacementModel, h as maxOpusModel, i as MAX_PROFILE_MODELS, k as fastEndpointForModel, m as maxGrokModel, p as maxGeminiModel, r as MAX_PROFILE_LEAD_MODEL, v as maxSonnetModel } from "./max-profile-contract-
|
|
12
|
+
import { A as normalizeTrailingOneMSuffix, D as maxPeerInstructions, E as maxPeerDescription, O as fastEndpointForCatalogId, b as MAX_ADVISOR_SYSTEM_PROMPT, f as maxCodexReviewerModel, g as maxProReplacementModel, h as maxOpusModel, i as MAX_PROFILE_MODELS, k as fastEndpointForModel, m as maxGrokModel, p as maxGeminiModel, r as MAX_PROFILE_LEAD_MODEL, v as maxSonnetModel } from "./max-profile-contract-CRj7N211.js";
|
|
13
13
|
import { i as registerExitHandlers$1, n as getInstanceUuid, r as recordWorkerRepo, t as WorktreeRegistry } from "./lifecycle-Gge2Dadd.js";
|
|
14
14
|
import { t as MCP_WORKSPACE_HEADER } from "./mcp-workspace-header-Xw9B1W6T.js";
|
|
15
15
|
import { n as ArtifactError, r as applyInsecureTls, t as ArtifactClient } from "./client-CQMfroGV.js";
|
|
16
16
|
import { f as stopReviewStateDir, n as fileFindingsStore, o as fileRewriteFlagStore, r as fileLastPromptStore } from "./stop-gate-policy-Dx9c98_d.js";
|
|
17
|
-
import { _ as RemoteMcpError, b as sanitizeRemoteDetail, f as getAzureRepoFromGit, g as RemoteMcpClient, h as describeAzFailure, l as ensureBluebirdClient, m as AzCliAccessTokenCache, o as BluebirdError, p as resolveAzureRepoIds, v as isRecord$4, x as sleep$4, y as parseRetryAfter } from "./bluebird-client-
|
|
17
|
+
import { _ as RemoteMcpError, b as sanitizeRemoteDetail, f as getAzureRepoFromGit, g as RemoteMcpClient, h as describeAzFailure, l as ensureBluebirdClient, m as AzCliAccessTokenCache, o as BluebirdError, p as resolveAzureRepoIds, v as isRecord$4, x as sleep$4, y as parseRetryAfter } from "./bluebird-client-ByCRusGQ.js";
|
|
18
18
|
import { r as registerColbertExitHandlers } from "./lifecycle-9nX09dBl.js";
|
|
19
|
-
import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, m as extractCopilotUsage, u as recordZeroCostRequest } from "./aic-ledger-
|
|
19
|
+
import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, m as extractCopilotUsage, u as recordZeroCostRequest } from "./aic-ledger-Cp7Yk9-Q.js";
|
|
20
|
+
import { d as WORKIQ_READ_TOOLS, f as WORKIQ_RETRIEVAL_CONTENT_TYPE, i as ensureWorkiqToken, m as WORKIQ_WRITE_TOOLS, n as WorkiqAuthError, t as AUTH_REMEDY, u as WORKIQ_PROTOCOL_VERSION } from "./token-CVG0yI_j.js";
|
|
20
21
|
import { h as runGateChecks, m as sealedGateIds, p as resolveSealedGate } from "./stop-gate-hook-DnLC09Lg.js";
|
|
21
22
|
import { t as liveExec } from "./orchestration-D3-2ulhX.js";
|
|
22
23
|
import { createRequire } from "node:module";
|
|
@@ -18460,7 +18461,7 @@ const GPT56_EXPLICIT_CACHE_MODELS = /* @__PURE__ */ new Set([
|
|
|
18460
18461
|
"gpt-5.6-luna"
|
|
18461
18462
|
]);
|
|
18462
18463
|
const priorSignatures = /* @__PURE__ */ new Map();
|
|
18463
|
-
function nonNegativeInt(value) {
|
|
18464
|
+
function nonNegativeInt$1(value) {
|
|
18464
18465
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return 0;
|
|
18465
18466
|
return Math.floor(value);
|
|
18466
18467
|
}
|
|
@@ -18503,15 +18504,15 @@ function normalizeOpenAIUsage(usage) {
|
|
|
18503
18504
|
cacheWrite: 0,
|
|
18504
18505
|
totalTokens: 0
|
|
18505
18506
|
};
|
|
18506
|
-
const totalInput = nonNegativeInt(usage.input_tokens ?? usage.prompt_tokens);
|
|
18507
|
-
const output = nonNegativeInt(usage.output_tokens ?? usage.completion_tokens);
|
|
18507
|
+
const totalInput = nonNegativeInt$1(usage.input_tokens ?? usage.prompt_tokens);
|
|
18508
|
+
const output = nonNegativeInt$1(usage.output_tokens ?? usage.completion_tokens);
|
|
18508
18509
|
const details = usageDetails(usage);
|
|
18509
|
-
const cacheRead = Math.min(totalInput, nonNegativeInt(details.cached_tokens));
|
|
18510
|
+
const cacheRead = Math.min(totalInput, nonNegativeInt$1(details.cached_tokens));
|
|
18510
18511
|
const remaining = Math.max(0, totalInput - cacheRead);
|
|
18511
|
-
const cacheWrite = Math.min(remaining, nonNegativeInt(details.cache_write_tokens ?? details.cache_creation_tokens));
|
|
18512
|
+
const cacheWrite = Math.min(remaining, nonNegativeInt$1(details.cache_write_tokens ?? details.cache_creation_tokens));
|
|
18512
18513
|
const uncachedInput = Math.max(0, totalInput - cacheRead - cacheWrite);
|
|
18513
|
-
const reportedTotal = nonNegativeInt(usage.total_tokens);
|
|
18514
|
-
const cacheTtlSeconds = nonNegativeInt(details.cache_ttl_seconds);
|
|
18514
|
+
const reportedTotal = nonNegativeInt$1(usage.total_tokens);
|
|
18515
|
+
const cacheTtlSeconds = nonNegativeInt$1(details.cache_ttl_seconds);
|
|
18515
18516
|
return {
|
|
18516
18517
|
totalInput,
|
|
18517
18518
|
uncachedInput,
|
|
@@ -27831,6 +27832,18 @@ function kustoToolsEnabled() {
|
|
|
27831
27832
|
function cloudAgentToolsEnabled() {
|
|
27832
27833
|
return state.cloudAgentEnabled;
|
|
27833
27834
|
}
|
|
27835
|
+
/**
|
|
27836
|
+
* Gate for the Work IQ MCP group (`mcp__workiq__*`).
|
|
27837
|
+
*
|
|
27838
|
+
* Returns true iff `setupAndServe` resolved the group ON, exactly like
|
|
27839
|
+
* `adoToolsEnabled()`. The launch path is the only availability check there
|
|
27840
|
+
* is: `provisionWorkiqTools()` performs the `initialize` + `tools/list` round
|
|
27841
|
+
* trip and turns the group OFF when either fails, so a true here means a real
|
|
27842
|
+
* snapshot is waiting behind the tools this gate is hiding or showing.
|
|
27843
|
+
*/
|
|
27844
|
+
function workiqToolsEnabled() {
|
|
27845
|
+
return state.workiqEnabled;
|
|
27846
|
+
}
|
|
27834
27847
|
const ADO_TOKEN_RESOURCE = "2a72489c-aab2-4b65-b93a-a91edccf33b8";
|
|
27835
27848
|
const ADO_PROTOCOL_VERSION = "2025-06-18";
|
|
27836
27849
|
const ADO_TOKEN_ENV = "ADO_MCP_TOKEN";
|
|
@@ -28035,16 +28048,16 @@ var AdoMcpClient = class extends RemoteMcpClient {
|
|
|
28035
28048
|
* a broken one, and neither is worth the bytes.
|
|
28036
28049
|
*/
|
|
28037
28050
|
/** Bound on the launch-time `initialize` + `tools/list` round trip. */
|
|
28038
|
-
const PROVISION_TIMEOUT_MS = 2e4;
|
|
28051
|
+
const PROVISION_TIMEOUT_MS$1 = 2e4;
|
|
28039
28052
|
const ADO_GROUP = "ado";
|
|
28040
|
-
let client = null;
|
|
28041
|
-
let inflight = null;
|
|
28042
|
-
let snapshot = [];
|
|
28053
|
+
let client$1 = null;
|
|
28054
|
+
let inflight$1 = null;
|
|
28055
|
+
let snapshot$1 = [];
|
|
28043
28056
|
/** Close the upstream session. Best-effort; safe when nothing was created. */
|
|
28044
28057
|
async function disposeAdoClients() {
|
|
28045
|
-
const current = client;
|
|
28046
|
-
client = null;
|
|
28047
|
-
snapshot = [];
|
|
28058
|
+
const current = client$1;
|
|
28059
|
+
client$1 = null;
|
|
28060
|
+
snapshot$1 = [];
|
|
28048
28061
|
if (current) await current.dispose().catch(() => {});
|
|
28049
28062
|
}
|
|
28050
28063
|
/**
|
|
@@ -28059,8 +28072,8 @@ async function disposeAdoClients() {
|
|
|
28059
28072
|
* request-end abort cannot tear down a client other calls are using.
|
|
28060
28073
|
*/
|
|
28061
28074
|
async function ensureAdoClient(signal) {
|
|
28062
|
-
if (client) return client;
|
|
28063
|
-
const existing = inflight;
|
|
28075
|
+
if (client$1) return client$1;
|
|
28076
|
+
const existing = inflight$1;
|
|
28064
28077
|
if (existing) return existing;
|
|
28065
28078
|
const promise = (async () => {
|
|
28066
28079
|
const organization = state.adoOrganization;
|
|
@@ -28073,14 +28086,14 @@ async function ensureAdoClient(signal) {
|
|
|
28073
28086
|
token
|
|
28074
28087
|
});
|
|
28075
28088
|
await created.initialize(signal);
|
|
28076
|
-
client = created;
|
|
28089
|
+
client$1 = created;
|
|
28077
28090
|
return created;
|
|
28078
28091
|
})();
|
|
28079
|
-
inflight = promise;
|
|
28092
|
+
inflight$1 = promise;
|
|
28080
28093
|
try {
|
|
28081
28094
|
return await promise;
|
|
28082
28095
|
} finally {
|
|
28083
|
-
if (inflight === promise) inflight = null;
|
|
28096
|
+
if (inflight$1 === promise) inflight$1 = null;
|
|
28084
28097
|
}
|
|
28085
28098
|
}
|
|
28086
28099
|
/**
|
|
@@ -28099,16 +28112,16 @@ async function provisionAdoTools() {
|
|
|
28099
28112
|
reason: "ado group is not enabled"
|
|
28100
28113
|
};
|
|
28101
28114
|
const timer = new AbortController();
|
|
28102
|
-
const handle = setTimeout(() => timer.abort(/* @__PURE__ */ new Error("Azure DevOps MCP provisioning timed out")), PROVISION_TIMEOUT_MS);
|
|
28115
|
+
const handle = setTimeout(() => timer.abort(/* @__PURE__ */ new Error("Azure DevOps MCP provisioning timed out")), PROVISION_TIMEOUT_MS$1);
|
|
28103
28116
|
handle.unref?.();
|
|
28104
28117
|
try {
|
|
28105
28118
|
const created = await ensureAdoClient(timer.signal);
|
|
28106
28119
|
if (timer.signal.aborted) throw new Error("Azure DevOps MCP provisioning timed out");
|
|
28107
|
-
snapshot = buildAdoToolEntries(created.listAdoTools());
|
|
28108
|
-
if (snapshot.length === 0) throw new Error("Azure DevOps advertised no tools for the selected toolsets");
|
|
28120
|
+
snapshot$1 = buildAdoToolEntries(created.listAdoTools());
|
|
28121
|
+
if (snapshot$1.length === 0) throw new Error("Azure DevOps advertised no tools for the selected toolsets");
|
|
28109
28122
|
return {
|
|
28110
28123
|
ok: true,
|
|
28111
|
-
toolCount: snapshot.length
|
|
28124
|
+
toolCount: snapshot$1.length
|
|
28112
28125
|
};
|
|
28113
28126
|
} catch (err) {
|
|
28114
28127
|
const reason = sanitizeRemoteDetail(err);
|
|
@@ -28171,6 +28184,414 @@ function buildAdoToolEntries(tools) {
|
|
|
28171
28184
|
*/
|
|
28172
28185
|
function adoMcpToolEntries() {
|
|
28173
28186
|
if (!state.adoEnabled) return [];
|
|
28187
|
+
return snapshot$1;
|
|
28188
|
+
}
|
|
28189
|
+
//#endregion
|
|
28190
|
+
//#region src/lib/workiq/client.ts
|
|
28191
|
+
/**
|
|
28192
|
+
* Work IQ MCP client: a thin subclass of the shared streamable-HTTP transport
|
|
28193
|
+
* pointed at `https://workiq.svc.cloud.microsoft/mcp`.
|
|
28194
|
+
*
|
|
28195
|
+
* The live server is STATELESS — `initialize` returns protocol `2025-06-18`
|
|
28196
|
+
* and no `mcp-session-id` — which `RemoteMcpClient` already handles: it sends
|
|
28197
|
+
* the header only when one was assigned. No transport change is required.
|
|
28198
|
+
*
|
|
28199
|
+
* The one thing this client adds beyond the transport is result shaping.
|
|
28200
|
+
* `retrieve` puts its payload in
|
|
28201
|
+
* `structuredContent["application/vnd.ms-workiq.retrieval"]`. The documented
|
|
28202
|
+
* shape there is a `markdown` answer beside `retrievalHits`; the live server
|
|
28203
|
+
* (measured 2026-11) instead returns `results`, each hit carrying its own
|
|
28204
|
+
* `markdown` snippet and an `id` that a `[^id]` marker would refer to. Both
|
|
28205
|
+
* shapes are rendered as text, because the unstructured fallback is raw JSON
|
|
28206
|
+
* that overruns the relay cap. Failure arrives two ways — `isError: true`, or a
|
|
28207
|
+
* successful envelope whose `stoppedReason` is `error`/`cancelled` — and both
|
|
28208
|
+
* must throw rather than reach the model as if they were an answer.
|
|
28209
|
+
*/
|
|
28210
|
+
var WorkiqError = class extends RemoteMcpError {
|
|
28211
|
+
constructor(message, opts = {}) {
|
|
28212
|
+
super(message, opts);
|
|
28213
|
+
this.name = "WorkiqError";
|
|
28214
|
+
}
|
|
28215
|
+
};
|
|
28216
|
+
/** Upper bound on the sources block, so a hundred-hit answer cannot flood the model. */
|
|
28217
|
+
const MAX_SOURCES = 25;
|
|
28218
|
+
/**
|
|
28219
|
+
* Per-request deadline for a Work IQ call.
|
|
28220
|
+
*
|
|
28221
|
+
* The shared transport default is 30 s, which is right for a control-plane
|
|
28222
|
+
* server: `initialize`, `tools/list`, and ADO's lookups all finish well inside
|
|
28223
|
+
* it. `ask` and `retrieve` are not lookups. They run a model over the tenant's
|
|
28224
|
+
* indexed content and routinely take longer than 30 s, so the first live
|
|
28225
|
+
* retrieval was killed at 30.004 s before it could answer. Three minutes leaves
|
|
28226
|
+
* room for a slow tenant while still bounding a hung call; the model can retry.
|
|
28227
|
+
*/
|
|
28228
|
+
const WORKIQ_REQUEST_TIMEOUT_MS = 18e4;
|
|
28229
|
+
function asNumber(value) {
|
|
28230
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
28231
|
+
}
|
|
28232
|
+
function asString(value) {
|
|
28233
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
28234
|
+
}
|
|
28235
|
+
/**
|
|
28236
|
+
* The single nested object under `resourceMetadata`.
|
|
28237
|
+
*
|
|
28238
|
+
* The live payload keys that object by entity kind (`email`, `file`, ...) and
|
|
28239
|
+
* keeps the display fields one level down, so `resourceMetadata.email.subject`
|
|
28240
|
+
* is where an email hit's title actually lives.
|
|
28241
|
+
*/
|
|
28242
|
+
function resourceMetadata(hit) {
|
|
28243
|
+
const metadata = isRecord$4(hit.resourceMetadata) ? hit.resourceMetadata : void 0;
|
|
28244
|
+
if (!metadata) return void 0;
|
|
28245
|
+
for (const value of Object.values(metadata)) if (isRecord$4(value)) return value;
|
|
28246
|
+
}
|
|
28247
|
+
/**
|
|
28248
|
+
* A hit's display title, falling back through the fields the live payload
|
|
28249
|
+
* carries (`title`, `name`, `subject`) and finally its entity type.
|
|
28250
|
+
*/
|
|
28251
|
+
function hitTitle(hit, index) {
|
|
28252
|
+
const nested = resourceMetadata(hit);
|
|
28253
|
+
const title = asString(hit.title) ?? asString(hit.name) ?? asString(hit.subject) ?? asString(hit.displayName) ?? (nested ? asString(nested.title) ?? asString(nested.name) ?? asString(nested.subject) : void 0);
|
|
28254
|
+
const type = asString(hit.entityType) ?? asString(hit.type);
|
|
28255
|
+
if (title && type) return `${title} (${type})`;
|
|
28256
|
+
if (title) return title;
|
|
28257
|
+
if (type) return `(${type})`;
|
|
28258
|
+
return `Hit ${index + 1}`;
|
|
28259
|
+
}
|
|
28260
|
+
function hitUrl(hit) {
|
|
28261
|
+
return asString(hit.webUrl) ?? asString(hit.url) ?? asString(hit.link) ?? asString(hit.entityUrl) ?? asString(hit.path);
|
|
28262
|
+
}
|
|
28263
|
+
/** The compact citation list appended after retrieval markdown. */
|
|
28264
|
+
function formatWorkiqSources(hits) {
|
|
28265
|
+
const lines = [];
|
|
28266
|
+
for (const [index, raw] of hits.entries()) {
|
|
28267
|
+
if (lines.length >= MAX_SOURCES) break;
|
|
28268
|
+
if (!isRecord$4(raw)) continue;
|
|
28269
|
+
const url = hitUrl(raw);
|
|
28270
|
+
lines.push(`${index + 1}. ${hitTitle(raw, index)}${url ? ` — ${url}` : ""}`);
|
|
28271
|
+
}
|
|
28272
|
+
if (lines.length === 0) return "";
|
|
28273
|
+
return `\n\nSources${hits.length > lines.length ? ` (${hits.length - lines.length} more)` : ""}:\n${lines.join("\n")}`;
|
|
28274
|
+
}
|
|
28275
|
+
/** The per-hit body fields the live `retrieve` payload can carry. */
|
|
28276
|
+
function hitBody(hit) {
|
|
28277
|
+
return asString(hit.markdown) ?? asString(hit.text) ?? asString(hit.snippet) ?? asString(hit.summary) ?? asString(hit.content);
|
|
28278
|
+
}
|
|
28279
|
+
/**
|
|
28280
|
+
* Render `retrieval.results` as the grounding document.
|
|
28281
|
+
*
|
|
28282
|
+
* The documented retrieval shape puts the answer in a top-level `markdown`
|
|
28283
|
+
* beside a `retrievalHits` list. The live server (measured 2026-11) returns
|
|
28284
|
+
* neither: no `content` blocks, no top-level `markdown`, and the hits under
|
|
28285
|
+
* `results`, each carrying its own `markdown` snippet. Falling through to
|
|
28286
|
+
* `JSON.stringify` handed the model ~44 KB of raw JSON and dropped it at the
|
|
28287
|
+
* relay cap, so the snippets are laid out as numbered sections instead. The
|
|
28288
|
+
* hit's `id` (`h1`, `h2`, ...) is the label a `[^id]` marker refers to.
|
|
28289
|
+
*/
|
|
28290
|
+
function formatWorkiqResults(hits) {
|
|
28291
|
+
const sections = [];
|
|
28292
|
+
for (const [index, raw] of hits.entries()) {
|
|
28293
|
+
if (!isRecord$4(raw)) continue;
|
|
28294
|
+
const body = hitBody(raw);
|
|
28295
|
+
if (!body) continue;
|
|
28296
|
+
const id = asString(raw.id) ?? String(index + 1);
|
|
28297
|
+
const url = hitUrl(raw);
|
|
28298
|
+
const heading = `[${id}] ${hitTitle(raw, index)}${url ? `\n${url}` : ""}`;
|
|
28299
|
+
sections.push(`${heading}\n${body}`);
|
|
28300
|
+
}
|
|
28301
|
+
return sections.join("\n\n");
|
|
28302
|
+
}
|
|
28303
|
+
/**
|
|
28304
|
+
* Turn an MCP `tools/call` result into the single text block the `/mcp`
|
|
28305
|
+
* handler forwards.
|
|
28306
|
+
*
|
|
28307
|
+
* - A tool-level failure throws. The message keeps Entra/the service's own
|
|
28308
|
+
* text and its `recoveryAction` (when present) so the model sees what the
|
|
28309
|
+
* server said it should do.
|
|
28310
|
+
* - A `retrieve` answer renders the structured payload. A top-level `markdown`
|
|
28311
|
+
* wins when the server sends one, because the generic `content[].text` copy
|
|
28312
|
+
* of a large answer is what the service truncates first; otherwise the
|
|
28313
|
+
* per-hit snippets in `results` are laid out as numbered sections.
|
|
28314
|
+
* - Everything else falls back to joining the text blocks.
|
|
28315
|
+
*/
|
|
28316
|
+
function workiqResultText(result) {
|
|
28317
|
+
if (!isRecord$4(result)) throw new WorkiqError("Work IQ returned an empty result.", { retriable: true });
|
|
28318
|
+
const structured = isRecord$4(result.structuredContent) ? result.structuredContent : void 0;
|
|
28319
|
+
const retrievalRaw = structured?.[WORKIQ_RETRIEVAL_CONTENT_TYPE];
|
|
28320
|
+
const retrieval = isRecord$4(retrievalRaw) ? retrievalRaw : void 0;
|
|
28321
|
+
const stoppedReason = asString(retrieval?.stoppedReason);
|
|
28322
|
+
const upstreamError = asString(result.error) ?? asString(retrieval?.error);
|
|
28323
|
+
const recoveryAction = asString(retrieval?.recoveryAction);
|
|
28324
|
+
if (result.isError === true || stoppedReason === "error" || stoppedReason === "cancelled") {
|
|
28325
|
+
const texts = [];
|
|
28326
|
+
if (Array.isArray(result.content)) {
|
|
28327
|
+
for (const block of result.content) if (isRecord$4(block) && typeof block.text === "string" && block.text.trim()) texts.push(block.text.trim());
|
|
28328
|
+
}
|
|
28329
|
+
const detail = upstreamError ?? (texts.length > 0 ? texts.join("\n\n") : void 0);
|
|
28330
|
+
const parts = [`Work IQ reported an error${stoppedReason ? ` (${stoppedReason})` : ""}`];
|
|
28331
|
+
if (detail) parts.push(detail);
|
|
28332
|
+
if (recoveryAction) parts.push(`Suggested action: ${recoveryAction}`);
|
|
28333
|
+
if (parts.length === 1) parts.push("The service returned no further detail.");
|
|
28334
|
+
throw new WorkiqError(parts.join(": "), { retriable: false });
|
|
28335
|
+
}
|
|
28336
|
+
const resultHits = Array.isArray(retrieval?.results) ? retrieval.results : Array.isArray(retrieval?.retrievalHits) ? retrieval.retrievalHits : [];
|
|
28337
|
+
const citationHits = Array.isArray(retrieval?.retrievalHits) ? retrieval.retrievalHits : resultHits;
|
|
28338
|
+
const markdown = asString(retrieval?.markdown);
|
|
28339
|
+
if (markdown) return `${markdown.trim()}${formatWorkiqSources(citationHits)}`;
|
|
28340
|
+
const rendered = formatWorkiqResults(resultHits);
|
|
28341
|
+
if (rendered) return rendered;
|
|
28342
|
+
const sourcesOnly = formatWorkiqSources(citationHits);
|
|
28343
|
+
if (sourcesOnly) return sourcesOnly.trim();
|
|
28344
|
+
if (asNumber(retrieval?.resultCount) === 0) return "Work IQ found no results.";
|
|
28345
|
+
const texts = [];
|
|
28346
|
+
if (Array.isArray(result.content)) {
|
|
28347
|
+
for (const block of result.content) if (isRecord$4(block) && typeof block.text === "string" && block.text.trim()) texts.push(block.text);
|
|
28348
|
+
}
|
|
28349
|
+
const joined = texts.join("\n\n").trim();
|
|
28350
|
+
if (joined) return joined;
|
|
28351
|
+
if (structured) try {
|
|
28352
|
+
return JSON.stringify(structured);
|
|
28353
|
+
} catch {}
|
|
28354
|
+
return "Work IQ returned an empty result.";
|
|
28355
|
+
}
|
|
28356
|
+
var WorkiqMcpClient = class extends RemoteMcpClient {
|
|
28357
|
+
constructor(opts) {
|
|
28358
|
+
super({
|
|
28359
|
+
label: "Work IQ",
|
|
28360
|
+
baseUrl: opts.baseUrl ?? "https://workiq.svc.cloud.microsoft/mcp",
|
|
28361
|
+
protocolVersion: WORKIQ_PROTOCOL_VERSION,
|
|
28362
|
+
clientName: "github-router",
|
|
28363
|
+
clientVersion: "workiq",
|
|
28364
|
+
errorClass: WorkiqError,
|
|
28365
|
+
token: opts.token,
|
|
28366
|
+
requestTimeoutMs: WORKIQ_REQUEST_TIMEOUT_MS,
|
|
28367
|
+
tokenProvider: opts.tokenProvider ?? ((signal) => {
|
|
28368
|
+
consola.warn("Work IQ rejected the access token (401). Refreshing it; if this persists, run `github-router workiq auth`.");
|
|
28369
|
+
return ensureWorkiqToken({
|
|
28370
|
+
signal,
|
|
28371
|
+
forceRefresh: true
|
|
28372
|
+
});
|
|
28373
|
+
})
|
|
28374
|
+
});
|
|
28375
|
+
}
|
|
28376
|
+
/** The tools the server advertised, in the order it listed them. */
|
|
28377
|
+
listWorkiqTools() {
|
|
28378
|
+
return [...this.toolSchemas.values()].map((tool) => ({
|
|
28379
|
+
name: tool.name,
|
|
28380
|
+
description: tool.description ?? "",
|
|
28381
|
+
inputSchema: isRecord$4(tool.inputSchema) ? tool.inputSchema : {
|
|
28382
|
+
type: "object",
|
|
28383
|
+
properties: {}
|
|
28384
|
+
}
|
|
28385
|
+
}));
|
|
28386
|
+
}
|
|
28387
|
+
/** True iff the server advertised `name`. Guards a call the model invented. */
|
|
28388
|
+
hasTool(name) {
|
|
28389
|
+
return this.toolSchemas.has(name);
|
|
28390
|
+
}
|
|
28391
|
+
/** One `tools/call`, shaped through `workiqResultText`. */
|
|
28392
|
+
async callWorkiqTool(name, args, signal) {
|
|
28393
|
+
await this.initialize(signal);
|
|
28394
|
+
if (!this.hasTool(name)) throw new WorkiqError(`Work IQ does not advertise a tool named "${name}". Advertised tools: ${[...this.toolSchemas.keys()].sort().join(", ")}.`, { retriable: false });
|
|
28395
|
+
return { content: [{
|
|
28396
|
+
type: "text",
|
|
28397
|
+
text: workiqResultText(await this.callTool(name, args, signal))
|
|
28398
|
+
}] };
|
|
28399
|
+
}
|
|
28400
|
+
};
|
|
28401
|
+
//#endregion
|
|
28402
|
+
//#region src/lib/workiq-tools.ts
|
|
28403
|
+
/**
|
|
28404
|
+
* The `workiq` MCP group: Microsoft 365 research through the hosted Work IQ
|
|
28405
|
+
* service.
|
|
28406
|
+
*
|
|
28407
|
+
* Same dynamic-surface pattern as `./ado-tools`: the remote server owns the
|
|
28408
|
+
* tool set, so `tools/list` is forwarded from the upstream `tools/list`
|
|
28409
|
+
* instead of a frozen transcription that would drift silently. Two differences
|
|
28410
|
+
* are deliberate:
|
|
28411
|
+
*
|
|
28412
|
+
* - **Read-only is enforced HERE, not by a header.** The Work IQ server
|
|
28413
|
+
* advertises all twelve tools to every caller; its four mutating tools
|
|
28414
|
+
* (`create_entity`, `update_entity`, `delete_entity`, `do_action`) are
|
|
28415
|
+
* removed from the snapshot unless `--workiq-write` was passed. `call`-time
|
|
28416
|
+
* enforcement comes for free because a tool absent from the snapshot is
|
|
28417
|
+
* absent from `tools/call` too.
|
|
28418
|
+
* - **An unknown name is a signal.** The read allow-list is keyed to the
|
|
28419
|
+
* documented names, so a name outside both sets means the service shipped
|
|
28420
|
+
* something new. It is dropped with a warning that names `--workiq-write`,
|
|
28421
|
+
* which exposes whatever the live server actually advertises.
|
|
28422
|
+
* - **One name is renamed on the way out.** See {@link WORKIQ_TOOL_ALIASES}.
|
|
28423
|
+
*
|
|
28424
|
+
* The snapshot is taken ONCE at launch, awaited before the child process
|
|
28425
|
+
* starts, because the handler's tool accessor is synchronous. A failed
|
|
28426
|
+
* provision turns the group OFF with an actionable warning rather than leaving
|
|
28427
|
+
* an empty group advertised.
|
|
28428
|
+
*/
|
|
28429
|
+
/** Bound on the launch-time `initialize` + `tools/list` round trip. */
|
|
28430
|
+
const PROVISION_TIMEOUT_MS = 2e4;
|
|
28431
|
+
const WORKIQ_GROUP = "workiq";
|
|
28432
|
+
/**
|
|
28433
|
+
* Upstream name → MCP-facing name. Only the exposed name changes; the handler
|
|
28434
|
+
* keeps calling the wire name.
|
|
28435
|
+
*
|
|
28436
|
+
* `list_agents` is the one collision: the `cloudagent` group already serves a
|
|
28437
|
+
* tool by that name, and `proxyOwnedMcpToolNames()` reserves it whether or not
|
|
28438
|
+
* that group is enabled in this process. On the canonical Azure DevOps setup,
|
|
28439
|
+
* where cloudagent auto-enables, an unrenamed `list_agents` would silently drop
|
|
28440
|
+
* one of the eight read tools on every launch. Renaming on the way out is the
|
|
28441
|
+
* same decoupling the browser tools use, and it is safe because dispatch keys
|
|
28442
|
+
* on `group`, not on the upstream name.
|
|
28443
|
+
*/
|
|
28444
|
+
const WORKIQ_TOOL_ALIASES = /* @__PURE__ */ new Map([["list_agents", "agents"]]);
|
|
28445
|
+
let client = null;
|
|
28446
|
+
let inflight = null;
|
|
28447
|
+
let snapshot = [];
|
|
28448
|
+
/** Close the upstream session. Best-effort; safe when nothing was created. */
|
|
28449
|
+
async function disposeWorkiqClients() {
|
|
28450
|
+
const current = client;
|
|
28451
|
+
client = null;
|
|
28452
|
+
snapshot = [];
|
|
28453
|
+
if (current) await current.dispose().catch(() => {});
|
|
28454
|
+
}
|
|
28455
|
+
/**
|
|
28456
|
+
* The one process-lifetime Work IQ client. Single-flight, like `ensureAdoClient`,
|
|
28457
|
+
* for the same reason: concurrent first calls must not each start an
|
|
28458
|
+
* `initialize` handshake (and, worse, each trigger a token refresh, which
|
|
28459
|
+
* ROTATES the refresh token).
|
|
28460
|
+
*
|
|
28461
|
+
* `signal` bounds construction only. Once the client is memoized every later
|
|
28462
|
+
* caller returns immediately, so a request-end abort cannot tear down a client
|
|
28463
|
+
* other calls are using.
|
|
28464
|
+
*/
|
|
28465
|
+
async function ensureWorkiqClient(signal) {
|
|
28466
|
+
if (client) return client;
|
|
28467
|
+
const existing = inflight;
|
|
28468
|
+
if (existing) return existing;
|
|
28469
|
+
const promise = (async () => {
|
|
28470
|
+
const created = new WorkiqMcpClient({ token: await ensureWorkiqToken({ ...signal ? { signal } : {} }) });
|
|
28471
|
+
await created.initialize(signal);
|
|
28472
|
+
client = created;
|
|
28473
|
+
return created;
|
|
28474
|
+
})();
|
|
28475
|
+
inflight = promise;
|
|
28476
|
+
try {
|
|
28477
|
+
return await promise;
|
|
28478
|
+
} finally {
|
|
28479
|
+
if (inflight === promise) inflight = null;
|
|
28480
|
+
}
|
|
28481
|
+
}
|
|
28482
|
+
/** The remedy a failed provision should print, or undefined for a network error. */
|
|
28483
|
+
function remedyFor(err) {
|
|
28484
|
+
if (err instanceof WorkiqAuthError) return err.remedy;
|
|
28485
|
+
const detail = sanitizeRemoteDetail(err);
|
|
28486
|
+
return /401|403|unauthori[sz]ed|forbidden|token/i.test(detail) ? AUTH_REMEDY : void 0;
|
|
28487
|
+
}
|
|
28488
|
+
/**
|
|
28489
|
+
* Fold the remedy into the message a TOOL CALL surfaces.
|
|
28490
|
+
*
|
|
28491
|
+
* The MCP boundary forwards only `err.message` to the model, so a
|
|
28492
|
+
* `WorkiqAuthError` whose `remedy` stays a separate property reaches the caller
|
|
28493
|
+
* as "No Work IQ login found at <path>." with nothing to act on. Provisioning
|
|
28494
|
+
* prints the remedy itself; the call path has to put it in the message.
|
|
28495
|
+
*/
|
|
28496
|
+
function withCallTimeRemedy(err) {
|
|
28497
|
+
if (!(err instanceof Error)) return err;
|
|
28498
|
+
const remedy = remedyFor(err);
|
|
28499
|
+
if (!remedy || err.message.includes(remedy)) return err;
|
|
28500
|
+
const surfaced = new Error(`${err.message} ${remedy}`, { cause: err });
|
|
28501
|
+
surfaced.name = err.name;
|
|
28502
|
+
return surfaced;
|
|
28503
|
+
}
|
|
28504
|
+
/**
|
|
28505
|
+
* Resolve the Work IQ tool surface and snapshot it for this process.
|
|
28506
|
+
*
|
|
28507
|
+
* Called from `setupAndServe` before the child spawns. Never throws: the launch
|
|
28508
|
+
* is not the right place to fail over a network or consent dependency. On
|
|
28509
|
+
* failure the group is turned OFF, because a `workiq` server that advertises no
|
|
28510
|
+
* tools is worse than an absent one.
|
|
28511
|
+
*/
|
|
28512
|
+
async function provisionWorkiqTools() {
|
|
28513
|
+
if (!state.workiqEnabled) return {
|
|
28514
|
+
ok: false,
|
|
28515
|
+
reason: "workiq group is not enabled"
|
|
28516
|
+
};
|
|
28517
|
+
const timer = new AbortController();
|
|
28518
|
+
const handle = setTimeout(() => timer.abort(/* @__PURE__ */ new Error("Work IQ MCP provisioning timed out")), PROVISION_TIMEOUT_MS);
|
|
28519
|
+
handle.unref?.();
|
|
28520
|
+
try {
|
|
28521
|
+
const created = await ensureWorkiqClient(timer.signal);
|
|
28522
|
+
if (timer.signal.aborted) throw new Error("Work IQ MCP provisioning timed out");
|
|
28523
|
+
snapshot = buildWorkiqToolEntries(created.listWorkiqTools(), { write: state.workiqWriteEnabled });
|
|
28524
|
+
if (snapshot.length === 0) throw new Error("Work IQ advertised no usable tools");
|
|
28525
|
+
return {
|
|
28526
|
+
ok: true,
|
|
28527
|
+
toolCount: snapshot.length
|
|
28528
|
+
};
|
|
28529
|
+
} catch (err) {
|
|
28530
|
+
const reason = sanitizeRemoteDetail(err);
|
|
28531
|
+
state.workiqEnabled = false;
|
|
28532
|
+
await disposeWorkiqClients();
|
|
28533
|
+
const remedy = remedyFor(err);
|
|
28534
|
+
consola.warn(`Work IQ MCP group disabled: ${reason}` + (remedy ? ` ${remedy}` : " Check the network path to workiq.svc.cloud.microsoft, then relaunch."));
|
|
28535
|
+
return {
|
|
28536
|
+
ok: false,
|
|
28537
|
+
reason
|
|
28538
|
+
};
|
|
28539
|
+
} finally {
|
|
28540
|
+
clearTimeout(handle);
|
|
28541
|
+
}
|
|
28542
|
+
}
|
|
28543
|
+
/**
|
|
28544
|
+
* Map the upstream descriptors onto the proxy's non-persona tool shape.
|
|
28545
|
+
*
|
|
28546
|
+
* Exported for tests, which feed recorded fixtures through it to pin the
|
|
28547
|
+
* read-only filter, the unknown-name warning, and the collision behaviour
|
|
28548
|
+
* without a live endpoint.
|
|
28549
|
+
*/
|
|
28550
|
+
function buildWorkiqToolEntries(tools, opts) {
|
|
28551
|
+
const proxyOwned = proxyOwnedMcpToolNames();
|
|
28552
|
+
const seen = /* @__PURE__ */ new Set();
|
|
28553
|
+
const entries = [];
|
|
28554
|
+
for (const tool of tools) {
|
|
28555
|
+
const wireName = tool.name?.trim();
|
|
28556
|
+
if (!wireName) continue;
|
|
28557
|
+
if (!opts.write && !WORKIQ_READ_TOOLS.has(wireName)) {
|
|
28558
|
+
if (!WORKIQ_WRITE_TOOLS.has(wireName)) consola.warn(`Work IQ tool "${wireName}" was dropped because it is not on the read-only allow-list. Relaunch with --workiq-write to expose the full live surface.`);
|
|
28559
|
+
continue;
|
|
28560
|
+
}
|
|
28561
|
+
const exposedName = WORKIQ_TOOL_ALIASES.get(wireName) ?? wireName;
|
|
28562
|
+
if (proxyOwned.has(exposedName)) {
|
|
28563
|
+
consola.warn(`Work IQ tool "${wireName}"${exposedName === wireName ? "" : ` (exposed as "${exposedName}")`} was dropped: the proxy already serves a tool by that name.`);
|
|
28564
|
+
continue;
|
|
28565
|
+
}
|
|
28566
|
+
if (seen.has(exposedName)) continue;
|
|
28567
|
+
seen.add(exposedName);
|
|
28568
|
+
entries.push({
|
|
28569
|
+
toolNameHttp: exposedName,
|
|
28570
|
+
group: WORKIQ_GROUP,
|
|
28571
|
+
capability: "workiq",
|
|
28572
|
+
description: tool.description || `Work IQ tool ${wireName}.`,
|
|
28573
|
+
inputSchema: tool.inputSchema,
|
|
28574
|
+
async handler(args, signal) {
|
|
28575
|
+
try {
|
|
28576
|
+
return { content: [{
|
|
28577
|
+
type: "text",
|
|
28578
|
+
text: await relaySafeText((await (await ensureWorkiqClient(signal)).callWorkiqTool(wireName, args, signal)).content.map((block) => block.text).join(""))
|
|
28579
|
+
}] };
|
|
28580
|
+
} catch (err) {
|
|
28581
|
+
if (signal?.aborted) throw err;
|
|
28582
|
+
throw withCallTimeRemedy(err);
|
|
28583
|
+
}
|
|
28584
|
+
}
|
|
28585
|
+
});
|
|
28586
|
+
}
|
|
28587
|
+
return entries;
|
|
28588
|
+
}
|
|
28589
|
+
/**
|
|
28590
|
+
* The Work IQ tools for THIS process, or an empty array when the group is off
|
|
28591
|
+
* or its snapshot never landed.
|
|
28592
|
+
*/
|
|
28593
|
+
function workiqMcpToolEntries() {
|
|
28594
|
+
if (!state.workiqEnabled) return [];
|
|
28174
28595
|
return snapshot;
|
|
28175
28596
|
}
|
|
28176
28597
|
//#endregion
|
|
@@ -28322,9 +28743,14 @@ function checkAuth(c) {
|
|
|
28322
28743
|
* which is every launch unless `--ado` resolved on.
|
|
28323
28744
|
*/
|
|
28324
28745
|
function allNonPersonaTools() {
|
|
28325
|
-
const
|
|
28326
|
-
|
|
28327
|
-
return
|
|
28746
|
+
const ado = adoMcpToolEntries();
|
|
28747
|
+
const workiq = workiqMcpToolEntries();
|
|
28748
|
+
if (ado.length === 0 && workiq.length === 0) return NON_PERSONA_MCP_TOOLS;
|
|
28749
|
+
return [
|
|
28750
|
+
...NON_PERSONA_MCP_TOOLS,
|
|
28751
|
+
...ado,
|
|
28752
|
+
...workiq
|
|
28753
|
+
];
|
|
28328
28754
|
}
|
|
28329
28755
|
/**
|
|
28330
28756
|
* The LIST surface only: `allNonPersonaTools()` minus hook-channel tools.
|
|
@@ -28507,6 +28933,7 @@ function maxToolIsEnabled(tool) {
|
|
|
28507
28933
|
if (tool.capability === "artifact") return artifactToolsEnabled();
|
|
28508
28934
|
if (tool.group === "ado") return adoToolsEnabled();
|
|
28509
28935
|
if (tool.group === "kusto") return kustoToolsEnabled();
|
|
28936
|
+
if (tool.group === "workiq") return workiqToolsEnabled();
|
|
28510
28937
|
if (tool.capability === "cloudagent" || tool.capability === "cloudagent_write") return cloudAgentToolsEnabled();
|
|
28511
28938
|
return true;
|
|
28512
28939
|
}
|
|
@@ -28533,6 +28960,7 @@ function fastToolIsEnabled(tool) {
|
|
|
28533
28960
|
if (tool.group === "workers") return tool.toolNameHttp === "browse" && tool.capability === "browse_agent" && browseAgentEnabled();
|
|
28534
28961
|
if (tool.group === "ado") return adoToolsEnabled();
|
|
28535
28962
|
if (tool.group === "kusto") return kustoToolsEnabled();
|
|
28963
|
+
if (tool.group === "workiq") return workiqToolsEnabled();
|
|
28536
28964
|
if (tool.capability === "cloudagent" || tool.capability === "cloudagent_write") return cloudAgentToolsEnabled();
|
|
28537
28965
|
if (tool.group !== "browser") return false;
|
|
28538
28966
|
if (!browserToolsEnabled()) return false;
|
|
@@ -28661,6 +29089,7 @@ function toolEntries(scope, launch, audience = "shared") {
|
|
|
28661
29089
|
if (t.capability === "artifact") return artifactToolsEnabled();
|
|
28662
29090
|
if (t.capability === "ado") return adoToolsEnabled();
|
|
28663
29091
|
if (t.capability === "kusto") return kustoToolsEnabled();
|
|
29092
|
+
if (t.capability === "workiq") return workiqToolsEnabled();
|
|
28664
29093
|
if (t.capability === "cloudagent" || t.capability === "cloudagent_write") return cloudAgentToolsEnabled();
|
|
28665
29094
|
if (t.capability === "browser_compound") return browserToolsEnabled() && browserCompoundToolsEnabled();
|
|
28666
29095
|
if (t.capability === "browser_power") return browserToolsEnabled() && browserPowerToolsEnabled();
|
|
@@ -29251,6 +29680,7 @@ async function handleToolsCall(body, scope, launch, audience = "shared", session
|
|
|
29251
29680
|
if (nonPersonaTool && nonPersonaTool.capability === "browser_power" && !(browserToolsEnabled() && browserPowerToolsEnabled())) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
|
|
29252
29681
|
if (nonPersonaTool && nonPersonaTool.capability === "ado" && !adoToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
|
|
29253
29682
|
if (nonPersonaTool && nonPersonaTool.capability === "kusto" && !kustoToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
|
|
29683
|
+
if (nonPersonaTool && nonPersonaTool.capability === "workiq" && !workiqToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
|
|
29254
29684
|
if (nonPersonaTool && (nonPersonaTool.capability === "cloudagent" || nonPersonaTool.capability === "cloudagent_write") && !cloudAgentToolsEnabled()) return rpcError(body.id, RPC_METHOD_NOT_FOUND, `tools/call: unknown tool "${name}"`);
|
|
29255
29685
|
let personaPrompt;
|
|
29256
29686
|
let personaContext;
|
|
@@ -29639,6 +30069,257 @@ function handleMcpDelete(c) {
|
|
|
29639
30069
|
return c.body(null, 200);
|
|
29640
30070
|
}
|
|
29641
30071
|
//#endregion
|
|
30072
|
+
//#region src/lib/anthropic-usage.ts
|
|
30073
|
+
const ENCODER$2 = new TextEncoder();
|
|
30074
|
+
const DECODER = new TextDecoder();
|
|
30075
|
+
/** The usage fields this module reasons about, in log order. */
|
|
30076
|
+
const USAGE_KEYS = [
|
|
30077
|
+
"input_tokens",
|
|
30078
|
+
"cache_creation_input_tokens",
|
|
30079
|
+
"cache_read_input_tokens",
|
|
30080
|
+
"output_tokens"
|
|
30081
|
+
];
|
|
30082
|
+
/**
|
|
30083
|
+
* Cap on a single un-terminated SSE record held in the transform buffer.
|
|
30084
|
+
* A record that grows past this is emitted verbatim rather than buffered
|
|
30085
|
+
* forever, so a pathological upstream event is passed through instead of
|
|
30086
|
+
* being truncated or held in memory.
|
|
30087
|
+
*/
|
|
30088
|
+
const MAX_PENDING_RECORD_BYTES = 1 << 20;
|
|
30089
|
+
function nonNegativeInt(value) {
|
|
30090
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return 0;
|
|
30091
|
+
return Math.floor(value);
|
|
30092
|
+
}
|
|
30093
|
+
/**
|
|
30094
|
+
* True when the operator has opted out of the Anthropic usage rewrite.
|
|
30095
|
+
*
|
|
30096
|
+
* The rewrite targets an upstream that reports `input_tokens` as the TOTAL
|
|
30097
|
+
* prompt with the cached prefix as a DETAIL of that total (OpenAI semantics)
|
|
30098
|
+
* rather than as the uncached remainder (the Anthropic contract). BOTH shapes
|
|
30099
|
+
* have been measured in real traffic through this proxy: session `ec65e3f9`
|
|
30100
|
+
* was inclusive on the native Copilot path, the same path captured exclusive
|
|
30101
|
+
* on 2026-11-05, and the local endpoint of session `a1ab11a5` was inclusive.
|
|
30102
|
+
* An operator pointing `--localurl` at an upstream whose shape the
|
|
30103
|
+
* `input < cached` guard cannot discriminate can disable the rewrite here.
|
|
30104
|
+
*/
|
|
30105
|
+
function anthropicUsageNormalizeDisabled() {
|
|
30106
|
+
return parseBoolEnv(process.env.GH_ROUTER_DISABLE_ANTHROPIC_USAGE_NORMALIZE) === true;
|
|
30107
|
+
}
|
|
30108
|
+
/**
|
|
30109
|
+
* Rewrite an Anthropic-shaped `usage` object so its three input buckets are
|
|
30110
|
+
* mutually exclusive, which is what Anthropic clients (and Claude Code's
|
|
30111
|
+
* context meter) sum.
|
|
30112
|
+
*
|
|
30113
|
+
* The problem this fixes: some upstreams report `input_tokens` INCLUSIVE of
|
|
30114
|
+
* `cache_read_input_tokens` — OpenAI semantics inside an Anthropic-shaped
|
|
30115
|
+
* usage object. Claude Code computes context size as `input_tokens +
|
|
30116
|
+
* cache_creation_input_tokens + cache_read_input_tokens + output_tokens`, so
|
|
30117
|
+
* forwarding the inclusive figure counts the cached prefix twice. Measured on
|
|
30118
|
+
* a warm turn in session `ec65e3f9` (native Copilot path): turn 1 `55931/0`
|
|
30119
|
+
* followed by turn 2 `56423/55808` across an exchange whose entire new
|
|
30120
|
+
* payload was under 2 KB. Under the exclusive reading that turn would have
|
|
30121
|
+
* added ~56,300 tokens; inclusive predicts +492, which is what happened. The
|
|
30122
|
+
* local egress is inclusive too: a 2026-11-05 capture of `-m local` showed a
|
|
30123
|
+
* warm `message_delta` of `input_tokens=45620 cache_read_input_tokens=45440`,
|
|
30124
|
+
* and the client meter read 91,060 for a 45,620-token prompt. The doubled
|
|
30125
|
+
* meter halves the effective context window and makes autocompact thrash on
|
|
30126
|
+
* sessions with a large static prefix.
|
|
30127
|
+
*
|
|
30128
|
+
* NOT every upstream is inclusive, and the Copilot path is not guaranteed to
|
|
30129
|
+
* be: an advisor-off capture of it on 2026-11-05 reported `message_start
|
|
30130
|
+
* input_tokens=2 cache_creation_input_tokens=66941`, which only the exclusive
|
|
30131
|
+
* reading explains. Every capture so far delivered `input_tokens` and the
|
|
30132
|
+
* cache buckets on the SAME SSE record, so the guard below is what
|
|
30133
|
+
* discriminates the two shapes rather than across-frame reassembly.
|
|
30134
|
+
*
|
|
30135
|
+
* The math mirrors `normalizeOpenAIUsage` in `~/lib/prompt-cache`:
|
|
30136
|
+
* `uncached = total - cacheRead - cacheWrite`.
|
|
30137
|
+
*
|
|
30138
|
+
* The guard is what lets this run unconditionally. An exclusive (conformant)
|
|
30139
|
+
* upstream reports the uncached remainder as `input_tokens`, which on a warm
|
|
30140
|
+
* turn is SMALLER than the cached prefix — a shape that is impossible under
|
|
30141
|
+
* inclusive semantics. Such a response is left byte-for-byte alone. A cold
|
|
30142
|
+
* turn reports no cache at all, where both conventions agree, so it is a
|
|
30143
|
+
* no-op too.
|
|
30144
|
+
*
|
|
30145
|
+
* Residual ambiguity: an exclusive upstream whose uncached remainder exceeds
|
|
30146
|
+
* its cached prefix (`input >= cached`) is misread as inclusive and
|
|
30147
|
+
* under-reported by the cached total. That takes a single turn adding more
|
|
30148
|
+
* new tokens than the whole cached prefix, and it applies to EITHER egress,
|
|
30149
|
+
* since the native Copilot path has been measured exclusive. The error
|
|
30150
|
+
* direction is the safe one: the meter under-reads, so the client compacts
|
|
30151
|
+
* later rather than earlier.
|
|
30152
|
+
* `GH_ROUTER_DISABLE_ANTHROPIC_USAGE_NORMALIZE` exists for an upstream whose
|
|
30153
|
+
* shape the guard cannot discriminate.
|
|
30154
|
+
*
|
|
30155
|
+
* CALL ONCE PER USAGE OBJECT. The rewrite is not idempotent: a second pass
|
|
30156
|
+
* over an already-corrected object subtracts the cache buckets again whenever
|
|
30157
|
+
* the remainder is at least the cached total. Every caller applies it exactly
|
|
30158
|
+
* once — one call per SSE record, one call per non-streaming response, and a
|
|
30159
|
+
* freshly built map per advisor `message_delta`.
|
|
30160
|
+
*
|
|
30161
|
+
* Never throws. Returns true iff `usage.input_tokens` was rewritten.
|
|
30162
|
+
*/
|
|
30163
|
+
function normalizeAnthropicUsageInPlace(usage) {
|
|
30164
|
+
if (!usage || typeof usage !== "object" || Array.isArray(usage)) return false;
|
|
30165
|
+
const record = usage;
|
|
30166
|
+
const input = nonNegativeInt(record.input_tokens);
|
|
30167
|
+
const cached = nonNegativeInt(record.cache_read_input_tokens) + nonNegativeInt(record.cache_creation_input_tokens);
|
|
30168
|
+
if (cached <= 0) return false;
|
|
30169
|
+
if (input < cached) return false;
|
|
30170
|
+
const next = Math.max(0, input - cached);
|
|
30171
|
+
if (next === record.input_tokens) return false;
|
|
30172
|
+
record.input_tokens = next;
|
|
30173
|
+
return true;
|
|
30174
|
+
}
|
|
30175
|
+
/**
|
|
30176
|
+
* Length of the SSE record terminator beginning at `index` (a `\n`), or 0 if
|
|
30177
|
+
* no blank-line terminator starts there. Handles both `\n\n` and `\r\n\r\n`.
|
|
30178
|
+
*/
|
|
30179
|
+
function terminatorLengthAt(buffer, index) {
|
|
30180
|
+
if (buffer[index + 1] === 10) return 2;
|
|
30181
|
+
if (buffer[index + 1] === 13 && buffer[index + 2] === 10) return 3;
|
|
30182
|
+
return 0;
|
|
30183
|
+
}
|
|
30184
|
+
/** First complete SSE record terminator in `buffer`, if any. */
|
|
30185
|
+
function findRecordTerminator(buffer) {
|
|
30186
|
+
for (let index = 0; index < buffer.byteLength - 1; index++) {
|
|
30187
|
+
if (buffer[index] !== 10) continue;
|
|
30188
|
+
const length = terminatorLengthAt(buffer, index);
|
|
30189
|
+
if (length > 0 && index + length <= buffer.byteLength) return {
|
|
30190
|
+
index,
|
|
30191
|
+
length
|
|
30192
|
+
};
|
|
30193
|
+
}
|
|
30194
|
+
}
|
|
30195
|
+
/**
|
|
30196
|
+
* Opt-in wire diagnostic (`GH_ROUTER_LOG_ANTHROPIC_USAGE_FRAMES=1`), matching
|
|
30197
|
+
* the `GH_ROUTER_LOG_FIELDS` / `GH_ROUTER_LOG_CACHE` convention.
|
|
30198
|
+
*
|
|
30199
|
+
* The rewrite rests on an upstream wire detail Copilot does not version:
|
|
30200
|
+
* whether `input_tokens` and the cache buckets arrive on the SAME SSE record.
|
|
30201
|
+
* Only a record carrying both is rewritten, so a split shape would silently
|
|
30202
|
+
* turn the rewrite into a no-op — and no unit test can observe the real
|
|
30203
|
+
* upstream shape. Logs one line per `message_start` / `message_delta` with
|
|
30204
|
+
* numeric usage fields only: no prompt text, no payloads, no identifiers.
|
|
30205
|
+
*
|
|
30206
|
+
* Called BEFORE normalization, so the values are exactly what upstream sent.
|
|
30207
|
+
* Writes to stderr directly (the `GH_ROUTER_LOG_PEER_MCP` pattern) so it is
|
|
30208
|
+
* visible regardless of consola level and can never interleave with a
|
|
30209
|
+
* JSONL-speaking client's stdout.
|
|
30210
|
+
*
|
|
30211
|
+
* Both egresses captured on 2026-11-05 (native Copilot, and `-m local` against
|
|
30212
|
+
* an LM Studio-backed gateway) delivered `input_tokens` and the cache buckets
|
|
30213
|
+
* on the same `message_delta` record, which is why the transform needs no
|
|
30214
|
+
* across-frame state. That is an unversioned upstream detail: if it ever
|
|
30215
|
+
* splits, the rewrite becomes a silent no-op and these lines are the only
|
|
30216
|
+
* signal, so the flag stays in the product rather than in a one-off script.
|
|
30217
|
+
*
|
|
30218
|
+
* It runs inside the rewrite transform, so it is silent when
|
|
30219
|
+
* `GH_ROUTER_DISABLE_ANTHROPIC_USAGE_NORMALIZE` is set — that path installs no
|
|
30220
|
+
* transform at all.
|
|
30221
|
+
*/
|
|
30222
|
+
function logUsageFrame(eventType, usage) {
|
|
30223
|
+
if (process.env.GH_ROUTER_LOG_ANTHROPIC_USAGE_FRAMES !== "1") return;
|
|
30224
|
+
if (!usage || typeof usage !== "object" || Array.isArray(usage)) {
|
|
30225
|
+
process.stderr.write(`[anthropic-usage] ${eventType} usage=absent\n`);
|
|
30226
|
+
return;
|
|
30227
|
+
}
|
|
30228
|
+
const record = usage;
|
|
30229
|
+
const fields = USAGE_KEYS.map((key) => {
|
|
30230
|
+
const value = record[key];
|
|
30231
|
+
return `${key}=${typeof value === "number" ? value : "absent"}`;
|
|
30232
|
+
});
|
|
30233
|
+
process.stderr.write(`[anthropic-usage] ${eventType} ${fields.join(" ")}\n`);
|
|
30234
|
+
}
|
|
30235
|
+
/**
|
|
30236
|
+
* Rewrite one complete SSE record if it carries usage. Records that need no
|
|
30237
|
+
* correction — every event type other than `message_start` / `message_delta`,
|
|
30238
|
+
* unparseable payloads, and already-disjoint usage — are returned as the
|
|
30239
|
+
* exact bytes they arrived as.
|
|
30240
|
+
*/
|
|
30241
|
+
function rewriteRecord(record) {
|
|
30242
|
+
const text = DECODER.decode(record);
|
|
30243
|
+
const dataMatch = /(?:^|\n)data:/.exec(text);
|
|
30244
|
+
if (!dataMatch) return record;
|
|
30245
|
+
const dataStart = dataMatch.index + (dataMatch[0].length - 5);
|
|
30246
|
+
const dataLines = [];
|
|
30247
|
+
for (const line of text.slice(dataStart).split("\n")) {
|
|
30248
|
+
if (!line.startsWith("data:")) break;
|
|
30249
|
+
dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
30250
|
+
}
|
|
30251
|
+
if (dataLines.length === 0) return record;
|
|
30252
|
+
let payload;
|
|
30253
|
+
try {
|
|
30254
|
+
payload = JSON.parse(dataLines.join("\n"));
|
|
30255
|
+
} catch {
|
|
30256
|
+
return record;
|
|
30257
|
+
}
|
|
30258
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return record;
|
|
30259
|
+
const event = payload;
|
|
30260
|
+
let changed = false;
|
|
30261
|
+
if (event.type === "message_start") {
|
|
30262
|
+
const message = event.message;
|
|
30263
|
+
if (message && typeof message === "object" && !Array.isArray(message)) {
|
|
30264
|
+
const usage = message.usage;
|
|
30265
|
+
logUsageFrame("message_start", usage);
|
|
30266
|
+
changed = normalizeAnthropicUsageInPlace(usage) || changed;
|
|
30267
|
+
}
|
|
30268
|
+
} else if (event.type === "message_delta") {
|
|
30269
|
+
logUsageFrame("message_delta", event.usage);
|
|
30270
|
+
changed = normalizeAnthropicUsageInPlace(event.usage) || changed;
|
|
30271
|
+
}
|
|
30272
|
+
if (!changed) return record;
|
|
30273
|
+
const prefix = text.slice(0, dataStart);
|
|
30274
|
+
return ENCODER$2.encode(`${prefix}data: ${JSON.stringify(event)}\n\n`);
|
|
30275
|
+
}
|
|
30276
|
+
function concat(left, right) {
|
|
30277
|
+
if (left.byteLength === 0) return right;
|
|
30278
|
+
if (right.byteLength === 0) return left;
|
|
30279
|
+
const out = new Uint8Array(left.byteLength + right.byteLength);
|
|
30280
|
+
out.set(left, 0);
|
|
30281
|
+
out.set(right, left.byteLength);
|
|
30282
|
+
return out;
|
|
30283
|
+
}
|
|
30284
|
+
/**
|
|
30285
|
+
* Streaming counterpart of `normalizeAnthropicUsageInPlace`, shaped for
|
|
30286
|
+
* `relayAnthropicStream`'s `transform` hook.
|
|
30287
|
+
*
|
|
30288
|
+
* Buffers across arbitrary chunk boundaries and only ever emits COMPLETE SSE
|
|
30289
|
+
* records, so an event split mid-record is never corrupted. `flush()` releases
|
|
30290
|
+
* a trailing partial record at upstream EOF; a stream that ends without its
|
|
30291
|
+
* terminator must not lose bytes.
|
|
30292
|
+
*/
|
|
30293
|
+
function createAnthropicUsageRewriteTransform() {
|
|
30294
|
+
let pending = /* @__PURE__ */ new Uint8Array(0);
|
|
30295
|
+
return {
|
|
30296
|
+
push(bytes) {
|
|
30297
|
+
pending = concat(pending, bytes);
|
|
30298
|
+
let emitted;
|
|
30299
|
+
for (;;) {
|
|
30300
|
+
const terminator = findRecordTerminator(pending);
|
|
30301
|
+
if (!terminator) break;
|
|
30302
|
+
const end = terminator.index + terminator.length;
|
|
30303
|
+
const record = pending.subarray(0, end);
|
|
30304
|
+
pending = pending.subarray(end);
|
|
30305
|
+
const rewritten = rewriteRecord(record);
|
|
30306
|
+
emitted = emitted ? concat(emitted, rewritten) : rewritten;
|
|
30307
|
+
}
|
|
30308
|
+
if (pending.byteLength > MAX_PENDING_RECORD_BYTES) {
|
|
30309
|
+
emitted = emitted ? concat(emitted, pending) : pending;
|
|
30310
|
+
pending = /* @__PURE__ */ new Uint8Array(0);
|
|
30311
|
+
}
|
|
30312
|
+
return emitted;
|
|
30313
|
+
},
|
|
30314
|
+
flush() {
|
|
30315
|
+
if (pending.byteLength === 0) return void 0;
|
|
30316
|
+
const tail = pending;
|
|
30317
|
+
pending = /* @__PURE__ */ new Uint8Array(0);
|
|
30318
|
+
return tail;
|
|
30319
|
+
}
|
|
30320
|
+
};
|
|
30321
|
+
}
|
|
30322
|
+
//#endregion
|
|
29642
30323
|
//#region src/lib/reasoning-effort.ts
|
|
29643
30324
|
/**
|
|
29644
30325
|
* Reasoning-effort bucketing + clamping shared by the `/v1/messages` handler
|
|
@@ -29733,6 +30414,15 @@ function clampEffort(bucketed, supported) {
|
|
|
29733
30414
|
//#endregion
|
|
29734
30415
|
//#region src/lib/stream-relay.ts
|
|
29735
30416
|
const ENCODER$1 = new TextEncoder();
|
|
30417
|
+
/** Concatenate two byte runs, preserving order (left first). */
|
|
30418
|
+
function concatBytes(left, right) {
|
|
30419
|
+
if (left.byteLength === 0) return right;
|
|
30420
|
+
if (right.byteLength === 0) return left;
|
|
30421
|
+
const out = new Uint8Array(left.byteLength + right.byteLength);
|
|
30422
|
+
out.set(left, 0);
|
|
30423
|
+
out.set(right, left.byteLength);
|
|
30424
|
+
return out;
|
|
30425
|
+
}
|
|
29736
30426
|
/**
|
|
29737
30427
|
* Detect the family of "controller has already closed" errors that Bun and
|
|
29738
30428
|
* the WHATWG streams runtime throw when an enqueue/close call races with
|
|
@@ -29775,11 +30465,67 @@ function relayAnthropicStream(body, opts) {
|
|
|
29775
30465
|
let bytesRelayed = 0;
|
|
29776
30466
|
let upstreamFinished = false;
|
|
29777
30467
|
let consumerCancelled = false;
|
|
30468
|
+
let transform = opts.transform;
|
|
29778
30469
|
const safeClose = (controller) => {
|
|
29779
30470
|
try {
|
|
29780
30471
|
controller.close();
|
|
29781
30472
|
} catch {}
|
|
29782
30473
|
};
|
|
30474
|
+
/**
|
|
30475
|
+
* Enqueue transform output, tolerating the consumer-cancel race exactly like
|
|
30476
|
+
* the untransformed path. Returns false when the consumer has gone away, in
|
|
30477
|
+
* which case the caller must stop pulling.
|
|
30478
|
+
*/
|
|
30479
|
+
const enqueueBytes = (controller, bytes) => {
|
|
30480
|
+
if (!bytes || bytes.byteLength === 0) return true;
|
|
30481
|
+
try {
|
|
30482
|
+
controller.enqueue(bytes);
|
|
30483
|
+
return true;
|
|
30484
|
+
} catch (enqueueError) {
|
|
30485
|
+
if (isControllerClosedError(enqueueError)) {
|
|
30486
|
+
consumerCancelled = true;
|
|
30487
|
+
return false;
|
|
30488
|
+
}
|
|
30489
|
+
throw enqueueError;
|
|
30490
|
+
}
|
|
30491
|
+
};
|
|
30492
|
+
/**
|
|
30493
|
+
* Run the optional transform. A throw retires the transform and delivers this
|
|
30494
|
+
* chunk verbatim — a rewriter bug must never break delivery.
|
|
30495
|
+
*
|
|
30496
|
+
* Bytes the transform buffered from EARLIER chunks are not recoverable from
|
|
30497
|
+
* this chunk, so they are flushed out best-effort ahead of it. Without that,
|
|
30498
|
+
* a transform that held a partial record and then threw would silently
|
|
30499
|
+
* truncate everything it was holding.
|
|
30500
|
+
*/
|
|
30501
|
+
const applyTransform = (bytes) => {
|
|
30502
|
+
const active = transform;
|
|
30503
|
+
if (!active) return bytes;
|
|
30504
|
+
try {
|
|
30505
|
+
return active.push(bytes);
|
|
30506
|
+
} catch (error) {
|
|
30507
|
+
transform = void 0;
|
|
30508
|
+
consola.warn(`Stream byte transform disabled at ${opts.routePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
30509
|
+
let buffered;
|
|
30510
|
+
try {
|
|
30511
|
+
buffered = active.flush();
|
|
30512
|
+
} catch {}
|
|
30513
|
+
if (!buffered || buffered.byteLength === 0) return bytes;
|
|
30514
|
+
return concatBytes(buffered, bytes);
|
|
30515
|
+
}
|
|
30516
|
+
};
|
|
30517
|
+
/** Release any bytes the transform buffered, at a clean upstream EOF. */
|
|
30518
|
+
const flushTransform = () => {
|
|
30519
|
+
const active = transform;
|
|
30520
|
+
if (!active) return void 0;
|
|
30521
|
+
transform = void 0;
|
|
30522
|
+
try {
|
|
30523
|
+
return active.flush();
|
|
30524
|
+
} catch (error) {
|
|
30525
|
+
consola.warn(`Stream byte transform flush failed at ${opts.routePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
30526
|
+
return;
|
|
30527
|
+
}
|
|
30528
|
+
};
|
|
29783
30529
|
return new ReadableStream({
|
|
29784
30530
|
async pull(controller) {
|
|
29785
30531
|
if (consumerCancelled || upstreamFinished) {
|
|
@@ -29787,30 +30533,28 @@ function relayAnthropicStream(body, opts) {
|
|
|
29787
30533
|
return;
|
|
29788
30534
|
}
|
|
29789
30535
|
try {
|
|
29790
|
-
|
|
29791
|
-
|
|
29792
|
-
|
|
29793
|
-
|
|
29794
|
-
|
|
29795
|
-
|
|
29796
|
-
if (
|
|
29797
|
-
|
|
29798
|
-
|
|
29799
|
-
|
|
29800
|
-
|
|
29801
|
-
|
|
29802
|
-
|
|
29803
|
-
if (
|
|
29804
|
-
|
|
29805
|
-
|
|
29806
|
-
|
|
29807
|
-
|
|
29808
|
-
|
|
29809
|
-
if (
|
|
29810
|
-
|
|
29811
|
-
|
|
29812
|
-
}
|
|
29813
|
-
throw enqueueError;
|
|
30536
|
+
for (;;) {
|
|
30537
|
+
const result = await readWithInactivityTimeout(reader, inactivityMs);
|
|
30538
|
+
if (consumerCancelled) {
|
|
30539
|
+
safeClose(controller);
|
|
30540
|
+
return;
|
|
30541
|
+
}
|
|
30542
|
+
if (result.done) {
|
|
30543
|
+
if (bytesRelayed === 0) consola.warn(`Upstream returned empty SSE stream at ${opts.routePath}`);
|
|
30544
|
+
upstreamFinished = true;
|
|
30545
|
+
if (!enqueueBytes(controller, flushTransform())) return;
|
|
30546
|
+
safeClose(controller);
|
|
30547
|
+
return;
|
|
30548
|
+
}
|
|
30549
|
+
if (result.value) {
|
|
30550
|
+
bytesRelayed += result.value.byteLength;
|
|
30551
|
+
if (opts.onBytes) try {
|
|
30552
|
+
opts.onBytes(result.value);
|
|
30553
|
+
} catch {}
|
|
30554
|
+
const out = applyTransform(result.value);
|
|
30555
|
+
if (!out || out.byteLength === 0) continue;
|
|
30556
|
+
if (!enqueueBytes(controller, out)) return;
|
|
30557
|
+
return;
|
|
29814
30558
|
}
|
|
29815
30559
|
}
|
|
29816
30560
|
} catch (error) {
|
|
@@ -31361,6 +32105,7 @@ function buildAdvisorStream(opts) {
|
|
|
31361
32105
|
}
|
|
31362
32106
|
const nextUsage = {};
|
|
31363
32107
|
for (const [key, value] of Object.entries(usage)) if (typeof value === "number" && Number.isFinite(value)) nextUsage[key] = value;
|
|
32108
|
+
if (!anthropicUsageNormalizeDisabled()) normalizeAnthropicUsageInPlace(nextUsage);
|
|
31364
32109
|
pendingMessageDelta.usage = nextUsage;
|
|
31365
32110
|
const turnAic = extractCopilotUsage(payload.copilot_usage);
|
|
31366
32111
|
if (!turnAic || turnAic.totalNanoAiu <= 0) return;
|
|
@@ -31418,7 +32163,9 @@ function buildAdvisorStream(opts) {
|
|
|
31418
32163
|
continue;
|
|
31419
32164
|
}
|
|
31420
32165
|
switch (ev.event) {
|
|
31421
|
-
case "message_start":
|
|
32166
|
+
case "message_start": {
|
|
32167
|
+
const startMessage = payload.message;
|
|
32168
|
+
if (!anthropicUsageNormalizeDisabled() && startMessage && typeof startMessage === "object" && !Array.isArray(startMessage)) normalizeAnthropicUsageInPlace(startMessage.usage);
|
|
31422
32169
|
if (!messageStartForwarded) {
|
|
31423
32170
|
if (!safeEnqueueEvent(ev.event, payload)) return {
|
|
31424
32171
|
capturedBlocks,
|
|
@@ -31428,6 +32175,7 @@ function buildAdvisorStream(opts) {
|
|
|
31428
32175
|
messageStartForwarded = true;
|
|
31429
32176
|
}
|
|
31430
32177
|
continue;
|
|
32178
|
+
}
|
|
31431
32179
|
case "content_block_start": {
|
|
31432
32180
|
const block = payload.content_block;
|
|
31433
32181
|
const upstreamIndex = payload.index;
|
|
@@ -36128,7 +36876,8 @@ const MCP_GROUPS = Object.freeze([
|
|
|
36128
36876
|
"first-mate",
|
|
36129
36877
|
"ado",
|
|
36130
36878
|
"kusto",
|
|
36131
|
-
"cloudagent"
|
|
36879
|
+
"cloudagent",
|
|
36880
|
+
"workiq"
|
|
36132
36881
|
]);
|
|
36133
36882
|
const GROUP_META = Object.freeze({
|
|
36134
36883
|
peers: {
|
|
@@ -36185,6 +36934,11 @@ const GROUP_META = Object.freeze({
|
|
|
36185
36934
|
preferredKey: "cloudagent",
|
|
36186
36935
|
urlSuffix: "cloudagent",
|
|
36187
36936
|
serverInfoName: "github-router-cloudagent"
|
|
36937
|
+
},
|
|
36938
|
+
workiq: {
|
|
36939
|
+
preferredKey: "workiq",
|
|
36940
|
+
urlSuffix: "workiq",
|
|
36941
|
+
serverInfoName: "github-router-workiq"
|
|
36188
36942
|
}
|
|
36189
36943
|
});
|
|
36190
36944
|
/** True iff `s` is a registered group name (route `:group` param validation). */
|
|
@@ -38279,6 +39033,6 @@ function enumerateInjectedMcpToolNames(groupKeys, opts = {}) {
|
|
|
38279
39033
|
return [...new Set(names)];
|
|
38280
39034
|
}
|
|
38281
39035
|
//#endregion
|
|
38282
|
-
export { buildAnthropicErrorEvent as $,
|
|
39036
|
+
export { buildAnthropicErrorEvent as $, UPSTREAM_FETCH_TIMEOUT_MS as $n, nativeSubagentModel as $t, TOOLBELT_TOOLS$1 as A, parseJsonOrDiagnose as An, brainstormModel as At, FAST_ADVISOR_TOOL_INSTRUCTIONS as B, colbertDegradedWarning as Bn, cloudAgentToolsEnabled as Bt, runWorkerAgent as C, assembleResponsesPayload as Cn, ADO_DEFAULT_TOOLSETS as Ct, toolbeltEnabled as D, createChatCompletions as Dn, artifactToolsEnabled as Dt, buildToolbeltAwareness as E, createResponses as En, agentToolsEnabled as Et, ADVISOR_TOOL_INSTRUCTIONS as F, hasSupportedBrowserInstalled as Fn, cheapOracleModel as Ft, isAdvisorRequested as G, collapsePathKeys as Gn, fastPlanModel as Gt, LOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS as H, semanticSearchOptedIn as Hn, fastAstraModel as Ht, CHEAPEST_ADVISOR_TOOL_INSTRUCTIONS as I, normalizeCloudAgentEnvironment as In, cheapReviewerModel as It, resolveCuratedAdvisorModel as J, BUDGET_SMALL_FAST_SLUG as Jn, fleetToolsEnabled as Jt, resolveAdvisorEffort as K, toolbeltPathOverride as Kn, fastReviewerModel as Kt, CHEAPEST_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS as L, normalizeKustoClusterUri as Ln, cheapestAdvisorModel as Lt, satisfiesMinVersion as M, effectiveLocalProfile as Mn, browserCompoundToolsEnabled as Mt, searchWeb as N, normalizeOpenAIUsage as Nn, browserToolsEnabled as Nt, toolbeltSkipSet as O, MAX_RESPONSE_BODY_BYTES as On, balancedOracleModel as Ot, ADVISOR_INTERNAL_TOOL_NAME as P, provisionBrowserAssets as Pn, cheapAdvisorModel as Pt, repairRejectedThinkingHistory as Q, DEFAULT_PORT as Qn, kustoToolsEnabled as Qt, CHEAPLOCAL_ADVISOR_TOOL_INSTRUCTIONS as R, CONDENSED_OPERATING_SEQUENCE as Rn, cheapestOracleModel as Rt, resolveWorkerRunOpts as S, unregisterLaunch as Sn, provisionAdoTools as St, availableToolCommands as T, resolveMcpToolTimeoutMs as Tn, adoToolsEnabled as Tt, buildAdvisorStream as U, shouldUseInsecureTls as Un, fastGeneralPurposeModel as Ut, LOCAL_ADVISOR_TOOL_INSTRUCTIONS as V, provisionAndIndexColbert as Vn, fastAdvisorModel as Vt, injectAdvisorTool as W, LOCAL_CONSULT_REDACTION_LINE as Wn, fastOracleModel as Wt, rememberThinkingHistoryRepair as X, DEFAULT_CODEX_MODEL as Xn, generalPurposeFastModel as Xt, formatThinkingRepairDecline as Y, DEFAULT_CLAUDE_MODEL_FALLBACKS as Yn, geminiAvailable as Yt, repairKnownThinkingHistory as Z, DEFAULT_CODEX_MODEL_FALLBACKS as Zn, implementerFastModel as Zt, REVIEW_DEFAULT_MODEL as _, LAUNCH_BOUND_TOKEN_PREFIX as _n, CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS as _r, provisionWorkiqTools as _t, buildAgentPrompt as a, standInToolEnabled as an, upstreamAllowH2 as ar, EFFORT_ORDER as at, resolveDefaultModel as b, registerLaunch as bn, buildAdoToolEntries as bt, enumerateInjectedMcpToolNames as c, shimDefaultsToXhigh as cn, catalogAdvertises1M as cr, clampEffort as ct, BROWSE_DEFAULT_MODEL as d, getTokenizerFromModel as dn, withOneMSuffixForLead as dr, normalizeAnthropicUsageInPlace as dt, resolveGeminiReviewModel as en, UPSTREAM_INACTIVITY_TIMEOUT_MS as er, buildOpenAIErrorEvent as et, DEFAULT_MODEL_CHAIN as f, configureLocalEgress as fn, CHEAP_PROFILE_ADVISOR_CLIENT_MODEL as fr, handleMcpDelete as ft, PLAN_DEFAULT_MODEL as g, createMessages as gn, CHEAP_PROFILE_NATIVE_MODELS as gr, disposeWorkiqClients as gt, IMPLEMENT_DEFAULT_MODEL as h, countTokens as hn, CHEAP_PROFILE_NATIVE_EFFORTS as hr, buildWorkiqToolEntries as ht, assertMcpToolSurfaceConsistent as i, scribeModel as in, resolveLeadSlugArg as ir, relayAnthropicStream as it, assetFor as j, assertCopilotModelAllowed as jn, browseAgentEnabled as jt, vscodeRipgrepPath as k, readResponseBodyCapped as kn, balancedReviewerModel as kt, maxPersonasFor as l, getTextTokenCount as ln, oneMContextDisabled as lr, anthropicUsageNormalizeDisabled as lt, EXPLORE_DEFAULT_THINKING as m, localSessionId as mn, CHEAP_PROFILE_NATIVE_AGENT_NAMES as mr, WORKIQ_TOOL_ALIASES as mt, MCP_GROUPS as n, reviewerModel as nn, isBudgetClaudeLead as nr, logStreamError as nt, buildPeerAwarenessSnippet as o, workerToolsEnabled as on, upstreamMaxConnections as or, UNKNOWN_EFFORT_ANCHOR as ot, EXPLORE_DEFAULT_MODEL as p, localBaseUrl as pn, CHEAP_PROFILE_MODELS as pr, handleMcpPost as pt, resolveAdvisorModel as q, BUDGET_SMALL_FAST_CATALOG_ID as qn, fastScoutModel as qt, agentNamesForToolAllowlist as r, scoutModel as rn, pickClaudeDefault as rr, readIteratorWithTimeout as rt, buildPeerAwarenessSummary as s, workiqToolsEnabled as sn, classifyMessagesRoute as sr, bucketEffort as st, GROUP_META as t, reviewerFastModel as tn, generateRandomPort as tr, isControllerClosedError as tt, personasFor as u, getTokenCount as un, withOneMSuffix as ur, createAnthropicUsageRewriteTransform as ut, TEST_DEFAULT_MODEL as v, findLaunchBySecret as vn, workiqMcpToolEntries as vt, buildEnv as w, warnOnTokenPriceDrift as wn, normalizeAdoToolsets as wt, resolveModeDefaults as x, rememberLaunchSessionId as xn, disposeAdoClients as xt, appendPlanReminder as y, launchBoundAccessToken as yn, adoMcpToolEntries as yt, CHEAPLOCAL_REVIEWER_ADVISOR_TOOL_INSTRUCTIONS as z, DEFINITION_OF_GREATNESS as zn, cheapestReviewerModel as zt };
|
|
38283
39037
|
|
|
38284
|
-
//# sourceMappingURL=peer-mcp-personas-
|
|
39038
|
+
//# sourceMappingURL=peer-mcp-personas-D7vaM-V5.js.map
|