@jsonstudio/llms 0.6.147 → 0.6.198

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.
Files changed (66) hide show
  1. package/dist/conversion/codecs/gemini-openai-codec.js +15 -1
  2. package/dist/conversion/compat/actions/auto-thinking.d.ts +6 -0
  3. package/dist/conversion/compat/actions/auto-thinking.js +25 -0
  4. package/dist/conversion/compat/actions/field-mapping.d.ts +14 -0
  5. package/dist/conversion/compat/actions/field-mapping.js +155 -0
  6. package/dist/conversion/compat/actions/qwen-transform.d.ts +3 -0
  7. package/dist/conversion/compat/actions/qwen-transform.js +209 -0
  8. package/dist/conversion/compat/actions/request-rules.d.ts +24 -0
  9. package/dist/conversion/compat/actions/request-rules.js +63 -0
  10. package/dist/conversion/compat/actions/response-blacklist.d.ts +14 -0
  11. package/dist/conversion/compat/actions/response-blacklist.js +85 -0
  12. package/dist/conversion/compat/actions/response-normalize.d.ts +5 -0
  13. package/dist/conversion/compat/actions/response-normalize.js +121 -0
  14. package/dist/conversion/compat/actions/response-validate.d.ts +5 -0
  15. package/dist/conversion/compat/actions/response-validate.js +76 -0
  16. package/dist/conversion/compat/actions/snapshot.d.ts +8 -0
  17. package/dist/conversion/compat/actions/snapshot.js +21 -0
  18. package/dist/conversion/compat/actions/tool-schema.d.ts +6 -0
  19. package/dist/conversion/compat/actions/tool-schema.js +91 -0
  20. package/dist/conversion/compat/actions/universal-shape-filter.d.ts +74 -0
  21. package/dist/conversion/compat/actions/universal-shape-filter.js +382 -0
  22. package/dist/conversion/compat/profiles/chat-glm.json +187 -13
  23. package/dist/conversion/compat/profiles/chat-iflow.json +194 -26
  24. package/dist/conversion/compat/profiles/chat-lmstudio.json +43 -35
  25. package/dist/conversion/compat/profiles/chat-qwen.json +20 -16
  26. package/dist/conversion/compat/profiles/responses-c4m.json +42 -42
  27. package/dist/conversion/hub/pipeline/compat/compat-engine.d.ts +7 -2
  28. package/dist/conversion/hub/pipeline/compat/compat-engine.js +429 -5
  29. package/dist/conversion/hub/pipeline/compat/compat-types.d.ts +47 -0
  30. package/dist/conversion/hub/pipeline/hub-pipeline.d.ts +2 -0
  31. package/dist/conversion/hub/pipeline/hub-pipeline.js +35 -1
  32. package/dist/conversion/hub/pipeline/stages/req_outbound/req_outbound_stage3_compat/index.js +2 -2
  33. package/dist/conversion/hub/pipeline/target-utils.js +3 -0
  34. package/dist/conversion/hub/response/response-runtime.js +23 -15
  35. package/dist/conversion/responses/responses-host-policy.d.ts +6 -0
  36. package/dist/conversion/responses/responses-host-policy.js +14 -0
  37. package/dist/conversion/responses/responses-openai-bridge.js +51 -2
  38. package/dist/conversion/shared/anthropic-message-utils.js +6 -0
  39. package/dist/conversion/shared/bridge-actions.js +1 -1
  40. package/dist/conversion/shared/bridge-policies.js +0 -1
  41. package/dist/conversion/shared/responses-conversation-store.js +3 -26
  42. package/dist/conversion/shared/responses-reasoning-registry.d.ts +4 -0
  43. package/dist/conversion/shared/responses-reasoning-registry.js +62 -1
  44. package/dist/conversion/shared/responses-response-utils.js +23 -1
  45. package/dist/conversion/shared/tool-canonicalizer.d.ts +2 -0
  46. package/dist/conversion/shared/tool-filter-pipeline.js +11 -0
  47. package/dist/router/virtual-router/bootstrap.js +239 -39
  48. package/dist/router/virtual-router/classifier.js +19 -51
  49. package/dist/router/virtual-router/context-advisor.d.ts +21 -0
  50. package/dist/router/virtual-router/context-advisor.js +76 -0
  51. package/dist/router/virtual-router/engine.d.ts +11 -27
  52. package/dist/router/virtual-router/engine.js +191 -396
  53. package/dist/router/virtual-router/features.js +24 -607
  54. package/dist/router/virtual-router/health-manager.js +2 -7
  55. package/dist/router/virtual-router/message-utils.d.ts +7 -0
  56. package/dist/router/virtual-router/message-utils.js +66 -0
  57. package/dist/router/virtual-router/provider-registry.js +6 -2
  58. package/dist/router/virtual-router/token-estimator.d.ts +2 -0
  59. package/dist/router/virtual-router/token-estimator.js +16 -0
  60. package/dist/router/virtual-router/token-file-scanner.d.ts +15 -0
  61. package/dist/router/virtual-router/token-file-scanner.js +56 -0
  62. package/dist/router/virtual-router/tool-signals.d.ts +13 -0
  63. package/dist/router/virtual-router/tool-signals.js +403 -0
  64. package/dist/router/virtual-router/types.d.ts +21 -7
  65. package/dist/router/virtual-router/types.js +1 -0
  66. package/package.json +2 -2
@@ -1,114 +1,15 @@
1
- import { countRequestTokens } from './token-counter.js';
1
+ import { detectExtendedThinkingKeyword, detectImageAttachment, detectKeyword, extractMessageText, getLatestMessageRole, getLatestUserMessage } from './message-utils.js';
2
+ import { detectCodingTool, detectLastAssistantToolCategory, detectVisionTool, detectWebTool, extractMeaningfulDeclaredToolNames } from './tool-signals.js';
3
+ import { computeRequestTokens } from './token-estimator.js';
2
4
  const THINKING_KEYWORDS = ['let me think', 'chain of thought', 'cot', 'reason step', 'deliberate'];
3
- const WEB_TOOL_KEYWORDS = ['websearch', 'web_search', 'web-search', 'webfetch', 'web_fetch', 'web_request', 'search_web', 'internet_search'];
4
- const READ_TOOL_EXACT = new Set([
5
- 'read_file',
6
- 'read_text',
7
- 'view_file',
8
- 'view_code',
9
- 'view_document',
10
- 'open_file',
11
- 'get_file',
12
- 'download_file',
13
- 'describe_current_request',
14
- 'list_dir',
15
- 'list_directory',
16
- 'list_files',
17
- 'list_documents',
18
- 'list_resources',
19
- 'search_files',
20
- 'find_files'
21
- ]);
22
- const WRITE_TOOL_EXACT = new Set([
23
- 'apply_patch',
24
- 'write_file',
25
- 'create_file',
26
- 'modify_file',
27
- 'edit_file',
28
- 'update_file',
29
- 'save_file',
30
- 'append_file',
31
- 'replace_file',
32
- 'delete_file',
33
- 'remove_file',
34
- 'rename_file',
35
- 'move_file',
36
- 'copy_file',
37
- 'mkdir',
38
- 'rmdir'
39
- ]);
40
- const SEARCH_TOOL_EXACT = new Set(['websearch', 'web_search', 'search_web', 'internet_search', 'webfetch', 'web_fetch']);
41
- const READ_TOOL_KEYWORDS = ['read', 'list', 'view', 'download', 'open', 'show', 'fetch', 'inspect'];
42
- const WRITE_TOOL_KEYWORDS = ['write', 'patch', 'modify', 'edit', 'create', 'update', 'append', 'replace', 'delete', 'remove'];
43
- const SEARCH_TOOL_KEYWORDS = ['search', 'websearch', 'web_fetch', 'webfetch', 'web-request', 'web_request', 'internet'];
44
- const SHELL_TOOL_NAMES = new Set(['shell_command', 'shell', 'bash']);
45
- const SHELL_HEREDOC_PATTERN = /<<\s*['"]?[a-z0-9_-]+/i;
46
- const COMMAND_DETAIL_MAX_LENGTH = 80;
47
- const TOOL_CATEGORY_PRIORITY = ['search', 'write', 'read', 'other'];
48
- const SHELL_WRITE_PATTERNS = [
49
- 'apply_patch',
50
- 'sed -i',
51
- 'perl -pi',
52
- 'tee ',
53
- 'cat <<',
54
- 'cat >',
55
- 'printf >',
56
- 'touch ',
57
- 'truncate',
58
- 'mkdir',
59
- 'mktemp',
60
- 'rmdir',
61
- 'rm ',
62
- 'rm-',
63
- 'unlink',
64
- 'mv ',
65
- 'cp ',
66
- 'ln -',
67
- 'chmod',
68
- 'chown',
69
- 'chgrp',
70
- 'tar ',
71
- 'git apply',
72
- 'git am',
73
- 'git checkout',
74
- 'git merge',
75
- 'patch <<'
76
- ];
77
- const SHELL_SEARCH_PATTERNS = [
78
- 'rg ',
79
- 'rg-',
80
- 'grep ',
81
- 'grep-',
82
- 'ripgrep',
83
- 'find ',
84
- 'fd ',
85
- 'locate ',
86
- 'search ',
87
- 'ack ',
88
- 'ag ',
89
- 'where ',
90
- 'which ',
91
- 'codesearch'
92
- ];
93
- const SHELL_READ_PATTERNS = [
94
- 'cat ',
95
- 'type ',
96
- 'head ',
97
- 'tail ',
98
- 'stat ',
99
- 'stat',
100
- 'wc ',
101
- 'python - <<',
102
- 'python -c',
103
- 'node - <<',
104
- 'node -e'
105
- ];
106
5
  export function buildRoutingFeatures(request, metadata) {
107
6
  const latestUserMessage = getLatestUserMessage(request.messages);
7
+ const latestMessageRole = getLatestMessageRole(request.messages);
108
8
  const assistantMessages = request.messages.filter((msg) => msg.role === 'assistant');
109
9
  const latestUserText = latestUserMessage ? extractMessageText(latestUserMessage) : '';
110
10
  const normalizedUserText = latestUserText.toLowerCase();
111
- const hasTools = Array.isArray(request.tools) && request.tools.length > 0;
11
+ const meaningfulDeclaredTools = extractMeaningfulDeclaredToolNames(request.tools);
12
+ const hasTools = meaningfulDeclaredTools.length > 0;
112
13
  const hasToolCallResponses = assistantMessages.some((msg) => Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0);
113
14
  const estimatedTokens = computeRequestTokens(request, latestUserText);
114
15
  const hasThinking = detectKeyword(normalizedUserText, THINKING_KEYWORDS);
@@ -117,13 +18,25 @@ export function buildRoutingFeatures(request, metadata) {
117
18
  const hasCodingTool = detectCodingTool(request);
118
19
  const hasWebTool = detectWebTool(request);
119
20
  const hasThinkingKeyword = hasThinking || detectExtendedThinkingKeyword(normalizedUserText);
120
- const assistantToolSummary = summarizeAssistantToolUsage(assistantMessages);
21
+ const lastAssistantTool = detectLastAssistantToolCategory(assistantMessages);
22
+ const lastAssistantToolLabel = (() => {
23
+ if (!lastAssistantTool) {
24
+ return undefined;
25
+ }
26
+ if (lastAssistantTool.commandSnippet && lastAssistantTool.commandSnippet.trim()) {
27
+ return lastAssistantTool.commandSnippet.trim();
28
+ }
29
+ if (lastAssistantTool.name && lastAssistantTool.name.trim()) {
30
+ return lastAssistantTool.name.trim();
31
+ }
32
+ return undefined;
33
+ })();
121
34
  return {
122
35
  requestId: metadata.requestId,
123
36
  model: request.model,
124
37
  totalMessages: request.messages?.length ?? 0,
125
38
  userTextSample: latestUserText.slice(0, 2000),
126
- toolCount: request.tools?.length ?? 0,
39
+ toolCount: meaningfulDeclaredTools.length,
127
40
  hasTools,
128
41
  hasToolCallResponses,
129
42
  hasVisionTool,
@@ -132,508 +45,12 @@ export function buildRoutingFeatures(request, metadata) {
132
45
  hasCodingTool,
133
46
  hasThinkingKeyword,
134
47
  estimatedTokens,
135
- lastAssistantToolCategory: assistantToolSummary.primary?.category,
136
- lastAssistantToolName: assistantToolSummary.primary?.name,
137
- lastAssistantToolDetail: assistantToolSummary.primary?.detail,
138
- assistantToolCategories: assistantToolSummary.categories,
139
- assistantCalledWebSearchTool: assistantToolSummary.usedWebSearchTool,
48
+ lastAssistantToolCategory: lastAssistantTool?.category,
49
+ lastAssistantToolSnippet: lastAssistantTool?.commandSnippet,
50
+ lastAssistantToolLabel,
51
+ latestMessageFromUser: latestMessageRole === 'user',
140
52
  metadata: {
141
53
  ...metadata
142
54
  }
143
55
  };
144
56
  }
145
- function getLatestUserMessage(messages) {
146
- for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
147
- if (messages[idx]?.role === 'user') {
148
- return messages[idx];
149
- }
150
- }
151
- return undefined;
152
- }
153
- function extractMessageText(message) {
154
- if (typeof message.content === 'string' && message.content.trim()) {
155
- return message.content;
156
- }
157
- return '';
158
- }
159
- function detectKeyword(text, keywords) {
160
- if (!text)
161
- return false;
162
- return keywords.some((keyword) => text.includes(keyword.toLowerCase()));
163
- }
164
- function detectImageAttachment(message) {
165
- if (!message)
166
- return false;
167
- if (!message.metadata || typeof message.metadata !== 'object') {
168
- return false;
169
- }
170
- const meta = message.metadata;
171
- const attachments = (meta.attachments ?? null);
172
- if (Array.isArray(attachments)) {
173
- return attachments.some((attachment) => {
174
- const candidate = attachment;
175
- const typeValue = typeof candidate.type === 'string' ? candidate.type.toLowerCase() : '';
176
- const urlValue = typeof candidate.url === 'string'
177
- ? candidate.url
178
- : typeof candidate.src === 'string'
179
- ? candidate.src
180
- : typeof candidate.image_url === 'string'
181
- ? candidate.image_url
182
- : typeof candidate.image_url?.url === 'string'
183
- ? candidate.image_url.url
184
- : '';
185
- return typeValue.includes('image') && urlValue.trim().length > 0;
186
- });
187
- }
188
- if (typeof meta.attachmentType === 'string' && meta.attachmentType.toLowerCase().includes('image')) {
189
- const urlCandidate = typeof meta.attachmentUrl === 'string' ? meta.attachmentUrl : '';
190
- return urlCandidate.trim().length > 0;
191
- }
192
- return false;
193
- }
194
- function detectVisionTool(request) {
195
- if (!Array.isArray(request.tools)) {
196
- return false;
197
- }
198
- return request.tools.some((tool) => {
199
- const functionName = extractToolName(tool);
200
- const description = extractToolDescription(tool);
201
- return /vision|image|picture|photo/i.test(functionName) || /vision|image|picture|photo/i.test(description || '');
202
- });
203
- }
204
- function detectCodingTool(request) {
205
- if (!Array.isArray(request.tools)) {
206
- return false;
207
- }
208
- return request.tools.some((tool) => {
209
- const functionName = extractToolName(tool).toLowerCase();
210
- const description = (extractToolDescription(tool) || '').toLowerCase();
211
- if (!functionName && !description) {
212
- return false;
213
- }
214
- if (WRITE_TOOL_EXACT.has(functionName)) {
215
- return true;
216
- }
217
- return WRITE_TOOL_KEYWORDS.some((keyword) => functionName.includes(keyword.toLowerCase()) || description.includes(keyword.toLowerCase()));
218
- });
219
- }
220
- function detectWebTool(request) {
221
- if (!Array.isArray(request.tools)) {
222
- return false;
223
- }
224
- return request.tools.some((tool) => {
225
- const functionName = extractToolName(tool);
226
- const description = extractToolDescription(tool);
227
- const normalizedName = functionName.toLowerCase();
228
- const normalizedDesc = (description || '').toLowerCase();
229
- return (WEB_TOOL_KEYWORDS.some((keyword) => normalizedName.includes(keyword)) ||
230
- WEB_TOOL_KEYWORDS.some((keyword) => normalizedDesc.includes(keyword)));
231
- });
232
- }
233
- function detectExtendedThinkingKeyword(text) {
234
- if (!text) {
235
- return false;
236
- }
237
- const keywords = ['仔细分析', '思考', '超级思考', '深度思考', 'careful analysis', 'deep thinking', 'deliberate'];
238
- return keywords.some((keyword) => text.includes(keyword));
239
- }
240
- function computeRequestTokens(request, fallbackText) {
241
- try {
242
- return countRequestTokens(request);
243
- }
244
- catch {
245
- return fallbackEstimateTokens(fallbackText, request.messages?.length ?? 0);
246
- }
247
- }
248
- function fallbackEstimateTokens(text, messageCount) {
249
- if (!text) {
250
- return Math.max(32, Math.max(messageCount, 1) * 16);
251
- }
252
- const rough = Math.ceil(text.length / 4);
253
- return Math.max(rough, Math.max(messageCount, 1) * 32);
254
- }
255
- function extractToolName(tool) {
256
- if (!tool || typeof tool !== 'object') {
257
- return '';
258
- }
259
- const candidate = tool;
260
- const fromFunction = candidate.function;
261
- if (fromFunction && typeof fromFunction.name === 'string' && fromFunction.name.trim()) {
262
- return fromFunction.name;
263
- }
264
- if (typeof candidate.name === 'string' && candidate.name.trim()) {
265
- return candidate.name;
266
- }
267
- return '';
268
- }
269
- function extractToolDescription(tool) {
270
- if (!tool || typeof tool !== 'object') {
271
- return '';
272
- }
273
- const candidate = tool;
274
- const fromFunction = candidate.function;
275
- if (fromFunction && typeof fromFunction.description === 'string' && fromFunction.description.trim()) {
276
- return fromFunction.description;
277
- }
278
- if (typeof candidate.description === 'string' && candidate.description.trim()) {
279
- return candidate.description;
280
- }
281
- return '';
282
- }
283
- function summarizeAssistantToolUsage(messages) {
284
- for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
285
- const msg = messages[idx];
286
- if (!msg || !Array.isArray(msg.tool_calls) || msg.tool_calls.length === 0) {
287
- continue;
288
- }
289
- const classifications = [];
290
- let usedWebSearchTool = false;
291
- for (const call of msg.tool_calls) {
292
- const classification = classifyToolCall(call);
293
- if (classification) {
294
- classifications.push(classification);
295
- if (classification.category === 'search' && isWebSearchToolInvocation(classification)) {
296
- usedWebSearchTool = true;
297
- }
298
- }
299
- }
300
- if (!classifications.length) {
301
- continue;
302
- }
303
- const categorySet = new Set();
304
- for (const classification of classifications) {
305
- categorySet.add(classification.category);
306
- }
307
- const categories = orderToolCategories(Array.from(categorySet));
308
- const primary = classifications.find((classification) => classification.category !== 'other') ?? classifications[0];
309
- return {
310
- categories,
311
- primary,
312
- usedWebSearchTool
313
- };
314
- }
315
- return { categories: [], usedWebSearchTool: false };
316
- }
317
- function orderToolCategories(categories) {
318
- const ordered = [];
319
- for (const category of TOOL_CATEGORY_PRIORITY) {
320
- if (categories.includes(category)) {
321
- ordered.push(category);
322
- }
323
- }
324
- for (const category of categories) {
325
- if (!ordered.includes(category)) {
326
- ordered.push(category);
327
- }
328
- }
329
- return ordered;
330
- }
331
- function isWebSearchToolName(name) {
332
- const normalized = name.toLowerCase();
333
- if (SEARCH_TOOL_EXACT.has(normalized)) {
334
- return true;
335
- }
336
- return WEB_TOOL_KEYWORDS.some((keyword) => normalized.includes(keyword.toLowerCase()));
337
- }
338
- function isWebSearchToolInvocation(classification) {
339
- if (!classification) {
340
- return false;
341
- }
342
- if (isWebSearchToolName(classification.name)) {
343
- return true;
344
- }
345
- if (classification.detail) {
346
- const detail = classification.detail.toLowerCase();
347
- return WEB_TOOL_KEYWORDS.some((keyword) => detail.includes(keyword.toLowerCase()));
348
- }
349
- return false;
350
- }
351
- function classifyToolCall(call) {
352
- if (!call || typeof call !== 'object') {
353
- return undefined;
354
- }
355
- const functionName = typeof call?.function?.name === 'string' && call.function.name.trim()
356
- ? canonicalizeToolName(call.function.name)
357
- : '';
358
- if (!functionName) {
359
- return undefined;
360
- }
361
- const argsObject = parseToolArguments(call?.function?.arguments);
362
- const commandText = extractCommandText(argsObject).trim();
363
- const commandDetail = summarizeCommandDetail(commandText);
364
- const nameCategory = categorizeToolName(functionName);
365
- if (nameCategory === 'write' || nameCategory === 'read' || nameCategory === 'search') {
366
- return { category: nameCategory, name: functionName };
367
- }
368
- if (SHELL_TOOL_NAMES.has(functionName)) {
369
- const shellCategory = classifyShellCommand(commandText);
370
- return {
371
- category: shellCategory,
372
- name: functionName,
373
- detail: commandDetail
374
- };
375
- }
376
- if (commandText) {
377
- const derivedCategory = classifyShellCommand(commandText);
378
- if (derivedCategory !== 'other') {
379
- return { category: derivedCategory, name: functionName };
380
- }
381
- }
382
- return { category: 'other', name: functionName };
383
- }
384
- function canonicalizeToolName(rawName) {
385
- const trimmed = rawName.trim();
386
- const markerIndex = trimmed.indexOf('arg_');
387
- if (markerIndex > 0) {
388
- return trimmed.slice(0, markerIndex);
389
- }
390
- return trimmed;
391
- }
392
- function parseToolArguments(rawArguments) {
393
- if (!rawArguments) {
394
- return undefined;
395
- }
396
- if (typeof rawArguments === 'string') {
397
- try {
398
- return JSON.parse(rawArguments);
399
- }
400
- catch {
401
- return rawArguments;
402
- }
403
- }
404
- if (typeof rawArguments === 'object') {
405
- return rawArguments;
406
- }
407
- return undefined;
408
- }
409
- function extractCommandText(args) {
410
- if (!args) {
411
- return '';
412
- }
413
- if (typeof args === 'string') {
414
- return args;
415
- }
416
- if (Array.isArray(args)) {
417
- const tokens = collectCommandTokens(args);
418
- if (tokens.length) {
419
- return tokens.join(' ');
420
- }
421
- const derived = extractFirstStringValue(args);
422
- return derived ?? '';
423
- }
424
- if (typeof args === 'object') {
425
- const record = args;
426
- const command = record.command;
427
- const input = record.input;
428
- const nestedArgs = record.args;
429
- if (typeof command === 'string') {
430
- return command;
431
- }
432
- if (Array.isArray(command)) {
433
- const tokens = collectCommandTokens(command);
434
- if (tokens.length) {
435
- return tokens.join(' ');
436
- }
437
- const derivedCommand = extractFirstStringValue(command);
438
- if (derivedCommand) {
439
- return derivedCommand;
440
- }
441
- }
442
- if (command && typeof command === 'object') {
443
- const derivedCommand = extractFirstStringValue(command);
444
- if (derivedCommand) {
445
- return derivedCommand;
446
- }
447
- }
448
- if (typeof input === 'string') {
449
- return input;
450
- }
451
- if (typeof nestedArgs === 'string') {
452
- return nestedArgs;
453
- }
454
- if (Array.isArray(nestedArgs)) {
455
- const tokens = collectCommandTokens(nestedArgs);
456
- if (tokens.length) {
457
- return tokens.join(' ');
458
- }
459
- const derivedArgs = extractFirstStringValue(nestedArgs);
460
- if (derivedArgs) {
461
- return derivedArgs;
462
- }
463
- }
464
- if (nestedArgs && typeof nestedArgs === 'object') {
465
- const derivedArgs = extractFirstStringValue(nestedArgs);
466
- if (derivedArgs) {
467
- return derivedArgs;
468
- }
469
- }
470
- const fallback = extractFirstStringValue(record);
471
- if (fallback) {
472
- return fallback;
473
- }
474
- try {
475
- return JSON.stringify(record);
476
- }
477
- catch {
478
- return '';
479
- }
480
- }
481
- return '';
482
- }
483
- function categorizeToolName(name) {
484
- const normalized = name.toLowerCase();
485
- if (SEARCH_TOOL_EXACT.has(normalized) ||
486
- SEARCH_TOOL_KEYWORDS.some((keyword) => normalized.includes(keyword.toLowerCase()))) {
487
- return 'search';
488
- }
489
- if (READ_TOOL_EXACT.has(normalized) ||
490
- READ_TOOL_KEYWORDS.some((keyword) => normalized.includes(keyword.toLowerCase()))) {
491
- return 'read';
492
- }
493
- if (WRITE_TOOL_EXACT.has(normalized) ||
494
- WRITE_TOOL_KEYWORDS.some((keyword) => normalized.includes(keyword.toLowerCase()))) {
495
- return 'write';
496
- }
497
- return 'other';
498
- }
499
- function classifyShellCommand(command) {
500
- if (!command) {
501
- return 'other';
502
- }
503
- if (SHELL_HEREDOC_PATTERN.test(command)) {
504
- return 'write';
505
- }
506
- const segments = splitCommandSegments(command)
507
- .map(stripShellWrapper)
508
- .filter(Boolean);
509
- const hasWrite = segments.some((segment) => matchesAnyPattern(segment, SHELL_WRITE_PATTERNS));
510
- const hasRead = segments.some((segment) => matchesAnyPattern(segment, SHELL_READ_PATTERNS));
511
- if (hasWrite) {
512
- return 'write';
513
- }
514
- if (hasRead) {
515
- return 'read';
516
- }
517
- const hasSearch = segments.some((segment) => matchesAnyPattern(segment, SHELL_SEARCH_PATTERNS));
518
- if (hasSearch) {
519
- return 'search';
520
- }
521
- const stripped = stripShellWrapper(command);
522
- if (matchesAnyPattern(stripped, SHELL_WRITE_PATTERNS)) {
523
- return 'write';
524
- }
525
- if (matchesAnyPattern(stripped, SHELL_READ_PATTERNS)) {
526
- return 'read';
527
- }
528
- if (matchesAnyPattern(stripped, SHELL_SEARCH_PATTERNS)) {
529
- return 'search';
530
- }
531
- return 'other';
532
- }
533
- function splitCommandSegments(command) {
534
- return command
535
- .split(/(?:\r?\n|&&|\|\||;)/)
536
- .map((segment) => segment.trim())
537
- .filter(Boolean);
538
- }
539
- function matchesAnyPattern(text, patterns) {
540
- if (!text) {
541
- return false;
542
- }
543
- const trimmed = text.trim().toLowerCase();
544
- const normalized = trimmed.startsWith('sudo ') ? trimmed.slice(5).trim() : trimmed;
545
- return patterns.some((pattern) => {
546
- const lowered = pattern.toLowerCase().trim();
547
- return normalized.startsWith(lowered);
548
- });
549
- }
550
- function stripShellWrapper(segment) {
551
- let normalized = segment.trim();
552
- const wrappers = ['bash -lc ', 'bash -lc', 'sh -c ', 'sh -c', '/bin/sh -c ', '/bin/sh -c', 'env -i bash -lc ', 'env -i bash -lc'];
553
- for (const wrapper of wrappers) {
554
- if (normalized.toLowerCase().startsWith(wrapper)) {
555
- normalized = normalized.slice(wrapper.length).trim();
556
- break;
557
- }
558
- }
559
- normalized = trimEnclosingQuotes(normalized);
560
- if (normalized.startsWith('sudo ')) {
561
- normalized = normalized.slice(5).trim();
562
- }
563
- return normalized;
564
- }
565
- function trimEnclosingQuotes(value) {
566
- if ((value.startsWith('"') && value.endsWith('"') && value.length > 1) ||
567
- (value.startsWith("'") && value.endsWith("'") && value.length > 1)) {
568
- return value.slice(1, -1).trim();
569
- }
570
- return value;
571
- }
572
- function summarizeCommandDetail(command) {
573
- if (!command) {
574
- return undefined;
575
- }
576
- const [firstSegment] = splitCommandSegments(command);
577
- const candidate = firstSegment ?? command;
578
- const normalized = candidate.replace(/\s+/g, ' ').trim();
579
- if (!normalized) {
580
- return undefined;
581
- }
582
- if (normalized.length > COMMAND_DETAIL_MAX_LENGTH) {
583
- return `${normalized.slice(0, COMMAND_DETAIL_MAX_LENGTH - 1)}…`;
584
- }
585
- return normalized;
586
- }
587
- function collectCommandTokens(values) {
588
- const tokens = [];
589
- for (const value of values) {
590
- if (typeof value === 'string') {
591
- const trimmed = value.trim();
592
- if (trimmed) {
593
- tokens.push(trimmed);
594
- }
595
- continue;
596
- }
597
- if (Array.isArray(value)) {
598
- const nested = collectCommandTokens(value);
599
- if (nested.length) {
600
- tokens.push(nested.join(' '));
601
- continue;
602
- }
603
- }
604
- if (value && typeof value === 'object') {
605
- const extracted = extractFirstStringValue(value);
606
- if (extracted) {
607
- tokens.push(extracted.trim());
608
- }
609
- }
610
- }
611
- return tokens.filter(Boolean).slice(0, 16);
612
- }
613
- function extractFirstStringValue(value) {
614
- if (!value) {
615
- return undefined;
616
- }
617
- if (typeof value === 'string') {
618
- const trimmed = value.trim();
619
- return trimmed || undefined;
620
- }
621
- if (Array.isArray(value)) {
622
- for (const item of value) {
623
- const extracted = extractFirstStringValue(item);
624
- if (extracted) {
625
- return extracted;
626
- }
627
- }
628
- return undefined;
629
- }
630
- if (typeof value === 'object') {
631
- for (const candidate of Object.values(value)) {
632
- const extracted = extractFirstStringValue(candidate);
633
- if (extracted) {
634
- return extracted;
635
- }
636
- }
637
- }
638
- return undefined;
639
- }
@@ -35,13 +35,8 @@ export class ProviderHealthManager {
35
35
  if (reason) {
36
36
  state.reason = reason;
37
37
  }
38
- if (state.failureCount >= this.config.failureThreshold) {
39
- state.state = 'tripped';
40
- state.cooldownExpiresAt = Date.now() + this.config.cooldownMs;
41
- if (reason) {
42
- state.reason = reason;
43
- }
44
- }
38
+ // 在新版策略中,普通失败仅用于监控;不再根据 failureThreshold 自动熔断。
39
+ // 只有显式 fatal 或 tripProvider 调用时才会进入 tripped 状态。
45
40
  return state;
46
41
  }
47
42
  recordSuccess(providerKey) {
@@ -0,0 +1,7 @@
1
+ import type { StandardizedMessage } from '../../conversion/hub/types/standardized.js';
2
+ export declare function getLatestUserMessage(messages: StandardizedMessage[]): StandardizedMessage | undefined;
3
+ export declare function getLatestMessageRole(messages: StandardizedMessage[]): string | undefined;
4
+ export declare function extractMessageText(message: StandardizedMessage): string;
5
+ export declare function detectKeyword(text: string, keywords: string[]): boolean;
6
+ export declare function detectExtendedThinkingKeyword(text: string): boolean;
7
+ export declare function detectImageAttachment(message: StandardizedMessage | undefined): boolean;