@blockrun/clawrouter 0.12.291 → 0.12.292
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/cli.js +120 -52
- package/dist/index.js +119 -51
- package/dist/router/index.js +110 -41
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -44245,6 +44245,55 @@ var init_esm5 = __esm({
|
|
|
44245
44245
|
});
|
|
44246
44246
|
|
|
44247
44247
|
// node_modules/@blockrun/router-core/dist/index.js
|
|
44248
|
+
function escapeRegExp2(value) {
|
|
44249
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
44250
|
+
}
|
|
44251
|
+
function keywordMatcher(keyword) {
|
|
44252
|
+
const cached = matcherCache.get(keyword);
|
|
44253
|
+
if (cached) return cached;
|
|
44254
|
+
const kw = keyword.toLowerCase();
|
|
44255
|
+
let matcher;
|
|
44256
|
+
if (UNSEGMENTED_SCRIPT.test(kw) || kw.length === 0) {
|
|
44257
|
+
matcher = { needle: kw, pattern: null };
|
|
44258
|
+
} else {
|
|
44259
|
+
const lead = WORD_CHAR.test(kw[0]) ? BOUNDARY_BEFORE : "";
|
|
44260
|
+
const escaped = escapeRegExp2(kw);
|
|
44261
|
+
let body = escaped;
|
|
44262
|
+
let trail = "";
|
|
44263
|
+
let needle = kw;
|
|
44264
|
+
const lastWord = kw.slice(kw.lastIndexOf(" ") + 1);
|
|
44265
|
+
if (WORD_CHAR.test(kw[kw.length - 1]) && ASCII_PHRASE.test(kw) && lastWord.length <= BOUNDED_LAST_WORD_LENGTH) {
|
|
44266
|
+
const forms = [];
|
|
44267
|
+
if (/\d$/.test(kw)) {
|
|
44268
|
+
forms.push(escaped);
|
|
44269
|
+
} else if (lastWord.length <= 3) {
|
|
44270
|
+
forms.push(`${escaped}${SHORT_SUFFIXES}`);
|
|
44271
|
+
if (/(?:x|s|z|ch|sh)$/.test(kw)) forms.push(`${escaped}${SIBILANT_PLURAL}`);
|
|
44272
|
+
} else {
|
|
44273
|
+
forms.push(`${escaped}${MID_SUFFIXES}`);
|
|
44274
|
+
if (kw.endsWith("e")) {
|
|
44275
|
+
forms.push(`${escaped.slice(0, -1)}${DROPPED_E_SUFFIXES}`);
|
|
44276
|
+
needle = kw.slice(0, -1);
|
|
44277
|
+
} else if (kw.endsWith("y")) {
|
|
44278
|
+
forms.push(`${escaped.slice(0, -1)}(?:ies|ied)`);
|
|
44279
|
+
needle = kw.slice(0, -1);
|
|
44280
|
+
} else if (/[aeiou][bdgmnprt]$/.test(kw)) {
|
|
44281
|
+
forms.push(`${escaped}${kw[kw.length - 1]}${DOUBLED_CONSONANT_SUFFIXES}`);
|
|
44282
|
+
}
|
|
44283
|
+
}
|
|
44284
|
+
body = `(?:${forms.join("|")})`;
|
|
44285
|
+
trail = BOUNDARY_AFTER;
|
|
44286
|
+
}
|
|
44287
|
+
matcher = { needle, pattern: new RegExp(`${lead}${body}${trail}`, "u") };
|
|
44288
|
+
}
|
|
44289
|
+
matcherCache.set(keyword, matcher);
|
|
44290
|
+
return matcher;
|
|
44291
|
+
}
|
|
44292
|
+
function matchesKeyword(text, keyword) {
|
|
44293
|
+
const { needle, pattern } = keywordMatcher(keyword);
|
|
44294
|
+
if (!text.includes(needle)) return false;
|
|
44295
|
+
return pattern === null ? true : pattern.test(text);
|
|
44296
|
+
}
|
|
44248
44297
|
function scoreTokenCount(estimatedTokens, thresholds) {
|
|
44249
44298
|
if (estimatedTokens < thresholds.simple) {
|
|
44250
44299
|
return { name: "tokenCount", score: -1, signal: `short (${estimatedTokens} tokens)` };
|
|
@@ -44255,7 +44304,7 @@ function scoreTokenCount(estimatedTokens, thresholds) {
|
|
|
44255
44304
|
return { name: "tokenCount", score: 0, signal: null };
|
|
44256
44305
|
}
|
|
44257
44306
|
function scoreKeywordMatch(text, keywords, name, signalLabel, thresholds, scores) {
|
|
44258
|
-
const matches = keywords.filter((kw) => text
|
|
44307
|
+
const matches = keywords.filter((kw) => matchesKeyword(text, kw));
|
|
44259
44308
|
if (matches.length >= thresholds.high) {
|
|
44260
44309
|
return {
|
|
44261
44310
|
name,
|
|
@@ -44291,7 +44340,7 @@ function scoreAgenticTask(text, keywords) {
|
|
|
44291
44340
|
let matchCount = 0;
|
|
44292
44341
|
const signals = [];
|
|
44293
44342
|
for (const keyword of keywords) {
|
|
44294
|
-
if (text
|
|
44343
|
+
if (matchesKeyword(text, keyword)) {
|
|
44295
44344
|
matchCount++;
|
|
44296
44345
|
if (signals.length < 3) {
|
|
44297
44346
|
signals.push(keyword);
|
|
@@ -44438,9 +44487,7 @@ function classifyByRules(prompt, systemPrompt, estimatedTokens, config) {
|
|
|
44438
44487
|
const w = weights[d.name] ?? 0;
|
|
44439
44488
|
weightedScore += d.score * w;
|
|
44440
44489
|
}
|
|
44441
|
-
const reasoningMatches = config.reasoningKeywords.filter(
|
|
44442
|
-
(kw) => userText.includes(kw.toLowerCase())
|
|
44443
|
-
);
|
|
44490
|
+
const reasoningMatches = config.reasoningKeywords.filter((kw) => matchesKeyword(userText, kw));
|
|
44444
44491
|
if (reasoningMatches.length >= 2) {
|
|
44445
44492
|
const confidence2 = calibrateConfidence(
|
|
44446
44493
|
Math.max(weightedScore, 0.3),
|
|
@@ -44502,7 +44549,7 @@ function selectModel(tier, confidence, method, reasoning, tierConfigs, modelPric
|
|
|
44502
44549
|
const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice;
|
|
44503
44550
|
const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice;
|
|
44504
44551
|
const baselineCost = baselineInput + baselineOutput;
|
|
44505
|
-
const savings = routingProfile === "premium" ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
|
|
44552
|
+
const savings = routingProfile === "premium" || pricing === void 0 ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
|
|
44506
44553
|
return {
|
|
44507
44554
|
model,
|
|
44508
44555
|
tier,
|
|
@@ -44580,6 +44627,20 @@ function filterCandidatesByCapacity(models, estimatedInputTokens, requestedOutpu
|
|
|
44580
44627
|
});
|
|
44581
44628
|
return filtered;
|
|
44582
44629
|
}
|
|
44630
|
+
function estimateTokens(text) {
|
|
44631
|
+
if (text.length === 0) return 0;
|
|
44632
|
+
const cjk = text.match(CJK_CHARS)?.length ?? 0;
|
|
44633
|
+
return cjk + Math.ceil((text.length - cjk) / 4);
|
|
44634
|
+
}
|
|
44635
|
+
function scanLimit(promptTruncationChars) {
|
|
44636
|
+
return Math.max(1, Math.min(8e3, promptTruncationChars));
|
|
44637
|
+
}
|
|
44638
|
+
function sampleForScan(value, limit) {
|
|
44639
|
+
if (value.length <= limit) return value;
|
|
44640
|
+
const prefixLength = Math.ceil(limit / 2);
|
|
44641
|
+
return `${value.slice(0, prefixLength)}
|
|
44642
|
+
${value.slice(-(limit - prefixLength))}`;
|
|
44643
|
+
}
|
|
44583
44644
|
function applyPromotions(tierConfigs, promotions, profile, now2 = /* @__PURE__ */ new Date()) {
|
|
44584
44645
|
if (!promotions || promotions.length === 0) return tierConfigs;
|
|
44585
44646
|
let result = tierConfigs;
|
|
@@ -44692,16 +44753,10 @@ function likelyNeedsParallelToolCalls(prompt, needsTools, toolCount, toolNames)
|
|
|
44692
44753
|
}
|
|
44693
44754
|
function classifyTask(prompt, systemPrompt, options) {
|
|
44694
44755
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
44695
|
-
const estimatedInputTokens =
|
|
44696
|
-
const
|
|
44697
|
-
const
|
|
44698
|
-
|
|
44699
|
-
const prefixLength = Math.ceil(scanLimit / 2);
|
|
44700
|
-
return `${value.slice(0, prefixLength)}
|
|
44701
|
-
${value.slice(-(scanLimit - prefixLength))}`;
|
|
44702
|
-
};
|
|
44703
|
-
const scannedPrompt = sample(prompt);
|
|
44704
|
-
const scannedSystemPrompt = sample(systemPrompt ?? "");
|
|
44756
|
+
const estimatedInputTokens = estimateTokens(fullText);
|
|
44757
|
+
const limit = scanLimit(options.config.classifier.promptTruncationChars);
|
|
44758
|
+
const scannedPrompt = sampleForScan(prompt, limit);
|
|
44759
|
+
const scannedSystemPrompt = sampleForScan(systemPrompt ?? "", limit);
|
|
44705
44760
|
const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`;
|
|
44706
44761
|
const text = scannedPrompt.toLowerCase();
|
|
44707
44762
|
const explicitCodeSignal = /```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(
|
|
@@ -44713,7 +44768,9 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
44713
44768
|
const nativeCodeSignal = /\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test(
|
|
44714
44769
|
scannedPrompt
|
|
44715
44770
|
);
|
|
44716
|
-
const
|
|
44771
|
+
const errorClassSignal = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt);
|
|
44772
|
+
const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal;
|
|
44773
|
+
const codeArtifact = /```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt) || codeConstructSignal || nativeCodeSignal || errorClassSignal;
|
|
44717
44774
|
const toolsAvailable = options.hasTools ?? false;
|
|
44718
44775
|
const needsTools = options.requiresTools ?? (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt));
|
|
44719
44776
|
const likelyParallelToolCalls = likelyNeedsParallelToolCalls(
|
|
@@ -44785,10 +44842,10 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
44785
44842
|
const needsVision = options.hasVision ?? false;
|
|
44786
44843
|
const needsStructuredOutput = options.requiresStructuredOutput ?? false;
|
|
44787
44844
|
const latencySensitive = /\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test(
|
|
44788
|
-
|
|
44845
|
+
scannedPrompt
|
|
44789
44846
|
);
|
|
44790
44847
|
const highStakes = /\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test(
|
|
44791
|
-
|
|
44848
|
+
scannedPrompt
|
|
44792
44849
|
);
|
|
44793
44850
|
const terminalToolSignal = normalizedToolNames.some(
|
|
44794
44851
|
(name) => /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name)
|
|
@@ -44824,7 +44881,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
44824
44881
|
);
|
|
44825
44882
|
const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal);
|
|
44826
44883
|
const implicitTerminalCode = needsTools && terminalToolSignal && agentRisk === "standard" && !highStakes && !complexTerminalOperation && numberedSteps < 3 && prompt.length <= 1e3 && simpleTerminalArtifact;
|
|
44827
|
-
const language = /[\u3400-\u9fff]/.test(
|
|
44884
|
+
const language = /[\u3400-\u9fff]/.test(scannedPrompt) ? "zh" : "other";
|
|
44828
44885
|
const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim) ?? []).length;
|
|
44829
44886
|
const numericSignals = (scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g) ?? []).length;
|
|
44830
44887
|
const compactMathProblem = !hasCode && prompt.length < 2500 && numericSignals >= 2 && (/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test(
|
|
@@ -44839,7 +44896,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
44839
44896
|
else if (needsTools) taskType = "tool_agent";
|
|
44840
44897
|
else if (multipleChoiceSignals >= 3) taskType = "reasoning_mcq";
|
|
44841
44898
|
else if (compactMathProblem) taskType = "reasoning_math";
|
|
44842
|
-
else if (/\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text))
|
|
44899
|
+
else if (errorClassSignal || /\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text))
|
|
44843
44900
|
taskType = "debug";
|
|
44844
44901
|
else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite|重构|实现|修改)\b/i.test(text))
|
|
44845
44902
|
taskType = "code_edit";
|
|
@@ -44865,7 +44922,8 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
44865
44922
|
agentRisk,
|
|
44866
44923
|
terminalToolSignal,
|
|
44867
44924
|
terminalSafetySensitive,
|
|
44868
|
-
implicitTerminalCode
|
|
44925
|
+
implicitTerminalCode,
|
|
44926
|
+
codeArtifact
|
|
44869
44927
|
};
|
|
44870
44928
|
}
|
|
44871
44929
|
function affinity(modelId, task, language = "other", agentDomain = "other", deepWebResearch = false, agentRisk = "standard", terminalToolSignal = false, terminalSafetySensitive = false) {
|
|
@@ -45257,30 +45315,38 @@ function route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
|
45257
45315
|
const strategy = getStrategy(options.config.strategy ?? "portfolio");
|
|
45258
45316
|
return strategy.route(prompt, systemPrompt, maxOutputTokens, options);
|
|
45259
45317
|
}
|
|
45260
|
-
var BASELINE_MODEL_ID, BASELINE_INPUT_PRICE, BASELINE_OUTPUT_PRICE, SERVER_MARGIN_PERCENT, MIN_PAYMENT_USD, RulesStrategy, registry, DEFAULT_MODEL_CAPABILITIES, model_profiles_generated_default, LIVE_MODEL_PROFILES, HISTORICAL_MODEL_PROFILES, DEFAULT_PORTFOLIO_WEIGHTS, VERIFIED_TOOL_FALLBACKS, PortfolioStrategy, DEFAULT_ROUTING_CONFIG;
|
|
45318
|
+
var UNSEGMENTED_SCRIPT, WORD_CHAR, ASCII_PHRASE, SEGMENTED_WORD_CHAR, BOUNDARY_BEFORE, BOUNDARY_AFTER, BOUNDED_LAST_WORD_LENGTH, SHORT_SUFFIXES, SIBILANT_PLURAL, MID_SUFFIXES, DROPPED_E_SUFFIXES, DOUBLED_CONSONANT_SUFFIXES, matcherCache, BASELINE_MODEL_ID, BASELINE_INPUT_PRICE, BASELINE_OUTPUT_PRICE, SERVER_MARGIN_PERCENT, MIN_PAYMENT_USD, CJK_CHARS, RulesStrategy, registry, DEFAULT_MODEL_CAPABILITIES, model_profiles_generated_default, LIVE_MODEL_PROFILES, HISTORICAL_MODEL_PROFILES, DEFAULT_PORTFOLIO_WEIGHTS, VERIFIED_TOOL_FALLBACKS, PortfolioStrategy, DEFAULT_ROUTING_CONFIG;
|
|
45261
45319
|
var init_dist = __esm({
|
|
45262
45320
|
"node_modules/@blockrun/router-core/dist/index.js"() {
|
|
45263
45321
|
"use strict";
|
|
45322
|
+
UNSEGMENTED_SCRIPT = /[-ۿ -ヿ㐀-䶿一-鿿가-豈--]/;
|
|
45323
|
+
WORD_CHAR = /[\p{L}\p{N}]/u;
|
|
45324
|
+
ASCII_PHRASE = /^[a-z0-9' -]+$/;
|
|
45325
|
+
SEGMENTED_WORD_CHAR = "\\p{Script=Latin}\\p{Script=Cyrillic}\\p{Script=Greek}\\p{N}";
|
|
45326
|
+
BOUNDARY_BEFORE = `(?<![${SEGMENTED_WORD_CHAR}])`;
|
|
45327
|
+
BOUNDARY_AFTER = `(?![${SEGMENTED_WORD_CHAR}])`;
|
|
45328
|
+
BOUNDED_LAST_WORD_LENGTH = 6;
|
|
45329
|
+
SHORT_SUFFIXES = "(?:s|ed|ing)?";
|
|
45330
|
+
SIBILANT_PLURAL = "es";
|
|
45331
|
+
MID_SUFFIXES = "(?:s|es|ed|d|ing|er|ers|ly|ment|ments|ation|ations|e|en|n|a|as|o|os|em|et|ung|ungen)?";
|
|
45332
|
+
DROPPED_E_SUFFIXES = "(?:ing|ed|es|er|ers|ation|ations)";
|
|
45333
|
+
DOUBLED_CONSONANT_SUFFIXES = "(?:ing|ed|er|ers)";
|
|
45334
|
+
matcherCache = /* @__PURE__ */ new Map();
|
|
45264
45335
|
BASELINE_MODEL_ID = "anthropic/claude-opus-4.7";
|
|
45265
45336
|
BASELINE_INPUT_PRICE = 5;
|
|
45266
45337
|
BASELINE_OUTPUT_PRICE = 25;
|
|
45267
45338
|
SERVER_MARGIN_PERCENT = 5;
|
|
45268
45339
|
MIN_PAYMENT_USD = 1e-3;
|
|
45340
|
+
CJK_CHARS = /[ -ヿ㐀-䶿一-鿿가-豈--]/g;
|
|
45269
45341
|
RulesStrategy = class {
|
|
45270
45342
|
name = "rules";
|
|
45271
45343
|
route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
45272
45344
|
const { config, modelPricing } = options;
|
|
45273
45345
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
45274
|
-
const estimatedTokens =
|
|
45275
|
-
const
|
|
45276
|
-
const
|
|
45277
|
-
|
|
45278
|
-
const prefixLength = Math.ceil(scanLimit / 2);
|
|
45279
|
-
return `${value.slice(0, prefixLength)}
|
|
45280
|
-
${value.slice(-(scanLimit - prefixLength))}`;
|
|
45281
|
-
};
|
|
45282
|
-
const scannedPrompt = sample(prompt);
|
|
45283
|
-
const scannedSystemPrompt = systemPrompt ? sample(systemPrompt) : void 0;
|
|
45346
|
+
const estimatedTokens = estimateTokens(fullText);
|
|
45347
|
+
const limit = scanLimit(config.classifier.promptTruncationChars);
|
|
45348
|
+
const scannedPrompt = sampleForScan(prompt, limit);
|
|
45349
|
+
const scannedSystemPrompt = systemPrompt ? sampleForScan(systemPrompt, limit) : void 0;
|
|
45284
45350
|
const ruleResult = classifyByRules(
|
|
45285
45351
|
scannedPrompt,
|
|
45286
45352
|
scannedSystemPrompt,
|
|
@@ -45334,7 +45400,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
45334
45400
|
);
|
|
45335
45401
|
return { ...decision2, tierConfigs, profile };
|
|
45336
45402
|
}
|
|
45337
|
-
const hasStructuredOutput = options.requiresStructuredOutput === true
|
|
45403
|
+
const hasStructuredOutput = options.requiresStructuredOutput === true;
|
|
45338
45404
|
let tier;
|
|
45339
45405
|
let confidence;
|
|
45340
45406
|
const method = "rules";
|
|
@@ -46527,15 +46593,17 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
46527
46593
|
];
|
|
46528
46594
|
PortfolioStrategy = class {
|
|
46529
46595
|
name = "portfolio";
|
|
46596
|
+
// Rules set the capability tier; the strategy is stateless, so one instance serves every request.
|
|
46597
|
+
rules = new RulesStrategy();
|
|
46530
46598
|
route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
46531
46599
|
const features = classifyTask(prompt, systemPrompt, options);
|
|
46532
|
-
const base4 =
|
|
46600
|
+
const base4 = this.rules.route(prompt, systemPrompt, maxOutputTokens, {
|
|
46533
46601
|
...options,
|
|
46534
46602
|
requiresTools: features.needsTools
|
|
46535
46603
|
});
|
|
46536
46604
|
const tierConfigs = base4.tierConfigs;
|
|
46537
46605
|
if (!tierConfigs) return base4;
|
|
46538
|
-
const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base4.tier === "SIMPLE" || base4.tier === "MEDIUM") ? "REASONING" : base4.tier;
|
|
46606
|
+
const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base4.tier === "SIMPLE" || base4.tier === "MEDIUM") ? "REASONING" : (features.taskType === "debug" || features.taskType === "code_edit") && features.codeArtifact && base4.tier === "SIMPLE" ? "MEDIUM" : base4.tier;
|
|
46539
46607
|
const tierConfig = tierConfigs[targetTier];
|
|
46540
46608
|
const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : [];
|
|
46541
46609
|
const unavailable = new Set(options.unavailableModels ?? []);
|
|
@@ -46553,10 +46621,10 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
46553
46621
|
].filter(
|
|
46554
46622
|
(model2) => typeof model2 === "string" && model2.length > 0 && !unavailable.has(model2)
|
|
46555
46623
|
);
|
|
46556
|
-
const eligible =
|
|
46557
|
-
(model2) => isEligible(model2, features, maxOutputTokens, options)
|
|
46624
|
+
const eligible = new Set(
|
|
46625
|
+
chain3.filter((model2) => isEligible(model2, features, maxOutputTokens, options))
|
|
46558
46626
|
);
|
|
46559
|
-
const eligibleCandidates = eligible.
|
|
46627
|
+
const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain3;
|
|
46560
46628
|
if (eligibleCandidates.length === 0) return base4;
|
|
46561
46629
|
const profileName = options.routingProfile === "eco" ? "eco" : options.routingProfile === "premium" ? "premium" : "auto";
|
|
46562
46630
|
const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS;
|
|
@@ -46591,11 +46659,11 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
46591
46659
|
const rankedEntries = candidates.map((model2, index2) => {
|
|
46592
46660
|
const cost = estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens);
|
|
46593
46661
|
const costScore = Number.isFinite(cost) && maxCost > minCost ? 1 - (cost - minCost) / (maxCost - minCost) : 0.5;
|
|
46594
|
-
const capabilityScore =
|
|
46662
|
+
const capabilityScore = eligible.has(model2) ? 1 : 0;
|
|
46595
46663
|
const profile = profileScore(model2, options, now2);
|
|
46596
46664
|
const observedQuality = profile?.quality === void 0 ? getAffinity(model2) : getAffinity(model2) * (1 - profile.freshness) + profile.quality * profile.freshness;
|
|
46597
|
-
const observedSpeed = profile ? profile.speed * profile.freshness : 0.5;
|
|
46598
|
-
const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness : 0.5;
|
|
46665
|
+
const observedSpeed = profile ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5;
|
|
46666
|
+
const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5;
|
|
46599
46667
|
const observedReliability = profile ? profile.reliability * profile.freshness + (1 - profile.freshness) : 1;
|
|
46600
46668
|
const legacyScore = 1 - index2 / Math.max(1, candidates.length - 1);
|
|
46601
46669
|
const qualityWeight = profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0);
|
|
@@ -91229,12 +91297,12 @@ function likelyNeedsParallelToolCalls2(prompt, needsTools, toolCount, toolNames)
|
|
|
91229
91297
|
function classifyTask2(prompt, systemPrompt, options) {
|
|
91230
91298
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
91231
91299
|
const estimatedInputTokens = Math.ceil(fullText.length / 4);
|
|
91232
|
-
const
|
|
91300
|
+
const scanLimit2 = Math.max(1, Math.min(8e3, options.config.classifier.promptTruncationChars));
|
|
91233
91301
|
const sample = (value) => {
|
|
91234
|
-
if (value.length <=
|
|
91235
|
-
const prefixLength = Math.ceil(
|
|
91302
|
+
if (value.length <= scanLimit2) return value;
|
|
91303
|
+
const prefixLength = Math.ceil(scanLimit2 / 2);
|
|
91236
91304
|
return `${value.slice(0, prefixLength)}
|
|
91237
|
-
${value.slice(-(
|
|
91305
|
+
${value.slice(-(scanLimit2 - prefixLength))}`;
|
|
91238
91306
|
};
|
|
91239
91307
|
const scannedPrompt = sample(prompt);
|
|
91240
91308
|
const scannedSystemPrompt = sample(systemPrompt ?? "");
|
|
@@ -93969,12 +94037,12 @@ var init_dist2 = __esm({
|
|
|
93969
94037
|
const { config, modelPricing } = options;
|
|
93970
94038
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
93971
94039
|
const estimatedTokens = Math.ceil(fullText.length / 4);
|
|
93972
|
-
const
|
|
94040
|
+
const scanLimit2 = Math.max(1, Math.min(8e3, config.classifier.promptTruncationChars));
|
|
93973
94041
|
const sample = (value) => {
|
|
93974
|
-
if (value.length <=
|
|
93975
|
-
const prefixLength = Math.ceil(
|
|
94042
|
+
if (value.length <= scanLimit2) return value;
|
|
94043
|
+
const prefixLength = Math.ceil(scanLimit2 / 2);
|
|
93976
94044
|
return `${value.slice(0, prefixLength)}
|
|
93977
|
-
${value.slice(-(
|
|
94045
|
+
${value.slice(-(scanLimit2 - prefixLength))}`;
|
|
93978
94046
|
};
|
|
93979
94047
|
const scannedPrompt = sample(prompt);
|
|
93980
94048
|
const scannedSystemPrompt = systemPrompt ? sample(systemPrompt) : void 0;
|
|
@@ -132953,7 +133021,7 @@ function resolveKimiTool(prose, blob, tools) {
|
|
|
132953
133021
|
const blobKeys = Object.keys(blob);
|
|
132954
133022
|
if (prose) {
|
|
132955
133023
|
const named = tools.filter(
|
|
132956
|
-
(t) => new RegExp(`(?:^|[^A-Za-z0-9_])${
|
|
133024
|
+
(t) => new RegExp(`(?:^|[^A-Za-z0-9_])${escapeRegExp3(t.name)}(?:[^A-Za-z0-9_]|$)`).test(prose)
|
|
132957
133025
|
);
|
|
132958
133026
|
if (named.length === 1) return named[0].name;
|
|
132959
133027
|
}
|
|
@@ -132964,7 +133032,7 @@ function resolveKimiTool(prose, blob, tools) {
|
|
|
132964
133032
|
);
|
|
132965
133033
|
return sigMatches.length === 1 ? sigMatches[0].name : null;
|
|
132966
133034
|
}
|
|
132967
|
-
function
|
|
133035
|
+
function escapeRegExp3(s3) {
|
|
132968
133036
|
return s3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
132969
133037
|
}
|
|
132970
133038
|
function extractKimiCalls(content, tools) {
|
package/dist/index.js
CHANGED
|
@@ -60291,12 +60291,12 @@ function likelyNeedsParallelToolCalls2(prompt, needsTools, toolCount, toolNames)
|
|
|
60291
60291
|
function classifyTask2(prompt, systemPrompt, options) {
|
|
60292
60292
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
60293
60293
|
const estimatedInputTokens = Math.ceil(fullText.length / 4);
|
|
60294
|
-
const
|
|
60294
|
+
const scanLimit2 = Math.max(1, Math.min(8e3, options.config.classifier.promptTruncationChars));
|
|
60295
60295
|
const sample = (value) => {
|
|
60296
|
-
if (value.length <=
|
|
60297
|
-
const prefixLength = Math.ceil(
|
|
60296
|
+
if (value.length <= scanLimit2) return value;
|
|
60297
|
+
const prefixLength = Math.ceil(scanLimit2 / 2);
|
|
60298
60298
|
return `${value.slice(0, prefixLength)}
|
|
60299
|
-
${value.slice(-(
|
|
60299
|
+
${value.slice(-(scanLimit2 - prefixLength))}`;
|
|
60300
60300
|
};
|
|
60301
60301
|
const scannedPrompt = sample(prompt);
|
|
60302
60302
|
const scannedSystemPrompt = sample(systemPrompt ?? "");
|
|
@@ -63031,12 +63031,12 @@ var init_dist = __esm({
|
|
|
63031
63031
|
const { config, modelPricing } = options;
|
|
63032
63032
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
63033
63033
|
const estimatedTokens = Math.ceil(fullText.length / 4);
|
|
63034
|
-
const
|
|
63034
|
+
const scanLimit2 = Math.max(1, Math.min(8e3, config.classifier.promptTruncationChars));
|
|
63035
63035
|
const sample = (value) => {
|
|
63036
|
-
if (value.length <=
|
|
63037
|
-
const prefixLength = Math.ceil(
|
|
63036
|
+
if (value.length <= scanLimit2) return value;
|
|
63037
|
+
const prefixLength = Math.ceil(scanLimit2 / 2);
|
|
63038
63038
|
return `${value.slice(0, prefixLength)}
|
|
63039
|
-
${value.slice(-(
|
|
63039
|
+
${value.slice(-(scanLimit2 - prefixLength))}`;
|
|
63040
63040
|
};
|
|
63041
63041
|
const scannedPrompt = sample(prompt);
|
|
63042
63042
|
const scannedSystemPrompt = systemPrompt ? sample(systemPrompt) : void 0;
|
|
@@ -253685,6 +253685,68 @@ function toClientEvmSigner(signer, publicClient) {
|
|
|
253685
253685
|
}
|
|
253686
253686
|
|
|
253687
253687
|
// node_modules/@blockrun/router-core/dist/index.js
|
|
253688
|
+
var UNSEGMENTED_SCRIPT = /[-ۿ -ヿ㐀-䶿一-鿿가-豈--]/;
|
|
253689
|
+
var WORD_CHAR = /[\p{L}\p{N}]/u;
|
|
253690
|
+
var ASCII_PHRASE = /^[a-z0-9' -]+$/;
|
|
253691
|
+
var SEGMENTED_WORD_CHAR = "\\p{Script=Latin}\\p{Script=Cyrillic}\\p{Script=Greek}\\p{N}";
|
|
253692
|
+
var BOUNDARY_BEFORE = `(?<![${SEGMENTED_WORD_CHAR}])`;
|
|
253693
|
+
var BOUNDARY_AFTER = `(?![${SEGMENTED_WORD_CHAR}])`;
|
|
253694
|
+
var BOUNDED_LAST_WORD_LENGTH = 6;
|
|
253695
|
+
var SHORT_SUFFIXES = "(?:s|ed|ing)?";
|
|
253696
|
+
var SIBILANT_PLURAL = "es";
|
|
253697
|
+
var MID_SUFFIXES = "(?:s|es|ed|d|ing|er|ers|ly|ment|ments|ation|ations|e|en|n|a|as|o|os|em|et|ung|ungen)?";
|
|
253698
|
+
var DROPPED_E_SUFFIXES = "(?:ing|ed|es|er|ers|ation|ations)";
|
|
253699
|
+
var DOUBLED_CONSONANT_SUFFIXES = "(?:ing|ed|er|ers)";
|
|
253700
|
+
var matcherCache = /* @__PURE__ */ new Map();
|
|
253701
|
+
function escapeRegExp2(value) {
|
|
253702
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
253703
|
+
}
|
|
253704
|
+
function keywordMatcher(keyword) {
|
|
253705
|
+
const cached = matcherCache.get(keyword);
|
|
253706
|
+
if (cached) return cached;
|
|
253707
|
+
const kw = keyword.toLowerCase();
|
|
253708
|
+
let matcher;
|
|
253709
|
+
if (UNSEGMENTED_SCRIPT.test(kw) || kw.length === 0) {
|
|
253710
|
+
matcher = { needle: kw, pattern: null };
|
|
253711
|
+
} else {
|
|
253712
|
+
const lead = WORD_CHAR.test(kw[0]) ? BOUNDARY_BEFORE : "";
|
|
253713
|
+
const escaped = escapeRegExp2(kw);
|
|
253714
|
+
let body = escaped;
|
|
253715
|
+
let trail = "";
|
|
253716
|
+
let needle = kw;
|
|
253717
|
+
const lastWord = kw.slice(kw.lastIndexOf(" ") + 1);
|
|
253718
|
+
if (WORD_CHAR.test(kw[kw.length - 1]) && ASCII_PHRASE.test(kw) && lastWord.length <= BOUNDED_LAST_WORD_LENGTH) {
|
|
253719
|
+
const forms = [];
|
|
253720
|
+
if (/\d$/.test(kw)) {
|
|
253721
|
+
forms.push(escaped);
|
|
253722
|
+
} else if (lastWord.length <= 3) {
|
|
253723
|
+
forms.push(`${escaped}${SHORT_SUFFIXES}`);
|
|
253724
|
+
if (/(?:x|s|z|ch|sh)$/.test(kw)) forms.push(`${escaped}${SIBILANT_PLURAL}`);
|
|
253725
|
+
} else {
|
|
253726
|
+
forms.push(`${escaped}${MID_SUFFIXES}`);
|
|
253727
|
+
if (kw.endsWith("e")) {
|
|
253728
|
+
forms.push(`${escaped.slice(0, -1)}${DROPPED_E_SUFFIXES}`);
|
|
253729
|
+
needle = kw.slice(0, -1);
|
|
253730
|
+
} else if (kw.endsWith("y")) {
|
|
253731
|
+
forms.push(`${escaped.slice(0, -1)}(?:ies|ied)`);
|
|
253732
|
+
needle = kw.slice(0, -1);
|
|
253733
|
+
} else if (/[aeiou][bdgmnprt]$/.test(kw)) {
|
|
253734
|
+
forms.push(`${escaped}${kw[kw.length - 1]}${DOUBLED_CONSONANT_SUFFIXES}`);
|
|
253735
|
+
}
|
|
253736
|
+
}
|
|
253737
|
+
body = `(?:${forms.join("|")})`;
|
|
253738
|
+
trail = BOUNDARY_AFTER;
|
|
253739
|
+
}
|
|
253740
|
+
matcher = { needle, pattern: new RegExp(`${lead}${body}${trail}`, "u") };
|
|
253741
|
+
}
|
|
253742
|
+
matcherCache.set(keyword, matcher);
|
|
253743
|
+
return matcher;
|
|
253744
|
+
}
|
|
253745
|
+
function matchesKeyword(text, keyword) {
|
|
253746
|
+
const { needle, pattern } = keywordMatcher(keyword);
|
|
253747
|
+
if (!text.includes(needle)) return false;
|
|
253748
|
+
return pattern === null ? true : pattern.test(text);
|
|
253749
|
+
}
|
|
253688
253750
|
function scoreTokenCount(estimatedTokens, thresholds) {
|
|
253689
253751
|
if (estimatedTokens < thresholds.simple) {
|
|
253690
253752
|
return { name: "tokenCount", score: -1, signal: `short (${estimatedTokens} tokens)` };
|
|
@@ -253695,7 +253757,7 @@ function scoreTokenCount(estimatedTokens, thresholds) {
|
|
|
253695
253757
|
return { name: "tokenCount", score: 0, signal: null };
|
|
253696
253758
|
}
|
|
253697
253759
|
function scoreKeywordMatch(text, keywords, name, signalLabel, thresholds, scores) {
|
|
253698
|
-
const matches = keywords.filter((kw) => text
|
|
253760
|
+
const matches = keywords.filter((kw) => matchesKeyword(text, kw));
|
|
253699
253761
|
if (matches.length >= thresholds.high) {
|
|
253700
253762
|
return {
|
|
253701
253763
|
name,
|
|
@@ -253731,7 +253793,7 @@ function scoreAgenticTask(text, keywords) {
|
|
|
253731
253793
|
let matchCount = 0;
|
|
253732
253794
|
const signals = [];
|
|
253733
253795
|
for (const keyword of keywords) {
|
|
253734
|
-
if (text
|
|
253796
|
+
if (matchesKeyword(text, keyword)) {
|
|
253735
253797
|
matchCount++;
|
|
253736
253798
|
if (signals.length < 3) {
|
|
253737
253799
|
signals.push(keyword);
|
|
@@ -253878,9 +253940,7 @@ function classifyByRules(prompt, systemPrompt, estimatedTokens, config) {
|
|
|
253878
253940
|
const w = weights[d.name] ?? 0;
|
|
253879
253941
|
weightedScore += d.score * w;
|
|
253880
253942
|
}
|
|
253881
|
-
const reasoningMatches = config.reasoningKeywords.filter(
|
|
253882
|
-
(kw) => userText.includes(kw.toLowerCase())
|
|
253883
|
-
);
|
|
253943
|
+
const reasoningMatches = config.reasoningKeywords.filter((kw) => matchesKeyword(userText, kw));
|
|
253884
253944
|
if (reasoningMatches.length >= 2) {
|
|
253885
253945
|
const confidence2 = calibrateConfidence(
|
|
253886
253946
|
Math.max(weightedScore, 0.3),
|
|
@@ -253945,7 +254005,7 @@ function selectModel(tier, confidence, method, reasoning, tierConfigs, modelPric
|
|
|
253945
254005
|
const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice;
|
|
253946
254006
|
const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice;
|
|
253947
254007
|
const baselineCost = baselineInput + baselineOutput;
|
|
253948
|
-
const savings = routingProfile === "premium" ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
|
|
254008
|
+
const savings = routingProfile === "premium" || pricing === void 0 ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
|
|
253949
254009
|
return {
|
|
253950
254010
|
model,
|
|
253951
254011
|
tier,
|
|
@@ -254025,6 +254085,21 @@ function filterCandidatesByCapacity(models, estimatedInputTokens, requestedOutpu
|
|
|
254025
254085
|
});
|
|
254026
254086
|
return filtered;
|
|
254027
254087
|
}
|
|
254088
|
+
var CJK_CHARS = /[ -ヿ㐀-䶿一-鿿가-豈--]/g;
|
|
254089
|
+
function estimateTokens(text) {
|
|
254090
|
+
if (text.length === 0) return 0;
|
|
254091
|
+
const cjk = text.match(CJK_CHARS)?.length ?? 0;
|
|
254092
|
+
return cjk + Math.ceil((text.length - cjk) / 4);
|
|
254093
|
+
}
|
|
254094
|
+
function scanLimit(promptTruncationChars) {
|
|
254095
|
+
return Math.max(1, Math.min(8e3, promptTruncationChars));
|
|
254096
|
+
}
|
|
254097
|
+
function sampleForScan(value, limit) {
|
|
254098
|
+
if (value.length <= limit) return value;
|
|
254099
|
+
const prefixLength = Math.ceil(limit / 2);
|
|
254100
|
+
return `${value.slice(0, prefixLength)}
|
|
254101
|
+
${value.slice(-(limit - prefixLength))}`;
|
|
254102
|
+
}
|
|
254028
254103
|
function applyPromotions(tierConfigs, promotions, profile, now2 = /* @__PURE__ */ new Date()) {
|
|
254029
254104
|
if (!promotions || promotions.length === 0) return tierConfigs;
|
|
254030
254105
|
let result = tierConfigs;
|
|
@@ -254067,16 +254142,10 @@ var RulesStrategy = class {
|
|
|
254067
254142
|
route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
254068
254143
|
const { config, modelPricing } = options;
|
|
254069
254144
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
254070
|
-
const estimatedTokens =
|
|
254071
|
-
const
|
|
254072
|
-
const
|
|
254073
|
-
|
|
254074
|
-
const prefixLength = Math.ceil(scanLimit / 2);
|
|
254075
|
-
return `${value.slice(0, prefixLength)}
|
|
254076
|
-
${value.slice(-(scanLimit - prefixLength))}`;
|
|
254077
|
-
};
|
|
254078
|
-
const scannedPrompt = sample(prompt);
|
|
254079
|
-
const scannedSystemPrompt = systemPrompt ? sample(systemPrompt) : void 0;
|
|
254145
|
+
const estimatedTokens = estimateTokens(fullText);
|
|
254146
|
+
const limit = scanLimit(config.classifier.promptTruncationChars);
|
|
254147
|
+
const scannedPrompt = sampleForScan(prompt, limit);
|
|
254148
|
+
const scannedSystemPrompt = systemPrompt ? sampleForScan(systemPrompt, limit) : void 0;
|
|
254080
254149
|
const ruleResult = classifyByRules(
|
|
254081
254150
|
scannedPrompt,
|
|
254082
254151
|
scannedSystemPrompt,
|
|
@@ -254130,7 +254199,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
254130
254199
|
);
|
|
254131
254200
|
return { ...decision2, tierConfigs, profile };
|
|
254132
254201
|
}
|
|
254133
|
-
const hasStructuredOutput = options.requiresStructuredOutput === true
|
|
254202
|
+
const hasStructuredOutput = options.requiresStructuredOutput === true;
|
|
254134
254203
|
let tier;
|
|
254135
254204
|
let confidence;
|
|
254136
254205
|
const method = "rules";
|
|
@@ -255383,16 +255452,10 @@ function likelyNeedsParallelToolCalls(prompt, needsTools, toolCount, toolNames)
|
|
|
255383
255452
|
}
|
|
255384
255453
|
function classifyTask(prompt, systemPrompt, options) {
|
|
255385
255454
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
255386
|
-
const estimatedInputTokens =
|
|
255387
|
-
const
|
|
255388
|
-
const
|
|
255389
|
-
|
|
255390
|
-
const prefixLength = Math.ceil(scanLimit / 2);
|
|
255391
|
-
return `${value.slice(0, prefixLength)}
|
|
255392
|
-
${value.slice(-(scanLimit - prefixLength))}`;
|
|
255393
|
-
};
|
|
255394
|
-
const scannedPrompt = sample(prompt);
|
|
255395
|
-
const scannedSystemPrompt = sample(systemPrompt ?? "");
|
|
255455
|
+
const estimatedInputTokens = estimateTokens(fullText);
|
|
255456
|
+
const limit = scanLimit(options.config.classifier.promptTruncationChars);
|
|
255457
|
+
const scannedPrompt = sampleForScan(prompt, limit);
|
|
255458
|
+
const scannedSystemPrompt = sampleForScan(systemPrompt ?? "", limit);
|
|
255396
255459
|
const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`;
|
|
255397
255460
|
const text = scannedPrompt.toLowerCase();
|
|
255398
255461
|
const explicitCodeSignal = /```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(
|
|
@@ -255404,7 +255467,9 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
255404
255467
|
const nativeCodeSignal = /\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test(
|
|
255405
255468
|
scannedPrompt
|
|
255406
255469
|
);
|
|
255407
|
-
const
|
|
255470
|
+
const errorClassSignal = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt);
|
|
255471
|
+
const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal;
|
|
255472
|
+
const codeArtifact = /```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt) || codeConstructSignal || nativeCodeSignal || errorClassSignal;
|
|
255408
255473
|
const toolsAvailable = options.hasTools ?? false;
|
|
255409
255474
|
const needsTools = options.requiresTools ?? (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt));
|
|
255410
255475
|
const likelyParallelToolCalls = likelyNeedsParallelToolCalls(
|
|
@@ -255476,10 +255541,10 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
255476
255541
|
const needsVision = options.hasVision ?? false;
|
|
255477
255542
|
const needsStructuredOutput = options.requiresStructuredOutput ?? false;
|
|
255478
255543
|
const latencySensitive = /\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test(
|
|
255479
|
-
|
|
255544
|
+
scannedPrompt
|
|
255480
255545
|
);
|
|
255481
255546
|
const highStakes = /\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test(
|
|
255482
|
-
|
|
255547
|
+
scannedPrompt
|
|
255483
255548
|
);
|
|
255484
255549
|
const terminalToolSignal = normalizedToolNames.some(
|
|
255485
255550
|
(name) => /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name)
|
|
@@ -255515,7 +255580,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
255515
255580
|
);
|
|
255516
255581
|
const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal);
|
|
255517
255582
|
const implicitTerminalCode = needsTools && terminalToolSignal && agentRisk === "standard" && !highStakes && !complexTerminalOperation && numberedSteps < 3 && prompt.length <= 1e3 && simpleTerminalArtifact;
|
|
255518
|
-
const language = /[\u3400-\u9fff]/.test(
|
|
255583
|
+
const language = /[\u3400-\u9fff]/.test(scannedPrompt) ? "zh" : "other";
|
|
255519
255584
|
const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim) ?? []).length;
|
|
255520
255585
|
const numericSignals = (scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g) ?? []).length;
|
|
255521
255586
|
const compactMathProblem = !hasCode && prompt.length < 2500 && numericSignals >= 2 && (/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test(
|
|
@@ -255530,7 +255595,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
255530
255595
|
else if (needsTools) taskType = "tool_agent";
|
|
255531
255596
|
else if (multipleChoiceSignals >= 3) taskType = "reasoning_mcq";
|
|
255532
255597
|
else if (compactMathProblem) taskType = "reasoning_math";
|
|
255533
|
-
else if (/\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text))
|
|
255598
|
+
else if (errorClassSignal || /\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text))
|
|
255534
255599
|
taskType = "debug";
|
|
255535
255600
|
else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite|重构|实现|修改)\b/i.test(text))
|
|
255536
255601
|
taskType = "code_edit";
|
|
@@ -255556,7 +255621,8 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
255556
255621
|
agentRisk,
|
|
255557
255622
|
terminalToolSignal,
|
|
255558
255623
|
terminalSafetySensitive,
|
|
255559
|
-
implicitTerminalCode
|
|
255624
|
+
implicitTerminalCode,
|
|
255625
|
+
codeArtifact
|
|
255560
255626
|
};
|
|
255561
255627
|
}
|
|
255562
255628
|
function affinity(modelId, task, language = "other", agentDomain = "other", deepWebResearch = false, agentRisk = "standard", terminalToolSignal = false, terminalSafetySensitive = false) {
|
|
@@ -255959,15 +256025,17 @@ function profileScore(modelId, options, now2) {
|
|
|
255959
256025
|
}
|
|
255960
256026
|
var PortfolioStrategy = class {
|
|
255961
256027
|
name = "portfolio";
|
|
256028
|
+
// Rules set the capability tier; the strategy is stateless, so one instance serves every request.
|
|
256029
|
+
rules = new RulesStrategy();
|
|
255962
256030
|
route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
255963
256031
|
const features = classifyTask(prompt, systemPrompt, options);
|
|
255964
|
-
const base4 =
|
|
256032
|
+
const base4 = this.rules.route(prompt, systemPrompt, maxOutputTokens, {
|
|
255965
256033
|
...options,
|
|
255966
256034
|
requiresTools: features.needsTools
|
|
255967
256035
|
});
|
|
255968
256036
|
const tierConfigs = base4.tierConfigs;
|
|
255969
256037
|
if (!tierConfigs) return base4;
|
|
255970
|
-
const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base4.tier === "SIMPLE" || base4.tier === "MEDIUM") ? "REASONING" : base4.tier;
|
|
256038
|
+
const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base4.tier === "SIMPLE" || base4.tier === "MEDIUM") ? "REASONING" : (features.taskType === "debug" || features.taskType === "code_edit") && features.codeArtifact && base4.tier === "SIMPLE" ? "MEDIUM" : base4.tier;
|
|
255971
256039
|
const tierConfig = tierConfigs[targetTier];
|
|
255972
256040
|
const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : [];
|
|
255973
256041
|
const unavailable = new Set(options.unavailableModels ?? []);
|
|
@@ -255985,10 +256053,10 @@ var PortfolioStrategy = class {
|
|
|
255985
256053
|
].filter(
|
|
255986
256054
|
(model2) => typeof model2 === "string" && model2.length > 0 && !unavailable.has(model2)
|
|
255987
256055
|
);
|
|
255988
|
-
const eligible =
|
|
255989
|
-
(model2) => isEligible(model2, features, maxOutputTokens, options)
|
|
256056
|
+
const eligible = new Set(
|
|
256057
|
+
chain3.filter((model2) => isEligible(model2, features, maxOutputTokens, options))
|
|
255990
256058
|
);
|
|
255991
|
-
const eligibleCandidates = eligible.
|
|
256059
|
+
const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain3;
|
|
255992
256060
|
if (eligibleCandidates.length === 0) return base4;
|
|
255993
256061
|
const profileName = options.routingProfile === "eco" ? "eco" : options.routingProfile === "premium" ? "premium" : "auto";
|
|
255994
256062
|
const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS;
|
|
@@ -256023,11 +256091,11 @@ var PortfolioStrategy = class {
|
|
|
256023
256091
|
const rankedEntries = candidates.map((model2, index2) => {
|
|
256024
256092
|
const cost = estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens);
|
|
256025
256093
|
const costScore = Number.isFinite(cost) && maxCost > minCost ? 1 - (cost - minCost) / (maxCost - minCost) : 0.5;
|
|
256026
|
-
const capabilityScore =
|
|
256094
|
+
const capabilityScore = eligible.has(model2) ? 1 : 0;
|
|
256027
256095
|
const profile = profileScore(model2, options, now2);
|
|
256028
256096
|
const observedQuality = profile?.quality === void 0 ? getAffinity(model2) : getAffinity(model2) * (1 - profile.freshness) + profile.quality * profile.freshness;
|
|
256029
|
-
const observedSpeed = profile ? profile.speed * profile.freshness : 0.5;
|
|
256030
|
-
const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness : 0.5;
|
|
256097
|
+
const observedSpeed = profile ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5;
|
|
256098
|
+
const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5;
|
|
256031
256099
|
const observedReliability = profile ? profile.reliability * profile.freshness + (1 - profile.freshness) : 1;
|
|
256032
256100
|
const legacyScore = 1 - index2 / Math.max(1, candidates.length - 1);
|
|
256033
256101
|
const qualityWeight = profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0);
|
|
@@ -260814,7 +260882,7 @@ function resolveKimiTool(prose, blob, tools) {
|
|
|
260814
260882
|
const blobKeys = Object.keys(blob);
|
|
260815
260883
|
if (prose) {
|
|
260816
260884
|
const named = tools.filter(
|
|
260817
|
-
(t) => new RegExp(`(?:^|[^A-Za-z0-9_])${
|
|
260885
|
+
(t) => new RegExp(`(?:^|[^A-Za-z0-9_])${escapeRegExp3(t.name)}(?:[^A-Za-z0-9_]|$)`).test(prose)
|
|
260818
260886
|
);
|
|
260819
260887
|
if (named.length === 1) return named[0].name;
|
|
260820
260888
|
}
|
|
@@ -260825,7 +260893,7 @@ function resolveKimiTool(prose, blob, tools) {
|
|
|
260825
260893
|
);
|
|
260826
260894
|
return sigMatches.length === 1 ? sigMatches[0].name : null;
|
|
260827
260895
|
}
|
|
260828
|
-
function
|
|
260896
|
+
function escapeRegExp3(s3) {
|
|
260829
260897
|
return s3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
260830
260898
|
}
|
|
260831
260899
|
function extractKimiCalls(content, tools) {
|
package/dist/router/index.js
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
import { createRequire as __blockrun_createRequire } from 'node:module'; const require = __blockrun_createRequire(import.meta.url);
|
|
2
2
|
|
|
3
3
|
// node_modules/@blockrun/router-core/dist/index.js
|
|
4
|
+
var UNSEGMENTED_SCRIPT = /[-ۿ -ヿ㐀-䶿一-鿿가-豈--]/;
|
|
5
|
+
var WORD_CHAR = /[\p{L}\p{N}]/u;
|
|
6
|
+
var ASCII_PHRASE = /^[a-z0-9' -]+$/;
|
|
7
|
+
var SEGMENTED_WORD_CHAR = "\\p{Script=Latin}\\p{Script=Cyrillic}\\p{Script=Greek}\\p{N}";
|
|
8
|
+
var BOUNDARY_BEFORE = `(?<![${SEGMENTED_WORD_CHAR}])`;
|
|
9
|
+
var BOUNDARY_AFTER = `(?![${SEGMENTED_WORD_CHAR}])`;
|
|
10
|
+
var BOUNDED_LAST_WORD_LENGTH = 6;
|
|
11
|
+
var SHORT_SUFFIXES = "(?:s|ed|ing)?";
|
|
12
|
+
var SIBILANT_PLURAL = "es";
|
|
13
|
+
var MID_SUFFIXES = "(?:s|es|ed|d|ing|er|ers|ly|ment|ments|ation|ations|e|en|n|a|as|o|os|em|et|ung|ungen)?";
|
|
14
|
+
var DROPPED_E_SUFFIXES = "(?:ing|ed|es|er|ers|ation|ations)";
|
|
15
|
+
var DOUBLED_CONSONANT_SUFFIXES = "(?:ing|ed|er|ers)";
|
|
16
|
+
var matcherCache = /* @__PURE__ */ new Map();
|
|
17
|
+
function escapeRegExp(value) {
|
|
18
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
19
|
+
}
|
|
20
|
+
function keywordMatcher(keyword) {
|
|
21
|
+
const cached = matcherCache.get(keyword);
|
|
22
|
+
if (cached) return cached;
|
|
23
|
+
const kw = keyword.toLowerCase();
|
|
24
|
+
let matcher;
|
|
25
|
+
if (UNSEGMENTED_SCRIPT.test(kw) || kw.length === 0) {
|
|
26
|
+
matcher = { needle: kw, pattern: null };
|
|
27
|
+
} else {
|
|
28
|
+
const lead = WORD_CHAR.test(kw[0]) ? BOUNDARY_BEFORE : "";
|
|
29
|
+
const escaped = escapeRegExp(kw);
|
|
30
|
+
let body = escaped;
|
|
31
|
+
let trail = "";
|
|
32
|
+
let needle = kw;
|
|
33
|
+
const lastWord = kw.slice(kw.lastIndexOf(" ") + 1);
|
|
34
|
+
if (WORD_CHAR.test(kw[kw.length - 1]) && ASCII_PHRASE.test(kw) && lastWord.length <= BOUNDED_LAST_WORD_LENGTH) {
|
|
35
|
+
const forms = [];
|
|
36
|
+
if (/\d$/.test(kw)) {
|
|
37
|
+
forms.push(escaped);
|
|
38
|
+
} else if (lastWord.length <= 3) {
|
|
39
|
+
forms.push(`${escaped}${SHORT_SUFFIXES}`);
|
|
40
|
+
if (/(?:x|s|z|ch|sh)$/.test(kw)) forms.push(`${escaped}${SIBILANT_PLURAL}`);
|
|
41
|
+
} else {
|
|
42
|
+
forms.push(`${escaped}${MID_SUFFIXES}`);
|
|
43
|
+
if (kw.endsWith("e")) {
|
|
44
|
+
forms.push(`${escaped.slice(0, -1)}${DROPPED_E_SUFFIXES}`);
|
|
45
|
+
needle = kw.slice(0, -1);
|
|
46
|
+
} else if (kw.endsWith("y")) {
|
|
47
|
+
forms.push(`${escaped.slice(0, -1)}(?:ies|ied)`);
|
|
48
|
+
needle = kw.slice(0, -1);
|
|
49
|
+
} else if (/[aeiou][bdgmnprt]$/.test(kw)) {
|
|
50
|
+
forms.push(`${escaped}${kw[kw.length - 1]}${DOUBLED_CONSONANT_SUFFIXES}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
body = `(?:${forms.join("|")})`;
|
|
54
|
+
trail = BOUNDARY_AFTER;
|
|
55
|
+
}
|
|
56
|
+
matcher = { needle, pattern: new RegExp(`${lead}${body}${trail}`, "u") };
|
|
57
|
+
}
|
|
58
|
+
matcherCache.set(keyword, matcher);
|
|
59
|
+
return matcher;
|
|
60
|
+
}
|
|
61
|
+
function matchesKeyword(text, keyword) {
|
|
62
|
+
const { needle, pattern } = keywordMatcher(keyword);
|
|
63
|
+
if (!text.includes(needle)) return false;
|
|
64
|
+
return pattern === null ? true : pattern.test(text);
|
|
65
|
+
}
|
|
4
66
|
function scoreTokenCount(estimatedTokens, thresholds) {
|
|
5
67
|
if (estimatedTokens < thresholds.simple) {
|
|
6
68
|
return { name: "tokenCount", score: -1, signal: `short (${estimatedTokens} tokens)` };
|
|
@@ -11,7 +73,7 @@ function scoreTokenCount(estimatedTokens, thresholds) {
|
|
|
11
73
|
return { name: "tokenCount", score: 0, signal: null };
|
|
12
74
|
}
|
|
13
75
|
function scoreKeywordMatch(text, keywords, name, signalLabel, thresholds, scores) {
|
|
14
|
-
const matches = keywords.filter((kw) => text
|
|
76
|
+
const matches = keywords.filter((kw) => matchesKeyword(text, kw));
|
|
15
77
|
if (matches.length >= thresholds.high) {
|
|
16
78
|
return {
|
|
17
79
|
name,
|
|
@@ -47,7 +109,7 @@ function scoreAgenticTask(text, keywords) {
|
|
|
47
109
|
let matchCount = 0;
|
|
48
110
|
const signals = [];
|
|
49
111
|
for (const keyword of keywords) {
|
|
50
|
-
if (text
|
|
112
|
+
if (matchesKeyword(text, keyword)) {
|
|
51
113
|
matchCount++;
|
|
52
114
|
if (signals.length < 3) {
|
|
53
115
|
signals.push(keyword);
|
|
@@ -194,9 +256,7 @@ function classifyByRules(prompt, systemPrompt, estimatedTokens, config) {
|
|
|
194
256
|
const w = weights[d.name] ?? 0;
|
|
195
257
|
weightedScore += d.score * w;
|
|
196
258
|
}
|
|
197
|
-
const reasoningMatches = config.reasoningKeywords.filter(
|
|
198
|
-
(kw) => userText.includes(kw.toLowerCase())
|
|
199
|
-
);
|
|
259
|
+
const reasoningMatches = config.reasoningKeywords.filter((kw) => matchesKeyword(userText, kw));
|
|
200
260
|
if (reasoningMatches.length >= 2) {
|
|
201
261
|
const confidence2 = calibrateConfidence(
|
|
202
262
|
Math.max(weightedScore, 0.3),
|
|
@@ -261,7 +321,7 @@ function selectModel(tier, confidence, method, reasoning, tierConfigs, modelPric
|
|
|
261
321
|
const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice;
|
|
262
322
|
const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice;
|
|
263
323
|
const baselineCost = baselineInput + baselineOutput;
|
|
264
|
-
const savings = routingProfile === "premium" ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
|
|
324
|
+
const savings = routingProfile === "premium" || pricing === void 0 ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
|
|
265
325
|
return {
|
|
266
326
|
model,
|
|
267
327
|
tier,
|
|
@@ -341,6 +401,21 @@ function filterCandidatesByCapacity(models, estimatedInputTokens, requestedOutpu
|
|
|
341
401
|
});
|
|
342
402
|
return filtered;
|
|
343
403
|
}
|
|
404
|
+
var CJK_CHARS = /[ -ヿ㐀-䶿一-鿿가-豈--]/g;
|
|
405
|
+
function estimateTokens(text) {
|
|
406
|
+
if (text.length === 0) return 0;
|
|
407
|
+
const cjk = text.match(CJK_CHARS)?.length ?? 0;
|
|
408
|
+
return cjk + Math.ceil((text.length - cjk) / 4);
|
|
409
|
+
}
|
|
410
|
+
function scanLimit(promptTruncationChars) {
|
|
411
|
+
return Math.max(1, Math.min(8e3, promptTruncationChars));
|
|
412
|
+
}
|
|
413
|
+
function sampleForScan(value, limit) {
|
|
414
|
+
if (value.length <= limit) return value;
|
|
415
|
+
const prefixLength = Math.ceil(limit / 2);
|
|
416
|
+
return `${value.slice(0, prefixLength)}
|
|
417
|
+
${value.slice(-(limit - prefixLength))}`;
|
|
418
|
+
}
|
|
344
419
|
function applyPromotions(tierConfigs, promotions, profile, now = /* @__PURE__ */ new Date()) {
|
|
345
420
|
if (!promotions || promotions.length === 0) return tierConfigs;
|
|
346
421
|
let result = tierConfigs;
|
|
@@ -383,16 +458,10 @@ var RulesStrategy = class {
|
|
|
383
458
|
route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
384
459
|
const { config, modelPricing } = options;
|
|
385
460
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
386
|
-
const estimatedTokens =
|
|
387
|
-
const
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
const prefixLength = Math.ceil(scanLimit / 2);
|
|
391
|
-
return `${value.slice(0, prefixLength)}
|
|
392
|
-
${value.slice(-(scanLimit - prefixLength))}`;
|
|
393
|
-
};
|
|
394
|
-
const scannedPrompt = sample(prompt);
|
|
395
|
-
const scannedSystemPrompt = systemPrompt ? sample(systemPrompt) : void 0;
|
|
461
|
+
const estimatedTokens = estimateTokens(fullText);
|
|
462
|
+
const limit = scanLimit(config.classifier.promptTruncationChars);
|
|
463
|
+
const scannedPrompt = sampleForScan(prompt, limit);
|
|
464
|
+
const scannedSystemPrompt = systemPrompt ? sampleForScan(systemPrompt, limit) : void 0;
|
|
396
465
|
const ruleResult = classifyByRules(
|
|
397
466
|
scannedPrompt,
|
|
398
467
|
scannedSystemPrompt,
|
|
@@ -446,7 +515,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
446
515
|
);
|
|
447
516
|
return { ...decision2, tierConfigs, profile };
|
|
448
517
|
}
|
|
449
|
-
const hasStructuredOutput = options.requiresStructuredOutput === true
|
|
518
|
+
const hasStructuredOutput = options.requiresStructuredOutput === true;
|
|
450
519
|
let tier;
|
|
451
520
|
let confidence;
|
|
452
521
|
const method = "rules";
|
|
@@ -1699,16 +1768,10 @@ function likelyNeedsParallelToolCalls(prompt, needsTools, toolCount, toolNames)
|
|
|
1699
1768
|
}
|
|
1700
1769
|
function classifyTask(prompt, systemPrompt, options) {
|
|
1701
1770
|
const fullText = `${systemPrompt ?? ""} ${prompt}`;
|
|
1702
|
-
const estimatedInputTokens =
|
|
1703
|
-
const
|
|
1704
|
-
const
|
|
1705
|
-
|
|
1706
|
-
const prefixLength = Math.ceil(scanLimit / 2);
|
|
1707
|
-
return `${value.slice(0, prefixLength)}
|
|
1708
|
-
${value.slice(-(scanLimit - prefixLength))}`;
|
|
1709
|
-
};
|
|
1710
|
-
const scannedPrompt = sample(prompt);
|
|
1711
|
-
const scannedSystemPrompt = sample(systemPrompt ?? "");
|
|
1771
|
+
const estimatedInputTokens = estimateTokens(fullText);
|
|
1772
|
+
const limit = scanLimit(options.config.classifier.promptTruncationChars);
|
|
1773
|
+
const scannedPrompt = sampleForScan(prompt, limit);
|
|
1774
|
+
const scannedSystemPrompt = sampleForScan(systemPrompt ?? "", limit);
|
|
1712
1775
|
const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`;
|
|
1713
1776
|
const text = scannedPrompt.toLowerCase();
|
|
1714
1777
|
const explicitCodeSignal = /```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(
|
|
@@ -1720,7 +1783,9 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
1720
1783
|
const nativeCodeSignal = /\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test(
|
|
1721
1784
|
scannedPrompt
|
|
1722
1785
|
);
|
|
1723
|
-
const
|
|
1786
|
+
const errorClassSignal = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt);
|
|
1787
|
+
const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal;
|
|
1788
|
+
const codeArtifact = /```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt) || codeConstructSignal || nativeCodeSignal || errorClassSignal;
|
|
1724
1789
|
const toolsAvailable = options.hasTools ?? false;
|
|
1725
1790
|
const needsTools = options.requiresTools ?? (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt));
|
|
1726
1791
|
const likelyParallelToolCalls = likelyNeedsParallelToolCalls(
|
|
@@ -1792,10 +1857,10 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
1792
1857
|
const needsVision = options.hasVision ?? false;
|
|
1793
1858
|
const needsStructuredOutput = options.requiresStructuredOutput ?? false;
|
|
1794
1859
|
const latencySensitive = /\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test(
|
|
1795
|
-
|
|
1860
|
+
scannedPrompt
|
|
1796
1861
|
);
|
|
1797
1862
|
const highStakes = /\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test(
|
|
1798
|
-
|
|
1863
|
+
scannedPrompt
|
|
1799
1864
|
);
|
|
1800
1865
|
const terminalToolSignal = normalizedToolNames.some(
|
|
1801
1866
|
(name) => /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name)
|
|
@@ -1831,7 +1896,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
1831
1896
|
);
|
|
1832
1897
|
const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal);
|
|
1833
1898
|
const implicitTerminalCode = needsTools && terminalToolSignal && agentRisk === "standard" && !highStakes && !complexTerminalOperation && numberedSteps < 3 && prompt.length <= 1e3 && simpleTerminalArtifact;
|
|
1834
|
-
const language = /[\u3400-\u9fff]/.test(
|
|
1899
|
+
const language = /[\u3400-\u9fff]/.test(scannedPrompt) ? "zh" : "other";
|
|
1835
1900
|
const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim) ?? []).length;
|
|
1836
1901
|
const numericSignals = (scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g) ?? []).length;
|
|
1837
1902
|
const compactMathProblem = !hasCode && prompt.length < 2500 && numericSignals >= 2 && (/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test(
|
|
@@ -1846,7 +1911,7 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
1846
1911
|
else if (needsTools) taskType = "tool_agent";
|
|
1847
1912
|
else if (multipleChoiceSignals >= 3) taskType = "reasoning_mcq";
|
|
1848
1913
|
else if (compactMathProblem) taskType = "reasoning_math";
|
|
1849
|
-
else if (/\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text))
|
|
1914
|
+
else if (errorClassSignal || /\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text))
|
|
1850
1915
|
taskType = "debug";
|
|
1851
1916
|
else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite|重构|实现|修改)\b/i.test(text))
|
|
1852
1917
|
taskType = "code_edit";
|
|
@@ -1872,7 +1937,8 @@ ${value.slice(-(scanLimit - prefixLength))}`;
|
|
|
1872
1937
|
agentRisk,
|
|
1873
1938
|
terminalToolSignal,
|
|
1874
1939
|
terminalSafetySensitive,
|
|
1875
|
-
implicitTerminalCode
|
|
1940
|
+
implicitTerminalCode,
|
|
1941
|
+
codeArtifact
|
|
1876
1942
|
};
|
|
1877
1943
|
}
|
|
1878
1944
|
function affinity(modelId, task, language = "other", agentDomain = "other", deepWebResearch = false, agentRisk = "standard", terminalToolSignal = false, terminalSafetySensitive = false) {
|
|
@@ -2275,15 +2341,17 @@ function profileScore(modelId, options, now) {
|
|
|
2275
2341
|
}
|
|
2276
2342
|
var PortfolioStrategy = class {
|
|
2277
2343
|
name = "portfolio";
|
|
2344
|
+
// Rules set the capability tier; the strategy is stateless, so one instance serves every request.
|
|
2345
|
+
rules = new RulesStrategy();
|
|
2278
2346
|
route(prompt, systemPrompt, maxOutputTokens, options) {
|
|
2279
2347
|
const features = classifyTask(prompt, systemPrompt, options);
|
|
2280
|
-
const base =
|
|
2348
|
+
const base = this.rules.route(prompt, systemPrompt, maxOutputTokens, {
|
|
2281
2349
|
...options,
|
|
2282
2350
|
requiresTools: features.needsTools
|
|
2283
2351
|
});
|
|
2284
2352
|
const tierConfigs = base.tierConfigs;
|
|
2285
2353
|
if (!tierConfigs) return base;
|
|
2286
|
-
const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base.tier === "SIMPLE" || base.tier === "MEDIUM") ? "REASONING" : base.tier;
|
|
2354
|
+
const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base.tier === "SIMPLE" || base.tier === "MEDIUM") ? "REASONING" : (features.taskType === "debug" || features.taskType === "code_edit") && features.codeArtifact && base.tier === "SIMPLE" ? "MEDIUM" : base.tier;
|
|
2287
2355
|
const tierConfig = tierConfigs[targetTier];
|
|
2288
2356
|
const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : [];
|
|
2289
2357
|
const unavailable = new Set(options.unavailableModels ?? []);
|
|
@@ -2301,10 +2369,10 @@ var PortfolioStrategy = class {
|
|
|
2301
2369
|
].filter(
|
|
2302
2370
|
(model2) => typeof model2 === "string" && model2.length > 0 && !unavailable.has(model2)
|
|
2303
2371
|
);
|
|
2304
|
-
const eligible =
|
|
2305
|
-
(model2) => isEligible(model2, features, maxOutputTokens, options)
|
|
2372
|
+
const eligible = new Set(
|
|
2373
|
+
chain.filter((model2) => isEligible(model2, features, maxOutputTokens, options))
|
|
2306
2374
|
);
|
|
2307
|
-
const eligibleCandidates = eligible.
|
|
2375
|
+
const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain;
|
|
2308
2376
|
if (eligibleCandidates.length === 0) return base;
|
|
2309
2377
|
const profileName = options.routingProfile === "eco" ? "eco" : options.routingProfile === "premium" ? "premium" : "auto";
|
|
2310
2378
|
const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS;
|
|
@@ -2339,11 +2407,11 @@ var PortfolioStrategy = class {
|
|
|
2339
2407
|
const rankedEntries = candidates.map((model2, index) => {
|
|
2340
2408
|
const cost = estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens);
|
|
2341
2409
|
const costScore = Number.isFinite(cost) && maxCost > minCost ? 1 - (cost - minCost) / (maxCost - minCost) : 0.5;
|
|
2342
|
-
const capabilityScore =
|
|
2410
|
+
const capabilityScore = eligible.has(model2) ? 1 : 0;
|
|
2343
2411
|
const profile = profileScore(model2, options, now);
|
|
2344
2412
|
const observedQuality = profile?.quality === void 0 ? getAffinity(model2) : getAffinity(model2) * (1 - profile.freshness) + profile.quality * profile.freshness;
|
|
2345
|
-
const observedSpeed = profile ? profile.speed * profile.freshness : 0.5;
|
|
2346
|
-
const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness : 0.5;
|
|
2413
|
+
const observedSpeed = profile ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5;
|
|
2414
|
+
const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5;
|
|
2347
2415
|
const observedReliability = profile ? profile.reliability * profile.freshness + (1 - profile.freshness) : 1;
|
|
2348
2416
|
const legacyScore = 1 - index / Math.max(1, candidates.length - 1);
|
|
2349
2417
|
const qualityWeight = profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0);
|
|
@@ -3914,6 +3982,7 @@ export {
|
|
|
3914
3982
|
applyUnavailableModels,
|
|
3915
3983
|
calculateModelCost,
|
|
3916
3984
|
classifyByRules,
|
|
3985
|
+
estimateTokens,
|
|
3917
3986
|
filterByExcludeList,
|
|
3918
3987
|
filterByToolCalling,
|
|
3919
3988
|
filterByVision,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blockrun/clawrouter",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.292",
|
|
4
4
|
"description": "Smart LLM router — save 84% on inference costs. 88 models (7 free). Pay by credit card (API key) or USDC (x402 wallet).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -116,7 +116,7 @@
|
|
|
116
116
|
},
|
|
117
117
|
"devDependencies": {
|
|
118
118
|
"@blockrun/model-catalog": "https://codeload.github.com/BlockRunAI/model-catalog/tar.gz/465c45941fb8ea9d6858fe8402abc8ba8934be90",
|
|
119
|
-
"@blockrun/router-core": "https://codeload.github.com/BlockRunAI/router-core/tar.gz/
|
|
119
|
+
"@blockrun/router-core": "https://codeload.github.com/BlockRunAI/router-core/tar.gz/65a92c85ea1f187a64e7611302ef6add236b0cba",
|
|
120
120
|
"@eslint/js": "^10.0.1",
|
|
121
121
|
"eslint": "^10.2.0",
|
|
122
122
|
"openclaw": "^2026.7.2-beta.7",
|