natureco-cli 5.20.3 → 5.21.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/CHANGELOG.md +779 -750
- package/README.md +608 -608
- package/bin/natureco.js +1099 -1095
- package/package.json +95 -94
- package/scripts/generate-qr.js +21 -0
- package/scripts/import-curated-skills-log.json +5 -0
- package/scripts/import-curated-skills.js +262 -0
- package/scripts/import-skills-log.json +167 -0
- package/scripts/import-skills.js +261 -0
- package/scripts/postinstall.js +125 -0
- package/src/commands/agent.js +280 -280
- package/src/commands/ask.js +4 -2
- package/src/commands/naturehub.js +206 -282
- package/src/commands/repl.js +1594 -1580
- package/src/providers/mem0-memory.js +121 -121
- package/src/providers/supermemory-memory.js +117 -117
- package/src/tools/llm_task.js +150 -150
- package/src/tools/mac_alarm.js +199 -199
- package/src/tools/workflow.js +424 -424
- package/src/utils/api.js +1211 -1188
- package/src/utils/cost-tracker.js +361 -360
- package/src/utils/inquirer-wrapper.js +43 -31
- package/src/utils/paste-safe-input.js +346 -334
- package/src/utils/process-errors.js +129 -115
- package/src/utils/provider-detect.js +76 -72
- package/src/utils/skills.js +1 -1
- package/src/utils/system-prompt.js +136 -136
- package/src/utils/tools.js +324 -324
- package/README.md.bak +0 -565
- package/src/tools/http.js +0 -78
package/src/tools/workflow.js
CHANGED
|
@@ -1,424 +1,424 @@
|
|
|
1
|
-
const https = require('https');
|
|
2
|
-
const fs = require('fs');
|
|
3
|
-
const path = require('path');
|
|
4
|
-
const os = require('os');
|
|
5
|
-
|
|
6
|
-
const WORKFLOW_DIR = path.join(os.homedir(), '.natureco', 'workflows');
|
|
7
|
-
const WORKFLOW_HISTORY = path.join(os.homedir(), '.natureco', 'workflow-history.json');
|
|
8
|
-
|
|
9
|
-
const { buildSkillIndex } = require('../utils/skill-index');
|
|
10
|
-
|
|
11
|
-
function ensureDir(dir) { try { fs.mkdirSync(dir, { recursive: true }); } catch {} }
|
|
12
|
-
function loadConfig() {
|
|
13
|
-
try { return JSON.parse(fs.readFileSync(path.join(os.homedir(), '.natureco', 'config.json'), 'utf8')); } catch { return {}; }
|
|
14
|
-
}
|
|
15
|
-
function isMiniMax(url) { return url && (url.includes('minimax.io') || url.includes('minimaxi.com') || url.includes('minimax.cn')); }
|
|
16
|
-
function isGemini(url) { return url && (url.includes('generativelanguage.googleapis.com') || url.includes('gemini')); }
|
|
17
|
-
|
|
18
|
-
function allToolNames() {
|
|
19
|
-
try {
|
|
20
|
-
const toolsDir = path.join(__dirname, '..', 'tools');
|
|
21
|
-
return fs.readdirSync(toolsDir).filter(f => f.endsWith('.js')).map(f => path.basename(f, '.js'));
|
|
22
|
-
} catch { return []; }
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function loadUserMemory(username) {
|
|
26
|
-
try {
|
|
27
|
-
const file = path.join(os.homedir(), '.natureco', 'memory', `${(username || 'default').toLowerCase()}.json`);
|
|
28
|
-
if (fs.existsSync(file)) {
|
|
29
|
-
const mem = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
30
|
-
const facts = (mem.facts || []).map(f => f.value || f).filter(Boolean);
|
|
31
|
-
let name = mem.name || '';
|
|
32
|
-
// Extract name from facts if not saved as memory.name
|
|
33
|
-
if (!name) {
|
|
34
|
-
for (const f of facts) {
|
|
35
|
-
const match = f.toLowerCase().match(/(?:kullanici\s*adi?|kullanıcı\s*adı?|isim|name)\s*:?\s*(.+)/);
|
|
36
|
-
if (match && match[1].trim().length > 2) { name = match[1].trim(); break; }
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
const parts = [];
|
|
40
|
-
if (name) parts.push(`Kullanici adi: ${name}`);
|
|
41
|
-
if (facts.length > 0) parts.push(`Bilinenler: ${facts.slice(0, 10).join('; ')}`);
|
|
42
|
-
return parts.join('\n');
|
|
43
|
-
}
|
|
44
|
-
} catch {}
|
|
45
|
-
return '';
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function memoryContext() {
|
|
49
|
-
const cfg = loadConfig();
|
|
50
|
-
return loadUserMemory(cfg.userName);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function apiCall(providerUrl, apiKey, body) {
|
|
54
|
-
return new Promise((resolve, reject) => {
|
|
55
|
-
const base = providerUrl.replace(/\/+$/, '');
|
|
56
|
-
const endpoint = isMiniMax(base)
|
|
57
|
-
? base + '/v1/text/chatcompletion_v2'
|
|
58
|
-
: isGemini(base)
|
|
59
|
-
? base + '/openai/chat/completions'
|
|
60
|
-
: base + '/chat/completions';
|
|
61
|
-
const req = https.request(endpoint, {
|
|
62
|
-
method: 'POST',
|
|
63
|
-
headers: { 'Authorization': 'Bearer ' + apiKey, 'Content-Type': 'application/json' },
|
|
64
|
-
timeout: 120000,
|
|
65
|
-
}, (res) => {
|
|
66
|
-
let data = '';
|
|
67
|
-
res.on('data', c => data += c);
|
|
68
|
-
res.on('end', () => {
|
|
69
|
-
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
70
|
-
try { resolve(JSON.parse(data)); } catch { reject(new Error('Parse hatasi')); }
|
|
71
|
-
} else if (res.statusCode === 429) {
|
|
72
|
-
reject(new Error('429: API rate limit. Bekleyip tekrar deneyin.'));
|
|
73
|
-
} else {
|
|
74
|
-
reject(new Error('HTTP ' + res.statusCode + ': ' + data.slice(0, 300)));
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
req.on('error', reject);
|
|
79
|
-
req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
|
|
80
|
-
req.write(JSON.stringify(body));
|
|
81
|
-
req.end();
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async function workflow(params) {
|
|
86
|
-
const { action, task, steps, name, workflowId, regenerateStep } = params;
|
|
87
|
-
const cfg = loadConfig();
|
|
88
|
-
const tools = allToolNames();
|
|
89
|
-
ensureDir(WORKFLOW_DIR);
|
|
90
|
-
|
|
91
|
-
const providerUrl = cfg.providerUrl;
|
|
92
|
-
const providerApiKey = cfg.providerApiKey;
|
|
93
|
-
const model = cfg.providerModel || 'default';
|
|
94
|
-
|
|
95
|
-
if (!providerUrl || !providerApiKey) {
|
|
96
|
-
return { success: false, error: 'Provider ayarli degil. Once: natureco setup' };
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const skillsIndexBlock = buildSkillIndex();
|
|
100
|
-
|
|
101
|
-
// Non-tool-calling model tespiti
|
|
102
|
-
function supportsToolCalls() {
|
|
103
|
-
const url = (providerUrl || '').toLowerCase();
|
|
104
|
-
// MiniMax, Gemini (direct), Ollama, Mistral (direct) tool calling'i desteklemez
|
|
105
|
-
if (url.includes('minimax')) return false;
|
|
106
|
-
if (url.includes('ollama')) return false;
|
|
107
|
-
if (url.includes('localhost')) return false;
|
|
108
|
-
if (url.includes('groq')) return false;
|
|
109
|
-
return true; // OpenAI, Anthropic, vs.
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// ── RUN: Execute a complete workflow ──────────────────────────────────
|
|
113
|
-
if (action === 'run') {
|
|
114
|
-
if (!task) return { success: false, error: 'task gerekli' };
|
|
115
|
-
|
|
116
|
-
// Non-tool-calling modellerde dogrudan passthrough (plan yok, direkt uretim)
|
|
117
|
-
if (!supportsToolCalls()) {
|
|
118
|
-
const memCtx = memoryContext();
|
|
119
|
-
const sysMsg = 'Sen yardimci bir asistansin. Kullanici ne istediyse onu dogrudan yap. Dosya olusturulacaksa icerigi eksiksiz olarak yanitla.' + (memCtx ? '\n\nKullanici bilgisi:\n' + memCtx : '') + '\n\n' + skillsIndexBlock;
|
|
120
|
-
const chatBody = { model, stream: false, messages: [{ role: 'system', content: sysMsg }, { role: 'user', content: task }], temperature: 0.7, max_tokens: 4000 };
|
|
121
|
-
try {
|
|
122
|
-
const chatResult = await apiCall(providerUrl, providerApiKey, chatBody);
|
|
123
|
-
const reply = chatResult.choices?.[0]?.message?.content || '';
|
|
124
|
-
return { success: true, workflowId: 'passthrough', name: 'Direct Generation', status: 'completed', totalSteps: 0, completedSteps: 0, results: [{ step: 0, tool: 'chat', status: 'done', result: { reply } }], passthrough: true, reply };
|
|
125
|
-
} catch (e) {
|
|
126
|
-
return { success: false, error: 'Yanit alinamadi: ' + e.message };
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// Phase 0: Check if simple chat (passthrough) — no planning needed
|
|
131
|
-
const simpleCheckPrompt = {
|
|
132
|
-
role: 'system',
|
|
133
|
-
content: 'Gorevin basit bir selamlasma/sohbet mi yoksa arac gerektiren bir islem mi oldugunu belirle. Sadece "simple" veya "complex" yaz, kesinlikle baska bir sey yazma. Noktalama isareti koyma.\n\nSimple: selamlasma, nasilsin, bugun ne yaptin, havadan sudan, genel bilgi sorusu, ben kimim, adim ne, kullanici bilgisi sorgulama, hatirlatma talebi\nComplex: dosya islemleri, kod yazma, arastirma, karsilastirma, duzenleme, otomasyon, proje yonetimi, debug, internette arama gerektiren isler'
|
|
134
|
-
};
|
|
135
|
-
const simpleBody = { model, stream: false, messages: [simpleCheckPrompt, { role: 'user', content: task }], temperature: 0, max_tokens: 20 };
|
|
136
|
-
let isSimple = false;
|
|
137
|
-
try {
|
|
138
|
-
const simpleResult = await apiCall(providerUrl, providerApiKey, simpleBody);
|
|
139
|
-
const raw = (simpleResult.choices?.[0]?.message?.content || '').trim().toLowerCase().replace(/[^a-z]/g, '');
|
|
140
|
-
isSimple = raw === 'simple';
|
|
141
|
-
} catch {}
|
|
142
|
-
|
|
143
|
-
if (isSimple) {
|
|
144
|
-
// Passthrough: just chat with LLM, no tools — include user memory
|
|
145
|
-
const memCtx = memoryContext();
|
|
146
|
-
const sysMsg = 'Sen yardimci bir asistansin. Kisa ve oz yanit ver.' + (memCtx ? '\n\nKullanici bilgisi:\n' + memCtx : '') + '\n\n' + skillsIndexBlock;
|
|
147
|
-
const chatBody = { model, stream: false, messages: [{ role: 'system', content: sysMsg }, { role: 'user', content: task }], temperature: 0.7, max_tokens: 1000 };
|
|
148
|
-
try {
|
|
149
|
-
const chatResult = await apiCall(providerUrl, providerApiKey, chatBody);
|
|
150
|
-
const reply = chatResult.choices?.[0]?.message?.content || '';
|
|
151
|
-
return { success: true, workflowId: 'passthrough', name: 'Direct Chat', status: 'completed', totalSteps: 0, completedSteps: 0, results: [{ step: 0, tool: 'chat', status: 'done', result: { reply } }], passthrough: true, reply };
|
|
152
|
-
} catch (e) {
|
|
153
|
-
return { success: false, error: 'Sohbet yaniti alinamadi: ' + e.message };
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// Phase 1: LLM plans the workflow
|
|
158
|
-
const memCtx = memoryContext();
|
|
159
|
-
const planPrompt = {
|
|
160
|
-
role: 'system',
|
|
161
|
-
content: 'Sen bir workflow planlama asistanisin. Verilen gorev icin hangi tool\'larin kullanilacagini ve hangi sirayla calisacagini belirle. SADECE JSON formatinda yanit ver, baska bir sey yazma.\n\nKullanilabilir tool\'lar:\n' +
|
|
162
|
-
tools.map(t => '- ' + t).join('\n') +
|
|
163
|
-
'\n\nKullanilabilir skill\'ler (gorevle ilgili skill varsa plana skill_view adimi olarak ekle):\n' + skillsIndexBlock +
|
|
164
|
-
(memCtx ? '\n\nKullanici bilgisi:\n' + memCtx : '') +
|
|
165
|
-
'\n\nJSON format:\n{\n "workflowName": "...",\n "description": "...",\n "skillsLoaded": ["..."],\n "steps": [\n { "step": 1, "tool": "tool_name", "purpose": "...", "params": { ... } }\n ]\n}\n\nHer adim icin params kismina tool\'un gerektirdigi parametreleri ekle. Adimlar birbirine bagimli olabilir, onceki adimin outputu sonraki adimin inputu olarak kullanilabilir.\n\nGorevle ilgili skill varsa ILK adim olarak skill_view ile yukle, ardindan diger adimlara gec.'
|
|
166
|
-
};
|
|
167
|
-
const planBody = {
|
|
168
|
-
model, stream: false,
|
|
169
|
-
messages: [planPrompt, { role: 'user', content: 'Gorev: ' + task }],
|
|
170
|
-
temperature: 0.3, max_tokens: 4000,
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
let planResult;
|
|
174
|
-
try {
|
|
175
|
-
planResult = await apiCall(providerUrl, providerApiKey, planBody);
|
|
176
|
-
} catch (e) {
|
|
177
|
-
return { success: false, error: 'Plan olusturulamadi: ' + e.message, phase: 'planning' };
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// v5.14.2: Brace-balanced JSON extraction (handles explanatory text around JSON)
|
|
181
|
-
function extractJSON(str) {
|
|
182
|
-
const start = str.indexOf('{');
|
|
183
|
-
if (start === -1) return null;
|
|
184
|
-
let depth = 0, inString = false, escape = false;
|
|
185
|
-
for (let i = start; i < str.length; i++) {
|
|
186
|
-
const ch = str[i];
|
|
187
|
-
if (escape) { escape = false; continue; }
|
|
188
|
-
if (ch === '\\' && inString) { escape = true; continue; }
|
|
189
|
-
if (ch === '"') { inString = !inString; continue; }
|
|
190
|
-
if (!inString) {
|
|
191
|
-
if (ch === '{') depth++;
|
|
192
|
-
else if (ch === '}') { depth--; if (depth === 0) return str.slice(start, i + 1); }
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
return null;
|
|
196
|
-
}
|
|
197
|
-
let plan;
|
|
198
|
-
try {
|
|
199
|
-
const content = planResult.choices?.[0]?.message?.content || '';
|
|
200
|
-
const jsonStr = extractJSON(content);
|
|
201
|
-
if (!jsonStr) throw new Error('JSON bloku bulunamadi');
|
|
202
|
-
plan = JSON.parse(jsonStr);
|
|
203
|
-
if (!plan.steps || !Array.isArray(plan.steps)) throw new Error('Steps bulunamadi');
|
|
204
|
-
} catch (e) {
|
|
205
|
-
// JSON parse hatasi — modelin ham ciktisini passthrough chat olarak goster
|
|
206
|
-
const rawReply = planResult.choices?.[0]?.message?.content || '';
|
|
207
|
-
if (rawReply) {
|
|
208
|
-
return { success: true, workflowId: 'passthrough', name: 'Direct Chat', status: 'completed', totalSteps: 0, completedSteps: 0, results: [{ step: 0, tool: 'chat', status: 'done', result: { reply: rawReply } }], passthrough: true, reply: rawReply };
|
|
209
|
-
}
|
|
210
|
-
return { success: false, error: 'Plan cozumlenemedi: ' + e.message, raw: rawReply.slice(0, 500) };
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// Save plan
|
|
214
|
-
const wfId = workflowId || 'wf_' + Date.now().toString(36);
|
|
215
|
-
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
216
|
-
const wfEntry = { id: wfId, task, name: plan.workflowName || task.slice(0, 50), description: plan.description || '', steps: plan.steps, status: 'running', startedAt: new Date().toISOString(), results: [] };
|
|
217
|
-
fs.writeFileSync(wfFile, JSON.stringify(wfEntry, null, 2));
|
|
218
|
-
|
|
219
|
-
// Phase 2: Execute steps sequentially
|
|
220
|
-
const stepResults = [];
|
|
221
|
-
let failed = false;
|
|
222
|
-
|
|
223
|
-
for (const step of plan.steps) {
|
|
224
|
-
if (failed) {
|
|
225
|
-
stepResults.push({ step: step.step, tool: step.tool, status: 'skipped', reason: 'Onceki adim basarisiz' });
|
|
226
|
-
continue;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// Check if tool is valid
|
|
230
|
-
if (!tools.includes(step.tool)) {
|
|
231
|
-
stepResults.push({ step: step.step, tool: step.tool, status: 'error', error: 'Bilinmeyen tool: ' + step.tool + '. Kullanilabilir: ' + tools.slice(0, 10).join(', ') + '...' });
|
|
232
|
-
failed = true;
|
|
233
|
-
continue;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// Build the execute prompt — we use LLM to call the tool with correct params
|
|
237
|
-
const executePrompt = {
|
|
238
|
-
role: 'system',
|
|
239
|
-
content: 'Bir sonraki adimi calistiriyorsun. Sana verilen tool\'u ve parametreleri kullanarak islemi gerceklestir. Tool cagrisini dogru formatta yap.\n\nTool: ' + step.tool + '\nAmac: ' + (step.purpose || '') + '\nPlanlanan parametreler: ' + JSON.stringify(step.params || {}) +
|
|
240
|
-
'\n\nOnceki adim sonuclari:\n' + stepResults.map(r => 'Adim ' + r.step + ' (' + r.tool + '): ' + (r.status === 'done' ? JSON.stringify(r.result).slice(0, 300) : r.status)).join('\n') +
|
|
241
|
-
'\n\nKullanilabilir skill\'ler:\n' + skillsIndexBlock +
|
|
242
|
-
'\n\nTek bir tool cagrisi yap ve sonucu bekle. Tool cagrisi yaparken Onceki adim sonuclarindaki gerekli verileri parametre olarak kullan. Ilgili skill varsa once skill_view ile yukle, sonra asil tool\'u cagir.'
|
|
243
|
-
};
|
|
244
|
-
const executeBody = {
|
|
245
|
-
model, stream: false,
|
|
246
|
-
messages: [executePrompt, { role: 'user', content: 'Adim ' + step.step + ': ' + step.tool + ' ile ' + (step.purpose || 'islem') + ' yap.' }],
|
|
247
|
-
temperature: 0.2, max_tokens: 2000,
|
|
248
|
-
tools: [{ type: 'function', function: { name: step.tool, description: step.purpose || '', parameters: {} } }],
|
|
249
|
-
tool_choice: { type: 'function', function: { name: step.tool } },
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
let execResult;
|
|
253
|
-
try {
|
|
254
|
-
execResult = await apiCall(providerUrl, providerApiKey, executeBody);
|
|
255
|
-
const msg = execResult.choices?.[0]?.message || {};
|
|
256
|
-
const tc = msg.tool_calls?.[0];
|
|
257
|
-
|
|
258
|
-
if (tc && tc.function) {
|
|
259
|
-
const args = JSON.parse(tc.function.arguments || '{}');
|
|
260
|
-
const toolMod = require(path.join(__dirname, '..', 'tools', step.tool + '.js'));
|
|
261
|
-
const fn = toolMod.execute || (toolMod.default && toolMod.default.execute);
|
|
262
|
-
if (!fn) { throw new Error(step.tool + ' toolunda execute fonksiyonu bulunamadi'); }
|
|
263
|
-
const toolResult = await fn(args);
|
|
264
|
-
stepResults.push({ step: step.step, tool: step.tool, status: 'done', args, result: toolResult });
|
|
265
|
-
} else if (msg.content) {
|
|
266
|
-
stepResults.push({ step: step.step, tool: step.tool, status: 'done', note: 'Tool cagrilmadi, model dogrudan yanit verdi', content: msg.content.slice(0, 500) });
|
|
267
|
-
} else {
|
|
268
|
-
stepResults.push({ step: step.step, tool: step.tool, status: 'error', error: 'Tool cagrisi yapilmadi' });
|
|
269
|
-
failed = true;
|
|
270
|
-
}
|
|
271
|
-
} catch (e) {
|
|
272
|
-
stepResults.push({ step: step.step, tool: step.tool, status: 'error', error: e.message });
|
|
273
|
-
failed = true;
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// Update workflow file
|
|
278
|
-
wfEntry.status = failed ? 'completed_with_errors' : 'completed';
|
|
279
|
-
wfEntry.completedAt = new Date().toISOString();
|
|
280
|
-
wfEntry.results = stepResults;
|
|
281
|
-
fs.writeFileSync(wfFile, JSON.stringify(wfEntry, null, 2));
|
|
282
|
-
|
|
283
|
-
// Save to history
|
|
284
|
-
ensureDir(path.dirname(WORKFLOW_HISTORY));
|
|
285
|
-
let history = [];
|
|
286
|
-
try { history = JSON.parse(fs.readFileSync(WORKFLOW_HISTORY, 'utf8')); } catch {}
|
|
287
|
-
history.unshift({ id: wfId, name: plan.workflowName || task.slice(0, 50), task, status: wfEntry.status, steps: plan.steps.length, completedAt: wfEntry.completedAt });
|
|
288
|
-
fs.writeFileSync(WORKFLOW_HISTORY, JSON.stringify(history.slice(0, 50), null, 2));
|
|
289
|
-
|
|
290
|
-
const skillsLoaded = stepResults
|
|
291
|
-
.filter(r => r.tool === 'skill_view' && r.status === 'done')
|
|
292
|
-
.map(r => r.args?.name || 'bilinmeyen-skill');
|
|
293
|
-
|
|
294
|
-
return {
|
|
295
|
-
success: true,
|
|
296
|
-
workflowId: wfId,
|
|
297
|
-
name: plan.workflowName || '',
|
|
298
|
-
description: plan.description || '',
|
|
299
|
-
totalSteps: plan.steps.length,
|
|
300
|
-
completedSteps: stepResults.filter(r => r.status === 'done').length,
|
|
301
|
-
failedSteps: stepResults.filter(r => r.status === 'error' || r.status === 'skipped').length,
|
|
302
|
-
status: wfEntry.status,
|
|
303
|
-
skillsLoaded: skillsLoaded.length > 0 ? skillsLoaded : undefined,
|
|
304
|
-
plan: plan.steps.map(s => ({ step: s.step, tool: s.tool, purpose: s.purpose })),
|
|
305
|
-
results: stepResults.map(r => ({
|
|
306
|
-
step: r.step, tool: r.tool, status: r.status,
|
|
307
|
-
result: r.status === 'done' ? r.result : undefined,
|
|
308
|
-
error: r.error, note: r.note,
|
|
309
|
-
})),
|
|
310
|
-
workflowFile: wfFile,
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
// ── PLAN_ONLY: Just generate the plan without executing ──────────────
|
|
315
|
-
if (action === 'plan') {
|
|
316
|
-
if (!task) return { success: false, error: 'task gerekli' };
|
|
317
|
-
const planPrompt = {
|
|
318
|
-
role: 'system',
|
|
319
|
-
content: 'Kullanilabilir tool\'lar:\n' + tools.map(t => '- ' + t).join('\n') +
|
|
320
|
-
'\n\nKullanilabilir skill\'ler:\n' + skillsIndexBlock +
|
|
321
|
-
'\n\nGorev icin bir workflow plani JSON formatinda olustur. JSON disinda hicbir sey yazma.\nFormat: { "workflowName": "...", "description": "...", "estimatedSteps": N, "skillsLoaded": ["..."], "steps": [{ "step": 1, "tool": "...", "purpose": "...", "params": {...}, "expectedOutput": "..." }] }\n\nGorevle ilgili skill varsa plana skill_view adimi olarak ekle.'
|
|
322
|
-
};
|
|
323
|
-
const planBody = {
|
|
324
|
-
model, stream: false,
|
|
325
|
-
messages: [planPrompt, { role: 'user', content: 'Gorev: ' + task }],
|
|
326
|
-
temperature: 0.3, max_tokens: 4000,
|
|
327
|
-
};
|
|
328
|
-
try {
|
|
329
|
-
const result = await apiCall(providerUrl, providerApiKey, planBody);
|
|
330
|
-
const content = result.choices?.[0]?.message?.content || '';
|
|
331
|
-
const jsonMatch = content.match(/\{[\s\S]*\}/);
|
|
332
|
-
const plan = JSON.parse(jsonMatch ? jsonMatch[0] : content);
|
|
333
|
-
return { success: true, plan, raw: content.slice(0, 1000) };
|
|
334
|
-
} catch (e) {
|
|
335
|
-
return { success: false, error: 'Plan olusturulamadi: ' + e.message };
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
// ── SAVE / LOAD / LIST / DELETE ───────────────────────────────────────
|
|
340
|
-
if (action === 'save') {
|
|
341
|
-
if (!name || !steps) return { success: false, error: 'name ve steps gerekli' };
|
|
342
|
-
const wfId = 'wf_' + name.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
343
|
-
const wf = { id: wfId, name, description: params.description || '', steps, status: 'saved', createdAt: new Date().toISOString() };
|
|
344
|
-
fs.writeFileSync(path.join(WORKFLOW_DIR, wfId + '.json'), JSON.stringify(wf, null, 2));
|
|
345
|
-
return { success: true, workflowId: wfId, message: name + ' kaydedildi' };
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
if (action === 'load') {
|
|
349
|
-
const wfId = workflowId || name;
|
|
350
|
-
if (!wfId) return { success: false, error: 'workflowId gerekli' };
|
|
351
|
-
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
352
|
-
if (!fs.existsSync(wfFile)) {
|
|
353
|
-
// Try to find by name
|
|
354
|
-
const files = fs.readdirSync(WORKFLOW_DIR).filter(f => f.endsWith('.json'));
|
|
355
|
-
for (const f of files) {
|
|
356
|
-
try {
|
|
357
|
-
const data = JSON.parse(fs.readFileSync(path.join(WORKFLOW_DIR, f), 'utf8'));
|
|
358
|
-
if (data.name === wfId || data.id === wfId) {
|
|
359
|
-
return { success: true, workflow: data };
|
|
360
|
-
}
|
|
361
|
-
} catch {}
|
|
362
|
-
}
|
|
363
|
-
return { success: false, error: 'Workflow bulunamadi: ' + wfId };
|
|
364
|
-
}
|
|
365
|
-
const data = JSON.parse(fs.readFileSync(wfFile, 'utf8'));
|
|
366
|
-
return { success: true, workflow: data };
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
if (action === 'list') {
|
|
370
|
-
const files = fs.readdirSync(WORKFLOW_DIR).filter(f => f.endsWith('.json'));
|
|
371
|
-
const list = files.map(f => {
|
|
372
|
-
try {
|
|
373
|
-
const data = JSON.parse(fs.readFileSync(path.join(WORKFLOW_DIR, f), 'utf8'));
|
|
374
|
-
return { id: data.id, name: data.name, status: data.status, steps: data.steps?.length || 0, createdAt: data.createdAt || data.startedAt };
|
|
375
|
-
} catch { return null; }
|
|
376
|
-
}).filter(Boolean);
|
|
377
|
-
return { success: true, workflows: list };
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
if (action === 'delete') {
|
|
381
|
-
const wfId = workflowId || name;
|
|
382
|
-
if (!wfId) return { success: false, error: 'workflowId gerekli' };
|
|
383
|
-
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
384
|
-
if (fs.existsSync(wfFile)) fs.unlinkSync(wfFile);
|
|
385
|
-
return { success: true, message: wfId + ' silindi' };
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
// ── RETRY: Regenerate and rerun a specific step ──────────────────────
|
|
389
|
-
if (action === 'retry') {
|
|
390
|
-
const wfId = workflowId;
|
|
391
|
-
if (!wfId) return { success: false, error: 'workflowId gerekli' };
|
|
392
|
-
if (typeof regenerateStep !== 'number') return { success: false, error: 'regenerateStep (step numarasi) gerekli' };
|
|
393
|
-
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
394
|
-
if (!fs.existsSync(wfFile)) return { success: false, error: 'Workflow bulunamadi: ' + wfId };
|
|
395
|
-
const wf = JSON.parse(fs.readFileSync(wfFile, 'utf8'));
|
|
396
|
-
const step = wf.steps?.find(s => s.step === regenerateStep);
|
|
397
|
-
if (!step) return { success: false, error: 'Adim bulunamadi: ' + regenerateStep };
|
|
398
|
-
step.params = params.newParams || step.params;
|
|
399
|
-
fs.writeFileSync(wfFile, JSON.stringify(wf, null, 2));
|
|
400
|
-
return { success: true, message: 'Adim ' + regenerateStep + ' yeniden calistirilmak uzere isaretlendi. Tekrar run yapin.', step };
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
return { success: false, error: 'Gecersiz action: ' + action + ' (run, plan, save, load, list, delete, retry)' };
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
module.exports = {
|
|
407
|
-
name: 'workflow',
|
|
408
|
-
description: '[ORCHESTRATOR]
|
|
409
|
-
inputSchema: {
|
|
410
|
-
type: 'object',
|
|
411
|
-
properties: {
|
|
412
|
-
action: { type: 'string', description: 'run (tam otomatik), plan (sadece plan), save, load, list, delete, retry', enum: ['run', 'plan', 'save', 'load', 'list', 'delete', 'retry'] },
|
|
413
|
-
task: { type: 'string', description: '(run/plan) Yapilacak gorev — dogal dil ile anlat' },
|
|
414
|
-
steps: { type: 'array', description: '(save) Kaydedilecek adimlar', items: { type: 'object' } },
|
|
415
|
-
name: { type: 'string', description: '(save/load) Workflow adi' },
|
|
416
|
-
workflowId: { type: 'string', description: '(load/delete/retry) Workflow ID' },
|
|
417
|
-
regenerateStep: { type: 'number', description: '(retry) Yeniden calistirilacak adim numarasi' },
|
|
418
|
-
newParams: { type: 'object', description: '(retry) Yeni parametreler' },
|
|
419
|
-
description: { type: 'string', description: 'Aciklama' },
|
|
420
|
-
},
|
|
421
|
-
required: ['action'],
|
|
422
|
-
},
|
|
423
|
-
async execute(params) { return await workflow(params); },
|
|
424
|
-
};
|
|
1
|
+
const https = require('https');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
|
|
6
|
+
const WORKFLOW_DIR = path.join(os.homedir(), '.natureco', 'workflows');
|
|
7
|
+
const WORKFLOW_HISTORY = path.join(os.homedir(), '.natureco', 'workflow-history.json');
|
|
8
|
+
|
|
9
|
+
const { buildSkillIndex } = require('../utils/skill-index');
|
|
10
|
+
|
|
11
|
+
function ensureDir(dir) { try { fs.mkdirSync(dir, { recursive: true }); } catch {} }
|
|
12
|
+
function loadConfig() {
|
|
13
|
+
try { return JSON.parse(fs.readFileSync(path.join(os.homedir(), '.natureco', 'config.json'), 'utf8')); } catch { return {}; }
|
|
14
|
+
}
|
|
15
|
+
function isMiniMax(url) { return url && (url.includes('minimax.io') || url.includes('minimaxi.com') || url.includes('minimax.cn')); }
|
|
16
|
+
function isGemini(url) { return url && (url.includes('generativelanguage.googleapis.com') || url.includes('gemini')); }
|
|
17
|
+
|
|
18
|
+
function allToolNames() {
|
|
19
|
+
try {
|
|
20
|
+
const toolsDir = path.join(__dirname, '..', 'tools');
|
|
21
|
+
return fs.readdirSync(toolsDir).filter(f => f.endsWith('.js')).map(f => path.basename(f, '.js'));
|
|
22
|
+
} catch { return []; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function loadUserMemory(username) {
|
|
26
|
+
try {
|
|
27
|
+
const file = path.join(os.homedir(), '.natureco', 'memory', `${(username || 'default').toLowerCase()}.json`);
|
|
28
|
+
if (fs.existsSync(file)) {
|
|
29
|
+
const mem = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
30
|
+
const facts = (mem.facts || []).map(f => f.value || f).filter(Boolean);
|
|
31
|
+
let name = mem.name || '';
|
|
32
|
+
// Extract name from facts if not saved as memory.name
|
|
33
|
+
if (!name) {
|
|
34
|
+
for (const f of facts) {
|
|
35
|
+
const match = f.toLowerCase().match(/(?:kullanici\s*adi?|kullanıcı\s*adı?|isim|name)\s*:?\s*(.+)/);
|
|
36
|
+
if (match && match[1].trim().length > 2) { name = match[1].trim(); break; }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const parts = [];
|
|
40
|
+
if (name) parts.push(`Kullanici adi: ${name}`);
|
|
41
|
+
if (facts.length > 0) parts.push(`Bilinenler: ${facts.slice(0, 10).join('; ')}`);
|
|
42
|
+
return parts.join('\n');
|
|
43
|
+
}
|
|
44
|
+
} catch {}
|
|
45
|
+
return '';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function memoryContext() {
|
|
49
|
+
const cfg = loadConfig();
|
|
50
|
+
return loadUserMemory(cfg.userName);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function apiCall(providerUrl, apiKey, body) {
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
const base = providerUrl.replace(/\/+$/, '');
|
|
56
|
+
const endpoint = isMiniMax(base)
|
|
57
|
+
? base + '/v1/text/chatcompletion_v2'
|
|
58
|
+
: isGemini(base)
|
|
59
|
+
? base + '/openai/chat/completions'
|
|
60
|
+
: base + '/chat/completions';
|
|
61
|
+
const req = https.request(endpoint, {
|
|
62
|
+
method: 'POST',
|
|
63
|
+
headers: { 'Authorization': 'Bearer ' + apiKey, 'Content-Type': 'application/json' },
|
|
64
|
+
timeout: 120000,
|
|
65
|
+
}, (res) => {
|
|
66
|
+
let data = '';
|
|
67
|
+
res.on('data', c => data += c);
|
|
68
|
+
res.on('end', () => {
|
|
69
|
+
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
70
|
+
try { resolve(JSON.parse(data)); } catch { reject(new Error('Parse hatasi')); }
|
|
71
|
+
} else if (res.statusCode === 429) {
|
|
72
|
+
reject(new Error('429: API rate limit. Bekleyip tekrar deneyin.'));
|
|
73
|
+
} else {
|
|
74
|
+
reject(new Error('HTTP ' + res.statusCode + ': ' + data.slice(0, 300)));
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
req.on('error', reject);
|
|
79
|
+
req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
|
|
80
|
+
req.write(JSON.stringify(body));
|
|
81
|
+
req.end();
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function workflow(params) {
|
|
86
|
+
const { action, task, steps, name, workflowId, regenerateStep } = params;
|
|
87
|
+
const cfg = loadConfig();
|
|
88
|
+
const tools = allToolNames();
|
|
89
|
+
ensureDir(WORKFLOW_DIR);
|
|
90
|
+
|
|
91
|
+
const providerUrl = cfg.providerUrl;
|
|
92
|
+
const providerApiKey = cfg.providerApiKey;
|
|
93
|
+
const model = cfg.providerModel || 'default';
|
|
94
|
+
|
|
95
|
+
if (!providerUrl || !providerApiKey) {
|
|
96
|
+
return { success: false, error: 'Provider ayarli degil. Once: natureco setup' };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const skillsIndexBlock = buildSkillIndex();
|
|
100
|
+
|
|
101
|
+
// Non-tool-calling model tespiti
|
|
102
|
+
function supportsToolCalls() {
|
|
103
|
+
const url = (providerUrl || '').toLowerCase();
|
|
104
|
+
// MiniMax, Gemini (direct), Ollama, Mistral (direct) tool calling'i desteklemez
|
|
105
|
+
if (url.includes('minimax')) return false;
|
|
106
|
+
if (url.includes('ollama')) return false;
|
|
107
|
+
if (url.includes('localhost')) return false;
|
|
108
|
+
if (url.includes('groq')) return false;
|
|
109
|
+
return true; // OpenAI, Anthropic, vs.
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── RUN: Execute a complete workflow ──────────────────────────────────
|
|
113
|
+
if (action === 'run') {
|
|
114
|
+
if (!task) return { success: false, error: 'task gerekli' };
|
|
115
|
+
|
|
116
|
+
// Non-tool-calling modellerde dogrudan passthrough (plan yok, direkt uretim)
|
|
117
|
+
if (!supportsToolCalls()) {
|
|
118
|
+
const memCtx = memoryContext();
|
|
119
|
+
const sysMsg = 'Sen yardimci bir asistansin. Kullanici ne istediyse onu dogrudan yap. Dosya olusturulacaksa icerigi eksiksiz olarak yanitla.' + (memCtx ? '\n\nKullanici bilgisi:\n' + memCtx : '') + '\n\n' + skillsIndexBlock;
|
|
120
|
+
const chatBody = { model, stream: false, messages: [{ role: 'system', content: sysMsg }, { role: 'user', content: task }], temperature: 0.7, max_tokens: 4000 };
|
|
121
|
+
try {
|
|
122
|
+
const chatResult = await apiCall(providerUrl, providerApiKey, chatBody);
|
|
123
|
+
const reply = chatResult.choices?.[0]?.message?.content || '';
|
|
124
|
+
return { success: true, workflowId: 'passthrough', name: 'Direct Generation', status: 'completed', totalSteps: 0, completedSteps: 0, results: [{ step: 0, tool: 'chat', status: 'done', result: { reply } }], passthrough: true, reply };
|
|
125
|
+
} catch (e) {
|
|
126
|
+
return { success: false, error: 'Yanit alinamadi: ' + e.message };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Phase 0: Check if simple chat (passthrough) — no planning needed
|
|
131
|
+
const simpleCheckPrompt = {
|
|
132
|
+
role: 'system',
|
|
133
|
+
content: 'Gorevin basit bir selamlasma/sohbet mi yoksa arac gerektiren bir islem mi oldugunu belirle. Sadece "simple" veya "complex" yaz, kesinlikle baska bir sey yazma. Noktalama isareti koyma.\n\nSimple: selamlasma, nasilsin, bugun ne yaptin, havadan sudan, genel bilgi sorusu, ben kimim, adim ne, kullanici bilgisi sorgulama, hatirlatma talebi\nComplex: dosya islemleri, kod yazma, arastirma, karsilastirma, duzenleme, otomasyon, proje yonetimi, debug, internette arama gerektiren isler'
|
|
134
|
+
};
|
|
135
|
+
const simpleBody = { model, stream: false, messages: [simpleCheckPrompt, { role: 'user', content: task }], temperature: 0, max_tokens: 20 };
|
|
136
|
+
let isSimple = false;
|
|
137
|
+
try {
|
|
138
|
+
const simpleResult = await apiCall(providerUrl, providerApiKey, simpleBody);
|
|
139
|
+
const raw = (simpleResult.choices?.[0]?.message?.content || '').trim().toLowerCase().replace(/[^a-z]/g, '');
|
|
140
|
+
isSimple = raw === 'simple';
|
|
141
|
+
} catch {}
|
|
142
|
+
|
|
143
|
+
if (isSimple) {
|
|
144
|
+
// Passthrough: just chat with LLM, no tools — include user memory
|
|
145
|
+
const memCtx = memoryContext();
|
|
146
|
+
const sysMsg = 'Sen yardimci bir asistansin. Kisa ve oz yanit ver.' + (memCtx ? '\n\nKullanici bilgisi:\n' + memCtx : '') + '\n\n' + skillsIndexBlock;
|
|
147
|
+
const chatBody = { model, stream: false, messages: [{ role: 'system', content: sysMsg }, { role: 'user', content: task }], temperature: 0.7, max_tokens: 1000 };
|
|
148
|
+
try {
|
|
149
|
+
const chatResult = await apiCall(providerUrl, providerApiKey, chatBody);
|
|
150
|
+
const reply = chatResult.choices?.[0]?.message?.content || '';
|
|
151
|
+
return { success: true, workflowId: 'passthrough', name: 'Direct Chat', status: 'completed', totalSteps: 0, completedSteps: 0, results: [{ step: 0, tool: 'chat', status: 'done', result: { reply } }], passthrough: true, reply };
|
|
152
|
+
} catch (e) {
|
|
153
|
+
return { success: false, error: 'Sohbet yaniti alinamadi: ' + e.message };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Phase 1: LLM plans the workflow
|
|
158
|
+
const memCtx = memoryContext();
|
|
159
|
+
const planPrompt = {
|
|
160
|
+
role: 'system',
|
|
161
|
+
content: 'Sen bir workflow planlama asistanisin. Verilen gorev icin hangi tool\'larin kullanilacagini ve hangi sirayla calisacagini belirle. SADECE JSON formatinda yanit ver, baska bir sey yazma.\n\nKullanilabilir tool\'lar:\n' +
|
|
162
|
+
tools.map(t => '- ' + t).join('\n') +
|
|
163
|
+
'\n\nKullanilabilir skill\'ler (gorevle ilgili skill varsa plana skill_view adimi olarak ekle):\n' + skillsIndexBlock +
|
|
164
|
+
(memCtx ? '\n\nKullanici bilgisi:\n' + memCtx : '') +
|
|
165
|
+
'\n\nJSON format:\n{\n "workflowName": "...",\n "description": "...",\n "skillsLoaded": ["..."],\n "steps": [\n { "step": 1, "tool": "tool_name", "purpose": "...", "params": { ... } }\n ]\n}\n\nHer adim icin params kismina tool\'un gerektirdigi parametreleri ekle. Adimlar birbirine bagimli olabilir, onceki adimin outputu sonraki adimin inputu olarak kullanilabilir.\n\nGorevle ilgili skill varsa ILK adim olarak skill_view ile yukle, ardindan diger adimlara gec.'
|
|
166
|
+
};
|
|
167
|
+
const planBody = {
|
|
168
|
+
model, stream: false,
|
|
169
|
+
messages: [planPrompt, { role: 'user', content: 'Gorev: ' + task }],
|
|
170
|
+
temperature: 0.3, max_tokens: 4000,
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
let planResult;
|
|
174
|
+
try {
|
|
175
|
+
planResult = await apiCall(providerUrl, providerApiKey, planBody);
|
|
176
|
+
} catch (e) {
|
|
177
|
+
return { success: false, error: 'Plan olusturulamadi: ' + e.message, phase: 'planning' };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// v5.14.2: Brace-balanced JSON extraction (handles explanatory text around JSON)
|
|
181
|
+
function extractJSON(str) {
|
|
182
|
+
const start = str.indexOf('{');
|
|
183
|
+
if (start === -1) return null;
|
|
184
|
+
let depth = 0, inString = false, escape = false;
|
|
185
|
+
for (let i = start; i < str.length; i++) {
|
|
186
|
+
const ch = str[i];
|
|
187
|
+
if (escape) { escape = false; continue; }
|
|
188
|
+
if (ch === '\\' && inString) { escape = true; continue; }
|
|
189
|
+
if (ch === '"') { inString = !inString; continue; }
|
|
190
|
+
if (!inString) {
|
|
191
|
+
if (ch === '{') depth++;
|
|
192
|
+
else if (ch === '}') { depth--; if (depth === 0) return str.slice(start, i + 1); }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
let plan;
|
|
198
|
+
try {
|
|
199
|
+
const content = planResult.choices?.[0]?.message?.content || '';
|
|
200
|
+
const jsonStr = extractJSON(content);
|
|
201
|
+
if (!jsonStr) throw new Error('JSON bloku bulunamadi');
|
|
202
|
+
plan = JSON.parse(jsonStr);
|
|
203
|
+
if (!plan.steps || !Array.isArray(plan.steps)) throw new Error('Steps bulunamadi');
|
|
204
|
+
} catch (e) {
|
|
205
|
+
// JSON parse hatasi — modelin ham ciktisini passthrough chat olarak goster
|
|
206
|
+
const rawReply = planResult.choices?.[0]?.message?.content || '';
|
|
207
|
+
if (rawReply) {
|
|
208
|
+
return { success: true, workflowId: 'passthrough', name: 'Direct Chat', status: 'completed', totalSteps: 0, completedSteps: 0, results: [{ step: 0, tool: 'chat', status: 'done', result: { reply: rawReply } }], passthrough: true, reply: rawReply };
|
|
209
|
+
}
|
|
210
|
+
return { success: false, error: 'Plan cozumlenemedi: ' + e.message, raw: rawReply.slice(0, 500) };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Save plan
|
|
214
|
+
const wfId = workflowId || 'wf_' + Date.now().toString(36);
|
|
215
|
+
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
216
|
+
const wfEntry = { id: wfId, task, name: plan.workflowName || task.slice(0, 50), description: plan.description || '', steps: plan.steps, status: 'running', startedAt: new Date().toISOString(), results: [] };
|
|
217
|
+
fs.writeFileSync(wfFile, JSON.stringify(wfEntry, null, 2));
|
|
218
|
+
|
|
219
|
+
// Phase 2: Execute steps sequentially
|
|
220
|
+
const stepResults = [];
|
|
221
|
+
let failed = false;
|
|
222
|
+
|
|
223
|
+
for (const step of plan.steps) {
|
|
224
|
+
if (failed) {
|
|
225
|
+
stepResults.push({ step: step.step, tool: step.tool, status: 'skipped', reason: 'Onceki adim basarisiz' });
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Check if tool is valid
|
|
230
|
+
if (!tools.includes(step.tool)) {
|
|
231
|
+
stepResults.push({ step: step.step, tool: step.tool, status: 'error', error: 'Bilinmeyen tool: ' + step.tool + '. Kullanilabilir: ' + tools.slice(0, 10).join(', ') + '...' });
|
|
232
|
+
failed = true;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Build the execute prompt — we use LLM to call the tool with correct params
|
|
237
|
+
const executePrompt = {
|
|
238
|
+
role: 'system',
|
|
239
|
+
content: 'Bir sonraki adimi calistiriyorsun. Sana verilen tool\'u ve parametreleri kullanarak islemi gerceklestir. Tool cagrisini dogru formatta yap.\n\nTool: ' + step.tool + '\nAmac: ' + (step.purpose || '') + '\nPlanlanan parametreler: ' + JSON.stringify(step.params || {}) +
|
|
240
|
+
'\n\nOnceki adim sonuclari:\n' + stepResults.map(r => 'Adim ' + r.step + ' (' + r.tool + '): ' + (r.status === 'done' ? JSON.stringify(r.result).slice(0, 300) : r.status)).join('\n') +
|
|
241
|
+
'\n\nKullanilabilir skill\'ler:\n' + skillsIndexBlock +
|
|
242
|
+
'\n\nTek bir tool cagrisi yap ve sonucu bekle. Tool cagrisi yaparken Onceki adim sonuclarindaki gerekli verileri parametre olarak kullan. Ilgili skill varsa once skill_view ile yukle, sonra asil tool\'u cagir.'
|
|
243
|
+
};
|
|
244
|
+
const executeBody = {
|
|
245
|
+
model, stream: false,
|
|
246
|
+
messages: [executePrompt, { role: 'user', content: 'Adim ' + step.step + ': ' + step.tool + ' ile ' + (step.purpose || 'islem') + ' yap.' }],
|
|
247
|
+
temperature: 0.2, max_tokens: 2000,
|
|
248
|
+
tools: [{ type: 'function', function: { name: step.tool, description: step.purpose || '', parameters: {} } }],
|
|
249
|
+
tool_choice: { type: 'function', function: { name: step.tool } },
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
let execResult;
|
|
253
|
+
try {
|
|
254
|
+
execResult = await apiCall(providerUrl, providerApiKey, executeBody);
|
|
255
|
+
const msg = execResult.choices?.[0]?.message || {};
|
|
256
|
+
const tc = msg.tool_calls?.[0];
|
|
257
|
+
|
|
258
|
+
if (tc && tc.function) {
|
|
259
|
+
const args = JSON.parse(tc.function.arguments || '{}');
|
|
260
|
+
const toolMod = require(path.join(__dirname, '..', 'tools', step.tool + '.js'));
|
|
261
|
+
const fn = toolMod.execute || (toolMod.default && toolMod.default.execute);
|
|
262
|
+
if (!fn) { throw new Error(step.tool + ' toolunda execute fonksiyonu bulunamadi'); }
|
|
263
|
+
const toolResult = await fn(args);
|
|
264
|
+
stepResults.push({ step: step.step, tool: step.tool, status: 'done', args, result: toolResult });
|
|
265
|
+
} else if (msg.content) {
|
|
266
|
+
stepResults.push({ step: step.step, tool: step.tool, status: 'done', note: 'Tool cagrilmadi, model dogrudan yanit verdi', content: msg.content.slice(0, 500) });
|
|
267
|
+
} else {
|
|
268
|
+
stepResults.push({ step: step.step, tool: step.tool, status: 'error', error: 'Tool cagrisi yapilmadi' });
|
|
269
|
+
failed = true;
|
|
270
|
+
}
|
|
271
|
+
} catch (e) {
|
|
272
|
+
stepResults.push({ step: step.step, tool: step.tool, status: 'error', error: e.message });
|
|
273
|
+
failed = true;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Update workflow file
|
|
278
|
+
wfEntry.status = failed ? 'completed_with_errors' : 'completed';
|
|
279
|
+
wfEntry.completedAt = new Date().toISOString();
|
|
280
|
+
wfEntry.results = stepResults;
|
|
281
|
+
fs.writeFileSync(wfFile, JSON.stringify(wfEntry, null, 2));
|
|
282
|
+
|
|
283
|
+
// Save to history
|
|
284
|
+
ensureDir(path.dirname(WORKFLOW_HISTORY));
|
|
285
|
+
let history = [];
|
|
286
|
+
try { history = JSON.parse(fs.readFileSync(WORKFLOW_HISTORY, 'utf8')); } catch {}
|
|
287
|
+
history.unshift({ id: wfId, name: plan.workflowName || task.slice(0, 50), task, status: wfEntry.status, steps: plan.steps.length, completedAt: wfEntry.completedAt });
|
|
288
|
+
fs.writeFileSync(WORKFLOW_HISTORY, JSON.stringify(history.slice(0, 50), null, 2));
|
|
289
|
+
|
|
290
|
+
const skillsLoaded = stepResults
|
|
291
|
+
.filter(r => r.tool === 'skill_view' && r.status === 'done')
|
|
292
|
+
.map(r => r.args?.name || 'bilinmeyen-skill');
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
success: true,
|
|
296
|
+
workflowId: wfId,
|
|
297
|
+
name: plan.workflowName || '',
|
|
298
|
+
description: plan.description || '',
|
|
299
|
+
totalSteps: plan.steps.length,
|
|
300
|
+
completedSteps: stepResults.filter(r => r.status === 'done').length,
|
|
301
|
+
failedSteps: stepResults.filter(r => r.status === 'error' || r.status === 'skipped').length,
|
|
302
|
+
status: wfEntry.status,
|
|
303
|
+
skillsLoaded: skillsLoaded.length > 0 ? skillsLoaded : undefined,
|
|
304
|
+
plan: plan.steps.map(s => ({ step: s.step, tool: s.tool, purpose: s.purpose })),
|
|
305
|
+
results: stepResults.map(r => ({
|
|
306
|
+
step: r.step, tool: r.tool, status: r.status,
|
|
307
|
+
result: r.status === 'done' ? r.result : undefined,
|
|
308
|
+
error: r.error, note: r.note,
|
|
309
|
+
})),
|
|
310
|
+
workflowFile: wfFile,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// ── PLAN_ONLY: Just generate the plan without executing ──────────────
|
|
315
|
+
if (action === 'plan') {
|
|
316
|
+
if (!task) return { success: false, error: 'task gerekli' };
|
|
317
|
+
const planPrompt = {
|
|
318
|
+
role: 'system',
|
|
319
|
+
content: 'Kullanilabilir tool\'lar:\n' + tools.map(t => '- ' + t).join('\n') +
|
|
320
|
+
'\n\nKullanilabilir skill\'ler:\n' + skillsIndexBlock +
|
|
321
|
+
'\n\nGorev icin bir workflow plani JSON formatinda olustur. JSON disinda hicbir sey yazma.\nFormat: { "workflowName": "...", "description": "...", "estimatedSteps": N, "skillsLoaded": ["..."], "steps": [{ "step": 1, "tool": "...", "purpose": "...", "params": {...}, "expectedOutput": "..." }] }\n\nGorevle ilgili skill varsa plana skill_view adimi olarak ekle.'
|
|
322
|
+
};
|
|
323
|
+
const planBody = {
|
|
324
|
+
model, stream: false,
|
|
325
|
+
messages: [planPrompt, { role: 'user', content: 'Gorev: ' + task }],
|
|
326
|
+
temperature: 0.3, max_tokens: 4000,
|
|
327
|
+
};
|
|
328
|
+
try {
|
|
329
|
+
const result = await apiCall(providerUrl, providerApiKey, planBody);
|
|
330
|
+
const content = result.choices?.[0]?.message?.content || '';
|
|
331
|
+
const jsonMatch = content.match(/\{[\s\S]*\}/);
|
|
332
|
+
const plan = JSON.parse(jsonMatch ? jsonMatch[0] : content);
|
|
333
|
+
return { success: true, plan, raw: content.slice(0, 1000) };
|
|
334
|
+
} catch (e) {
|
|
335
|
+
return { success: false, error: 'Plan olusturulamadi: ' + e.message };
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ── SAVE / LOAD / LIST / DELETE ───────────────────────────────────────
|
|
340
|
+
if (action === 'save') {
|
|
341
|
+
if (!name || !steps) return { success: false, error: 'name ve steps gerekli' };
|
|
342
|
+
const wfId = 'wf_' + name.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
343
|
+
const wf = { id: wfId, name, description: params.description || '', steps, status: 'saved', createdAt: new Date().toISOString() };
|
|
344
|
+
fs.writeFileSync(path.join(WORKFLOW_DIR, wfId + '.json'), JSON.stringify(wf, null, 2));
|
|
345
|
+
return { success: true, workflowId: wfId, message: name + ' kaydedildi' };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (action === 'load') {
|
|
349
|
+
const wfId = workflowId || name;
|
|
350
|
+
if (!wfId) return { success: false, error: 'workflowId gerekli' };
|
|
351
|
+
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
352
|
+
if (!fs.existsSync(wfFile)) {
|
|
353
|
+
// Try to find by name
|
|
354
|
+
const files = fs.readdirSync(WORKFLOW_DIR).filter(f => f.endsWith('.json'));
|
|
355
|
+
for (const f of files) {
|
|
356
|
+
try {
|
|
357
|
+
const data = JSON.parse(fs.readFileSync(path.join(WORKFLOW_DIR, f), 'utf8'));
|
|
358
|
+
if (data.name === wfId || data.id === wfId) {
|
|
359
|
+
return { success: true, workflow: data };
|
|
360
|
+
}
|
|
361
|
+
} catch {}
|
|
362
|
+
}
|
|
363
|
+
return { success: false, error: 'Workflow bulunamadi: ' + wfId };
|
|
364
|
+
}
|
|
365
|
+
const data = JSON.parse(fs.readFileSync(wfFile, 'utf8'));
|
|
366
|
+
return { success: true, workflow: data };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (action === 'list') {
|
|
370
|
+
const files = fs.readdirSync(WORKFLOW_DIR).filter(f => f.endsWith('.json'));
|
|
371
|
+
const list = files.map(f => {
|
|
372
|
+
try {
|
|
373
|
+
const data = JSON.parse(fs.readFileSync(path.join(WORKFLOW_DIR, f), 'utf8'));
|
|
374
|
+
return { id: data.id, name: data.name, status: data.status, steps: data.steps?.length || 0, createdAt: data.createdAt || data.startedAt };
|
|
375
|
+
} catch { return null; }
|
|
376
|
+
}).filter(Boolean);
|
|
377
|
+
return { success: true, workflows: list };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (action === 'delete') {
|
|
381
|
+
const wfId = workflowId || name;
|
|
382
|
+
if (!wfId) return { success: false, error: 'workflowId gerekli' };
|
|
383
|
+
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
384
|
+
if (fs.existsSync(wfFile)) fs.unlinkSync(wfFile);
|
|
385
|
+
return { success: true, message: wfId + ' silindi' };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ── RETRY: Regenerate and rerun a specific step ──────────────────────
|
|
389
|
+
if (action === 'retry') {
|
|
390
|
+
const wfId = workflowId;
|
|
391
|
+
if (!wfId) return { success: false, error: 'workflowId gerekli' };
|
|
392
|
+
if (typeof regenerateStep !== 'number') return { success: false, error: 'regenerateStep (step numarasi) gerekli' };
|
|
393
|
+
const wfFile = path.join(WORKFLOW_DIR, wfId + '.json');
|
|
394
|
+
if (!fs.existsSync(wfFile)) return { success: false, error: 'Workflow bulunamadi: ' + wfId };
|
|
395
|
+
const wf = JSON.parse(fs.readFileSync(wfFile, 'utf8'));
|
|
396
|
+
const step = wf.steps?.find(s => s.step === regenerateStep);
|
|
397
|
+
if (!step) return { success: false, error: 'Adim bulunamadi: ' + regenerateStep };
|
|
398
|
+
step.params = params.newParams || step.params;
|
|
399
|
+
fs.writeFileSync(wfFile, JSON.stringify(wf, null, 2));
|
|
400
|
+
return { success: true, message: 'Adim ' + regenerateStep + ' yeniden calistirilmak uzere isaretlendi. Tekrar run yapin.', step };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
return { success: false, error: 'Gecersiz action: ' + action + ' (run, plan, save, load, list, delete, retry)' };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
module.exports = {
|
|
407
|
+
name: 'workflow',
|
|
408
|
+
description: '[ORCHESTRATOR] SADECE cok adimli EYLEM gorevleri icin (dosya islemleri, komutlar, arastirma zinciri). Soru-cevap, sohbet, bilgi/aciklama isteklerinde KULLANMA — onlara dogrudan metinle yanit ver. Plan/run/save/load/list/delete/retry.',
|
|
409
|
+
inputSchema: {
|
|
410
|
+
type: 'object',
|
|
411
|
+
properties: {
|
|
412
|
+
action: { type: 'string', description: 'run (tam otomatik), plan (sadece plan), save, load, list, delete, retry', enum: ['run', 'plan', 'save', 'load', 'list', 'delete', 'retry'] },
|
|
413
|
+
task: { type: 'string', description: '(run/plan) Yapilacak gorev — dogal dil ile anlat' },
|
|
414
|
+
steps: { type: 'array', description: '(save) Kaydedilecek adimlar', items: { type: 'object' } },
|
|
415
|
+
name: { type: 'string', description: '(save/load) Workflow adi' },
|
|
416
|
+
workflowId: { type: 'string', description: '(load/delete/retry) Workflow ID' },
|
|
417
|
+
regenerateStep: { type: 'number', description: '(retry) Yeniden calistirilacak adim numarasi' },
|
|
418
|
+
newParams: { type: 'object', description: '(retry) Yeni parametreler' },
|
|
419
|
+
description: { type: 'string', description: 'Aciklama' },
|
|
420
|
+
},
|
|
421
|
+
required: ['action'],
|
|
422
|
+
},
|
|
423
|
+
async execute(params) { return await workflow(params); },
|
|
424
|
+
};
|