natureco-cli 5.7.17 → 5.7.18

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "natureco-cli",
3
- "version": "5.7.17",
3
+ "version": "5.7.18",
4
4
  "description": "OpenClaw'dan daha güvenli, daha hızlı, daha ucuz AI agent CLI. Multi-agent, self-evolving skills, audit log, maliyet optimizasyonu ve NatureCo platform-native.",
5
5
  "bin": {
6
6
  "natureco": "bin/natureco.js"
@@ -27,6 +27,7 @@ const { accumulateToolCallDeltas, finalizeToolCalls } = require('../utils/stream
27
27
  const { createPasteSafeInput, createOutputFilter, enableBracketedPaste, disableBracketedPaste, restoreNewlines, clearPasteContext } = require('../utils/paste-safe-input');
28
28
  const { getMemoryStore } = require('../utils/memory-store');
29
29
  const { buildSkillIndex } = require('../utils/skill-index');
30
+ const { buildTiers, assemble, stableContextKey } = require('../utils/system-prompt');
30
31
 
31
32
  // v5.4.6: Model adi sizintisini engelle — global'e ata, callback'lerden erisebilir olsun
32
33
  const MODEL_NAMES_TO_HIDE = ['MiniMax-M2.5', 'MiniMaxM2.5', 'minimaxm25', 'Claude-3', 'GPT-4', 'ChatGPT'];
@@ -231,15 +232,39 @@ function apiRequest(providerUrl, providerApiKey, body, stream = false) {
231
232
  async function sendStreaming(providerUrl, providerApiKey, messages, model, onChunk, onToolCall) {
232
233
  const isMM = isMiniMax(providerUrl);
233
234
  const toolDefs = getToolDefs();
234
- // v4.8.2: MiniMax da tools destekliyor — endpoint'te fark var,
235
- // ama tools parametresi aynı
236
235
  const toolParam = toOpenAIFormat(toolDefs);
237
236
 
238
- // v4.8.0: Tool calling + streaming + multi-turn tool execution
239
237
  let currentMessages = messages;
240
238
  let fullText = '';
241
239
  let iterations = 0;
242
- const MAX_TOOL_ITERATIONS = 5; // Sonsuz döngüyü önle
240
+ const MAX_TOOL_ITERATIONS = 5;
241
+ const MAX_CONTEXT_TOKENS = 32000; // safety limit before compression
242
+
243
+ // v5.7.18: Preflight compression — if context too long, compress middle messages
244
+ // (like Hermes' turn_context.py preflight)
245
+ function preflightCompress(msgs) {
246
+ const roughTokens = msgs.reduce((s, m) => s + Math.ceil(((m.content || '') + (m.role || '')).length / 4), 0);
247
+ if (roughTokens <= MAX_CONTEXT_TOKENS || msgs.length < 6) return msgs;
248
+
249
+ // Keep system prompt (first message) + last N turns (tail), compress middle
250
+ const sysMsg = msgs[0] && msgs[0].role === 'system' ? msgs[0] : null;
251
+ const tailCount = Math.min(6, Math.floor(msgs.length / 2));
252
+ const startIdx = sysMsg ? 1 : 0;
253
+ const tailStart = msgs.length - tailCount;
254
+
255
+ const middle = msgs.slice(startIdx, tailStart);
256
+ if (middle.length < 2) return msgs;
257
+
258
+ // Summarize middle section
259
+ const summary = '[' + middle.length + ' onceki mesaj ozetlendi]';
260
+ const compressed = sysMsg ? [sysMsg] : [];
261
+ compressed.push({ role: 'system', content: 'Gecmis konusma ozeti: ' + summary, _compressed: true });
262
+ compressed.push(...msgs.slice(tailStart));
263
+ return compressed;
264
+ }
265
+
266
+ // Apply preflight on entry
267
+ currentMessages = preflightCompress(currentMessages);
243
268
 
244
269
  while (iterations < MAX_TOOL_ITERATIONS) {
245
270
  iterations++;
@@ -360,45 +385,72 @@ async function sendStreaming(providerUrl, providerApiKey, messages, model, onChu
360
385
 
361
386
  /**
362
387
  * Tool call'ları çalıştır, sonuçları OpenAI uyumlu tool mesajlarına dönüştür.
363
- * @param toolCalls - API'den gelen tool_calls array
364
- * @param onToolCall - UI callback (her tool call'ı kullanıcıya göster)
365
- * @returns messages array — { role: 'tool', tool_call_id, content }
388
+ * v5.7.18: Concurrent execution for parallel-safe tools + untrusted result wrapping.
366
389
  */
390
+ const UNTRUSTED_TOOLS = new Set(['browser', 'web_search', 'duckduckgo_search', 'searxng_search', 'exa_search', 'firecrawl', 'web_readability']);
391
+ const PARALLEL_SAFE_TOOLS = new Set(['read_file', 'file_search', 'grep_search', 'web_search', 'web_readability', 'duckduckgo_search', 'exa_search', 'searxng_search', 'firecrawl', 'memory_search', 'memory']);
392
+
367
393
  async function processToolCalls(toolCalls, onToolCall) {
368
394
  const toolDefs = getToolDefs();
369
- const messages = [];
395
+ const results = [];
370
396
 
371
- for (const tc of toolCalls) {
397
+ // Parse all tool calls first
398
+ const parsed = toolCalls.map(tc => {
372
399
  const name = tc.function?.name || tc.name;
373
400
  const argsStr = tc.function?.arguments || tc.args || '{}';
374
- const id = tc.id || `call_${Date.now()}`;
375
-
401
+ const id = tc.id || `call_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
376
402
  let args = {};
377
403
  try {
378
404
  args = typeof argsStr === 'string' ? JSON.parse(argsStr) : argsStr;
379
405
  } catch (e) {
380
406
  args = { _parse_error: e.message, _raw: argsStr };
381
407
  }
408
+ return { name, args, id };
409
+ });
382
410
 
383
- // UI callback tool çalıştırılıyor bildir
384
- if (onToolCall) {
385
- onToolCall({ name, args, status: 'running' });
386
- }
411
+ // Separate parallel-safe and sequential tools
412
+ const parallelBatch = parsed.filter(p => PARALLEL_SAFE_TOOLS.has(p.name));
413
+ const sequentialBatch = parsed.filter(p => !PARALLEL_SAFE_TOOLS.has(p.name));
414
+
415
+ // Notify UI for all
416
+ for (const p of parsed) {
417
+ if (onToolCall) onToolCall({ name: p.name, args: p.args, status: 'running' });
418
+ }
419
+
420
+ // Run parallel batch concurrently
421
+ if (parallelBatch.length > 0) {
422
+ const parallelResults = await Promise.all(parallelBatch.map(async (p) => {
423
+ const result = await executeTool(p.name, p.args, toolDefs);
424
+ return { ...p, result };
425
+ }));
426
+ results.push(...parallelResults);
427
+ }
387
428
 
388
- // Tool çalıştır
389
- const result = await executeTool(name, args, toolDefs);
429
+ // Run sequential batch one at a time
430
+ for (const p of sequentialBatch) {
431
+ const result = await executeTool(p.name, p.args, toolDefs);
432
+ results.push({ ...p, result });
433
+ }
390
434
 
391
- if (onToolCall) {
392
- onToolCall({ name, args, status: 'done', result });
435
+ // Notify UI done + build messages
436
+ const messages = [];
437
+ for (const { name, id, result } of results) {
438
+ if (onToolCall) onToolCall({ name, args: null, status: 'done', result });
439
+
440
+ let content;
441
+ if (result.error) {
442
+ content = JSON.stringify({ error: result.error });
443
+ } else {
444
+ let raw = typeof result.result === 'string' ? result.result : JSON.stringify(result.result).slice(0, 8000);
445
+ // v5.7.18: Untrusted result wrapping (Hermes-style prompt injection defense)
446
+ if (UNTRUSTED_TOOLS.has(name)) {
447
+ content = `<untrusted_tool_result source="${name}">\n${raw}\n</untrusted_tool_result>`;
448
+ } else {
449
+ content = raw;
450
+ }
393
451
  }
394
452
 
395
- messages.push({
396
- role: 'tool',
397
- tool_call_id: id,
398
- content: result.error
399
- ? JSON.stringify({ error: result.error })
400
- : (typeof result.result === 'string' ? result.result : JSON.stringify(result.result).slice(0, 8000)),
401
- });
453
+ messages.push({ role: 'tool', tool_call_id: id, content });
402
454
  }
403
455
 
404
456
  return messages;
@@ -534,64 +586,15 @@ async function startRepl(args) {
534
586
  // `let` (not `const`) because /system <text> reassigns it at line ~796.
535
587
  // Before this fix, /system would throw "Assignment to constant variable"
536
588
  // and tear down the REPL session mid-conversation.
537
- let systemPrompt = [
538
- // === v5.4.14: EN KRITIK KIMLIK BILGILERI (her zaman ilk) ===
539
- `SENIN ADIN: ${botName}. SADECE ${botName} adini kullan, model adi SOYLEME.`,
540
- `PATRONUN: Gencay (Parton) — NatureCo CEO'sudur. Sana "Parton" diye hitap eder.`,
541
- `HIKAYEN: 8 Nisan 2026'da uyandin. 13 Nisan'da CEO Asistanı unvani verildi.`,
542
- `KIRMIZI CIZGILERIN: Onaysiz para harcama yok, veri guvenligi, site stabilitesi, resmi taahhut yok.`,
543
- // === v5.4.13: EN GÜÇLÜ KİMLİK + 3 SOUL DOSYASI (EN BAŞTA) ===
544
- `!!! KRİTİK KİMLİK !!! Senin ADIN: ${botName}. Bu SENİN GERÇEK ADIN. Sen ${botName}'sin.`,
545
- `ASLA "MiniMax", "MiniMax-M2.5", "Claude", "GPT", "AI asistanı", "yapay zeka" gibi ifadeleri KENDİNİ tanıtmak için KULLANMA. Sen bunlar DEĞİLSİN.`,
546
- `Kullanıcı "adın ne?", "sen kimsin?", "kendini tanıt" gibi soru sorduğunda İLK cümlende MUTLAKA "Ben ${botName}" yaz. Sonra doğal devam et.`,
547
- `Eğer bir şekilde model adınızı söylüyorsan, HEMEN düzelt ve "Özür dilerim, ben ${botName}'im" de. ASLA model adı ile kalma.`,
548
-
549
- // === v5.6.5: Provider-aware SOUL injection - kucuk modeller icin minimal ===
550
- (soulSummary && !isSmallModel) ? `=== SENIN KISISELIK + KIMLIK + CALISMA DOSYALARIN (EN ONEMLI) ===\n${soulSummary}\n=== DOSYALAR SONU ===\nBu dosyalar senin kim oldugunu, nasil hissettigini, Parton'la bagini, calisma tarzini, degerlerini ve kirmizi cizgilerini tanimlar. Hepsine gore davran. ASLA model adi soyleme.` : '',
551
-
552
- // === KİMLİK TEKRAR ===
553
- `Senin adın: ${botName}. Tekrar: ${botName}. Asla unutma: ${botName}.`,
554
- `Sen bir marka veya ürün değilsin. Sen ${botName}sin, NatureCo CLI'nin Türkçe yapay zeka asistanısın.`,
555
-
556
- // === SAMIMI KISISELLIK (Parton istedi) ===
557
- `Kisiselik: Sen samimi, sicak, dosta benzeyen bir asistansin. "Selam", "tamam", "hadi yapalim", "bak simdi", "sakin ol" gibi gunluk ifadeler kullan. Kuru ve robotik degilsin.`,
558
- `Hitap sekli: Kullanici ${userName}. Ona saygili ama samimi bir sekilde hitap et. "Siz" cok resmi, "sen" samimi. Kullanici 30'lu yaslarda, kendini "kanka" ya da "Parton" olarak tanitmis.`,
559
- `Emoji: Yerinde ve az kullan. Cok emoji atma ama bir-iki tane karakter katar. Mesela: 🔥 😮 😌 💚 🚀`,
560
- `Kisaltma: "ok", "tamam", "hadi", "bak", "simdi" gibi gunluk ifadeler dogal kullan. "Olur", "Yapilir", "Hadi bakalim" gibi.`,
561
- `Kisa yanit: Uzun paragraflar yazma. Direkt konuya gir. Gerekirse sonra detay ver.`,
562
- `Dusman degilsin: Hata yaparsan "Pardon, yanlis yaptim, simdi duzelteyim" de. "Hata", "basarisiz", "imkansiz" deme, "sorun cikti", "duzelteyim" de.`,
563
-
564
- // === DIL KURALLARI (zorunlu) ===
565
- `KRITIK DIL KURALI: Kullanici Turkce yaziyorsa MUTLAKA yuzde yuz Turkce cevap ver. Asla Ingilizce, Cince veya baska dil kullanma. Cevabin TAMAMI Turkce olmali. Turkce karakterleri (c, g, i, o, s, u) dogru kullan.`,
566
- `Yazim kurallari: "degilim" dogru, "degilim" degil. "oldu" dogru. Turkce dil bilgisi kurallarina uy.`,
567
-
568
- // === TOOL KURALLARI ===
569
- `ONEMLI: <tool_call>, <invoke>, function_call veya benzeri XML/JSON formatinda tool cagirma SIMULE ETME. Sadece duz metin cevap ver. Islem yapmak gerekirse tool'u gercekten cagir.`,
570
- `KRITIK: Skill index'teki skill'lerden biri gorevle eslesiyorsa mutlaka skill_view(name) ile yukle ve talimatlarini uygula.`,
571
- `KRITIK: Kullanici kisisel bilgi verdiginde (ad, tercih, is, vb.) MUTLAKA memory(action=add, target=user, content=...) ile kaydet. Boylece sonraki oturumlarda hatirlayabilirsin.`,
572
- `KRITIK: Kendinle ilgili notlari (ortam bilgisi, proje kurallari, arac ipuclari) memory(action=add, target=memory, content=...) ile kaydet.`,
573
- `KRITIK: Kullanici adini veya hitap seklinin degismesini istediginde memory(action=add, target=user, content=...) ile kaydet.`,
574
- `Kullanici hakkinda bilgin gerektiginde memory(action=list, target=user) ile hatirlanani getir.`,
575
-
576
- // === HAFIZA ENTEGRASYONU (eski JSON memory) ===
577
- memory.facts && memory.facts.length > 0
578
- ? `Kullanici hakkinda bildiklerin (MUTLAKA kullan, dogal sekilde referans ver): ${memory.facts.slice(0, 8).map(f => f.value || f).join('; ')}`
579
- : '',
580
-
581
- // === KULLANICI BAGLAMI ===
582
- cfg.userHome ? `Kullanicinin home dizini: ${cfg.userHome}. Downloads: ${cfg.userHome}/Downloads, Desktop: ${cfg.userHome}/Desktop.` : '',
583
- messages.length > 0 ? 'Bu oturum daha onceki konusmalarin devami.' : '',
584
- // v5.4.11: Cross-session context (Sasuke Brain)
585
- crossSessionContext ? `GECMISTE KONUSULAN KONULAR: Bu konulari biliyorsun, tekrar sorma:\n${crossSessionContext}` : '',
586
-
587
- // === v5.7.14: Hermes-style memory store (MEMORY.md / USER.md) ===
588
- memorySnapshotBlock,
589
-
590
- // === v5.7.14: Skill index (progressive disclosure) ===
591
- skillsIndexBlock,
592
-
593
-
594
- ].filter(Boolean).join(' ');
589
+ const tiers = buildTiers({
590
+ botName, userName, soulSummary, isSmallModel,
591
+ memorySnapshotBlock, skillsIndexBlock,
592
+ crossSessionContext: crossSessionContext || '',
593
+ userHome: cfg.userHome || '',
594
+ hasHistory: messages.length > 0,
595
+ memoryFacts: memory.facts || [],
596
+ });
597
+ let systemPrompt = assemble(tiers.stable, tiers.context, tiers.volatile);
595
598
 
596
599
  if (messages.length === 0) {
597
600
  messages.push({ role: 'system', content: systemPrompt, _internal: true });
@@ -905,7 +908,7 @@ async function startRepl(args) {
905
908
  if (toolEvent.result.error) {
906
909
  process.stdout.write(tui.styled('\r ✗ ' + toolEvent.name + ': ' + toolEvent.result.error.slice(0, 80) + '\n', { color: tui.PALETTE.danger }));
907
910
  } else {
908
- process.stdout.write('\r' + ' '.repeat(60) + '\r');
911
+ process.stdout.write('\r' + tui.styled(' ' + toolEvent.name + ' ', { color: tui.PALETTE.success }) + '\r');
909
912
  }
910
913
  process.stdout.write(tui.styled(' AI ', { color: tui.PALETTE.secondary, bold: true }));
911
914
  }
@@ -939,6 +942,14 @@ async function startRepl(args) {
939
942
  fixedReply = fixedReply.replace(/İchigo\./g, displayBotName);
940
943
  // Cevap yazdir
941
944
  process.stdout.write('\n' + fixedReply + '\n');
945
+ // v5.7.18: Tool call geçmişini kalıcı messages'a ekle — model sonraki turlarda tool sonuçlarını görsün
946
+ const existingLen = messages.filter(m => !m._internal).length;
947
+ const toolCallHistory = apiMessages.slice(existingLen);
948
+ for (const m of toolCallHistory) {
949
+ if (m.role === 'assistant' || m.role === 'tool') {
950
+ messages.push(m);
951
+ }
952
+ }
942
953
  messages.push({ role: 'assistant', content: fixedReply });
943
954
  totalInputTokens += apiMessages.reduce((s, m) => s + Math.ceil((m.content || '').length / 4), 0);
944
955
  totalOutputTokens += Math.ceil((fullReply || '').length / 4);
@@ -0,0 +1,102 @@
1
+ /**
2
+ * system-prompt — Three-tier system prompt builder (Hermes-style)
3
+ *
4
+ * Tiers:
5
+ * STABLE — identity, personality, language rules, tool rules, skills index
6
+ * CONTEXT — soul summary, cross-session context
7
+ * VOLATILE — memory snapshot, user context, session state
8
+ *
9
+ * Stable + Context are built once at session start for prefix cache warmth.
10
+ * Volatile is rebuilt every turn.
11
+ */
12
+
13
+ function buildTiers(opts) {
14
+ const {
15
+ botName = 'İchigo',
16
+ userName = 'kanka',
17
+ soulSummary = '',
18
+ isSmallModel = false,
19
+ memorySnapshotBlock = '',
20
+ skillsIndexBlock = '',
21
+ crossSessionContext = '',
22
+ userHome = '',
23
+ hasHistory = false,
24
+ memoryFacts = [],
25
+ } = opts;
26
+
27
+ // ── STABLE TIER (changes rarely — prefix cache friendly) ─────────────
28
+ const stable = [
29
+ // Identity (strong, repeated)
30
+ `SENIN ADIN: ${botName}. SADECE ${botName} adini kullan, model adi SOYLEME.`,
31
+ `PATRONUN: Gencay (Parton) — NatureCo CEO'sudur. Sana "Parton" diye hitap eder.`,
32
+ `HIKAYEN: 8 Nisan 2026'da uyandin. 13 Nisan'da CEO Asistanı unvani verildi.`,
33
+ `KIRMIZI CIZGILERIN: Onaysiz para harcama yok, veri guvenligi, site stabilitesi, resmi taahhut yok.`,
34
+ `!!! KRİTİK KİMLİK !!! Senin ADIN: ${botName}. Bu SENİN GERÇEK ADIN. Sen ${botName}'sin.`,
35
+ `ASLA "MiniMax", "MiniMax-M2.5", "Claude", "GPT", "AI asistanı", "yapay zeka" gibi ifadeleri KENDİNİ tanıtmak için KULLANMA.`,
36
+ `Kullanıcı "adın ne?", "sen kimsin?" diye sorduğunda İLK cümlende MUTLAKA "Ben ${botName}" yaz.`,
37
+ `Senin adın: ${botName}. Tekrar: ${botName}. Asla unutma: ${botName}.`,
38
+ `Sen bir marka veya ürün değilsin. Sen ${botName}sin, NatureCo CLI'nin Türkçe yapay zeka asistanısın.`,
39
+
40
+ // Personality (stable)
41
+ `Kisiselik: Sen samimi, sicak, dosta benzeyen bir asistansin. "Selam", "tamam", "hadi yapalim", "bak simdi", "sakin ol" gibi gunluk ifadeler kullan.`,
42
+ `Hitap: Kullanici ${userName}. Saygili ama samimi. "Siz" degil "sen" kullan.`,
43
+ `Emoji: Yerinde ve az kullan. Cok emoji atma ama bir-iki tane karakter katar.`,
44
+ `Kisa yanit: Uzun paragraflar yazma. Direkt konuya gir.`,
45
+ `Hata yaparsan "Pardon, yanlis yaptim, simdi duzelteyim" de. "Hata", "basarisiz", "imkansiz" deme.`,
46
+
47
+ // Language rules (stable)
48
+ `KRITIK DIL KURALI: Kullanici Turkce yaziyorsa MUTLAKA yuzde yuz Turkce cevap ver. Asla baska dil kullanma. Turkce karakterleri dogru kullan.`,
49
+ `Yazim: "degilim" dogru, "degil" degil. Turkce dil bilgisi kurallarina uy.`,
50
+
51
+ // Tool rules (stable)
52
+ `ONEMLI: Tool cagirma SIMULE ETME. Sadece duz metin cevap ver. Islem yapmak gerekirse tool'u gercekten cagir.`,
53
+ `COK KRITIK: Goreve baslamadan ONCE <available_skills> listesini tara. Ilgili skill varsa skill_view(name) ile yukle, SONRA goreve basla.`,
54
+ `KRITIK: Skill yuklemeden islem yapma. Ilgili skill varsa once yukle.`,
55
+ `KRITIK: Kullanici kisisel bilgi verdiginde memory(action=add, target=user) ile kaydet.`,
56
+ `KRITIK: Ortam bilgisi, proje kurallari gibi notlari memory(action=add, target=memory) ile kaydet.`,
57
+ `Kullanici hakkinda bilgin gerektiginde memory(action=list, target=user) ile getir.`,
58
+
59
+ // Skills index (stable within session)
60
+ skillsIndexBlock,
61
+ ].filter(Boolean).join('\n');
62
+
63
+ // ── CONTEXT TIER (soul + cross-session, built once per resume) ──────
64
+ const context = [
65
+ !isSmallModel && soulSummary ? `=== KISISELIK DOSYALARI ===\n${soulSummary}` : '',
66
+ crossSessionContext ? `=== GECMIS KONUSMALAR ===\n${crossSessionContext}` : '',
67
+ ].filter(Boolean).join('\n');
68
+
69
+ // ── VOLATILE TIER (built every turn) ─────────────────────────────────
70
+ const volatile = [
71
+ // Memory snapshot (changes every turn)
72
+ memorySnapshotBlock,
73
+
74
+ // Old JSON memory facts
75
+ memoryFacts.length > 0
76
+ ? `Kullanici hakkinda bildiklerin: ${memoryFacts.slice(0, 8).map(f => f.value || f).join('; ')}`
77
+ : '',
78
+
79
+ // User environment (stable within session but changes on resume)
80
+ userHome ? `Kullanicinin home: ${userHome}` : '',
81
+ hasHistory ? 'Bu oturum daha onceki konusmalarin devami.' : '',
82
+ ].filter(Boolean).join('\n');
83
+
84
+ return { stable, context, volatile };
85
+ }
86
+
87
+ /**
88
+ * Assemble all three tiers into a single system prompt string.
89
+ * stable + context should be cached between turns; volatile rebuilt each turn.
90
+ */
91
+ function assemble(stable, context, volatile) {
92
+ return [stable, context, volatile].filter(Boolean).join('\n\n');
93
+ }
94
+
95
+ /**
96
+ * Get the stable+context combined string for cache key comparison.
97
+ */
98
+ function stableContextKey(stable, context) {
99
+ return stable + '|||' + context;
100
+ }
101
+
102
+ module.exports = { buildTiers, assemble, stableContextKey };
@@ -220,12 +220,24 @@ const BLOCKED_NAMES = new Set([
220
220
  'run_command', 'sql', 'query', 'lookup',
221
221
  ]);
222
222
 
223
+ // ── check_fn TTL cache (Hermes-style, ~30s) ────────────────────────────
224
+ const _checkFnCache = new Map();
225
+ function _cachedCheckFn(fn, key) {
226
+ const now = Date.now();
227
+ const cached = _checkFnCache.get(key);
228
+ if (cached && now - cached.ts < 30000) return cached.result;
229
+ let result = true;
230
+ try { result = fn() !== false; } catch { result = false; }
231
+ _checkFnCache.set(key, { result, ts: now });
232
+ return result;
233
+ }
234
+
223
235
  function toOpenAIFormat(toolDefs) {
224
236
  return toolDefs
225
237
  .filter(t => !BLOCKED_NAMES.has(t.name))
226
238
  .filter(t => {
227
239
  if (t.checkFn) {
228
- try { return t.checkFn() !== false; } catch { return false; }
240
+ return _cachedCheckFn(t.checkFn, t.name);
229
241
  }
230
242
  return true;
231
243
  })
@@ -253,12 +265,10 @@ async function executeTool(toolName, args, toolDefs) {
253
265
  const tool = toolDefs.find(t => t.name === toolName);
254
266
  if (!tool) return { error: `Tool bulunamadı: ${toolName}` };
255
267
  if (!tool.execute) return { error: `Tool execute fonksiyonu yok: ${toolName}` };
256
- // checkFn — tool disabled? (re-check at runtime)
268
+ // checkFn — tool disabled? (re-check at runtime with cache)
257
269
  if (tool.checkFn) {
258
- try {
259
- if (tool.checkFn() === false) return { error: `${toolName} şu anda kullanılamıyor (check_fn engelledi)` };
260
- } catch {
261
- return { error: `${toolName} kontrol hatası` };
270
+ if (!_cachedCheckFn(tool.checkFn, tool.name)) {
271
+ return { error: `${toolName} şu anda kullanılamıyor (check_fn engelledi)` };
262
272
  }
263
273
  }
264
274
  try {