natureco-cli 5.7.19 → 5.8.0
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 +1 -1
- package/src/commands/repl.js +117 -30
- package/src/utils/api.js +50 -33
- package/src/utils/memory-store.js +9 -0
- package/src/utils/tool-guardrails.js +85 -0
- package/src/utils/tool-runner.js +22 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "natureco-cli",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.8.0",
|
|
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"
|
package/src/commands/repl.js
CHANGED
|
@@ -27,7 +27,8 @@ 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
|
|
30
|
+
const { buildTiers, assemble } = require('../utils/system-prompt');
|
|
31
|
+
const { ToolGuardrails } = require('../utils/tool-guardrails');
|
|
31
32
|
|
|
32
33
|
// v5.4.6: Model adi sizintisini engelle — global'e ata, callback'lerden erisebilir olsun
|
|
33
34
|
const MODEL_NAMES_TO_HIDE = ['MiniMax-M2.5', 'MiniMaxM2.5', 'minimaxm25', 'Claude-3', 'GPT-4', 'ChatGPT'];
|
|
@@ -58,6 +59,46 @@ function getToolDefs() {
|
|
|
58
59
|
return _toolDefs;
|
|
59
60
|
}
|
|
60
61
|
|
|
62
|
+
// ── System prompt tier cache (Hermes-style prefix cache warmth) ────────────
|
|
63
|
+
// stable+context built once at session start, volatile rebuilt per turn.
|
|
64
|
+
let _cachedStable = '';
|
|
65
|
+
let _cachedContext = '';
|
|
66
|
+
let _cachedTierOpts = null; // opts snapshot for volatile-only rebuilds
|
|
67
|
+
|
|
68
|
+
function rebuildSystemPrompt(opts) {
|
|
69
|
+
// If stable/context opts changed, rebuild them too
|
|
70
|
+
const needsFullRebuild = !_cachedTierOpts ||
|
|
71
|
+
_cachedTierOpts.botName !== opts.botName ||
|
|
72
|
+
_cachedTierOpts.soulSummary !== opts.soulSummary ||
|
|
73
|
+
_cachedTierOpts.skillsIndexBlock !== opts.skillsIndexBlock ||
|
|
74
|
+
_cachedTierOpts.crossSessionContext !== opts.crossSessionContext;
|
|
75
|
+
|
|
76
|
+
if (needsFullRebuild || !_cachedStable) {
|
|
77
|
+
const tiers = buildTiers(opts);
|
|
78
|
+
_cachedStable = tiers.stable;
|
|
79
|
+
_cachedContext = tiers.context;
|
|
80
|
+
_cachedTierOpts = {
|
|
81
|
+
botName: opts.botName,
|
|
82
|
+
soulSummary: opts.soulSummary,
|
|
83
|
+
skillsIndexBlock: opts.skillsIndexBlock,
|
|
84
|
+
crossSessionContext: opts.crossSessionContext,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
// Volatile always rebuilt fresh
|
|
88
|
+
const volatileOnly = buildTiers({
|
|
89
|
+
...opts,
|
|
90
|
+
// Pass empty strings for stable/context fields so buildTiers only builds volatile
|
|
91
|
+
botName: '',
|
|
92
|
+
soulSummary: '',
|
|
93
|
+
skillsIndexBlock: '',
|
|
94
|
+
crossSessionContext: '',
|
|
95
|
+
});
|
|
96
|
+
return assemble(_cachedStable, _cachedContext, volatileOnly.volatile);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── Tool Guardrails instance (Hermes-style) ─────────────────────────────
|
|
100
|
+
const guardrails = new ToolGuardrails();
|
|
101
|
+
|
|
61
102
|
// CLI komutları (REPL içinden çalıştırılabilir)
|
|
62
103
|
const CLI_COMMANDS = {
|
|
63
104
|
'/doctor': { desc: 'Sistem sağlığı kontrolü', run: ['doctor'] },
|
|
@@ -233,6 +274,7 @@ async function sendStreaming(providerUrl, providerApiKey, messages, model, onChu
|
|
|
233
274
|
const isMM = isMiniMax(providerUrl);
|
|
234
275
|
const toolDefs = getToolDefs();
|
|
235
276
|
const toolParam = toOpenAIFormat(toolDefs);
|
|
277
|
+
guardrails.reset();
|
|
236
278
|
|
|
237
279
|
let currentMessages = messages;
|
|
238
280
|
let fullText = '';
|
|
@@ -268,17 +310,18 @@ async function sendStreaming(providerUrl, providerApiKey, messages, model, onChu
|
|
|
268
310
|
|
|
269
311
|
while (iterations < MAX_TOOL_ITERATIONS) {
|
|
270
312
|
iterations++;
|
|
313
|
+
const shouldStream = !isMM; // MiniMax streaming endpoint doesn't support tool_calls
|
|
271
314
|
const body = {
|
|
272
315
|
model,
|
|
273
316
|
messages: currentMessages,
|
|
274
|
-
stream:
|
|
317
|
+
stream: shouldStream,
|
|
275
318
|
temperature: 0.3,
|
|
276
319
|
max_tokens: 2048,
|
|
277
320
|
};
|
|
278
321
|
if (toolParam) body.tools = toolParam;
|
|
279
322
|
if (isMM) body.tool_choice = 'auto'; // MiniMax için explicit
|
|
280
323
|
|
|
281
|
-
if (!
|
|
324
|
+
if (!shouldStream) {
|
|
282
325
|
// MiniMax (non-stream) — tool_calls desteklemiyor varsayalım
|
|
283
326
|
const res = await apiRequest(providerUrl, providerApiKey, body, false);
|
|
284
327
|
const msg = res.choices?.[0]?.message || {};
|
|
@@ -408,12 +451,25 @@ async function processToolCalls(toolCalls, onToolCall) {
|
|
|
408
451
|
return { name, args, id };
|
|
409
452
|
});
|
|
410
453
|
|
|
411
|
-
//
|
|
412
|
-
|
|
413
|
-
const
|
|
454
|
+
// Filter out blocked tools via guardrails
|
|
455
|
+
guardrails.startIteration();
|
|
456
|
+
const blocked = parsed.filter(p => {
|
|
457
|
+
const check = guardrails.check(p.name, p.args);
|
|
458
|
+
if (check.blocked) {
|
|
459
|
+
if (onToolCall) onToolCall({ name: p.name, args: p.args, status: 'done', result: { error: check.reason } });
|
|
460
|
+
results.push({ ...p, result: { error: check.reason }, _blocked: true });
|
|
461
|
+
return false;
|
|
462
|
+
}
|
|
463
|
+
return true;
|
|
464
|
+
});
|
|
465
|
+
const allowed = parsed.filter(p => !results.some(r => r.id === p.id && r._blocked));
|
|
466
|
+
|
|
467
|
+
// Separate parallel-safe and sequential tools (over allowed only)
|
|
468
|
+
const parallelBatch = allowed.filter(p => PARALLEL_SAFE_TOOLS.has(p.name));
|
|
469
|
+
const sequentialBatch = allowed.filter(p => !PARALLEL_SAFE_TOOLS.has(p.name));
|
|
414
470
|
|
|
415
|
-
// Notify UI for all
|
|
416
|
-
for (const p of
|
|
471
|
+
// Notify UI for all non-blocked
|
|
472
|
+
for (const p of allowed) {
|
|
417
473
|
if (onToolCall) onToolCall({ name: p.name, args: p.args, status: 'running' });
|
|
418
474
|
}
|
|
419
475
|
|
|
@@ -421,6 +477,8 @@ async function processToolCalls(toolCalls, onToolCall) {
|
|
|
421
477
|
if (parallelBatch.length > 0) {
|
|
422
478
|
const parallelResults = await Promise.all(parallelBatch.map(async (p) => {
|
|
423
479
|
const result = await executeTool(p.name, p.args, toolDefs);
|
|
480
|
+
const success = result?.success !== false;
|
|
481
|
+
guardrails.record(p.name, p.args, success);
|
|
424
482
|
return { ...p, result };
|
|
425
483
|
}));
|
|
426
484
|
results.push(...parallelResults);
|
|
@@ -429,9 +487,16 @@ async function processToolCalls(toolCalls, onToolCall) {
|
|
|
429
487
|
// Run sequential batch one at a time
|
|
430
488
|
for (const p of sequentialBatch) {
|
|
431
489
|
const result = await executeTool(p.name, p.args, toolDefs);
|
|
490
|
+
const success = result?.success !== false;
|
|
491
|
+
guardrails.record(p.name, p.args, success);
|
|
432
492
|
results.push({ ...p, result });
|
|
433
493
|
}
|
|
434
494
|
|
|
495
|
+
// No-progress check: if all tools failed, inject warning
|
|
496
|
+
if (guardrails.isNoProgress()) {
|
|
497
|
+
if (onToolCall) onToolCall({ name: '_no_progress', args: null, status: 'done', result: { error: 'All tools failed this iteration' } });
|
|
498
|
+
}
|
|
499
|
+
|
|
435
500
|
// Notify UI done + build messages
|
|
436
501
|
const messages = [];
|
|
437
502
|
for (const { name, id, result } of results) {
|
|
@@ -575,26 +640,23 @@ async function startRepl(args) {
|
|
|
575
640
|
}
|
|
576
641
|
|
|
577
642
|
// System prompt oluştur (memory + identity + persistent bağlam)
|
|
578
|
-
// v5.
|
|
643
|
+
// v5.6.5: Kucuk model tespiti (Groq, Mistral Small, Ollama) - SOUL injection skip
|
|
579
644
|
const botName = memory.botName || 'Asistan';
|
|
580
645
|
const userName = memory.name || memory.nickname || 'kanka';
|
|
581
|
-
// v5.6.5: Kucuk model tespiti (Groq, Mistral Small, Ollama) - SOUL injection skip
|
|
582
646
|
const isSmallModel = (cfg.providerUrl || '').includes('groq.com') ||
|
|
583
647
|
(cfg.providerUrl || '').includes('mistral.ai') ||
|
|
584
648
|
(cfg.providerUrl || '').includes('localhost') ||
|
|
585
649
|
(cfg.providerUrl || '').includes('ollama');
|
|
586
|
-
//
|
|
587
|
-
|
|
588
|
-
// and tear down the REPL session mid-conversation.
|
|
589
|
-
const tiers = buildTiers({
|
|
650
|
+
// Build system prompt with tier caching (stable+context cached, volatile fresh)
|
|
651
|
+
const promptOpts = {
|
|
590
652
|
botName, userName, soulSummary, isSmallModel,
|
|
591
653
|
memorySnapshotBlock, skillsIndexBlock,
|
|
592
654
|
crossSessionContext: crossSessionContext || '',
|
|
593
655
|
userHome: cfg.userHome || '',
|
|
594
656
|
hasHistory: messages.length > 0,
|
|
595
657
|
memoryFacts: memory.facts || [],
|
|
596
|
-
}
|
|
597
|
-
let systemPrompt =
|
|
658
|
+
};
|
|
659
|
+
let systemPrompt = rebuildSystemPrompt(promptOpts);
|
|
598
660
|
|
|
599
661
|
if (messages.length === 0) {
|
|
600
662
|
messages.push({ role: 'system', content: systemPrompt, _internal: true });
|
|
@@ -790,9 +852,12 @@ async function startRepl(args) {
|
|
|
790
852
|
fs.unlinkSync(path.join(MEMORY_DIR, `${(cfg.userName || 'default').toLowerCase()}.json`));
|
|
791
853
|
}
|
|
792
854
|
memory = { name: cfg.userName, nickname: null, botName: 'Asistan', facts: [], preferences: [], history: [] };
|
|
793
|
-
// System prompt'u
|
|
794
|
-
|
|
795
|
-
|
|
855
|
+
// System prompt'u rebuild with cleared memory
|
|
856
|
+
promptOpts.memoryFacts = [];
|
|
857
|
+
memoryStore.clear();
|
|
858
|
+
promptOpts.memorySnapshotBlock = memoryStore.getSystemPromptBlock();
|
|
859
|
+
systemPrompt = rebuildSystemPrompt(promptOpts);
|
|
860
|
+
messages[0] = { role: 'system', content: systemPrompt, _internal: true };
|
|
796
861
|
console.log(chalk.green(' ✓ Memory temizlendi'));
|
|
797
862
|
} catch (e) {
|
|
798
863
|
console.log(chalk.red(' ❌ ' + e.message));
|
|
@@ -822,7 +887,15 @@ async function startRepl(args) {
|
|
|
822
887
|
break;
|
|
823
888
|
case 'system':
|
|
824
889
|
if (!arg) { console.log(chalk.yellow(' Kullanım: /system <text>')); break; }
|
|
825
|
-
|
|
890
|
+
// Override stable tier directly (user's custom text)
|
|
891
|
+
_cachedStable = arg;
|
|
892
|
+
// Rebuild volatile only (context stays unchanged)
|
|
893
|
+
memoryStore.load();
|
|
894
|
+
promptOpts.memorySnapshotBlock = memoryStore.getSystemPromptBlock();
|
|
895
|
+
promptOpts.memoryFacts = memory.facts || [];
|
|
896
|
+
const volOpts = { ...promptOpts, botName: '', soulSummary: '', skillsIndexBlock: '', crossSessionContext: '' };
|
|
897
|
+
const volTiers = buildTiers(volOpts);
|
|
898
|
+
systemPrompt = assemble(_cachedStable, _cachedContext, volTiers.volatile);
|
|
826
899
|
messages[0] = { role: 'system', content: systemPrompt, _internal: true };
|
|
827
900
|
console.log(chalk.green(' ✓ System prompt güncellendi'));
|
|
828
901
|
break;
|
|
@@ -835,8 +908,14 @@ async function startRepl(args) {
|
|
|
835
908
|
if (!arg) { console.log(chalk.yellow(` Mevcut: ${memory.botName || 'Asistan'}`)); break; }
|
|
836
909
|
memory.botName = arg;
|
|
837
910
|
saveMemory(cfg.userName, memory);
|
|
838
|
-
|
|
839
|
-
|
|
911
|
+
// Rebuild stable tier with new botName
|
|
912
|
+
promptOpts.botName = arg;
|
|
913
|
+
_cachedTierOpts = null; // force full rebuild
|
|
914
|
+
memoryStore.load();
|
|
915
|
+
promptOpts.memorySnapshotBlock = memoryStore.getSystemPromptBlock();
|
|
916
|
+
promptOpts.memoryFacts = memory.facts || [];
|
|
917
|
+
systemPrompt = rebuildSystemPrompt(promptOpts);
|
|
918
|
+
messages[0] = { role: 'system', content: systemPrompt, _internal: true };
|
|
840
919
|
console.log(chalk.green(' ✓ Bot adı: ') + chalk.cyan(arg));
|
|
841
920
|
break;
|
|
842
921
|
case 'tokens':
|
|
@@ -891,6 +970,14 @@ async function startRepl(args) {
|
|
|
891
970
|
// AI cevabı
|
|
892
971
|
process.stdout.write(tui.styled('\n AI ', { color: tui.PALETTE.secondary, bold: true }));
|
|
893
972
|
try {
|
|
973
|
+
// Per-turn: rebuild volatile tier with current memory snapshot (Hermes frozen snapshot)
|
|
974
|
+
guardrails.reset();
|
|
975
|
+
memory = loadMemory(cfg.userName);
|
|
976
|
+
memoryStore.load();
|
|
977
|
+
promptOpts.memorySnapshotBlock = memoryStore.getSystemPromptBlock();
|
|
978
|
+
promptOpts.memoryFacts = memory.facts || [];
|
|
979
|
+
systemPrompt = rebuildSystemPrompt(promptOpts);
|
|
980
|
+
messages[0] = { role: 'system', content: systemPrompt, _internal: true };
|
|
894
981
|
const apiMessages = messages.filter(m => !m._internal);
|
|
895
982
|
const reply = await sendStreaming(
|
|
896
983
|
providerUrl,
|
|
@@ -899,19 +986,19 @@ async function startRepl(args) {
|
|
|
899
986
|
model,
|
|
900
987
|
// v5.6.12: Callback bos - tam metin 'reply' olarak gelecek (non-stream mode)
|
|
901
988
|
() => {},
|
|
902
|
-
// Tool call callback —
|
|
903
|
-
(toolEvent) => {
|
|
989
|
+
// Tool call callback — Hermes-style per-tool status line
|
|
990
|
+
((toolEvent) => {
|
|
991
|
+
const name = toolEvent.name;
|
|
904
992
|
if (toolEvent.status === 'running') {
|
|
905
|
-
process.stdout.write(tui.styled('\r 🔧 ' +
|
|
993
|
+
process.stdout.write(tui.styled('\r 🔧 ' + name + '... ', { color: tui.PALETTE.muted }));
|
|
906
994
|
} else if (toolEvent.status === 'done') {
|
|
907
|
-
if (toolEvent.result
|
|
908
|
-
process.stdout.write(tui.styled('
|
|
995
|
+
if (toolEvent.result?.error) {
|
|
996
|
+
process.stdout.write(tui.styled(' ✗ ' + name + ': ' + String(toolEvent.result.error).slice(0, 80) + '\n', { color: tui.PALETTE.danger }));
|
|
909
997
|
} else {
|
|
910
|
-
process.stdout.write(
|
|
998
|
+
process.stdout.write(tui.styled(' ✓ ' + name + '\n', { color: tui.PALETTE.success }));
|
|
911
999
|
}
|
|
912
|
-
process.stdout.write(tui.styled(' AI ', { color: tui.PALETTE.secondary, bold: true }));
|
|
913
1000
|
}
|
|
914
|
-
}
|
|
1001
|
+
})
|
|
915
1002
|
);
|
|
916
1003
|
// v5.6.12: Tam metin 'reply' olarak zaten geldi (non-stream mode)
|
|
917
1004
|
const fullReply = String(reply || '');
|
package/src/utils/api.js
CHANGED
|
@@ -10,6 +10,8 @@ const { getToolDefinitions, executeToolCalls } = require('./tool-runner');
|
|
|
10
10
|
const { MCPClient } = require('./mcp-client');
|
|
11
11
|
const TB = require('./token-budget');
|
|
12
12
|
const { accumulateToolCallDeltas } = require('./streaming-tools');
|
|
13
|
+
const { ToolGuardrails } = require('./tool-guardrails');
|
|
14
|
+
const guardrails = new ToolGuardrails();
|
|
13
15
|
|
|
14
16
|
/**
|
|
15
17
|
* v5.5.0: Provider-specific format detection
|
|
@@ -756,44 +758,59 @@ async function sendMessageToProvider(apiKey, message, conversationId = null, sys
|
|
|
756
758
|
input: JSON.parse(tc.function.arguments)
|
|
757
759
|
}));
|
|
758
760
|
|
|
759
|
-
|
|
760
|
-
const
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
const
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
761
|
+
// Group MCP and local tools
|
|
762
|
+
const mcpTools = getMcpTools();
|
|
763
|
+
const mcpCalls = toolCalls.filter(tc => mcpTools.find(t => t.name === tc.name));
|
|
764
|
+
const localCalls = toolCalls.filter(tc => !mcpTools.find(t => t.name === tc.name));
|
|
765
|
+
|
|
766
|
+
// Guardrails: filter blocked tools
|
|
767
|
+
guardrails.reset();
|
|
768
|
+
guardrails.startIteration();
|
|
769
|
+
const blockedMcp = mcpCalls.filter(tc => {
|
|
770
|
+
const check = guardrails.check(tc.name, tc.input);
|
|
771
|
+
return check.blocked;
|
|
772
|
+
});
|
|
773
|
+
const blockedLocal = localCalls.filter(tc => {
|
|
774
|
+
const check = guardrails.check(tc.name, tc.input);
|
|
775
|
+
return check.blocked;
|
|
776
|
+
});
|
|
777
|
+
|
|
778
|
+
// Execute local tools in parallel (tool-runner already parallelizes safe tools)
|
|
779
|
+
let localResults = [];
|
|
780
|
+
if (localCalls.filter(tc => !blockedLocal.includes(tc)).length > 0) {
|
|
781
|
+
debugLog(`[Local] Executing ${localCalls.length} tool(s) concurrently`);
|
|
782
|
+
localResults = await executeToolCalls(
|
|
783
|
+
localCalls.filter(tc => !blockedLocal.includes(tc)),
|
|
784
|
+
{ toolDefinitions: getToolDefinitions() }
|
|
785
|
+
);
|
|
786
|
+
for (const r of localResults) {
|
|
787
|
+
guardrails.record(r.name, {}, r.result?.success !== false);
|
|
784
788
|
}
|
|
789
|
+
}
|
|
785
790
|
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
791
|
+
// Execute MCP tools in parallel (they're independent by nature)
|
|
792
|
+
let mcpResults = [];
|
|
793
|
+
if (mcpCalls.filter(tc => !blockedMcp.includes(tc)).length > 0) {
|
|
794
|
+
debugLog(`[MCP] Executing ${mcpCalls.length} tool(s) concurrently`);
|
|
795
|
+
mcpResults = await Promise.all(
|
|
796
|
+
mcpCalls.filter(tc => !blockedMcp.includes(tc)).map(async (tc) => {
|
|
797
|
+
const result = await executeMcpTool(tc.name, tc.input);
|
|
798
|
+
guardrails.record(tc.name, tc.input, result?.success !== false);
|
|
799
|
+
return { id: tc.id, name: tc.name, result };
|
|
800
|
+
})
|
|
801
|
+
);
|
|
790
802
|
}
|
|
791
803
|
|
|
792
|
-
// Add tool results
|
|
793
|
-
|
|
794
|
-
|
|
804
|
+
// Add blocked tool results as errors
|
|
805
|
+
const allResults = [
|
|
806
|
+
...blockedMcp.map(tc => ({ id: tc.id, name: tc.name, result: { error: `blocked_by_guardrails: ${tc.name}` } })),
|
|
807
|
+
...blockedLocal.map(tc => ({ id: tc.id, name: tc.name, result: { error: `blocked_by_guardrails: ${tc.name}` } })),
|
|
808
|
+
...localResults,
|
|
809
|
+
...mcpResults,
|
|
810
|
+
];
|
|
811
|
+
|
|
812
|
+
for (const result of allResults) {
|
|
795
813
|
const encodedContent = encodeToolResult(result.result);
|
|
796
|
-
|
|
797
814
|
messages.push({
|
|
798
815
|
role: 'tool',
|
|
799
816
|
tool_call_id: result.id,
|
|
@@ -120,6 +120,15 @@ class MemoryStore {
|
|
|
120
120
|
return JSON.stringify({ success: true, message: 'Memory entry removed.', removed: removed[0] });
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
clear(target) {
|
|
124
|
+
const path = this._pathFor(target);
|
|
125
|
+
this._ensureDir();
|
|
126
|
+
fs.writeFileSync(path, '', 'utf8');
|
|
127
|
+
const entries = target === 'user' ? this._userEntries : this._memoryEntries;
|
|
128
|
+
entries.length = 0;
|
|
129
|
+
return JSON.stringify({ success: true, message: `Memory ${target} cleared.` });
|
|
130
|
+
}
|
|
131
|
+
|
|
123
132
|
replace(target, oldContent, newContent) {
|
|
124
133
|
if (!oldContent || !newContent) {
|
|
125
134
|
return JSON.stringify({ success: false, error: 'Both old and new content required.' });
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool Guardrails — Hermes-style ToolCallGuardrailController
|
|
3
|
+
*
|
|
4
|
+
* Tracks per-iteration:
|
|
5
|
+
* - failure count per tool
|
|
6
|
+
* - repeated identical calls (same name + same args)
|
|
7
|
+
* - no-progress detection (all tools failing)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
class ToolGuardrails {
|
|
11
|
+
constructor() {
|
|
12
|
+
this.reset();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
reset() {
|
|
16
|
+
this.callLog = []; // [{ name, argsKey, iteration, success }]
|
|
17
|
+
this.failureCounts = {}; // { toolName: count }
|
|
18
|
+
this.iteration = 0;
|
|
19
|
+
this.blockedTools = new Set();
|
|
20
|
+
this.consecutiveFailures = {};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
startIteration() {
|
|
24
|
+
this.iteration++;
|
|
25
|
+
// Decay consecutive failures each iteration (Hermes: decay factor 0.5)
|
|
26
|
+
for (const name of Object.keys(this.consecutiveFailures)) {
|
|
27
|
+
this.consecutiveFailures[name] = Math.floor(this.consecutiveFailures[name] * 0.5);
|
|
28
|
+
if (this.consecutiveFailures[name] <= 0) {
|
|
29
|
+
delete this.consecutiveFailures[name];
|
|
30
|
+
this.blockedTools.delete(name);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Returns blocked tool names if guardrails trigger.
|
|
37
|
+
*/
|
|
38
|
+
check(toolName, toolArgs) {
|
|
39
|
+
const argsKey = JSON.stringify(toolArgs || {});
|
|
40
|
+
|
|
41
|
+
// 1. Too many repeated identical calls (Hermes: same name+args in last 3 calls)
|
|
42
|
+
const identicalCount = this.callLog.filter(
|
|
43
|
+
c => c.name === toolName && c.argsKey === argsKey && c.iteration >= this.iteration - 2
|
|
44
|
+
).length;
|
|
45
|
+
if (identicalCount >= 2) {
|
|
46
|
+
return { blocked: true, reason: `repeated_call: ${toolName} called ${identicalCount + 1}x with same args` };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 2. Too many failures (Hermes: 2+ failures = blocked for this iteration)
|
|
50
|
+
const recentFailures = this.callLog.filter(
|
|
51
|
+
c => c.name === toolName && !c.success && c.iteration >= this.iteration - 1
|
|
52
|
+
).length;
|
|
53
|
+
if (recentFailures >= 2 || (this.consecutiveFailures[toolName] || 0) >= 2) {
|
|
54
|
+
this.blockedTools.add(toolName);
|
|
55
|
+
return { blocked: true, reason: `too_many_failures: ${toolName} failed ${recentFailures + 1}x` };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return { blocked: false };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Record a tool call result.
|
|
63
|
+
*/
|
|
64
|
+
record(toolName, toolArgs, success) {
|
|
65
|
+
const argsKey = JSON.stringify(toolArgs || {});
|
|
66
|
+
this.callLog.push({ name: toolName, argsKey, iteration: this.iteration, success });
|
|
67
|
+
|
|
68
|
+
if (!success) {
|
|
69
|
+
this.failureCounts[toolName] = (this.failureCounts[toolName] || 0) + 1;
|
|
70
|
+
this.consecutiveFailures[toolName] = (this.consecutiveFailures[toolName] || 0) + 1;
|
|
71
|
+
} else {
|
|
72
|
+
this.consecutiveFailures[toolName] = 0;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Returns true if no tool has succeeded this iteration (no-progress).
|
|
78
|
+
*/
|
|
79
|
+
isNoProgress() {
|
|
80
|
+
const thisIter = this.callLog.filter(c => c.iteration === this.iteration);
|
|
81
|
+
return thisIter.length > 0 && thisIter.every(c => !c.success);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
module.exports = { ToolGuardrails };
|
package/src/utils/tool-runner.js
CHANGED
|
@@ -146,13 +146,33 @@ async function executeTool(toolName, params, opts = {}) {
|
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
// ── Execute multiple tool calls
|
|
149
|
+
// ── Execute multiple tool calls (parallel for independent, sequential for others) ──
|
|
150
|
+
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']);
|
|
151
|
+
|
|
150
152
|
async function executeToolCalls(toolCalls, opts = {}) {
|
|
153
|
+
if (!toolCalls || toolCalls.length === 0) return [];
|
|
154
|
+
|
|
155
|
+
// Group: parallel-safe vs sequential
|
|
156
|
+
const safe = toolCalls.filter(c => PARALLEL_SAFE_TOOLS.has(c.name));
|
|
157
|
+
const sequential = toolCalls.filter(c => !PARALLEL_SAFE_TOOLS.has(c.name));
|
|
158
|
+
|
|
151
159
|
const results = [];
|
|
152
|
-
|
|
160
|
+
|
|
161
|
+
// Run parallel-safe tools concurrently
|
|
162
|
+
if (safe.length > 0) {
|
|
163
|
+
const safeResults = await Promise.all(safe.map(async (call) => {
|
|
164
|
+
const result = await executeTool(call.name, call.input, opts);
|
|
165
|
+
return { id: call.id, name: call.name, result };
|
|
166
|
+
}));
|
|
167
|
+
results.push(...safeResults);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Run sequential tools one at a time
|
|
171
|
+
for (const call of sequential) {
|
|
153
172
|
const result = await executeTool(call.name, call.input, opts);
|
|
154
173
|
results.push({ id: call.id, name: call.name, result });
|
|
155
174
|
}
|
|
175
|
+
|
|
156
176
|
return results;
|
|
157
177
|
}
|
|
158
178
|
|