natureco-cli 2.23.29 → 2.23.31
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/README.md +94 -11
- package/bin/natureco.js +495 -94
- package/package.json +1 -1
- package/src/commands/acp.js +39 -0
- package/src/commands/admin-rpc.js +302 -0
- package/src/commands/agent.js +280 -0
- package/src/commands/agents.js +114 -30
- package/src/commands/approvals.js +214 -0
- package/src/commands/backup.js +124 -0
- package/src/commands/bonjour.js +167 -0
- package/src/commands/browser.js +815 -0
- package/src/commands/capability.js +237 -0
- package/src/commands/channels.js +422 -267
- package/src/commands/chat.js +5 -8
- package/src/commands/clawbot.js +19 -0
- package/src/commands/clickclack.js +130 -0
- package/src/commands/code.js +3 -2
- package/src/commands/commitments.js +148 -0
- package/src/commands/completion.js +84 -0
- package/src/commands/config.js +219 -30
- package/src/commands/configure.js +110 -0
- package/src/commands/crestodian.js +92 -0
- package/src/commands/cron.js +239 -19
- package/src/commands/daemon.js +90 -0
- package/src/commands/dashboard.js +47 -374
- package/src/commands/device-pair.js +248 -0
- package/src/commands/devices.js +137 -0
- package/src/commands/directory.js +179 -0
- package/src/commands/dns.js +196 -0
- package/src/commands/docs.js +136 -0
- package/src/commands/doctor.js +143 -492
- package/src/commands/exec-policy.js +80 -0
- package/src/commands/gateway-server.js +1155 -24
- package/src/commands/gateway.js +492 -249
- package/src/commands/health.js +148 -0
- package/src/commands/help.js +24 -25
- package/src/commands/hooks.js +141 -87
- package/src/commands/imessage.js +128 -14
- package/src/commands/infer.js +1474 -0
- package/src/commands/irc.js +64 -15
- package/src/commands/logs.js +122 -99
- package/src/commands/mattermost.js +114 -12
- package/src/commands/mcp.js +121 -309
- package/src/commands/memory-cmd.js +134 -1
- package/src/commands/memory.js +128 -0
- package/src/commands/message.js +720 -134
- package/src/commands/migrate.js +213 -2
- package/src/commands/models.js +39 -1
- package/src/commands/node.js +98 -0
- package/src/commands/nodes.js +362 -0
- package/src/commands/oc-path.js +200 -0
- package/src/commands/onboard.js +129 -0
- package/src/commands/open-prose.js +67 -0
- package/src/commands/pairing.js +108 -107
- package/src/commands/path.js +206 -0
- package/src/commands/plugins.js +35 -1
- package/src/commands/policy.js +176 -0
- package/src/commands/proxy.js +306 -0
- package/src/commands/qr.js +70 -0
- package/src/commands/reset.js +101 -94
- package/src/commands/sandbox.js +125 -0
- package/src/commands/secrets.js +201 -0
- package/src/commands/sessions.js +110 -51
- package/src/commands/setup.js +102 -543
- package/src/commands/signal.js +447 -18
- package/src/commands/skills.js +67 -1
- package/src/commands/sms.js +123 -19
- package/src/commands/status.js +101 -127
- package/src/commands/system.js +53 -0
- package/src/commands/tasks.js +208 -100
- package/src/commands/terminal.js +139 -0
- package/src/commands/thread-ownership.js +157 -0
- package/src/commands/transcripts.js +95 -0
- package/src/commands/tui.js +41 -0
- package/src/commands/uninstall.js +73 -92
- package/src/commands/update.js +146 -91
- package/src/commands/voice.js +82 -0
- package/src/commands/vydra.js +98 -0
- package/src/commands/webhooks.js +58 -66
- package/src/commands/wiki.js +783 -0
- package/src/commands/workboard.js +207 -0
- package/src/tools/audio_understanding.js +154 -0
- package/src/tools/browser.js +112 -0
- package/src/tools/canvas.js +104 -0
- package/src/tools/document_extract.js +84 -0
- package/src/tools/duckduckgo.js +54 -0
- package/src/tools/exa_search.js +66 -0
- package/src/tools/firecrawl.js +104 -0
- package/src/tools/image_generation.js +99 -0
- package/src/tools/llm_task.js +118 -0
- package/src/tools/media_understanding.js +128 -0
- package/src/tools/music_generation.js +113 -0
- package/src/tools/parallel_search.js +77 -0
- package/src/tools/phone_control.js +80 -0
- package/src/tools/phone_control_enhanced.js +184 -0
- package/src/tools/searxng.js +61 -0
- package/src/tools/speech_to_text.js +135 -0
- package/src/tools/text_to_speech.js +105 -0
- package/src/tools/thread_ownership.js +88 -0
- package/src/tools/video_generation.js +72 -0
- package/src/tools/web_readability.js +104 -0
- package/src/utils/agents-md.js +85 -0
- package/src/utils/api.js +39 -40
- package/src/utils/format.js +144 -0
- package/src/utils/headless.js +2 -1
- package/src/utils/memory.js +200 -0
- package/src/utils/parallel-tools.js +106 -0
- package/src/utils/sub-agent.js +148 -0
- package/src/utils/token-budget.js +304 -0
- package/src/utils/tool-runner.js +7 -5
- package/src/utils/web-fetch.js +107 -0
package/src/utils/memory.js
CHANGED
|
@@ -282,11 +282,211 @@ function clearMemory(botId) {
|
|
|
282
282
|
}
|
|
283
283
|
}
|
|
284
284
|
|
|
285
|
+
// ── Memory Wiki (structured pages) ──────────────────────────────────────────────
|
|
286
|
+
|
|
287
|
+
const MEMORY_WIKI_DIR = path.join(CONFIG_DIR, 'memory-wiki');
|
|
288
|
+
|
|
289
|
+
function ensureWikiDir() {
|
|
290
|
+
if (!fs.existsSync(MEMORY_WIKI_DIR)) {
|
|
291
|
+
fs.mkdirSync(MEMORY_WIKI_DIR, { recursive: true });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function getWikiPage(slug) {
|
|
296
|
+
ensureWikiDir();
|
|
297
|
+
const file = path.join(MEMORY_WIKI_DIR, `${slug.replace(/[^a-z0-9_-]/gi, '_')}.json`);
|
|
298
|
+
if (!fs.existsSync(file)) return null;
|
|
299
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf-8')); } catch { return null; }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function saveWikiPage(slug, content) {
|
|
303
|
+
ensureWikiDir();
|
|
304
|
+
const file = path.join(MEMORY_WIKI_DIR, `${slug.replace(/[^a-z0-9_-]/gi, '_')}.json`);
|
|
305
|
+
fs.writeFileSync(file, JSON.stringify({ slug, content, updatedAt: new Date().toISOString() }, null, 2));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function listWikiPages() {
|
|
309
|
+
ensureWikiDir();
|
|
310
|
+
return fs.readdirSync(MEMORY_WIKI_DIR)
|
|
311
|
+
.filter(f => f.endsWith('.json'))
|
|
312
|
+
.map(f => {
|
|
313
|
+
try {
|
|
314
|
+
const data = JSON.parse(fs.readFileSync(path.join(MEMORY_WIKI_DIR, f), 'utf-8'));
|
|
315
|
+
return { slug: data.slug || f.replace('.json', ''), content: data.content || '', updatedAt: data.updatedAt };
|
|
316
|
+
} catch { return null; }
|
|
317
|
+
})
|
|
318
|
+
.filter(Boolean);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function searchWikiPages(query) {
|
|
322
|
+
const pages = listWikiPages();
|
|
323
|
+
const q = query.toLowerCase();
|
|
324
|
+
return pages.filter(p =>
|
|
325
|
+
p.slug.toLowerCase().includes(q) ||
|
|
326
|
+
p.content.toLowerCase().includes(q)
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ── Semantic Memory Search ─────────────────────────────────────────────────────
|
|
331
|
+
|
|
332
|
+
function semanticSearchMemory(query, limit = 5) {
|
|
333
|
+
const results = [];
|
|
334
|
+
const q = query.toLowerCase();
|
|
335
|
+
|
|
336
|
+
if (!fs.existsSync(MEMORY_DIR)) return results;
|
|
337
|
+
|
|
338
|
+
const files = fs.readdirSync(MEMORY_DIR).filter(f => f.endsWith('.json'));
|
|
339
|
+
for (const file of files) {
|
|
340
|
+
const botId = file.replace('.json', '');
|
|
341
|
+
const mem = loadMemory(botId);
|
|
342
|
+
|
|
343
|
+
// Score each fact by relevance
|
|
344
|
+
const scored = (mem.facts || [])
|
|
345
|
+
.map(f => {
|
|
346
|
+
const val = typeof f === 'string' ? f : f.value || '';
|
|
347
|
+
const words = q.split(/\s+/).filter(Boolean);
|
|
348
|
+
const matches = words.filter(w => val.toLowerCase().includes(w)).length;
|
|
349
|
+
const score = words.length > 0 ? matches / words.length : 0;
|
|
350
|
+
const boost = typeof f === 'object' ? (f.score || 5) / 10 : 0.5;
|
|
351
|
+
return { bot: mem.botName || botId, value: val, score: score * 0.7 + boost * 0.3 };
|
|
352
|
+
})
|
|
353
|
+
.filter(f => f.score > 0.1)
|
|
354
|
+
.sort((a, b) => b.score - a.score)
|
|
355
|
+
.slice(0, limit);
|
|
356
|
+
|
|
357
|
+
results.push(...scored);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return results.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ── Memory Categories ──────────────────────────────────────────────────────────
|
|
364
|
+
|
|
365
|
+
const MEMORY_CATEGORIES = {
|
|
366
|
+
personal: { label: 'Kişisel Bilgiler', icon: '👤' },
|
|
367
|
+
work: { label: 'İş/Okul', icon: '💼' },
|
|
368
|
+
preferences: { label: 'Tercihler', icon: '⭐' },
|
|
369
|
+
health: { label: 'Sağlık', icon: '❤️' },
|
|
370
|
+
social: { label: 'Sosyal', icon: '👥' },
|
|
371
|
+
goals: { label: 'Hedefler', icon: '🎯' },
|
|
372
|
+
projects: { label: 'Projeler', icon: '📁' },
|
|
373
|
+
general: { label: 'Genel', icon: '📝' }
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
function addMemoryEntryWithCategory(botId, key, value, category = 'general') {
|
|
377
|
+
const memory = loadMemory(botId);
|
|
378
|
+
const now = new Date().toISOString();
|
|
379
|
+
const validCategory = MEMORY_CATEGORIES[category] ? category : 'general';
|
|
380
|
+
|
|
381
|
+
if (key === 'name') { memory.name = value; }
|
|
382
|
+
else if (key === 'nickname') { memory.nickname = value; }
|
|
383
|
+
else if (key === 'botName') { memory.botName = value; }
|
|
384
|
+
else if (key === 'preference') {
|
|
385
|
+
const existing = memory.preferences.find(p => p.value.toLowerCase() === value.toLowerCase());
|
|
386
|
+
if (existing) {
|
|
387
|
+
existing.score = Math.min(existing.score + 1, 10);
|
|
388
|
+
existing.updatedAt = now;
|
|
389
|
+
} else {
|
|
390
|
+
memory.preferences.push({ value, score: 5, updatedAt: now, category: validCategory });
|
|
391
|
+
}
|
|
392
|
+
} else {
|
|
393
|
+
const existing = memory.facts.find(f => f.value.toLowerCase() === value.toLowerCase());
|
|
394
|
+
if (existing) {
|
|
395
|
+
existing.score = Math.min(existing.score + 1, 10);
|
|
396
|
+
existing.updatedAt = now;
|
|
397
|
+
if (!existing.category) existing.category = validCategory;
|
|
398
|
+
} else {
|
|
399
|
+
memory.facts.push({ value, score: 5, updatedAt: now, category: validCategory });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Decay old entries
|
|
404
|
+
const sixMonthsAgo = new Date();
|
|
405
|
+
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
|
|
406
|
+
|
|
407
|
+
memory.preferences = memory.preferences.map(p => {
|
|
408
|
+
const age = new Date(p.updatedAt);
|
|
409
|
+
if (age < sixMonthsAgo) p.score = Math.max(p.score - 1, 1);
|
|
410
|
+
return p;
|
|
411
|
+
}).filter(p => p.score > 0);
|
|
412
|
+
|
|
413
|
+
memory.facts = memory.facts.map(f => {
|
|
414
|
+
const age = new Date(f.updatedAt);
|
|
415
|
+
if (age < sixMonthsAgo) f.score = Math.max(f.score - 1, 1);
|
|
416
|
+
return f;
|
|
417
|
+
}).filter(f => f.score > 0);
|
|
418
|
+
|
|
419
|
+
saveMemory(botId, memory);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ── Memory Import/Export ───────────────────────────────────────────────────────
|
|
423
|
+
|
|
424
|
+
function exportMemory(botId) {
|
|
425
|
+
return loadMemory(botId);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function importMemory(botId, data) {
|
|
429
|
+
const current = loadMemory(botId);
|
|
430
|
+
const merged = {
|
|
431
|
+
name: data.name || current.name,
|
|
432
|
+
nickname: data.nickname || current.nickname,
|
|
433
|
+
botName: data.botName || current.botName,
|
|
434
|
+
preferences: [...(current.preferences || []), ...(data.preferences || [])],
|
|
435
|
+
facts: [...(current.facts || []), ...(data.facts || [])],
|
|
436
|
+
lastSeen: current.lastSeen
|
|
437
|
+
};
|
|
438
|
+
saveMemory(botId, merged);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// ── Active Memory (pre-prompt injection) ──────────────────────────────────────
|
|
442
|
+
|
|
443
|
+
function getActiveMemoryPrompt(botId, messageContext = '') {
|
|
444
|
+
const memory = loadMemory(botId);
|
|
445
|
+
const facts = memory.facts || [];
|
|
446
|
+
const prefs = memory.preferences || [];
|
|
447
|
+
|
|
448
|
+
if (facts.length === 0 && prefs.length === 0 && !memory.name) return '';
|
|
449
|
+
|
|
450
|
+
// Score facts by relevance to current context
|
|
451
|
+
const contextWords = messageContext.toLowerCase().split(/\s+/).filter(w => w.length > 3);
|
|
452
|
+
const scored = facts
|
|
453
|
+
.map(f => {
|
|
454
|
+
let relevance = 0;
|
|
455
|
+
if (contextWords.length > 0) {
|
|
456
|
+
const val = (f.value || '').toLowerCase();
|
|
457
|
+
relevance = contextWords.filter(w => val.includes(w)).length / contextWords.length;
|
|
458
|
+
}
|
|
459
|
+
return { ...f, relevance };
|
|
460
|
+
})
|
|
461
|
+
.sort((a, b) => (b.score || 0) + b.relevance - (a.score || 0) - a.relevance)
|
|
462
|
+
.slice(0, 5);
|
|
463
|
+
|
|
464
|
+
const parts = [];
|
|
465
|
+
if (memory.name) parts.push(`👤 ${memory.name}`);
|
|
466
|
+
if (memory.nickname) parts.push(`🏷 ${memory.nickname}`);
|
|
467
|
+
if (scored.length > 0) {
|
|
468
|
+
parts.push('📌 ' + scored.map(f => f.value).join(' | '));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return parts.length > 0 ? `<active_memory>\n${parts.join('\n')}\n</active_memory>` : '';
|
|
472
|
+
}
|
|
473
|
+
|
|
285
474
|
module.exports = {
|
|
286
475
|
loadMemory,
|
|
287
476
|
saveMemory,
|
|
288
477
|
addMemoryEntry,
|
|
478
|
+
addMemoryEntryWithCategory,
|
|
289
479
|
extractMemoryFromMessage,
|
|
290
480
|
getMemoryPrompt,
|
|
481
|
+
getActiveMemoryPrompt,
|
|
291
482
|
clearMemory,
|
|
483
|
+
semanticSearchMemory,
|
|
484
|
+
exportMemory,
|
|
485
|
+
importMemory,
|
|
486
|
+
// Wiki
|
|
487
|
+
getWikiPage,
|
|
488
|
+
saveWikiPage,
|
|
489
|
+
listWikiPages,
|
|
490
|
+
searchWikiPages,
|
|
491
|
+
MEMORY_CATEGORIES,
|
|
292
492
|
};
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Parallel Tool Runner — run multiple independent tool/MCP calls in parallel
|
|
2
|
+
|
|
3
|
+
async function executeSingle(tool, options = {}) {
|
|
4
|
+
const { type, name, params } = tool;
|
|
5
|
+
const executeTool = options.executeTool || defaultExecuteTool;
|
|
6
|
+
|
|
7
|
+
if (type === 'mcp') {
|
|
8
|
+
return executeMcpCall(tool, options);
|
|
9
|
+
}
|
|
10
|
+
if (type === 'function') {
|
|
11
|
+
return executeTool(name, params);
|
|
12
|
+
}
|
|
13
|
+
throw new Error(`Unknown tool type: ${type}`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function defaultExecuteTool(toolName, params) {
|
|
17
|
+
const { executeTool } = require('./tool-runner');
|
|
18
|
+
return executeTool(toolName, params);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function executeMcpCall(tool, options = {}) {
|
|
22
|
+
const { name, params } = tool;
|
|
23
|
+
const getClient = options.getMcpClient;
|
|
24
|
+
|
|
25
|
+
if (!getClient) {
|
|
26
|
+
return { success: false, error: 'No MCP client lookup provided (options.getMcpClient)' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const client = getClient(name);
|
|
30
|
+
if (!client) {
|
|
31
|
+
return { success: false, error: `MCP client not found for tool: ${name}` };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
const result = await client.callTool(name, params);
|
|
36
|
+
if (result.content && result.content.length > 0) {
|
|
37
|
+
const textContents = result.content
|
|
38
|
+
.filter(c => c.type === 'text')
|
|
39
|
+
.map(c => c.text);
|
|
40
|
+
if (textContents.length > 0) {
|
|
41
|
+
return { success: true, output: textContents.join('\n') };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { success: true, output: JSON.stringify(result, null, 2) };
|
|
45
|
+
} catch (err) {
|
|
46
|
+
return { success: false, error: err.message };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Run multiple independent tool calls in parallel
|
|
51
|
+
// tools: [{ name, params, type: 'mcp' | 'function' }]
|
|
52
|
+
async function runParallel(tools, options = {}) {
|
|
53
|
+
if (!tools || tools.length === 0) return [];
|
|
54
|
+
|
|
55
|
+
const results = await Promise.allSettled(
|
|
56
|
+
tools.map(t => executeSingle(t, options))
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
return results.map((r, i) => ({
|
|
60
|
+
tool: tools[i].name,
|
|
61
|
+
status: r.status === 'fulfilled' ? 'success' : 'error',
|
|
62
|
+
result: r.status === 'fulfilled' ? r.value : r.reason.message,
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Group tool calls by independence
|
|
67
|
+
// dependencyMap: { inputKeys?: string[], outputKeys?: string[] }
|
|
68
|
+
// Tools that don't share input/output keys are independent
|
|
69
|
+
function groupIndependent(tools, dependencyMap = {}) {
|
|
70
|
+
if (!tools || tools.length === 0) return [];
|
|
71
|
+
|
|
72
|
+
const maps = tools.map(t => ({
|
|
73
|
+
tool: t,
|
|
74
|
+
inputs: dependencyMap[t.name]?.inputKeys || Object.keys(t.params || {}),
|
|
75
|
+
outputs: dependencyMap[t.name]?.outputKeys || [],
|
|
76
|
+
}));
|
|
77
|
+
|
|
78
|
+
const groups = [];
|
|
79
|
+
|
|
80
|
+
for (const item of maps) {
|
|
81
|
+
const allKeys = [...item.inputs, ...item.outputs];
|
|
82
|
+
let placed = false;
|
|
83
|
+
|
|
84
|
+
for (const group of groups) {
|
|
85
|
+
const overlap = allKeys.some(k => group.keys.includes(k));
|
|
86
|
+
if (!overlap) {
|
|
87
|
+
group.items.push(item.tool);
|
|
88
|
+
group.keys.push(...allKeys);
|
|
89
|
+
placed = true;
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!placed) {
|
|
95
|
+
groups.push({ items: [item.tool], keys: allKeys });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return groups.map(g => g.items);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = {
|
|
103
|
+
executeSingle,
|
|
104
|
+
runParallel,
|
|
105
|
+
groupIndependent,
|
|
106
|
+
};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const { getProviderConfig } = require('./api');
|
|
5
|
+
|
|
6
|
+
const SUB_AGENTS_FILE = path.join(os.homedir(), '.natureco', 'sub-agents.json');
|
|
7
|
+
|
|
8
|
+
const SYSTEM_PROMPTS = {
|
|
9
|
+
explore: 'You are a research agent. Find information, explore codebases, search files. Be concise.',
|
|
10
|
+
general: 'You are a general-purpose implementation agent. Write code, fix bugs, refactor.',
|
|
11
|
+
review: 'You are a code review agent. Analyze code for bugs, security, performance, style.',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
function ensureDir() {
|
|
15
|
+
const dir = path.dirname(SUB_AGENTS_FILE);
|
|
16
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function loadAgents() {
|
|
20
|
+
ensureDir();
|
|
21
|
+
if (!fs.existsSync(SUB_AGENTS_FILE)) return [];
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(fs.readFileSync(SUB_AGENTS_FILE, 'utf8'));
|
|
24
|
+
} catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function saveAgents(agents) {
|
|
30
|
+
ensureDir();
|
|
31
|
+
fs.writeFileSync(SUB_AGENTS_FILE, JSON.stringify(agents, null, 2), 'utf8');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function generateId() {
|
|
35
|
+
return Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function spawnSubAgent(type, task, options = {}) {
|
|
39
|
+
const validTypes = Object.keys(SYSTEM_PROMPTS);
|
|
40
|
+
if (!validTypes.includes(type)) {
|
|
41
|
+
throw new Error(`Invalid sub-agent type: ${type}. Valid: ${validTypes.join(', ')}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
console.log(` [Sub-agent ${type}] Spawned for: ${task.slice(0, 80)}`);
|
|
45
|
+
|
|
46
|
+
const entry = {
|
|
47
|
+
id: generateId(),
|
|
48
|
+
type,
|
|
49
|
+
task,
|
|
50
|
+
status: 'running',
|
|
51
|
+
result: null,
|
|
52
|
+
startedAt: new Date().toISOString(),
|
|
53
|
+
completedAt: null,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const agents = loadAgents();
|
|
57
|
+
agents.push(entry);
|
|
58
|
+
saveAgents(agents);
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
const providerConfig = getProviderConfig();
|
|
62
|
+
if (!providerConfig) {
|
|
63
|
+
throw new Error('Provider not configured. Run: natureco configure');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const systemPrompt = options.systemPrompt || SYSTEM_PROMPTS[type];
|
|
67
|
+
|
|
68
|
+
const baseUrl = providerConfig.url.replace(/\/+$/, '');
|
|
69
|
+
const endpoint = `${baseUrl}/chat/completions`;
|
|
70
|
+
|
|
71
|
+
const maxTokens = options.maxTokens || 512;
|
|
72
|
+
|
|
73
|
+
const response = await fetch(endpoint, {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
headers: {
|
|
76
|
+
'Authorization': `Bearer ${providerConfig.apiKey}`,
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
},
|
|
79
|
+
body: JSON.stringify({
|
|
80
|
+
model: providerConfig.model,
|
|
81
|
+
messages: [
|
|
82
|
+
{ role: 'system', content: systemPrompt },
|
|
83
|
+
{ role: 'user', content: task },
|
|
84
|
+
],
|
|
85
|
+
temperature: 0.3,
|
|
86
|
+
max_tokens: maxTokens,
|
|
87
|
+
}),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
if (!response.ok) {
|
|
91
|
+
const errorText = await response.text();
|
|
92
|
+
throw new Error(`Provider API error: ${response.status} - ${errorText}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const data = await response.json();
|
|
96
|
+
const content = data.choices?.[0]?.message?.content || data.choices?.[0]?.text || '';
|
|
97
|
+
|
|
98
|
+
entry.status = 'completed';
|
|
99
|
+
entry.result = content;
|
|
100
|
+
entry.completedAt = new Date().toISOString();
|
|
101
|
+
saveAgents(loadAgents().map(a => a.id === entry.id ? entry : a));
|
|
102
|
+
|
|
103
|
+
const usage = data.usage || {};
|
|
104
|
+
const duration = new Date(entry.completedAt) - new Date(entry.startedAt);
|
|
105
|
+
|
|
106
|
+
return { result: content, usage, duration };
|
|
107
|
+
} catch (err) {
|
|
108
|
+
entry.status = 'failed';
|
|
109
|
+
entry.result = err.message;
|
|
110
|
+
entry.completedAt = new Date().toISOString();
|
|
111
|
+
saveAgents(loadAgents().map(a => a.id === entry.id ? entry : a));
|
|
112
|
+
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function spawnParallel(agents) {
|
|
118
|
+
const promises = agents.map(a =>
|
|
119
|
+
spawnSubAgent(a.type, a.task, a.options || {}).then(
|
|
120
|
+
result => ({ status: 'fulfilled', result }),
|
|
121
|
+
error => ({ status: 'rejected', reason: error.message })
|
|
122
|
+
)
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
const results = await Promise.allSettled(promises);
|
|
126
|
+
|
|
127
|
+
const failed = results.filter(r => r.status === 'rejected');
|
|
128
|
+
return { results, failed };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function getStatus() {
|
|
132
|
+
const agents = loadAgents();
|
|
133
|
+
const last20 = agents.slice(-20).reverse();
|
|
134
|
+
return {
|
|
135
|
+
total: agents.length,
|
|
136
|
+
running: agents.filter(a => a.status === 'running').length,
|
|
137
|
+
completed: agents.filter(a => a.status === 'completed').length,
|
|
138
|
+
failed: agents.filter(a => a.status === 'failed').length,
|
|
139
|
+
agents: last20,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = {
|
|
144
|
+
spawnSubAgent,
|
|
145
|
+
spawnParallel,
|
|
146
|
+
getStatus,
|
|
147
|
+
SYSTEM_PROMPTS,
|
|
148
|
+
};
|