@blockrun/clawrouter 0.12.291 → 0.12.293

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.
@@ -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.includes(kw.toLowerCase()));
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.includes(keyword.toLowerCase())) {
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 = Math.ceil(fullText.length / 4);
387
- const scanLimit = Math.max(1, Math.min(8e3, config.classifier.promptTruncationChars));
388
- const sample = (value) => {
389
- if (value.length <= scanLimit) return value;
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 || (scannedSystemPrompt ? /json|structured|schema/i.test(scannedSystemPrompt) : false);
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 = Math.ceil(fullText.length / 4);
1703
- const scanLimit = Math.max(1, Math.min(8e3, options.config.classifier.promptTruncationChars));
1704
- const sample = (value) => {
1705
- if (value.length <= scanLimit) return value;
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 hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal;
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
- scannedFullText
1860
+ scannedPrompt
1796
1861
  );
1797
1862
  const highStakes = /\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test(
1798
- scannedFullText
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(scannedFullText) ? "zh" : "other";
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 = new RulesStrategy().route(prompt, systemPrompt, maxOutputTokens, {
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 = chain.filter(
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.length > 0 ? eligible : chain;
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 = isEligible(model2, features, maxOutputTokens, options) ? 1 : 0;
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.291",
3
+ "version": "0.12.293",
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",
@@ -92,7 +92,7 @@
92
92
  "@noble/hashes": "^2.2.0",
93
93
  "@polymarket/builder-relayer-client": "^0.0.10",
94
94
  "@polymarket/builder-signing-sdk": "0.0.8",
95
- "@polymarket/clob-client-v2": "1.0.8",
95
+ "@polymarket/clob-client-v2": "1.2.0",
96
96
  "@scure/bip32": "^2.0.1",
97
97
  "@scure/bip39": "^1.5.0",
98
98
  "@solana/kit": "^8.4.0",
@@ -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/27125a3dfe319a6f422a0c0f41bf1666b0dc61a9",
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",